@full-self-browsing/phantom-stream 0.1.0 → 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.
Files changed (64) hide show
  1. package/README.md +48 -2
  2. package/dist/types/adapters/extension.d.ts.map +1 -1
  3. package/dist/types/adapters/playwright.d.ts.map +1 -1
  4. package/dist/types/capture/index.d.ts +150 -0
  5. package/dist/types/capture/index.d.ts.map +1 -1
  6. package/dist/types/index.d.ts +2 -0
  7. package/dist/types/player/index.d.ts +136 -0
  8. package/dist/types/player/index.d.ts.map +1 -0
  9. package/dist/types/protocol/constants.d.ts +22 -0
  10. package/dist/types/protocol/constants.d.ts.map +1 -1
  11. package/dist/types/protocol/index.d.ts +1 -0
  12. package/dist/types/protocol/media-reconcile.d.ts +53 -0
  13. package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
  14. package/dist/types/protocol/messages.d.ts +326 -4
  15. package/dist/types/protocol/messages.d.ts.map +1 -1
  16. package/dist/types/recorder/index.d.ts +207 -0
  17. package/dist/types/recorder/index.d.ts.map +1 -0
  18. package/dist/types/renderer/asset-policy.d.ts +72 -0
  19. package/dist/types/renderer/asset-policy.d.ts.map +1 -0
  20. package/dist/types/renderer/diff.d.ts.map +1 -1
  21. package/dist/types/renderer/index.d.ts +61 -8
  22. package/dist/types/renderer/index.d.ts.map +1 -1
  23. package/dist/types/renderer/media-player.d.ts +114 -0
  24. package/dist/types/renderer/media-player.d.ts.map +1 -0
  25. package/dist/types/renderer/overlays.d.ts +12 -0
  26. package/dist/types/renderer/overlays.d.ts.map +1 -1
  27. package/dist/types/renderer/parser-safe.d.ts +26 -0
  28. package/dist/types/renderer/parser-safe.d.ts.map +1 -0
  29. package/dist/types/renderer/sanitize.d.ts +22 -0
  30. package/dist/types/renderer/sanitize.d.ts.map +1 -1
  31. package/dist/types/renderer/snapshot.d.ts +38 -0
  32. package/dist/types/renderer/snapshot.d.ts.map +1 -1
  33. package/dist/types/transport/websocket.d.ts.map +1 -1
  34. package/docs/ARCHITECTURE.md +83 -4
  35. package/docs/QUICKSTARTS.md +64 -0
  36. package/docs/SECURITY.md +279 -2
  37. package/docs/paper/OUTLINE.md +24 -91
  38. package/examples/bookmarklet-demo/viewer.html +12 -3
  39. package/examples/extension-mv3/viewer.html +10 -3
  40. package/package.json +25 -1
  41. package/src/adapters/extension.js +202 -7
  42. package/src/adapters/playwright-inject.js +645 -28
  43. package/src/adapters/playwright.js +176 -2
  44. package/src/capture/README.md +96 -1
  45. package/src/capture/index.js +1672 -40
  46. package/src/index.js +2 -0
  47. package/src/player/README.md +175 -0
  48. package/src/player/index.js +627 -0
  49. package/src/protocol/constants.js +24 -0
  50. package/src/protocol/index.js +1 -0
  51. package/src/protocol/media-reconcile.js +188 -0
  52. package/src/protocol/messages.js +195 -4
  53. package/src/recorder/README.md +225 -0
  54. package/src/recorder/index.js +487 -0
  55. package/src/renderer/README.md +111 -8
  56. package/src/renderer/asset-policy.js +172 -0
  57. package/src/renderer/diff.js +158 -15
  58. package/src/renderer/index.js +978 -21
  59. package/src/renderer/media-player.js +367 -0
  60. package/src/renderer/overlays.js +324 -0
  61. package/src/renderer/parser-safe.js +111 -0
  62. package/src/renderer/sanitize.js +25 -3
  63. package/src/renderer/snapshot.js +534 -3
  64. package/src/transport/websocket.js +36 -0
@@ -0,0 +1,188 @@
1
+ // Pure drift reconciler for media-playback sync (Phase 13: MWIRE-02, MEDIA-03).
2
+ //
3
+ // reconcileMediaDrift(local, remote, now, config) is a PURE function over plain
4
+ // objects: no DOM, no media element, no clock read inside (the caller passes
5
+ // `now`), and ZERO imports (the zero-dependency protocol invariant). That purity
6
+ // is what makes it jsdom-unit-testable with no real media timeline -- the whole
7
+ // MWIRE-02 contract.
8
+ //
9
+ // It is the phase's novel contribution over rrweb's MediaManager: rrweb
10
+ // interpolates the expected position with `currentTime + rate*elapsed` and then
11
+ // ALWAYS hard-seeks. PhantomStream keeps that interpolation but adds a tolerance
12
+ // band + a bounded temporary rate-nudge (so small drift converges smoothly
13
+ // instead of snapping) and a live-edge rejoin (so streams never absolute-seek).
14
+ //
15
+ // The returned action is a plain object { action, ... } where action is one of
16
+ // hold | pause | nudge | seek | rejoin-edge. The DRIVER (renderer, Plan 03)
17
+ // decides whether to apply it; the reconciler itself is side-effect-free and
18
+ // keeps NO internal memory -- whether a nudge is currently applied is read back
19
+ // from local.playbackRate vs remote.playbackRate on the next call.
20
+
21
+ /**
22
+ * @typedef {Object} MediaReconcileConfig
23
+ * @property {number} holdBandSec In-tolerance band (s); within this, hold. Default 0.25
24
+ * @property {number} hardSeekSec Hard-seek threshold (s); above this, seek. Default 1.0
25
+ * @property {number} maxNudgeFraction Max temporary rate delta (fraction). Default 0.05
26
+ * @property {number} liveRejoinSec Live-edge rejoin threshold (s). Default 1.0
27
+ */
28
+
29
+ /** Locked defaults (13-CONTEXT); tunable against the v2.1 evaluation harness. */
30
+ export var DEFAULT_MEDIA_RECONCILE_CONFIG = {
31
+ holdBandSec: 0.25, // |drift| <= this -> hold (no correction)
32
+ hardSeekSec: 1.0, // |drift| > this -> hard-seek to the clamped expected position
33
+ maxNudgeFraction: 0.05, // (0.25, 1.0] band nudges playbackRate by at most +/- this
34
+ liveRejoinSec: 1.0 // live streams rejoin the edge only when drift exceeds this
35
+ };
36
+
37
+ /** Is v a usable finite number? Rejects NaN, +/-Infinity, null, undefined, non-numbers. */
38
+ function isFiniteNum(v) {
39
+ return typeof v === 'number' && isFinite(v);
40
+ }
41
+
42
+ /**
43
+ * Merge a partial config over the locked defaults so a missing field can never
44
+ * leave a threshold `undefined` (which would make every comparison NaN). Only
45
+ * finite overrides are accepted; anything else falls back to the default.
46
+ * @param {Partial<MediaReconcileConfig>} [config]
47
+ * @returns {MediaReconcileConfig}
48
+ */
49
+ function mergeConfig(config) {
50
+ var d = DEFAULT_MEDIA_RECONCILE_CONFIG;
51
+ var c = config || {};
52
+ return {
53
+ holdBandSec: isFiniteNum(c.holdBandSec) ? c.holdBandSec : d.holdBandSec,
54
+ hardSeekSec: isFiniteNum(c.hardSeekSec) ? c.hardSeekSec : d.hardSeekSec,
55
+ maxNudgeFraction: isFiniteNum(c.maxNudgeFraction) ? c.maxNudgeFraction : d.maxNudgeFraction,
56
+ liveRejoinSec: isFiniteNum(c.liveRejoinSec) ? c.liveRejoinSec : d.liveRejoinSec
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Clamp a seek target into [0, duration]. When duration is non-finite or absent,
62
+ * only the lower bound applies (the live branch handles streams before this is
63
+ * ever called for an absolute seek). Always returns a finite number.
64
+ * @param {number} t
65
+ * @param {number} duration
66
+ * @returns {number}
67
+ */
68
+ function clampToDuration(t, duration) {
69
+ var lo = isFiniteNum(t) ? t : 0;
70
+ if (lo < 0) lo = 0;
71
+ if (isFiniteNum(duration) && lo > duration) lo = duration;
72
+ return lo;
73
+ }
74
+
75
+ /**
76
+ * Loop-wrap detector: a looping element where the local position is near the end
77
+ * of the timeline while the expected position has wrapped to near the start (or
78
+ * vice versa). This produces a huge raw |drift| that must NOT trigger a spurious
79
+ * hard-seek across the whole timeline; instead the driver seeks to the wrapped
80
+ * position. The wrap window is a fraction of duration, floored at the hard-seek
81
+ * threshold so tiny clips still register a wrap.
82
+ * @param {number} localTime
83
+ * @param {number} expected
84
+ * @param {number} duration
85
+ * @param {MediaReconcileConfig} cfg
86
+ * @returns {boolean}
87
+ */
88
+ function isLoopWrap(localTime, expected, duration, cfg) {
89
+ if (!isFiniteNum(duration) || duration <= 0) return false;
90
+ if (!isFiniteNum(localTime) || !isFiniteNum(expected)) return false;
91
+ // Window near each edge of the timeline.
92
+ var window = Math.max(cfg.hardSeekSec, duration * 0.1);
93
+ if (window >= duration / 2) return false; // timeline too short to distinguish ends
94
+ var localNearEnd = localTime >= duration - window;
95
+ var localNearStart = localTime <= window;
96
+ var expectedNearEnd = expected >= duration - window;
97
+ var expectedNearStart = expected <= window;
98
+ return (localNearEnd && expectedNearStart) || (localNearStart && expectedNearEnd);
99
+ }
100
+
101
+ /**
102
+ * Decide the single drift-correction action for one media element.
103
+ *
104
+ * Decision order (RESEARCH Pattern 1, exact):
105
+ * merge cfg -> incomplete-remote guard -> explicit `seeked` short-circuit ->
106
+ * paused/rate-0 -> NaN local guard -> latency-compensated `expected` (elapsed
107
+ * clamped >= 0) -> LIVE branch (before any duration math) -> VOD: loop-wrap ->
108
+ * hold band (carries revertRate) -> bounded sign-correct nudge (carries
109
+ * baseRate) -> hard-seek (clamp toTime into [0, duration]).
110
+ *
111
+ * @param {{currentTime?: number, paused?: boolean, playbackRate?: number}} local Observed element state
112
+ * @param {import('./messages.js').MediaSyncPayload|null} remote Latency-uncompensated captured state
113
+ * @param {number} now Caller clock (ms), e.g. performance.now()-equivalent
114
+ * @param {Partial<MediaReconcileConfig>} [config] Overrides merged over DEFAULT_MEDIA_RECONCILE_CONFIG
115
+ * @returns {{action:'hold'|'pause'|'nudge'|'seek'|'rejoin-edge', toTime?:number, rate?:number, baseRate?:number, revertRate?:number, reason?:string}}
116
+ */
117
+ export function reconcileMediaDrift(local, remote, now, config) {
118
+ var cfg = mergeConfig(config);
119
+
120
+ // ---- 0. guard incomplete / non-finite remote (no NaN propagation) ----
121
+ if (!remote || remote.currentTime == null ||
122
+ !isFiniteNum(remote.currentTime) || !isFiniteNum(remote.sentAt)) {
123
+ return { action: 'hold', reason: 'incomplete-remote' };
124
+ }
125
+
126
+ // ---- 1. explicit seek short-circuits everything (CONTEXT: always hard-seek) ----
127
+ if (remote.event === 'seeked') {
128
+ return { action: 'seek', toTime: clampToDuration(remote.currentTime, remote.duration) };
129
+ }
130
+
131
+ // ---- 2. paused / rate-0: mirror pause, never interpolate position ----
132
+ if (remote.paused === true || remote.playbackRate === 0) {
133
+ return (local && local.paused)
134
+ ? { action: 'hold', reason: 'paused' }
135
+ : { action: 'pause' };
136
+ }
137
+
138
+ // ---- 3. NaN local (element not ready): wait for readiness ----
139
+ var localTime = (local && isFiniteNum(local.currentTime)) ? local.currentTime : null;
140
+ if (localTime === null) {
141
+ return { action: 'hold', reason: 'local-not-ready' };
142
+ }
143
+
144
+ // ---- 4. latency-compensated expected position (playing only) ----
145
+ var elapsedSec = Math.max(0, (now - remote.sentAt) / 1000); // negative clock skew -> 0
146
+ if (!isFiniteNum(elapsedSec)) elapsedSec = 0;
147
+ var rate = isFiniteNum(remote.playbackRate) && remote.playbackRate > 0 ? remote.playbackRate : 1;
148
+ var expected = remote.currentTime + rate * elapsedSec;
149
+
150
+ // ---- 5. LIVE branch: before ANY duration arithmetic; never absolute-seek ----
151
+ if (remote.live === true || !isFiniteNum(remote.duration)) {
152
+ var liveDrift = Math.abs(expected - localTime);
153
+ return liveDrift > cfg.liveRejoinSec
154
+ ? { action: 'rejoin-edge' }
155
+ : { action: 'hold', reason: 'live-in-band' };
156
+ }
157
+
158
+ // ---- 6. VOD branch (duration is finite here by construction) ----
159
+ var duration = remote.duration;
160
+
161
+ // duration 0 is a non-seekable timeline: never seek into it.
162
+ if (duration <= 0) {
163
+ return { action: 'hold', reason: 'zero-duration' };
164
+ }
165
+
166
+ // loop wrap: seek to the wrapped position, not the raw (huge) delta.
167
+ if (remote.loop === true && isLoopWrap(localTime, expected, duration, cfg)) {
168
+ return { action: 'seek', toTime: clampToDuration(expected, duration) };
169
+ }
170
+
171
+ var drift = expected - localTime;
172
+ var adrift = Math.abs(drift);
173
+
174
+ // hold band: carry revertRate so the driver restores the true rate if a nudge was active.
175
+ if (adrift <= cfg.holdBandSec) {
176
+ return { action: 'hold', reason: 'in-band', revertRate: rate };
177
+ }
178
+
179
+ // (holdBandSec, hardSeekSec]: bounded, sign-correct temporary rate nudge.
180
+ if (adrift <= cfg.hardSeekSec) {
181
+ var sign = drift > 0 ? 1 : -1; // behind (expected ahead) -> speed up; ahead -> slow down
182
+ var nudgeRate = rate * (1 + sign * cfg.maxNudgeFraction);
183
+ return { action: 'nudge', rate: nudgeRate, baseRate: rate };
184
+ }
185
+
186
+ // adrift > hardSeekSec: hard-seek to the clamped expected position.
187
+ return { action: 'seek', toTime: clampToDuration(expected, duration) };
188
+ }
@@ -21,6 +21,10 @@ export const STREAM = {
21
21
  MUTATIONS: 'ext:dom-mutations',
22
22
  /** Scroll position. Payload: { scrollX, scrollY, streamSessionId, snapshotId } */
23
23
  SCROLL: 'ext:dom-scroll',
24
+ /** Media playback state. Payload: MediaSyncPayload */
25
+ MEDIA: 'ext:dom-media',
26
+ /** Adaptive-manifest discovery hint (opt-in, adapter-originated). Payload: MediaHintPayload */
27
+ MEDIA_HINT: 'ext:dom-media-hint',
24
28
  /** Automation overlay state. Payload: { glow, progress, streamSessionId, snapshotId } */
25
29
  OVERLAY: 'ext:dom-overlay',
26
30
  /** Native dialog mirroring. Payload: { dialog: DialogPayload } */
@@ -59,7 +63,7 @@ export { REMOTE_CONTROL_STATE_VALUES as REMOTE_CONTROL_STATE };
59
63
 
60
64
  /** Diff op codes carried in STREAM.MUTATIONS payloads. */
61
65
  export const DIFF_OP = {
62
- /** { op:'add', parentNid, html, beforeNid|null, nodeIds:string[] } — insert serialized subtree */
66
+ /** { op:'add', parentNid, html, beforeNid|null, nodeIds:string[] } — insert serialized subtree; parentNid is a tracked element nid, or BODY_NID for a direct child of the main <body> */
63
67
  ADD: 'add',
64
68
  /** { op:'rm', nid } — remove subtree */
65
69
  REMOVE: 'rm',
@@ -67,7 +71,7 @@ export const DIFF_OP = {
67
71
  ATTR: 'attr',
68
72
  /** { op:'text', nid, text } — character data change, addressed via parent nid */
69
73
  TEXT: 'text',
70
- /** { op:'value', nid, value?, checked?, selectedValues? } — live form state change */
74
+ /** { op:'value', nid, value?, checked?, selectedValues?, selectedIndexes? } — live form state change */
71
75
  VALUE: 'value',
72
76
  /** ShadowRootPayload plus op:'shadow-root' — replace/open an observed shadow root */
73
77
  SHADOW_ROOT: 'shadow-root',
@@ -85,6 +89,51 @@ export const DIFF_OP = {
85
89
  */
86
90
  export const NID_ATTR = 'data-fsb-nid';
87
91
 
92
+ /**
93
+ * Reserved identity for the MAIN document `<body>` (quick task 261127-u5c).
94
+ *
95
+ * The snapshot sidecar starts below `<body>`, so the body itself never gets a
96
+ * counter nid. This value is non-numeric, so it can never collide with the
97
+ * capture counter (which only ever yields `String(n)` for n >= 1), and it
98
+ * consumes no counter value, so nodeIds sidecars keep their exact numbering.
99
+ *
100
+ * - Carried on every main snapshot as SnapshotPayload.bodyNid.
101
+ * - The add-op parentNid for a direct child of the main `<body>` (toasts,
102
+ * modals, portals); beforeNid resolution is unchanged.
103
+ * - The attr-op nid for a `<body>` attribute change other than `style` (the
104
+ * snapshot shell bodyStyle owns the mirror body's style attribute).
105
+ * - Not returned by capture getNodeId, and not a subtree-request target: the
106
+ * body is a structural anchor for body-level diffs, not an addressable
107
+ * element.
108
+ *
109
+ * Same-origin frame documents keep their counter htmlNid/bodyNid
110
+ * (FramePayload); only the main document body uses this value.
111
+ */
112
+ export const BODY_NID = 'body';
113
+
114
+ /**
115
+ * Parser-safe placeholder element and attribute (quick task 261202-jwf).
116
+ *
117
+ * A DOM built by scripts can hold nesting that HTML text cannot express: a
118
+ * `<button>` inside a `<button>`, an `<a>` inside an `<a>`, a `<div>` inside a
119
+ * `<p>`, a `<tr>` without a `<tbody>`, an `<img>` with children. Re-parsing the
120
+ * serialized HTML rewrites such a tree, which moves content and breaks the
121
+ * positional nodeIds pairing.
122
+ *
123
+ * - Capture renames each such element in its detached wire clone to
124
+ * `<ps-node>` (PARSER_SAFE_TAG), copying every attribute and setting
125
+ * PARSER_SAFE_TAG_ATTR to the lowercase original tag. Element order and
126
+ * count are unchanged, so nodeIds sidecars stay aligned. Capture strips
127
+ * PARSER_SAFE_TAG_ATTR from page-owned `<ps-node>` elements.
128
+ * - Viewers restore only an allowlist of tags (never script, iframe, object,
129
+ * embed, style, link, meta, base, html, head, body or frameset), right
130
+ * after each parse and before the post-parse scrub and identity pairing.
131
+ * - Viewers older than 0.3.0 render the placeholders as generic elements:
132
+ * structure and nid pairing stay intact, only the original tags are lost.
133
+ */
134
+ export const PARSER_SAFE_TAG = 'ps-node';
135
+ export const PARSER_SAFE_TAG_ATTR = 'data-ps-tag';
136
+
88
137
  /**
89
138
  * @typedef {Object} StyleScope
90
139
  * @property {'document'|'shadow'|'frame'} kind
@@ -127,7 +176,7 @@ export const NID_ATTR = 'data-fsb-nid';
127
176
  /**
128
177
  * @typedef {Object} AddDiffOp
129
178
  * @property {'add'} op
130
- * @property {string} parentNid Parent node id in the current mirror
179
+ * @property {string} parentNid Parent node id in the current mirror, or BODY_NID for a direct child of the main <body>
131
180
  * @property {string} html Serialized subtree HTML, without framework identity attrs
132
181
  * @property {string|null} beforeNid Insert before this sibling nid, or append when null
133
182
  * @property {string[]} nodeIds Preorder ids for every serialized element in html
@@ -152,6 +201,8 @@ export const NID_ATTR = 'data-fsb-nid';
152
201
  * @property {string} kind Frame policy kind, e.g. 'same-origin' or 'cross-origin'
153
202
  * @property {string} [html] Serialized frame body HTML for accessible frames
154
203
  * @property {string[]} [nodeIds] Preorder ids for serialized frame elements
204
+ * @property {string} [htmlNid] Counter nid of the frame document <html> (empty string when unavailable)
205
+ * @property {string} [bodyNid] Counter nid of the frame document <body> (empty string when unavailable)
155
206
  * @property {string[]} [stylesheets] Absolutified stylesheet URLs
156
207
  * @property {string[]} [inlineStyles] Sanitized inline style blocks
157
208
  * @property {StyleSource[]} [styleSources] Scoped CSSOM sources for this frame document
@@ -171,7 +222,84 @@ export const NID_ATTR = 'data-fsb-nid';
171
222
  * @property {string} nid
172
223
  * @property {string} [value] Textual value for input/textarea/select-like controls
173
224
  * @property {boolean} [checked] Checked state for checkbox/radio controls
174
- * @property {string[]} [selectedValues] Selected option values for multi-select controls
225
+ * @property {string[]} [selectedValues] Selected option values for select controls (masked when maskInputs is on, so renderers must not treat these as a selection key)
226
+ * @property {number[]} [selectedIndexes] Authoritative positional identity of selected options; preferred over selectedValues because option indexes never carry page content and stay unambiguous under masking
227
+ */
228
+
229
+ /**
230
+ * Captured live playback state of a single <video>/<audio> element, keyed by
231
+ * nid. Models the DIFF_OP.VALUE side-channel-property-state precedent: live
232
+ * media properties travel as side-channel data, never serialized into the HTML
233
+ * clone (preserves the Phase 7 no-mutation invariant + HTML byte-identity).
234
+ *
235
+ * Live/Infinity-duration encoding: `duration` is present ONLY when finite;
236
+ * non-finite (streaming) durations are encoded as `live: true` instead, never
237
+ * both. This sidesteps the JSON Infinity -> null trap (JSON.stringify(Infinity)
238
+ * === "null") so the reconciler can branch on `live` before any duration math
239
+ * and never compute NaN.
240
+ *
241
+ * @typedef {Object} MediaBaselineEntry
242
+ * @property {string} nid Element nid the playback state addresses
243
+ * @property {number} currentTime Playback position in seconds
244
+ * @property {boolean} paused Whether the element is paused
245
+ * @property {boolean} muted Whether audio output is muted
246
+ * @property {number} volume Audio volume in [0, 1]
247
+ * @property {number} playbackRate Effective playback rate (1 = normal)
248
+ * @property {boolean} loop Whether the element loops
249
+ * @property {boolean} ended Whether playback reached the end
250
+ * @property {number} [duration] Media duration in seconds; present ONLY when finite
251
+ * @property {boolean} [live] true when duration is non-finite (stream); mutually exclusive with duration
252
+ */
253
+
254
+ /**
255
+ * One STREAM.MEDIA wire message: a MediaBaselineEntry enriched with the event
256
+ * that triggered emission, a capture-side monotonic timestamp for latency
257
+ * compensation, and the stream identity stamps every side channel carries.
258
+ *
259
+ * The reconciler predicts the expected position from `currentTime`,
260
+ * `playbackRate`, and `(now - sentAt)`; `streamSessionId`/`snapshotId` let the
261
+ * renderer reject stale cross-generation frames via isCurrentStream (Plan 03).
262
+ * One message is emitted per media element per tick (scroll-like granularity).
263
+ *
264
+ * @typedef {Object} MediaSyncPayload
265
+ * @property {string} nid Element nid the playback state addresses
266
+ * @property {'play'|'pause'|'seeked'|'ratechange'|'ended'|'volumechange'|'loadedmetadata'|'timeupdate'} event Triggering media event
267
+ * @property {number} currentTime Playback position in seconds at capture
268
+ * @property {boolean} paused Whether the element is paused
269
+ * @property {boolean} muted Whether audio output is muted
270
+ * @property {number} volume Audio volume in [0, 1]
271
+ * @property {number} playbackRate Effective playback rate (1 = normal)
272
+ * @property {boolean} loop Whether the element loops
273
+ * @property {boolean} ended Whether playback reached the end
274
+ * @property {number} [duration] Media duration in seconds; present ONLY when finite
275
+ * @property {boolean} [live] true when duration is non-finite (stream); mutually exclusive with duration
276
+ * @property {number} sentAt Capture-side monotonic ms stamp for latency compensation
277
+ * @property {string} streamSessionId Identity: minted per stream session
278
+ * @property {number} snapshotId Identity: minted per snapshot
279
+ */
280
+
281
+ /**
282
+ * One adaptive-manifest discovery hint surfaced by an adapter's opt-in network
283
+ * observation (Playwright `page.on('response')` / extension `chrome.webRequest`).
284
+ * The hint originates in the ADAPTER, never the capture core, so it adds no
285
+ * capture-wire divergence (no differential-oracle entry); it rides the existing
286
+ * raw relay + 1 MiB cap with the envelope byte-unchanged, and old viewers ignore
287
+ * the unknown STREAM.MEDIA_HINT type via the renderer dispatch default.
288
+ *
289
+ * Addressing is nid-scoped when manifest->element correlation is confident, else
290
+ * page-scoped (nid omitted, scope 'page'); a page hint is matched to an
291
+ * MSE-opaque media element on play by the viewer. Identity-stamped like every
292
+ * side channel; the viewer re-gates `manifestUrl` through the same fail-closed
293
+ * origin policy before any use.
294
+ *
295
+ * @typedef {Object} MediaHintPayload
296
+ * @property {string} [nid] Element nid when correlation is confident; omitted for page-level
297
+ * @property {'page'|'element'} scope 'element' (nid set) or 'page' (viewer matches on play)
298
+ * @property {string} manifestUrl Absolute manifest URL (https; viewer re-gates before use)
299
+ * @property {'hls'|'dash'} kind Derived from URL extension and/or content-type
300
+ * @property {string} [contentType] Observed response content-type (diagnostic)
301
+ * @property {string} streamSessionId Identity: minted per stream session
302
+ * @property {number} snapshotId Identity: minted per snapshot
175
303
  */
176
304
 
177
305
  /**
@@ -202,6 +330,7 @@ export const NID_ATTR = 'data-fsb-nid';
202
330
  * @typedef {Object} SnapshotPayload
203
331
  * @property {string} html Serialized body innerHTML (style-inlined; framework identity-clean)
204
332
  * @property {string[]} nodeIds Preorder ids for every serialized element in html
333
+ * @property {string} [bodyNid] Reserved main <body> identity, always BODY_NID (absent on captures older than this fix)
205
334
  * @property {ShadowRootPayload[]} [shadowRoots] Open shadow roots keyed by host nid
206
335
  * @property {FramePayload[]} [frames] Frame sidecars keyed by iframe nid
207
336
  * @property {boolean} truncated True if the size budget forced subtree drops
@@ -266,3 +395,65 @@ export function isCurrentStream(msg, active) {
266
395
  }
267
396
  return true;
268
397
  }
398
+
399
+ // HLS content-type tokens (lowercased, charset-stripped before compare). DASH
400
+ // is the single application/dash+xml token below. CDNs frequently serve
401
+ // extensionless or signed manifest URLs, so the content-type is the more
402
+ // robust of the two signals.
403
+ const HLS_CONTENT_TYPES = {
404
+ 'application/vnd.apple.mpegurl': true,
405
+ 'application/x-mpegurl': true,
406
+ 'audio/mpegurl': true,
407
+ 'audio/x-mpegurl': true,
408
+ };
409
+ const DASH_CONTENT_TYPE = 'application/dash+xml';
410
+
411
+ /**
412
+ * Extract a lowercased URL path, ignoring query/hash, defensively. A malformed
413
+ * url never throws: a `new URL()` failure falls back to a regex strip of the
414
+ * first `?`/`#` (mirrors the isHlsManifest defensiveness in 14-RESEARCH). A
415
+ * non-string url yields an empty path.
416
+ * @param {*} url
417
+ * @returns {string} lowercased path (or '' on failure)
418
+ */
419
+ function manifestPathOf(url) {
420
+ if (typeof url !== 'string' || url === '') return '';
421
+ try {
422
+ return new URL(url).pathname.toLowerCase();
423
+ } catch (e) {
424
+ // Not an absolute/parseable URL: strip query + hash, then lowercase.
425
+ return String(url).split('#')[0].split('?')[0].toLowerCase();
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Pure manifest classifier: is an observed response an adaptive-streaming
431
+ * manifest, and of which kind? Returns `'hls'` for an `.m3u8` path OR an HLS
432
+ * content-type; `'dash'` for an `.mpd` path OR `application/dash+xml`; `null`
433
+ * otherwise. URL-OR-content-type: either signal is independently sufficient.
434
+ *
435
+ * Never throws (T-14-03): a malformed/hostile url string is a guarded `null`
436
+ * (or a regex-fallback classification when the extension is still discernible),
437
+ * so it can never wedge the adapter. Project convention: a pure helper returns
438
+ * a primitive, not the `{ok,...}` fallible shape.
439
+ *
440
+ * @param {{url?: string, contentType?: string}} [input]
441
+ * @returns {'hls'|'dash'|null}
442
+ */
443
+ export function classifyManifest(input) {
444
+ if (!input) return null;
445
+ // Content-type first (the more robust signal): lowercase, drop the ;charset.
446
+ const ct = (typeof input.contentType === 'string' ? input.contentType : '')
447
+ .split(';')[0].trim().toLowerCase();
448
+ if (ct) {
449
+ if (HLS_CONTENT_TYPES[ct]) return 'hls';
450
+ if (ct === DASH_CONTENT_TYPE) return 'dash';
451
+ }
452
+ // URL path extension (query/hash ignored; malformed url -> guarded).
453
+ const path = manifestPathOf(input.url);
454
+ if (path) {
455
+ if (/\.m3u8$/.test(path)) return 'hls';
456
+ if (/\.mpd$/.test(path)) return 'dash';
457
+ }
458
+ return null;
459
+ }
@@ -0,0 +1,225 @@
1
+ # recorder
2
+
3
+ Timestamped capture transport and the portable recording format. The
4
+ recorder is a `Transport` that capture sends into directly: every message is
5
+ stamped `{ t, type, payload }` with the recorder clock, so a recording holds
6
+ exactly the post-masking wire messages capture sent. Play recordings back
7
+ with the player (`src/player/`).
8
+
9
+ The module has no DOM access, no timers, and no side effects at import, so it
10
+ imports in bare Node, workers, and pages alike.
11
+
12
+ ## Factory
13
+
14
+ ```js
15
+ import { createRecorder } from '@full-self-browsing/phantom-stream/recorder';
16
+
17
+ const recorder = createRecorder({
18
+ now: () => Date.now(),
19
+ onChunk: undefined,
20
+ chunkMaxEvents: 200,
21
+ chunkMaxMs: 1000,
22
+ recordReady: false,
23
+ });
24
+ // -> { transport, mark, overlay, identity, flush, toRecording }
25
+ ```
26
+
27
+ | Option | Required | Default | Purpose |
28
+ |--------|----------|---------|---------|
29
+ | `now` | no | `() => Date.now()` | Clock in ms. Every event gets `t = max(now(), previous t)`, so a wall-clock step back never produces a decreasing recording. A non-finite reading reuses the previous `t`. The factory throws `Error('recorder-now-invalid')` for a non-function. |
30
+ | `onChunk` | no | none (retained mode) | `(chunk) => void`. Turns on chunk mode (below): events are not retained and finished chunks are handed to this callback. The factory throws `Error('recorder-onchunk-invalid')` for a non-function. |
31
+ | `chunkMaxEvents` | no | `200` | Positive integer. Chunk mode emits a chunk once it holds this many events. Otherwise `Error('recorder-chunk-max-events-invalid')`. |
32
+ | `chunkMaxMs` | no | `1000` | Positive finite ms. Chunk mode emits the open chunk before an event that would make it span more than this. Otherwise `Error('recorder-chunk-max-ms-invalid')`. |
33
+ | `recordReady` | no | `false` | Record `STREAM.READY` too. Capture sends it once at factory creation; it carries no mirror state, so it is dropped by default. |
34
+
35
+ Factory-time validation is the only place the recorder throws.
36
+
37
+ ## Handle contract
38
+
39
+ - `transport` — `{ send(type, payload), flush() }`, the capture transport.
40
+ `send` stamps and records one message (keeping the same payload
41
+ reference), drops `STREAM.READY` unless `recordReady`, and tracks the
42
+ identity of every snapshot with string `html`. A message whose type is not
43
+ a non-empty string or whose payload is not an object is not recorded, so
44
+ recorder output always passes the event shape check. `transport.flush` is
45
+ the same function as `recorder.flush`.
46
+ - `mark(kind, data?)` — record a host timeline mark
47
+ `{ t, type: 'host:mark', payload: { kind, ...data } }`. `kind` is stamped
48
+ last, so `data.kind` cannot override it, and the payload is a JSON clone
49
+ (functions and `undefined` values drop). Returns `false` and records
50
+ nothing when `kind` is not a non-empty string or `data` cannot be
51
+ serialized (a cycle or a BigInt). Marks are allowed before the first
52
+ snapshot.
53
+ - `overlay(payload)` — record a `STREAM.OVERLAY` for the current snapshot,
54
+ following capture's overlay rule (E1): `glow` and `progress` default to
55
+ `null`, and the identity keys are stamped last, so an input can never
56
+ spoof `streamSessionId` or `snapshotId`. Returns `false` and records
57
+ nothing before the first snapshot. The input object is never mutated.
58
+ - `identity()` — a fresh copy of `{ streamSessionId, snapshotId }` from the
59
+ latest snapshot, or `null` before the first one.
60
+ - `flush()` — record the end time (`max(now(), last t)`) and, in chunk mode,
61
+ emit the open chunk when it holds any event.
62
+ - `toRecording(meta?)` — the full recording in retained mode, or `null` in
63
+ chunk mode. `startedAt` is the first event's `t`; `endedAt` is the last
64
+ flush time, or `now()` when the recorder was never flushed, and never less
65
+ than the last event's `t`. `meta` is shallow-copied (a non-object becomes
66
+ `{}`).
67
+
68
+ ## Wiring with capture
69
+
70
+ ```js
71
+ import { createCapture } from '@full-self-browsing/phantom-stream/capture';
72
+ import { createRecorder } from '@full-self-browsing/phantom-stream/recorder';
73
+
74
+ const recorder = createRecorder();
75
+ const capture = createCapture({ transport: recorder.transport });
76
+
77
+ capture.start();
78
+ // ... the session runs; the host may annotate it:
79
+ recorder.mark('action', { label: 'Click "Add to cart"' });
80
+ recorder.overlay({ glow: { state: 'active', nid: capture.getNodeId(button) } });
81
+ // ...
82
+ capture.stop(); // flushes pending mutations, then transport.flush() sets endedAt
83
+
84
+ const json = JSON.stringify(recorder.toRecording({ title: 'checkout' }));
85
+ ```
86
+
87
+ Capture contains transport throws, so a throwing `onChunk` is logged by
88
+ capture and never breaks the capture path.
89
+
90
+ ## Recording format
91
+
92
+ ```js
93
+ {
94
+ format: 'phantomstream-recording/1', // RECORDING_FORMAT
95
+ version: 1, // RECORDING_VERSION
96
+ startedAt: 1795849257000, // recorder clock ms of the first event
97
+ endedAt: 1795849263000, // recorder clock ms of the end
98
+ meta: { title: 'checkout' }, // host metadata
99
+ events: [
100
+ { t: 1795849257000, type: 'ext:dom-snapshot', payload: { /* SnapshotPayload */ } },
101
+ { t: 1795849257400, type: 'host:mark', payload: { kind: 'action', label: 'Click' } },
102
+ { t: 1795849257520, type: 'ext:dom-mutations', payload: { /* mutations, identity */ } },
103
+ ],
104
+ }
105
+ ```
106
+
107
+ - Each event is `{ t, type, payload }`. `type` is a `STREAM.*` protocol
108
+ string exactly as capture sent it, or `HOST_MARK_TYPE` (`'host:mark'`) for
109
+ host marks, whose payload always carries a non-empty string `kind`.
110
+ - The time base is the recorder clock in ms (`Date.now()` by default).
111
+ Player time is ms from the first event: `t - events[0].t`.
112
+ - `t` never decreases, and playback needs at least one `STREAM.SNAPSHOT`
113
+ whose `payload.html` is a string.
114
+ - A recording is JSON-safe: capture payloads and host marks are plain data,
115
+ so `JSON.parse(JSON.stringify(recording))` validates and plays the same.
116
+
117
+ `createRecording({ events, meta, startedAt, endedAt })` builds this object.
118
+ `events` is copied; `meta` is shallow-copied (a non-object becomes `{}`);
119
+ `startedAt` and `endedAt` default to the first and last event times (`0` and
120
+ `0` with no events), and explicit finite values are kept. It never
121
+ validates. `validateRecording(rec)` does (below).
122
+
123
+ ## Chunk mode
124
+
125
+ Pass `onChunk` to stream a recording out as it is made instead of holding it
126
+ in memory:
127
+
128
+ ```js
129
+ const recorder = createRecorder({
130
+ onChunk(chunk) {
131
+ upload(chunk); // { seq, t0, t1, keyframe, events }
132
+ },
133
+ });
134
+ setInterval(() => recorder.flush(), 5000); // optional timed cut
135
+ ```
136
+
137
+ - Chunks are keyframe-aligned: every `STREAM.SNAPSHOT` opens a new chunk, so
138
+ a chunk holds at most one snapshot, and only at index 0. `keyframe` is
139
+ `true` when `events[0]` is a snapshot; playback can start from such a
140
+ chunk without any earlier one.
141
+ - A chunk is emitted when it reaches `chunkMaxEvents`, before an event that
142
+ would make it span more than `chunkMaxMs`, or on `flush()`. An empty open
143
+ chunk emits nothing.
144
+ - There are no timers: a chunk is cut on the next event or on `flush()`.
145
+ Hosts that want timed uploads call `flush()` on their own interval.
146
+ - `onChunk` runs synchronously. The recorder places the event and updates
147
+ its own state (resets the open chunk, increments `seq`) before calling it,
148
+ so a throwing `onChunk` propagates to the caller without corrupting the
149
+ recorder or losing the event.
150
+ - Events are not retained, so `toRecording()` returns `null`. Rebuild a
151
+ recording from the stored chunks, in `seq` order:
152
+
153
+ ```js
154
+ import { createRecording, validateRecording } from '@full-self-browsing/phantom-stream/recorder';
155
+
156
+ const recording = createRecording({
157
+ events: chunks.flatMap((c) => c.events),
158
+ meta: { title: 'checkout' },
159
+ });
160
+ validateRecording(recording); // -> { ok: true }
161
+ ```
162
+
163
+ ## Recording while also streaming live
164
+
165
+ Capture takes one transport. To record a session that is also mirrored live,
166
+ pass a host-written transport that fans out to both:
167
+
168
+ ```js
169
+ const live = transport; // the transport you already stream with
170
+ const recorder = createRecorder();
171
+
172
+ const capture = createCapture({
173
+ transport: {
174
+ send(type, payload) {
175
+ recorder.transport.send(type, payload);
176
+ live.send(type, payload);
177
+ },
178
+ flush() {
179
+ recorder.transport.flush();
180
+ if (typeof live.flush === 'function') return live.flush();
181
+ },
182
+ },
183
+ });
184
+ ```
185
+
186
+ The recorder keeps the payload reference it is given and never mutates it.
187
+
188
+ ## validateRecording reasons
189
+
190
+ `validateRecording(rec)` returns `{ ok: true }` or
191
+ `{ ok: false, error }`. It never throws, checks structure in this order, and
192
+ reports the first fault only:
193
+
194
+ | `error` | Meaning |
195
+ |---------|---------|
196
+ | `recording-not-object` | Not a non-array object (or reading it threw). |
197
+ | `recording-format-unsupported` | `format` is not `'phantomstream-recording/1'`. |
198
+ | `recording-version-unsupported` | `version` is not `1`. |
199
+ | `recording-bounds-invalid` | `startedAt` or `endedAt` is not finite, or `startedAt` is greater than `endedAt`. |
200
+ | `recording-meta-invalid` | `meta` is not a non-array object. |
201
+ | `recording-events-missing` | `events` is not an array, or is empty. |
202
+ | `recording-event-invalid` | An event lacks a finite `t`, a non-empty string `type`, or an object `payload`, or a `host:mark` payload lacks a non-empty string `kind`. |
203
+ | `recording-time-decreasing` | An event's `t` is below the previous event's `t`. |
204
+ | `recording-no-snapshot` | No `STREAM.SNAPSHOT` has a string `payload.html`. |
205
+
206
+ Validation is structural only. It does not make a recording trustworthy:
207
+ the player still routes every payload through the viewer's sanitizers.
208
+
209
+ ## Keyframes and seek cost
210
+
211
+ The player rebuilds any moment from the nearest snapshot at or before it,
212
+ then applies every later event up to that moment. Seek cost therefore grows
213
+ with the distance from the last snapshot. Capture mints a snapshot on every
214
+ `start()`, so calling `capture.start()` at quiet points (for example after
215
+ each agent action settles) adds a fresh keyframe, bounds that cost, and in
216
+ chunk mode starts a new keyframe chunk.
217
+
218
+ ## Privacy
219
+
220
+ A recording holds exactly the post-masking wire content: DOM text,
221
+ attribute values, unmasked form values, overlay labels, and mark data.
222
+ Masking happens in capture, before a message reaches the recorder, so
223
+ configure `blockSelector`, `maskTextSelector`, and `maskInputs` before
224
+ recording. Treat stored recordings like the live stream (access control,
225
+ retention, encryption at rest). See `docs/SECURITY.md`.