'use strict'; const fs = require('fs'); const path = require('path'); const vm = require('vm'); // A small DOM/media fixture verifies lifecycle behavior without launching the app // or touching the gym's database. Actual Safari decoding still needs an iPad run. function eventTarget(target = {}) { const listeners = new Map(); target.addEventListener = (type, callback) => { if (!listeners.has(type)) listeners.set(type, []); listeners.get(type).push(callback); }; target.dispatch = (type, event = {}) => { for (const callback of listeners.get(type) || []) callback(event); }; return target; } function setup(search = '?id=1') { const videos = []; class Element { constructor(tagName) { eventTarget(this); this.tagName = tagName; this.children = []; this.attributes = {}; this.hidden = false; this.classList = { toggle: jest.fn() }; if (tagName === 'video') { videos.push(this); this.currentTime = 0; this.paused = true; this.play = jest.fn(() => { this.paused = false; return Promise.resolve(); }); this.pause = jest.fn(() => { this.paused = true; }); this.load = jest.fn(() => { this.currentTime = 0; this.error = null; }); } } append(...children) { for (const child of children) { this.children.push(child); child.parentNode = this; } } appendChild(child) { this.append(child); } remove() { if (!this.parentNode) return; const parent = this.parentNode; parent.children.splice(parent.children.indexOf(this), 1); this.parentNode = null; } replaceWith(replacement) { const parent = this.parentNode; parent.children[parent.children.indexOf(this)] = replacement; replacement.parentNode = parent; this.parentNode = null; } replaceChildren() { this.children.slice().forEach(child => child.remove()); } set innerHTML(value) { this.replaceChildren(); this.html = value; } setAttribute(key, value) { this.attributes[key] = value; } removeAttribute(key) { delete this.attributes[key]; if (key === 'src') this.src = ''; } } const grid = new Element('div'); const banner = new Element('div'); const document = eventTarget({ hidden: false, body: new Element('body'), createElement: tag => new Element(tag), getElementById: id => ({ 'display-video-grid': grid, 'display-offline-banner': banner })[id], }); const window = eventTarget({ location: { search, href: `https://vitfit.test/workout-display.html${search}` } }); const auth = { jwt: 'test-token', org: { id: 3 } }; const Api = { fetch: jest.fn() }; const context = vm.createContext({ document, window, URL, URLSearchParams, Date, AbortController, setInterval, clearInterval, setTimeout, clearTimeout, Auth: { getJwt: () => auth.jwt, getSelectedOrg: () => auth.org }, Branding: { apply: jest.fn() }, Api, fetch: jest.fn(() => Promise.resolve({ ok: false })), }); const source = fs.readFileSync(path.join(__dirname, '../../public/js/display.js'), 'utf8'); vm.runInContext(`${source}\nglobalThis.display = Display;`, context); const workout = { videos: [1, 2, 3, 4].map(id => ({ video: { streamUrl: `/api/v1/videos/stream/${id}.mp4` }, reps: 10 })) }; return { context, display: context.display, document, window, grid, videos, auth, workout, Api, banner }; } beforeEach(() => { jest.useFakeTimers(); jest.setSystemTime(100000); }); afterEach(() => { jest.clearAllTimers(); jest.useRealTimers(); }); test('12 simulated hours of polling and looping retain four players and one watchdog', () => { const { display, workout, videos, grid } = setup(); display.renderWorkout(workout); const originals = [...videos]; for (let tick = 1; tick <= 8640; tick++) { for (const video of videos) { video.currentTime = tick % 8; // include wraparound at each loop boundary video.dispatch('timeupdate'); } jest.advanceTimersByTime(5000); if (tick % 6 === 0) display.renderWorkout(workout); } expect(videos).toEqual(originals); expect(grid.children).toHaveLength(4); for (const video of videos) { expect(video.load).not.toHaveBeenCalled(); expect(video.play).toHaveBeenCalledTimes(1); } expect(jest.getTimerCount()).toBe(1); }); test('changing repetitions preserves every video and changing one source releases only that player', () => { const { display, workout, videos, grid } = setup(); display.renderWorkout(workout); workout.videos[0].reps = 20; display.renderWorkout(workout); expect(videos).toHaveLength(4); expect(grid.children[0].children.at(-1).textContent).toBe('20'); const old = videos[1]; workout.videos[1].video.streamUrl = '/api/v1/videos/stream/new.mp4'; display.renderWorkout(workout); expect(videos).toHaveLength(5); expect(old.pause).toHaveBeenCalledTimes(1); expect(old.load).toHaveBeenCalledTimes(1); expect(old.src).toBe(''); expect(videos[0].load).not.toHaveBeenCalled(); expect(grid.children).toHaveLength(4); }); test('a stalled player recovers while progressing players stay loaded, with bounded retries', () => { const { display, workout, videos } = setup(); display.renderWorkout(workout); for (let tick = 1; tick <= 60; tick++) { for (const video of videos.slice(1)) { video.currentTime = tick; video.dispatch('timeupdate'); } jest.advanceTimersByTime(5000); } // 20s, 40s, 80s, 160s: the next attempt waits until 320s. expect(videos[0].load).toHaveBeenCalledTimes(8); for (const video of videos.slice(1)) expect(video.load).not.toHaveBeenCalled(); expect(jest.getTimerCount()).toBe(1); }); test('Safari autoplay denial offers a tap and suppresses automatic reloads', async () => { const { display, workout, videos, grid } = setup(); display.renderWorkout(workout); const video = videos[0]; video.play.mockRejectedValueOnce(Object.assign(new Error('Gesture required'), { name: 'NotAllowedError' })); video.paused = true; jest.advanceTimersByTime(20000); await Promise.resolve(); const resume = grid.children[0].children[1]; expect(resume.hidden).toBe(false); jest.advanceTimersByTime(600000); expect(video.load).not.toHaveBeenCalled(); resume.dispatch('click'); expect(resume.hidden).toBe(true); expect(video.play).toHaveBeenCalledTimes(3); }); test('hidden pages pause playback and returning pages resume without reloading', () => { const { display, workout, videos, document } = setup(); display.renderWorkout(workout); document.hidden = true; document.dispatch('visibilitychange'); jest.advanceTimersByTime(600000); for (const video of videos) { expect(video.pause).toHaveBeenCalledTimes(1); expect(video.load).not.toHaveBeenCalled(); } document.hidden = false; document.dispatch('visibilitychange'); for (const video of videos) expect(video.play).toHaveBeenCalledTimes(2); }); test('empty workouts and navigation release resources; back navigation restores playback', () => { const { display, workout, videos, window, grid } = setup(); display.renderWorkout(workout); window.dispatch('pagehide'); expect(jest.getTimerCount()).toBe(0); for (const video of videos) expect(video.src).toBe(''); window.dispatch('pageshow', { persisted: true }); expect(grid.children).toHaveLength(4); expect(videos).toHaveLength(8); expect(jest.getTimerCount()).toBe(1); display.renderWorkout({ videos: [] }); expect(grid.children).toHaveLength(0); expect(grid.html).toContain('No exercises assigned'); expect(jest.getTimerCount()).toBe(0); }); test('stream URLs preserve query parameters, scope and refreshed authentication', () => { const { display, workout, videos, auth } = setup(); workout.videos[0].video.streamUrl += '?quality=small'; display.renderWorkout(workout); const url = new URL(videos[0].src); expect(url.searchParams.get('quality')).toBe('small'); expect(url.searchParams.get('orgId')).toBe('3'); expect(url.searchParams.get('token')).toBe('test-token'); expect(videos[0].disableRemotePlayback).toBe(true); expect(videos[0].attributes['x-webkit-airplay']).toBe('deny'); auth.jwt = 'refreshed-token'; display.renderWorkout(workout); expect(new URL(videos[4].src).searchParams.get('token')).toBe('refreshed-token'); expect(videos[0].src).toBe(''); }); test('polling keeps last data on errors, clears the banner on recovery and never overlaps', async () => { const fixture = setup(); const { context, document, Api, workout, banner, window } = fixture; const html = fs.readFileSync(path.join(__dirname, '../../public/workout-display.html'), 'utf8'); const script = html.match(/