1pub const PLAYER_JS: &str =
16 concat!(include_str!("vt.js"), "\n", include_str!("controller.js"), "\n", include_str!("player.js"),);
17
18pub const PLAYER_CSS: &str = include_str!("player.css");
21
22#[cfg(test)]
23mod tests {
24 use super::*;
25
26 #[test]
32 fn player_bundle_is_inline_safe_and_first_party() {
33 assert!(!PLAYER_JS.contains("</script"), "bundle would terminate an inline <script>");
34 assert!(!PLAYER_JS.contains("<!--"), "bundle would enter the script double-escaped state");
35 assert!(!PLAYER_JS.to_lowercase().contains("worker"), "bundle must not load a worker sidecar");
36 assert!(!PLAYER_CSS.contains("url("), "player CSS must not fetch fonts/images");
37 assert!(PLAYER_JS.contains("BeeCastPlayer") && PLAYER_JS.contains("Clean-room implementation"));
38 assert!(PLAYER_JS.contains("BeeCastController"));
39 assert!(PLAYER_JS.contains("beecast-player"));
40 for banned in ["asciinema-player", "AsciinemaPlayer", "@license", "Apache"] {
41 assert!(!PLAYER_JS.contains(banned) && !PLAYER_CSS.contains(banned), "third-party marker '{banned}'");
42 }
43 }
44
45 #[test]
48 fn overlay_and_marker_jumps_do_not_autoplay() {
49 assert!(
50 PLAYER_JS.contains("state.status !== 'playing' && state.duration > 0"),
51 "overlay must show whenever not playing, not only at t = 0"
52 );
53 assert!(!PLAYER_JS.contains("currentTime <= 1e-9 && state.duration"), "the t≈0-only overlay gate must stay gone");
54 assert!(
56 !PLAYER_JS.contains("this.play(origin || 'marker')") && !PLAYER_JS.contains("self.play('marker')"),
57 "marker/chapter navigation must not force play"
58 );
59 }
60
61 #[test]
65 fn fit_both_refuses_the_content_sized_shrink_ratchet() {
66 assert!(
67 PLAYER_JS.contains("mountHeightIsDefinite"),
68 "layout must probe whether the mount's height is independent of the screen box"
69 );
70 assert!(
71 PLAYER_JS.contains("before > 0 && before === after"),
72 "definite-height probe must compare mount clientHeight before/after collapsing the box"
73 );
74 assert!(
75 !PLAYER_JS.contains("availH - 4"),
76 "the availH-4 trigger forced another shrink on every ResizeObserver tick"
77 );
78 }
79
80 #[test]
82 fn public_api_surface_is_documented() {
83 for key in [
84 "BeeCastVT",
85 "BeeCastController",
86 "BeeCastPlayer",
87 "parseCast",
88 "appendCast",
89 "buildPacing",
90 "extendPacing",
91 "mapTime",
92 "create",
93 "getState",
94 "subscribe",
95 "setSpeed",
96 "publicMethods",
97 "supportedCssVariables",
98 "nonPublicFields",
99 ] {
100 assert!(PLAYER_JS.contains(key), "public surface missing {key}");
101 }
102 for token in
103 ["--beecast-color-surface", "--beecast-color-accent", "--beecast-color-focus", "--beecast-font-terminal"]
104 {
105 assert!(PLAYER_CSS.contains(token), "theme token missing {token}");
106 }
107 }
108
109 #[test]
112 fn vt_core_node_selftest() {
113 let dir = std::env::temp_dir().join(format!("beecast-vt-selftest-{}", std::process::id()));
114 std::fs::create_dir_all(&dir).unwrap();
115 let bundle = dir.join("player.js");
116 std::fs::write(&bundle, PLAYER_JS).unwrap();
117 let script = r#"
118const assert = require('assert');
119require(process.argv[2]);
120const VT = globalThis.BeeCastVT;
121const C = globalThis.BeeCastController;
122const P = globalThis.BeeCastPlayer;
123
124// ---- Phase 0: public keys --------------------------------------------------------------
125for (const k of ['parseCast','appendCast','buildPacing','extendPacing','mapTime','Term']) {
126 assert.strictEqual(typeof VT[k], 'function', 'BeeCastVT.' + k);
127}
128assert.strictEqual(typeof C.create, 'function');
129assert.strictEqual(typeof P.create, 'function');
130assert.ok(Array.isArray(P.publicMethods));
131for (const m of ['create','play','pause','toggle','seek','getCurrentTime','append','dispose']) {
132 assert.ok(P.publicMethods.includes(m), 'publicMethods missing ' + m);
133}
134assert.ok(P.nonPublicFields.includes('playing'));
135assert.ok(P.nonPublicFields.includes('pacedPos'));
136assert.ok(P.supportedCssVariables.includes('--beecast-color-accent'));
137
138// ---- VT core (existing coverage) -------------------------------------------------------
139let c = VT.parseCast('{"version":3,"term":{"cols":10,"rows":3}}\n# note\n[0.5,"o","hi"]\n[0.5,"m","chapter"]\n[1.0,"r","20x5"]\n');
140assert.strictEqual(c.cols, 10); assert.strictEqual(c.rows, 3);
141assert.strictEqual(c.events.length, 3);
142assert.strictEqual(c.duration, 2);
143
144c = VT.parseCast('{"version":2,"width":80,"height":24}\n[0.5,"o","a"]\n[2.0,"o","b"]\n');
145assert.strictEqual(c.duration, 2); assert.strictEqual(c.events[1].t, 2);
146
147c = VT.parseCast('{"version":1,"width":5,"height":2,"stdout":[[0.1,"x"],[0.2,"y"]]}');
148assert.strictEqual(c.cols, 5); assert.strictEqual(c.events.length, 2);
149
150c = VT.parseCast('{"version":3,"term":{"cols":10,"rows":3}}\n[1.0,"o","a"]\n');
151assert.strictEqual(VT.appendCast(c, '[0.5,"o",'), 0);
152assert.strictEqual(c.duration, 1);
153assert.strictEqual(VT.appendCast(c, '"b"]\n[0.5,"m","x"]\n'), 2);
154assert.strictEqual(c.duration, 2);
155assert.strictEqual(c.events.length, 3);
156assert.strictEqual(c.events[1].t, 1.5);
157
158c = VT.parseCast('{"version":2,"width":80,"height":24}\n[1.0,"o","a"]\n');
159VT.appendCast(c, '# noise\n{"version":2}\n[3.0,"o","b"]\n');
160assert.strictEqual(c.duration, 3); assert.strictEqual(c.events[1].t, 3);
161
162c = VT.parseCast('{"version":3,"term":{"cols":4,"rows":1}}\n[1.0,"o","hi"]\n[2.0,"o');
163assert.strictEqual(c.events.length, 1);
164VT.appendCast(c, '","yo"]\n');
165assert.strictEqual(c.events.length, 2); assert.strictEqual(c.duration, 3);
166
167c = VT.parseCast('{"version":1,"width":5,"height":2,"stdout":[[0.1,"x"]]}');
168assert.strictEqual(VT.appendCast(c, '[1.0,"o","y"]\n'), 0);
169
170const ev = [{t:1},{t:2}];
171const pacing = VT.buildPacing(ev, 2, null);
172ev.push({t:10});
173VT.extendPacing(pacing, ev, 2, 10);
174assert.strictEqual(pacing.pacedDuration, 10);
175assert.strictEqual(VT.mapTime(pacing.rec, pacing.paced, 10), 10);
176const limited = VT.buildPacing([{t:1}], 1, 2);
177VT.extendPacing(limited, [{t:1},{t:9}], 1, 9);
178assert.strictEqual(limited.pacedDuration, 3);
179assert.strictEqual(VT.mapTime(limited.paced, limited.rec, 3), 9);
180
181let t = new VT.Term(10, 3);
182t.write('hello\r\nworld');
183assert.deepStrictEqual(t.textLines(), ['hello', 'world', '']);
184t.write('\x1b[1;3Hga');
185assert.strictEqual(t.textLines()[0], 'hegao');
186t.write('\x1b[2J');
187assert.deepStrictEqual(t.textLines(), ['', '', '']);
188
189t = new VT.Term(10, 1);
190t.write('\x1b[31mred\x1b[0m ok');
191const runs = t.snapshot().rows[0];
192assert.strictEqual(runs[0].text, 'red'); assert.strictEqual(runs[0].fg, 1);
193t = new VT.Term(4, 1);
194t.write('\x1b[38;5;196mX\x1b[38;2;1;2;3mY');
195assert.strictEqual(t.snapshot().rows[0][0].fg, 196);
196assert.strictEqual(t.snapshot().rows[0][1].fg, '#010203');
197
198t = new VT.Term(3, 2);
199t.write('abc');
200assert.strictEqual(t.snapshot().cursor.y, 0);
201t.write('d');
202assert.deepStrictEqual(t.textLines(), ['abc', 'd']);
203
204t = new VT.Term(5, 4);
205t.write('aa\r\nbb\r\ncc\r\ndd');
206t.write('\x1b[2;3r\x1b[3;1H\n');
207assert.strictEqual(t.textLines()[0], 'aa');
208assert.strictEqual(t.textLines()[1], 'cc');
209assert.strictEqual(t.textLines()[3], 'dd');
210
211t = new VT.Term(5, 2);
212t.write('main');
213t.write('\x1b[?1049h\x1b[Halt');
214assert.strictEqual(t.textLines()[0], 'alt');
215t.write('\x1b[?1049l');
216assert.strictEqual(t.textLines()[0], 'main');
217
218t = new VT.Term(4, 1);
219t.write('\x1b(0qqx\x1b(B');
220assert.strictEqual(t.textLines()[0], '──│');
221t = new VT.Term(8, 1);
222t.write('\x1b]0;title\x07ok');
223assert.strictEqual(t.textLines()[0], 'ok');
224t.write('\x1b[?25l');
225assert.strictEqual(t.snapshot().cursor.visible, false);
226
227// ---- Phase 1: headless controller (no DOM) ---------------------------------------------
228function fakeClock() {
229 let now = 0;
230 const q = [];
231 return {
232 now: () => now,
233 requestAnimationFrame: (cb) => { q.push(cb); return q.length; },
234 cancelAnimationFrame: () => { q.length = 0; },
235 flush: (ms) => {
236 now += ms;
237 const batch = q.splice(0, q.length);
238 for (const cb of batch) cb(now);
239 },
240 };
241}
242
243const castText = '{"version":3,"term":{"cols":8,"rows":2}}\n[0,"o","hi"]\n[1.0,"o","!"]\n[1.0,"m","mid"]\n';
244const clock = fakeClock();
245const ctrl = C.create({
246 data: castText,
247 idleTimeLimit: 2,
248 speed: 1,
249 markers: [[0, 'start']],
250 clock: clock,
251});
252
253// Initial state
254let state = ctrl.getState();
255assert.strictEqual(state.status, 'idle');
256assert.strictEqual(state.currentTime, 0);
257assert.strictEqual(state.duration, 2);
258assert.strictEqual(state.speed, 1);
259assert.strictEqual(state.canAppend, true);
260assert.ok(state.markers.length >= 2); // sidecar + in-band
261assert.ok(state.markers.every(m => m.id && typeof m.time === 'number' && m.label != null));
262assert.ok(state.terminal.rows.length === 2);
263assert.strictEqual(state.dimensions.columns, 8);
264
265// Terminal snapshots are cached until output or resize dirties the terminal.
266let snapshotCalls = 0;
267const originalSnapshot = ctrl.term.snapshot;
268ctrl.term.snapshot = function () { snapshotCalls++; return originalSnapshot.call(this); };
269const cachedTerminal = ctrl.getState().terminal;
270assert.strictEqual(ctrl.getState().terminal, cachedTerminal);
271assert.strictEqual(snapshotCalls, 0, 'initial snapshot remains cached');
272ctrl.seek(1.5);
273const changedTerminal = ctrl.getState().terminal;
274assert.notStrictEqual(changedTerminal, cachedTerminal);
275assert.strictEqual(snapshotCalls, 1, 'events invalidate the cached snapshot once');
276assert.strictEqual(ctrl.getState().terminal, changedTerminal);
277assert.strictEqual(snapshotCalls, 1, 'unchanged state does not copy the terminal again');
278ctrl.seek(0);
279
280// subscribe delivers immediately and is removable
281const seen = [];
282const unsub = ctrl.subscribe((s, meta) => { seen.push(meta.type); });
283assert.ok(seen.includes('ready'));
284unsub();
285unsub(); // idempotent
286const n = seen.length;
287ctrl.setSpeed(2);
288// no more callbacks after unsubscribe
289assert.strictEqual(seen.length, n);
290
291// setSpeed does not rebuild terminal / changes state
292ctrl.setSpeed(1.5);
293assert.strictEqual(ctrl.getState().speed, 1.5);
294
295// play / pause / seek / getCurrentTime
296// First animation frame establishes lastTick (dt=0); the second advances the clock.
297ctrl.play();
298assert.strictEqual(ctrl.getState().status, 'playing');
299clock.flush(0);
300clock.flush(500); // 0.5s wall * 1.5 speed ≈ 0.75s paced
301assert.ok(ctrl.getCurrentTime() > 0);
302ctrl.pause();
303assert.strictEqual(ctrl.getState().status, 'paused');
304
305ctrl.seek(1.5);
306assert.ok(Math.abs(ctrl.getCurrentTime() - 1.5) < 1e-9);
307ctrl.seek(0);
308assert.ok(ctrl.getCurrentTime() < 1e-9);
309
310// toggle
311ctrl.toggle();
312assert.strictEqual(ctrl.getState().status, 'playing');
313ctrl.toggle();
314assert.strictEqual(ctrl.getState().status, 'paused');
315
316// replay after end
317ctrl.seek(2);
318ctrl.play();
319// playing from end rewinds
320assert.strictEqual(ctrl.getState().status, 'playing');
321assert.ok(ctrl.getCurrentTime() < 1e-6);
322
323// append live-follow at edge
324ctrl.pause();
325ctrl.seek(2);
326assert.ok(ctrl.getState().atLiveEdge);
327ctrl.append('[0.5,"o","more"]\n');
328assert.strictEqual(ctrl.getState().duration, 2.5);
329
330// Declared-live mode: parked mid-recording, setLive pins the playhead to the edge; an
331// append keeps it pinned (unconditionally — no positional check); a rewinding seek or
332// play() drops live; a seek TO the edge keeps it.
333ctrl.seek(1);
334ctrl.setLive(true);
335let live = ctrl.getState();
336assert.strictEqual(live.live, true);
337assert.ok(live.atLiveEdge, 'setLive parks at the edge');
338assert.ok(Math.abs(live.currentTime - live.duration) < 1e-9);
339ctrl.append('[0.5,"o","live"]\n');
340live = ctrl.getState();
341assert.strictEqual(live.live, true);
342assert.ok(Math.abs(live.currentTime - live.duration) < 1e-9, 'append keeps the pin');
343ctrl.seek(live.duration); // to the edge: still live
344assert.strictEqual(ctrl.getState().live, true);
345const liveEvents = [];
346const unsubLive = ctrl.subscribe((st, meta) => { liveEvents.push(meta.type); });
347ctrl.seek(0.5); // a rewind: live drops, with a livechange event
348assert.strictEqual(ctrl.getState().live, false);
349assert.ok(liveEvents.includes('livechange'));
350unsubLive();
351ctrl.setLive(true);
352ctrl.play(); // play from the parked edge is a rewind: live drops
353assert.strictEqual(ctrl.getState().live, false);
354ctrl.pause();
355
356// getState is a snapshot (mutating returned markers does not corrupt internal list)
357const s1 = ctrl.getState();
358s1.markers.push({ id: 'x', time: 99, type: 'chapter', label: 'x' });
359assert.ok(ctrl.getState().markers.every(m => m.id !== 'x'));
360
361// dispose makes commands no-ops
362ctrl.dispose();
363ctrl.play();
364ctrl.seek(1);
365ctrl.append('[1,"o","z"]\n');
366assert.strictEqual(ctrl.getState().status, 'idle');
367
368// Marker object form + tuple compatibility
369const c2 = C.create({
370 data: '{"version":3,"term":{"cols":4,"rows":1}}\n[0,"o","a"]\n',
371 markers: [{ time: 0, label: 'A', type: 'chapter' }, [1, 'B']],
372 clock: fakeClock(),
373});
374const marks = c2.getState().markers;
375assert.strictEqual(marks[0].label, 'A');
376assert.strictEqual(marks[1].label, 'B');
377c2.dispose();
378
379// Source type text
380const c3 = C.create({
381 source: { type: 'text', data: '{"version":3,"term":{"cols":4,"rows":1}}\n[0,"o","z"]\n' },
382 clock: fakeClock(),
383});
384assert.strictEqual(c3.getState().duration, 0);
385c3.dispose();
386
387// Discrete events survive playback: seek/speedchange/durationchange/markerchange emitted
388// WHILE PLAYING must each reach subscribers with their own meta type — timeupdate
389// coalescing must never swallow them.
390const clock4 = fakeClock();
391const c4 = C.create({ data: castText, idleTimeLimit: 2, clock: clock4 });
392const types = [];
393c4.subscribe(function (s, meta) { types.push(meta.type); });
394c4.play();
395clock4.flush(0);
396clock4.flush(200);
397assert.ok(types.includes('timeupdate'), 'timeupdate flows while playing');
398assert.strictEqual(c4.getState().status, 'playing');
399c4.seek(1.5, { origin: 'api' });
400assert.ok(types.includes('seek'), 'seek delivered while playing, saw: ' + types.join(','));
401c4.append('[5,"o","tail"]\n');
402assert.ok(types.includes('durationchange'), 'durationchange delivered while playing');
403c4.setSpeed(2);
404assert.ok(types.includes('speedchange'), 'speedchange delivered while playing');
405c4.setMarkers([[0.5, 'half']]);
406assert.ok(types.includes('markerchange'), 'markerchange delivered');
407assert.strictEqual(c4.getState().markers.filter(m => m.source === 'integration').length, 1);
408c4.dispose();
409
410// ---- marker jumps seek without autoplay ----------------------------------------------
411const clockM = fakeClock();
412const cM = C.create({
413 data: '{"version":3,"term":{"cols":4,"rows":1}}\n[0,"o","a"]\n[1.0,"o","b"]\n[2.0,"o","c"]\n',
414 markers: [[0, 'start'], [1, 'mid'], [2, 'end']],
415 clock: clockM,
416});
417cM.play();
418clockM.flush(0);
419cM.pause();
420assert.strictEqual(cM.getState().status, 'paused');
421cM.seek(0);
422cM.jumpMarker(1, 'keyboard');
423assert.ok(Math.abs(cM.getCurrentTime() - 1) < 1e-9, ' ] seeks to next marker');
424assert.strictEqual(cM.getState().status, 'paused', '[ ] must not autoplay');
425cM.play();
426assert.strictEqual(cM.getState().status, 'playing');
427cM.jumpMarker(1, 'keyboard');
428assert.ok(Math.abs(cM.getCurrentTime() - 2) < 1e-9);
429assert.strictEqual(cM.getState().status, 'playing', 'jump while playing stays playing');
430cM.pause();
431cM.jumpMarker(-1, 'keyboard');
432assert.ok(Math.abs(cM.getCurrentTime() - 1) < 1e-9);
433assert.strictEqual(cM.getState().status, 'paused', '[ while paused stays paused');
434cM.dispose();
435
436// ---- fit:'both' scale rule: content-sized mounts must not ratchet -----------------
437// Mirrors layout()'s definite-height gate (vertical fit only when the mount's height
438// does not track the screen box). The old `availH - 4` trigger shrank forever on
439// content-sized embeds.
440function fitScale(naturalH, availH, definite) {
441 let scale = 1;
442 if (definite && availH > 40 && naturalH * scale > availH) {
443 scale = Math.min(scale, availH / naturalH);
444 }
445 return scale;
446}
447let contentH = 400;
448const natural = 400, bar = 32;
449for (let i = 0; i < 30; i++) {
450 // Content-sized: mount height tracks the box — vertical fit must stay off.
451 const s = fitScale(natural, contentH - bar, false);
452 assert.strictEqual(s, 1, 'content-sized mount must not vertically scale');
453 contentH = natural * s + bar;
454}
455const short = fitScale(400, 200 - 32, true);
456assert.ok(short < 1 && short > 0, 'definite short mount scales down once');
457assert.strictEqual(fitScale(400, 200 - 32, true), short, 'definite scale is stable');
458// The banned ratchet: subtracting 4 from availH forces another shrink every pass.
459let ratchetH = 400;
460for (let i = 0; i < 5; i++) {
461 const avail = ratchetH - bar;
462 if (natural > avail - 4) ratchetH = natural * ((avail - 4) / natural) + bar;
463}
464assert.ok(ratchetH < 390, 'sanity: the old availH-4 rule really does ratchet');
465
466console.log('vt selftest OK');
467"#;
468 let spawned = std::process::Command::new("node")
469 .arg("-")
470 .arg(&bundle)
471 .stdin(std::process::Stdio::piped())
472 .stdout(std::process::Stdio::piped())
473 .stderr(std::process::Stdio::piped())
474 .spawn();
475 let Ok(mut child) = spawned else {
476 let _ = std::fs::remove_dir_all(&dir);
477 return; };
479 use std::io::Write;
480 child.stdin.take().unwrap().write_all(script.as_bytes()).unwrap();
481 let out = child.wait_with_output().unwrap();
482 let _ = std::fs::remove_dir_all(&dir);
483 assert!(
484 out.status.success() && String::from_utf8_lossy(&out.stdout).contains("vt selftest OK"),
485 "vt selftest failed:\nstdout: {}\nstderr: {}",
486 String::from_utf8_lossy(&out.stdout),
487 String::from_utf8_lossy(&out.stderr)
488 );
489 }
490}