'use strict' const { EventEmitter, getEventListeners } = require('events') const fs = require('fs/promises') const path = require('path') const os = require('os') const { getBrowserContext, runServer } = require('@browserless/test') const { default: test } = require('ava') const createFramesCapture = require('../src/frames') const { TIMEWEB, patchTimeweb } = require('../src/frames/timeweb') const { createFrameMuxer } = require('../src/recorder') const { writeHeader, writeClusterHeader } = require('../src/recorder/ebml') const { MODES } = require('..') const VIEWPORT = { width: 640, height: 400, deviceScaleFactor: 1 } const pendingTimeouts = () => process.getActiveResourcesInfo().filter(name => name === 'Timeout').length const rejectIfRunning = (work, ms) => { let watchdog const expired = new Promise((_resolve, reject) => { watchdog = setTimeout(() => reject(new Error('still running')), ms) }) return Promise.race([work, expired]).finally(() => clearTimeout(watchdog)) } const createGoto = (onCall, fallback = VIEWPORT) => { const goto = async (page, opts) => { await onCall?.(page, opts) return { device: { viewport: opts.viewport || fallback } } } goto.getDevice = ({ viewport } = {}) => ({ viewport: viewport || fallback }) return goto } const createPage = ({ hasTimeweb = true, timewebAt, onFrame, onDocumentCheck, childFrames = [], renders = () => true, removeFails = false, goToError = null } = {}) => { const events = [] const virtualTimes = [] const clockMoves = [] let screenshots = 0 let mark const mainFrame = { evaluate: async (fn, arg) => { if (typeof arg === 'string') { const previous = global.window global.window = {} try { await fn(arg) mark = global.window.__browserlessFrames return mark } finally { if (previous === undefined) delete global.window else global.window = previous } } if (arg && typeof arg === 'object' && !('ms' in arg)) { const previous = global.window global.window = { __browserlessFrames: mark } try { await onDocumentCheck?.(arg) return await fn(arg) } finally { if (previous === undefined) delete global.window else global.window = previous } } const ms = typeof arg === 'object' ? arg.ms : arg virtualTimes.push(ms) await onFrame?.(virtualTimes.length - 1) const previous = global.window const armed = timewebAt === undefined || virtualTimes.length >= timewebAt global.window = hasTimeweb && armed ? { __browserlessFrames: mark, timeweb: { goTo: ms => { clockMoves.push({ ms, isMarked: mark !== undefined }) return goToError ? Promise.reject(goToError) : Promise.resolve() } } } : { __browserlessFrames: mark } try { return await fn(arg) } finally { if (previous === undefined) delete global.window else global.window = previous } } } const client = { on: () => {}, off: () => {}, send: async (method, params) => { events.push([method, params]) const verdict = renders(screenshots) if (verdict && typeof verdict.then === 'function') return verdict if (!verdict) return new Promise(() => {}) return { data: Buffer.from(`frame-${screenshots++}`).toString('base64') } }, detach: async () => { events.push(['detach']) } } const page = { events, virtualTimes, clockMoves, setViewport: async viewport => events.push(['setViewport', viewport]), viewport: () => VIEWPORT, evaluateOnNewDocument: async source => { events.push(['inject', source.includes('timeweb')]) return { identifier: 'timeweb-script' } }, removeScriptToEvaluateOnNewDocument: async identifier => { events.push(['remove', identifier]) if (removeFails) throw new Error('remove failed') }, mainFrame: () => mainFrame, frames: () => [mainFrame, ...childFrames], _client: () => client, on: () => {}, off: () => {}, dropDocument: () => { mark = undefined } } return page } const createChildFrame = ({ fails = false, error } = {}) => { const virtualTimes = [] return { virtualTimes, get advances () { return virtualTimes.length }, evaluate: async (fn, arg) => { if (fails) throw error || new Error('Execution context was destroyed') virtualTimes.push(arg && typeof arg === 'object' ? arg.ms : arg) return true } } } const expectedStream = ({ frames, fps }) => Buffer.concat([ writeHeader(VIEWPORT.width, VIEWPORT.height), ...Array.from({ length: frames }, (_, frame) => { const payload = Buffer.from(`frame-${frame}`) return Buffer.concat([ writeClusterHeader(Math.round((frame * 1000) / fps), payload.length), payload ]) }) ]) const startsWithHeader = (buffer, width, height) => { const header = writeHeader(width, height) return buffer.subarray(0, header.length).equals(header) } test.before(async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'capture-frames-')) const ffmpegPath = path.join(dir, 'ffmpeg') const argsFile = path.join(dir, 'args') const stdinFile = path.join(dir, 'stdin') await fs.writeFile( ffmpegPath, `#!/bin/sh\nprintf '%s\\n' "$@" > '${argsFile}'\nexec tee '${stdinFile}'\n`, { mode: 0o755 } ) test.ffmpegPath = ffmpegPath test.argsFile = argsFile test.stdinFile = stdinFile }) test('a settled watchdog leaves no timer behind', async t => { const timers = pendingTimeouts() t.is(await rejectIfRunning(Promise.resolve('done'), 500), 'done') t.is(pendingTimeouts(), timers) }) test('frames is listed as a mode', t => { t.true(MODES.includes('frames')) }) test('steps virtual time one frame at a time and muxes every frame on its slot', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) const result = await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.deepEqual(page.virtualTimes, [0, 1000 / 30, 2000 / 30]) t.deepEqual(result, expectedStream({ frames: 3, fps: 30 })) }) test('injects timeweb before navigation and removes it after the capture', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto(page => page.events.push(['goto'])) }) await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) const names = page.events.map(([name]) => name) t.deepEqual(names.slice(0, 3), ['setViewport', 'inject', 'goto']) t.is(names.at(-1), 'remove') t.deepEqual(page.events[1], ['inject', true]) }) test('takes each frame as a fast jpeg at the given quality', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 20, fps: 50, quality: 70, ffmpegPath: test.ffmpegPath }) t.deepEqual( page.events.find(([name]) => name === 'Page.captureScreenshot'), ['Page.captureScreenshot', { format: 'jpeg', quality: 70, optimizeForSpeed: true }] ) }) test('a frame rate that does not divide a second keeps every frame on its own slot', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) const result = await capture(page)('https://example.com', { duration: 1000, fps: 49, ffmpegPath: test.ffmpegPath }) t.is(page.virtualTimes.length, 49) t.deepEqual(result, expectedStream({ frames: 49, fps: 49 })) }) test('frame count rounds `duration * fps`, with at least one frame', t => { const { frameCount } = createFramesCapture t.is(frameCount({ duration: 5000, fps: 30 }), 150) t.is(frameCount({ duration: 5000, fps: 60 }), 300) t.is(frameCount({ duration: 1, fps: 30 }), 1) }) test('rejects when the page has no timeweb, and still removes the script', async t => { const page = createPage({ hasTimeweb: false }) const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }), { message: /needs the page loaded by `goto`/ } ) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test('an aborted signal stops stepping and rejects with its reason', async t => { const controller = new AbortController() const reason = new Error('over budget') const page = createPage({ onFrame: frame => frame === 2 && controller.abort(reason) }) const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 1000, fps: 30, signal: controller.signal, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) t.is(page.virtualTimes.length, 3) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test('a navigation failure rejects before any frame', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto(() => { throw new Error('navigation failed') }) }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, ffmpegPath: test.ffmpegPath }), { message: 'navigation failed' } ) t.deepEqual(page.virtualTimes, []) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test('advances every frame of the page to the same virtual time', async t => { const child = createChildFrame() const page = createPage({ childFrames: [child] }) const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.deepEqual(child.virtualTimes, [0, 1000 / 30, 2000 / 30]) }) test('a child frame that goes away does not fail the capture', async t => { const page = createPage({ childFrames: [createChildFrame({ fails: true })] }) const capture = createFramesCapture({ goto: createGoto() }) const result = await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.deepEqual(result, expectedStream({ frames: 3, fps: 30 })) }) test('a frame that never renders rejects after `frameTimeout`', async t => { const page = createPage({ renders: () => false }) const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, frameTimeout: 50, ffmpegPath: test.ffmpegPath }), { message: 'Frame 0 did not render within 50ms.' } ) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) t.false(page.events.some(([name]) => name === 'detach')) }) test('rejects when `video` is disabled', async t => { const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync(() => capture(createPage())('https://example.com', { video: false }), { instanceOf: TypeError, message: /video.*cannot be disabled/ }) }) test('writes `path` and returns the same buffer', async t => { const output = path.join(os.tmpdir(), `capture-frames-${process.pid}.mkv`) const capture = createFramesCapture({ goto: createGoto() }) const result = await capture(createPage())('https://example.com', { duration: 40, fps: 50, path: output, ffmpegPath: test.ffmpegPath }) t.deepEqual(await fs.readFile(output), result) await fs.rm(output) }) test('`video: true` captures the same way as leaving video on', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) const result = await capture(page)('https://example.com', { video: true, duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.deepEqual(result, expectedStream({ frames: 3, fps: 30 })) }) test('an already aborted signal does not leave an encoder failure unhandled', async t => { const fail = path.join(path.dirname(test.ffmpegPath), 'fail-now') await fs.writeFile(fail, '#!/bin/sh\nexit 1\n', { mode: 0o755 }) const controller = new AbortController() const reason = new Error('over budget') controller.abort(reason) const unhandled = [] const onUnhandled = error => unhandled.push(error) process.on('unhandledRejection', onUnhandled) try { const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 100, fps: 30, signal: controller.signal, ffmpegPath: fail }) ) await new Promise(resolve => setImmediate(resolve)) t.is(error, reason) t.deepEqual(unhandled, []) } finally { process.off('unhandledRejection', onUnhandled) } }) test('an already aborted signal rejects before any frame', async t => { const controller = new AbortController() const reason = new Error('over budget') controller.abort(reason) const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 1000, fps: 30, signal: controller.signal, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) t.deepEqual(page.virtualTimes, []) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test('uses the default duration, frame rate, jpeg quality, and mp4 encoder', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) const timers = pendingTimeouts() await capture(page)('https://example.com', { ffmpegPath: test.ffmpegPath }) t.is(page.virtualTimes.length, 300) t.is(page.virtualTimes[1], 1000 / 60) t.deepEqual( page.events.find(([name]) => name === 'Page.captureScreenshot'), ['Page.captureScreenshot', { format: 'jpeg', quality: 90, optimizeForSpeed: true }] ) const args = await fs.readFile(test.argsFile, 'utf8') t.true(args.includes('libx264')) t.true(args.includes('out_color_matrix=bt709:out_range=pc')) t.true(pendingTimeouts() <= timers) }) test('a frame that never renders rejects after the default frame timeout', async t => { const page = createPage({ renders: () => false }) const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }), { message: 'Frame 0 did not render within 5000ms.' } ) }) test('a virtual-time seek that fails rejects the capture', async t => { const reason = new Error('seek failed') const page = createPage({ goToError: reason }) const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test('a main frame that goes away rejects and still removes the script', async t => { const page = createPage() const gone = { evaluate: async () => { throw new Error('Execution context was destroyed') } } page.mainFrame = () => gone const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, frameTimeout: 100, ffmpegPath: test.ffmpegPath }), { message: 'Frame 0 did not render within 100ms.' } ) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test("the page's own session is never detached", async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.false(page.events.some(([name]) => name === 'detach')) }) test('removing the injected script can fail without losing the video', async t => { const page = createPage({ removeFails: true }) const capture = createFramesCapture({ goto: createGoto() }) const result = await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.deepEqual(result, expectedStream({ frames: 2, fps: 50 })) }) test('a capture failure is not replaced when ffmpeg exits with an error', async t => { const fail = path.join(path.dirname(test.ffmpegPath), 'fail') await fs.writeFile(fail, '#!/bin/sh\ncat >/dev/null\nexit 1\n', { mode: 0o755 }) const page = createPage({ hasTimeweb: false }) const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: fail }), { message: /needs the page loaded by `goto`/ } ) }) test('a screenshot that fails after the frame timeout does not reject twice', async t => { const page = createPage({ renders: () => new Promise((_resolve, reject) => setTimeout(() => reject(new Error('late')), 80)) }) const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, frameTimeout: 20, ffmpegPath: test.ffmpegPath }), { message: 'Frame 0 did not render within 20ms.' } ) await new Promise(resolve => setTimeout(resolve, 120)) }) test('`timeout` kills ffmpeg when the encoder does not exit', async t => { const hang = path.join(path.dirname(test.ffmpegPath), 'hang') await fs.writeFile(hang, '#!/bin/sh\nsleep 30\n', { mode: 0o755 }) const page = createPage() const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 40, fps: 50, timeout: 50, ffmpegPath: hang }), { message: /did not finish within 50ms/ } ) }) test('sizes the video at device pixels', async t => { const capture = createFramesCapture({ goto: createGoto() }) const retina = await capture(createPage())('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath, viewport: { width: 640, height: 400, deviceScaleFactor: 2 } }) t.true(startsWithHeader(retina, 1280, 800)) const missing = await capture(createPage())('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath, viewport: { width: 640, height: 400 } }) t.true(startsWithHeader(missing, 640, 400)) const fractional = await capture(createPage())('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath, viewport: { width: 640, height: 400, deviceScaleFactor: 0.5 } }) t.true(startsWithHeader(fractional, 320, 200)) }) test('a document that is still navigating does not fail the clock pump', async t => { let attempts = 0 let navigated const navigation = new Promise(resolve => { navigated = resolve }) const page = createPage({ onFrame: () => { attempts += 1 if (attempts < 3) throw new Error('Execution context was destroyed') navigated() } }) const capture = createFramesCapture({ goto: createGoto(() => navigation) }) await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.true(attempts >= 3) }) test('the clock waits until timeweb is on the document', async t => { const page = createPage({ timewebAt: 2 }) const capture = createFramesCapture({ goto: createGoto(async () => { while (!page.released && page.virtualTimes.length < 2) { await new Promise(resolve => setImmediate(resolve)) } }) }) try { await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.deepEqual(page.virtualTimes.slice(0, 2), [0, 0]) } finally { page.released = true } }) test('a child error from the step still in flight does not fail the capture', async t => { let release const gate = new Promise(resolve => { release = resolve }) let failed = false const page = createPage({ childFrames: [ { evaluate: async () => { release() await new Promise(resolve => setImmediate(resolve)) if (!failed) { failed = true throw new Error('timer failed') } return true } } ] }) const capture = createFramesCapture({ goto: createGoto(() => gate) }) const stream = await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.true(failed) t.deepEqual(stream, expectedStream({ frames: 2, fps: 50 })) }) test('a finished clock step clears its timeout and abort listener', async t => { const controller = new AbortController() let release const gate = new Promise(resolve => { release = resolve }) const page = createPage({ childFrames: [ { evaluate: async () => { release() await new Promise(resolve => setImmediate(resolve)) return true } } ] }) const capture = createFramesCapture({ goto: createGoto(() => gate) }) const timers = pendingTimeouts() const listeners = getEventListeners(controller.signal, 'abort').length await capture(page)('https://example.com', { duration: 40, fps: 50, signal: controller.signal, ffmpegPath: test.ffmpegPath }) t.is(pendingTimeouts(), timers) t.is(getEventListeners(controller.signal, 'abort').length, listeners) }) test('an abort during the in-flight step rejects the capture', async t => { const controller = new AbortController() const reason = new Error('over budget') let release const gate = new Promise(resolve => { release = resolve }) const page = createPage({ childFrames: [ { evaluate: async () => { release() controller.abort(reason) await new Promise(() => {}) } } ] }) const capture = createFramesCapture({ goto: createGoto(() => gate) }) try { const error = await t.throwsAsync(() => rejectIfRunning( capture(page)('https://example.com', { duration: 40, fps: 50, signal: controller.signal, frameTimeout: 5000, ffmpegPath: test.ffmpegPath }), 500 ) ) t.is(error, reason) } finally { controller.abort() } }) test('a clock step that never finishes rejects after the frame timeout', async t => { const controller = new AbortController() let release const gate = new Promise(resolve => { release = resolve }) const page = createPage({ childFrames: [ { evaluate: async () => { release() await new Promise(() => {}) } } ] }) const capture = createFramesCapture({ goto: createGoto(() => gate) }) const started = Date.now() try { const error = await t.throwsAsync(() => rejectIfRunning( capture(page)('https://example.com', { duration: 40, fps: 50, frameTimeout: 200, signal: controller.signal, ffmpegPath: test.ffmpegPath }), 1000 ) ) t.true(Date.now() - started >= 150) t.is(error.message, 'The clock did not advance within 200ms.') } finally { controller.abort() } }) test('an abort while goto is waiting rejects the capture', async t => { const controller = new AbortController() const reason = new Error('over budget') let release const gate = new Promise(resolve => { release = resolve }) const page = createPage() const capture = createFramesCapture({ goto: createGoto(() => gate) }) try { const pending = capture(page)('https://example.com', { duration: 40, fps: 50, signal: controller.signal, ffmpegPath: test.ffmpegPath }) await new Promise(resolve => setImmediate(resolve)) controller.abort(reason) const error = await t.throwsAsync(() => rejectIfRunning(pending, 500)) t.is(error, reason) } finally { release() } }) test('a child timer error while goto is waiting does not fail the capture', async t => { let failures = 0 let release const gate = new Promise(resolve => { release = resolve }) const page = createPage({ childFrames: [ { evaluate: async () => { if (++failures === 3) release() throw new Error('timer failed') } } ] }) const capture = createFramesCapture({ goto: createGoto(() => gate) }) const stream = await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.true(failures >= 3) t.deepEqual(stream, expectedStream({ frames: 2, fps: 50 })) }) test('virtual time advances while goto is still waiting', async t => { const page = createPage() const capture = createFramesCapture({ goto: createGoto(async () => { while (!page.released && page.virtualTimes.length < 3) { await new Promise(resolve => setImmediate(resolve)) } }) }) try { await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.true(page.virtualTimes.length > 3) t.true(page.virtualTimes.at(-1) > page.virtualTimes[2]) } finally { page.released = true } }) test('a goto that settles between clock steps leaves no timer behind', async t => { let settle const navigation = new Promise(resolve => { settle = resolve }) const page = createPage({ onFrame: () => setImmediate(settle) }) const timers = pendingTimeouts() let timersAfterGoto page._client = (getClient => () => { timersAfterGoto = pendingTimeouts() return getClient() })(page._client) const capture = createFramesCapture({ goto: createGoto(() => navigation) }) await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) t.is(timersAfterGoto, timers) }) test('virtual time never runs ahead of real time while goto is waiting', async t => { const GOTO_MS = 300 let firstStepAt let gotoSettledAt const page = createPage({ onFrame: () => { firstStepAt ??= performance.now() } }) const capture = createFramesCapture({ goto: createGoto(async () => { await new Promise(resolve => setTimeout(resolve, GOTO_MS)) gotoSettledAt = performance.now() }) }) await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) const elapsed = gotoSettledAt - firstStepAt const clipStart = page.virtualTimes.at(-2) t.true(clipStart > 0) t.true(clipStart <= elapsed) t.true(page.virtualTimes.length < elapsed / 8) }) test('the clock starts when the document accepts its first step', async t => { const NAVIGATING_MS = 200 const startedAt = performance.now() const accepted = [] let navigated const navigation = new Promise(resolve => { navigated = resolve }) const page = createPage({ onFrame: index => { if (performance.now() - startedAt < NAVIGATING_MS) { throw new Error('Execution context was destroyed') } accepted.push({ virtual: page.virtualTimes[index], at: performance.now() }) if (accepted.length === 2) navigated() } }) const capture = createFramesCapture({ goto: createGoto(() => navigation) }) await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) const [first, second] = accepted t.is(first.virtual, 0) t.true(second.virtual > 0) t.true(second.virtual <= second.at - first.at) }) test('a slow clock step is not caught up by a longer one', async t => { const STEP_MS = 80 let settle const navigation = new Promise(resolve => { settle = resolve }) const page = createPage({ onFrame: async index => { if (index < 4) await new Promise(resolve => setTimeout(resolve, STEP_MS)) if (index === 4) settle() } }) const capture = createFramesCapture({ goto: createGoto(() => navigation) }) await capture(page)('https://example.com', { duration: 40, fps: 1, ffmpegPath: test.ffmpegPath }) const steps = page.virtualTimes.slice(0, 5) for (let index = 1; index < steps.length; index++) { const delta = steps[index] - steps[index - 1] t.true(delta > 0) t.true(delta <= 1000 / 30 + 1e-6) if (index > 1) t.true(Math.abs(delta - 1000 / 30) < 1e-6) } }) test('time spent navigating to another document does not count', async t => { const REDIRECT_MS = 250 const accepted = [] let redirectedAt let settle const navigation = new Promise(resolve => { settle = resolve }) const page = createPage({ onFrame: index => { if (index === 2) redirectedAt = performance.now() if (redirectedAt !== undefined && performance.now() - redirectedAt < REDIRECT_MS) { throw new Error('Execution context was destroyed') } accepted.push({ index, virtual: page.virtualTimes[index] }) if (redirectedAt !== undefined) settle() } }) const capture = createFramesCapture({ goto: createGoto(() => navigation) }) await capture(page)('https://example.com', { duration: 40, fps: 50, ffmpegPath: test.ffmpegPath }) const beforeRedirect = accepted.find(({ index }) => index === 1) const afterRedirect = accepted.find(({ index }) => index > 2) t.true(afterRedirect.virtual - beforeRedirect.virtual < 40) }) test('an abort during the only frame rejects before the frame is written', async t => { const controller = new AbortController() const reason = new Error('over budget') const page = createPage({ onFrame: () => controller.abort(reason) }) const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 1, fps: 30, signal: controller.signal, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) const written = await fs.readFile(test.stdinFile) t.is(written.length, writeHeader(VIEWPORT.width, VIEWPORT.height).length) }) test('an abort during the last write rejects', async t => { const controller = new AbortController() const reason = new Error('over budget') let checks = 0 const page = createPage({ onDocumentCheck: () => { checks += 1 if (checks === 1) controller.abort(reason) } }) const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 1, fps: 30, signal: controller.signal, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) }) test('a page that navigates mid-capture starts its next document at zero', async t => { const page = createPage({ onFrame: step => { if (step === 1) page.dropDocument() } }) const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.deepEqual(page.virtualTimes.map(Math.round), [0, 33, 0, 33]) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test('a screenshot that chrome drops when the page navigates is taken again', async t => { let onNavigated let dropped = false const page = createPage({ renders: screenshot => { if (screenshot !== 1 || dropped) return true dropped = true page.dropDocument() onNavigated({ frame: { id: 'main' } }) return new Promise(() => {}) } }) Object.assign(page._client(), { on: (event, listener) => { if (event === 'Page.frameNavigated') onNavigated = listener } }) const capture = createFramesCapture({ goto: createGoto() }) const stream = await capture(page)('https://example.com', { duration: 100, fps: 30, frameTimeout: 1000, ffmpegPath: test.ffmpegPath }) t.true(dropped) t.deepEqual(stream, expectedStream({ frames: 3, fps: 30 })) t.deepEqual(page.virtualTimes.map(Math.round), [0, 33, 0, 33]) }) test('a capture stops listening for navigations once it ends', async t => { const page = createPage() const listeners = new Set() Object.assign(page._client(), { on: (event, listener) => listeners.add(listener), off: (event, listener) => listeners.delete(listener) }) const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.is(listeners.size, 0) }) test('a document that arrives between frames never moves on the clock of the last one', async t => { let dropped = false const child = createChildFrame() const page = createPage({ childFrames: [child], onFrame: step => { if (step !== 1) return dropped = true page.dropDocument() } }) const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.true(dropped) t.true(page.clockMoves.every(({ isMarked }) => isMarked)) t.deepEqual( page.clockMoves.map(({ ms }) => Math.round(ms)), [0, 0, 33] ) t.is(child.advances, 3) }) test('waiting for the next document ends with the capture', async t => { let marks = 0 const page = createPage({ onFrame: () => page.dropDocument() }) const mainFrame = page.mainFrame() const { evaluate } = mainFrame mainFrame.evaluate = async (fn, arg) => { if (typeof arg === 'string' && marks++ > 0) { throw new Error('Execution context was destroyed') } return evaluate(fn, arg) } const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, frameTimeout: 100, ffmpegPath: test.ffmpegPath }), { message: 'Frame 0 did not render within 100ms.' } ) const attempts = marks await new Promise(resolve => setTimeout(resolve, 100)) t.true(attempts > 1) t.true(marks - attempts <= 1, String(marks - attempts)) }) test('a page can navigate ten times and still finish', async t => { let drops = 0 const page = createPage({ onFrame: () => { if (drops < 10) { drops += 1 page.dropDocument() } } }) const capture = createFramesCapture({ goto: createGoto() }) const stream = await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.is(drops, 10) t.true(stream.length > 0) }) test('a frame whose document goes away is taken again', async t => { let thrown = false const page = createPage({ onFrame: () => { if (thrown) return thrown = true page.dropDocument() throw new Error('Execution context was destroyed') } }) const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.true(thrown) t.deepEqual(page.virtualTimes.map(Math.round), [0, 0, 33, 67]) }) test('an abort while the next document is settling rejects and stops marking', async t => { const controller = new AbortController() const reason = new Error('over budget') let marks = 0 const page = createPage({ onFrame: () => page.dropDocument() }) const frame = page.mainFrame() const evaluate = frame.evaluate frame.evaluate = async (fn, arg) => { if (typeof arg === 'string') { marks += 1 if (marks === 1) return evaluate.call(frame, fn, arg) controller.abort(reason) throw new Error('Execution context was destroyed') } return evaluate.call(frame, fn, arg) } const capture = createFramesCapture({ goto: createGoto() }) const listeners = getEventListeners(controller.signal, 'abort').length const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 100, fps: 30, signal: controller.signal, frameTimeout: 5000, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) t.is(getEventListeners(controller.signal, 'abort').length, listeners) await new Promise(resolve => setTimeout(resolve, 50)) const marked = marks await new Promise(resolve => setTimeout(resolve, 200)) t.is(marks, marked) }) test('an abort during a document check that never returns rejects with its reason', async t => { const controller = new AbortController() const reason = new Error('over budget') let marks = 0 const page = createPage({ onFrame: () => page.dropDocument() }) const frame = page.mainFrame() const evaluate = frame.evaluate frame.evaluate = async (fn, arg) => { if (typeof arg === 'string') { marks += 1 if (marks === 1) return evaluate.call(frame, fn, arg) controller.abort(reason) return new Promise(() => {}) } return evaluate.call(frame, fn, arg) } const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 100, fps: 30, signal: controller.signal, frameTimeout: 5000, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) const marked = marks await new Promise(resolve => setTimeout(resolve, 50)) t.is(marks, marked) }) test('an abort that lands before a document check that never returns rejects with its reason', async t => { const controller = new AbortController() const reason = new Error('over budget') let marks = 0 const page = createPage({ onFrame: () => { page.dropDocument() controller.abort(reason) } }) const frame = page.mainFrame() const evaluate = frame.evaluate frame.evaluate = async (fn, arg) => { if (typeof arg === 'string') { marks += 1 if (marks === 1) return evaluate.call(frame, fn, arg) return new Promise(() => {}) } return evaluate.call(frame, fn, arg) } const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 100, fps: 30, signal: controller.signal, frameTimeout: 5000, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) const marked = marks await new Promise(resolve => setTimeout(resolve, 50)) t.is(marks, marked) }) test('an abort that lands while the page is navigating rejects and stops marking', async t => { const controller = new AbortController() const reason = new Error('over budget') let marks = 0 const page = createPage({ onFrame: () => { page.dropDocument() controller.abort(reason) } }) const frame = page.mainFrame() const evaluate = frame.evaluate frame.evaluate = async (fn, arg) => { if (typeof arg === 'string') { marks += 1 if (marks === 1) return evaluate.call(frame, fn, arg) throw new Error('Execution context was destroyed') } return evaluate.call(frame, fn, arg) } const capture = createFramesCapture({ goto: createGoto() }) const listeners = getEventListeners(controller.signal, 'abort').length const error = await t.throwsAsync(() => capture(page)('https://example.com', { duration: 100, fps: 30, signal: controller.signal, frameTimeout: 5000, ffmpegPath: test.ffmpegPath }) ) t.is(error, reason) t.is(getEventListeners(controller.signal, 'abort').length, listeners) const marked = marks await new Promise(resolve => setTimeout(resolve, 50)) t.is(marks, marked) }) test('a screenshot of a document that has already changed is taken again', async t => { let dropped = false const page = createPage({ renders: screenshot => { if (screenshot !== 0 || dropped) return true dropped = true page.dropDocument() return true } }) const capture = createFramesCapture({ goto: createGoto() }) await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.true(dropped) t.deepEqual(page.virtualTimes.map(Math.round), [0, 0, 33, 67]) }) test('a page replaced as the capture starts begins at zero', async t => { const page = createPage() const mainFrame = page.mainFrame() const { evaluate } = mainFrame let marks = 0 mainFrame.evaluate = async (fn, arg) => { if (typeof arg === 'string' && marks++ === 0) { throw new Error('Execution context was destroyed') } return evaluate(fn, arg) } const capture = createFramesCapture({ goto: createGoto(() => new Promise(resolve => setTimeout(resolve, 150))) }) await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.true(page.clockMoves.some(({ ms }) => ms > 0)) t.deepEqual( page.clockMoves.slice(-3).map(({ ms }) => Math.round(ms)), [0, 33, 67] ) }) test('a page that never stops navigating rejects', async t => { const page = createPage({ onFrame: () => page.dropDocument() }) const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }), { message: 'The page navigated away more than 10 times.' } ) t.is(page.virtualTimes.length, 11) t.deepEqual(page.events.at(-1), ['remove', 'timeweb-script']) }) test('a timeweb patch that no longer matches exactly once throws', t => { t.throws(() => patchTimeweb(''), { message: /`helpers` matches 0 times/ }) t.throws(() => patchTimeweb(TIMEWEB), { message: /matches [0-9]+ times instead of once/ }) }) test('a finished seek does not cancel the seek after it', t => { t.true(TIMEWEB.includes('if (pendingSeeked !== resolve) return;')) }) test('a child frame that is gone does not fail the capture', async t => { for (const message of [ 'Execution context was destroyed', 'Execution context is not available in detached frame or worker "https://example.com"', 'Frame was detached', "Attempted to use detached Frame 'abc'" ]) { const page = createPage({ childFrames: [createChildFrame({ fails: true, error: new Error(message) })] }) const capture = createFramesCapture({ goto: createGoto() }) const result = await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.deepEqual(result, expectedStream({ frames: 3, fps: 30 })) } }) test('an error in a child frame does not fail the capture', async t => { const page = createPage({ childFrames: [createChildFrame({ fails: true, error: new Error('timer failed') })] }) const capture = createFramesCapture({ goto: createGoto() }) const stream = await capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }) t.deepEqual(stream, expectedStream({ frames: 3, fps: 30 })) }) test('ffmpeg dying mid-capture rejects with the encoder error', async t => { const hang = path.join(path.dirname(test.ffmpegPath), 'hang-mid') await fs.writeFile(hang, '#!/bin/sh\nsleep 30\n', { mode: 0o755 }) const page = createPage({ renders: () => false }) const capture = createFramesCapture({ goto: createGoto() }) await t.throwsAsync( () => capture(page)('https://example.com', { duration: 100, fps: 30, timeout: 50, frameTimeout: 400, ffmpegPath: hang }), { message: /did not finish within 50ms/ } ) }) test('frame muxer `writeFrame` emits a frame on the slot it is given', t => { const stdin = new EventEmitter() const writes = [] stdin.write = chunk => writes.push(chunk) const muxer = createFrameMuxer({ stdin, fps: 49, durationMs: 1000 }) muxer.writeFrame(Buffer.from('a'), 0) muxer.writeFrame(Buffer.from('b'), 1) t.deepEqual(writes, [ writeClusterHeader(0, 1), Buffer.from('a'), writeClusterHeader(Math.round(1000 / 49), 1), Buffer.from('b') ]) }) const JPEG_START = Buffer.from([0xff, 0xd8, 0xff]) const jpegSizeAt = (buffer, start) => { let offset = start + 2 while (buffer[offset + 1] < 0xc0 || buffer[offset + 1] > 0xc3) { offset += 2 + buffer.readUInt16BE(offset + 2) } return [buffer.readUInt16BE(offset + 7), buffer.readUInt16BE(offset + 5)] } const jpegSizes = stream => { const sizes = [] let start = stream.indexOf(JPEG_START) while (start !== -1) { sizes.push(jpegSizeAt(stream, start)) start = stream.indexOf(JPEG_START, start + JPEG_START.length) } return sizes } for (const [viewport, size] of [ [{ width: 640, height: 400, deviceScaleFactor: 0.5 }, [320, 200]], [{ width: 640, height: 400, deviceScaleFactor: 0.75 }, [480, 300]], [{ width: 320, height: 240, deviceScaleFactor: 1 }, [320, 240]], [{ width: 320, height: 240, deviceScaleFactor: 1.5 }, [480, 360]], [{ width: 320, height: 240, deviceScaleFactor: 2 }, [640, 480]], [{ width: 320, height: 240, deviceScaleFactor: 3 }, [960, 720]], [{ width: 320, height: 240, deviceScaleFactor: 3, isMobile: true }, [960, 720]] ]) { const { width, height, deviceScaleFactor, isMobile } = viewport const name = `${width}x${height} at ${deviceScaleFactor}x${isMobile ? ' on mobile' : ''}` test(`chrome takes every frame of ${name} at the size of the video`, async t => { const browserless = await getBrowserContext(t) const url = await runServer(t, ({ res }) => { res.setHeader('content-type', 'text/html') res.end( '

frames

' ) }) const run = browserless.withPage((page, goto) => async () => { const stream = await createFramesCapture({ goto })(page)(url, { duration: 100, fps: 30, viewport, ffmpegPath: test.ffmpegPath }) return { stream, pageScale: await page.evaluate(() => window.devicePixelRatio) } }) const { stream, pageScale } = await run() t.deepEqual(jpegSizes(stream), [size, size, size]) t.true(startsWithHeader(stream, ...size)) t.is(pageScale, deviceScaleFactor) }) } const BOX = '
' const html = body => `${body}` const whenLoaded = (code, ms = 100) => ` const poll = setInterval(() => { if (!window.loaded) return clearInterval(poll) setTimeout(() => { ${code} }, ${ms}) }, 10) ` const captureInChrome = async (t, { routes, inspect = () => {}, duration = 500 }) => { const browserless = await getBrowserContext(t) const url = await runServer(t, ({ req, res }) => { const { pathname } = new URL(req.url, 'http://localhost') const route = routes[pathname] if (route === undefined) { res.statusCode = 404 return res.end() } if (typeof route === 'function') return route({ req, res }) res.setHeader('content-type', 'text/html') res.end(route) }) const run = browserless.withPage((page, goto) => async () => { const loadedGoto = Object.assign(async (...args) => { const result = await goto(...args) await page.evaluate(() => { window.loaded = true }) return result }, goto) const startedAt = Date.now() const stream = await createFramesCapture({ goto: loadedGoto })(page)(url, { duration, fps: 30, viewport: { width: 320, height: 240, deviceScaleFactor: 1 }, ffmpegPath: test.ffmpegPath }) const elapsed = Date.now() - startedAt return { frames: jpegSizes(stream).length, elapsed, state: await page.evaluate(inspect) } }) return run() } test('an error in a page timer is reported to the page and the timer keeps running', async t => { const { frames, state } = await captureInChrome(t, { routes: { '/': html(``) }, inspect: () => ({ errors: window.errors, ticks: window.ticks, stringTicks: window.stringTicks }) }) t.is(frames, 15) t.true(state.ticks >= 8, String(state.ticks)) t.true(state.stringTicks >= 8, String(state.stringTicks)) t.true(state.errors.some(message => message.includes('missing is not defined'))) t.true(state.errors.some(message => message.includes('timeout boom'))) }) test('an error in an animation frame does not stop the other callbacks', async t => { const { frames, state } = await captureInChrome(t, { routes: { '/': html(``) }, inspect: () => ({ errors: window.errors, drawn: window.drawn }) }) t.is(frames, 15) t.true(state.errors >= 10, String(state.errors)) t.true(state.drawn >= 10, String(state.drawn)) }) test('an animation driven by scroll stays with the scroll, and the others keep moving', async t => { const { frames, state } = await captureInChrome(t, { routes: { '/': html(`
a
${BOX}
b
`) }, inspect: () => ({ opacity: window.getComputedStyle(document.querySelector('#scroll')).opacity, left: parseFloat(window.getComputedStyle(document.querySelector('#box')).marginLeft) }) }) t.is(frames, 15) t.is(state.opacity, '0') t.true(state.left > 30, String(state.left)) }) test('an animation that becomes driven by scroll does not stop the capture', async t => { const { frames } = await captureInChrome(t, { routes: { '/': html(`
a
`) } }) t.is(frames, 15) }) for (const [name, video] of [ ['a missing source', ''], ['no source', ''], ['a source that never answers', ''] ]) { test(`a video with ${name} does not hold the clock`, async t => { const { frames, elapsed, state } = await captureInChrome(t, { routes: { '/': html(`${BOX}${video}`), '/hang': () => {} }, inspect: () => document.querySelector('video').currentTime }) t.is(frames, 15) t.is(state, 0) t.true(elapsed < 15000, String(elapsed)) }) } const silentWav = ({ seconds, sampleRate = 8000 }) => { const samples = Buffer.alloc(seconds * sampleRate, 128) const header = Buffer.alloc(44) header.write('RIFF', 0, 'latin1') header.writeUInt32LE(36 + samples.length, 4) header.write('WAVEfmt ', 8, 'latin1') header.writeUInt32LE(16, 16) header.writeUInt16LE(1, 20) header.writeUInt16LE(1, 22) header.writeUInt32LE(sampleRate, 24) header.writeUInt32LE(sampleRate, 28) header.writeUInt16LE(1, 32) header.writeUInt16LE(8, 34) header.write('data', 36, 'latin1') header.writeUInt32LE(samples.length, 40) return Buffer.concat([header, samples]) } test('a video that can play keeps the place the clock gives it', async t => { const source = `data:audio/wav;base64,${silentWav({ seconds: 5 }).toString('base64')}` const { frames, state } = await captureInChrome(t, { duration: 1000, routes: { '/': html(``) }, inspect: () => document.querySelector('video').currentTime }) t.is(frames, 30) t.true(state > 0.5, String(state)) }) test('a video whose seeks never finish holds the clock once', async t => { const source = `data:audio/wav;base64,${silentWav({ seconds: 5 }).toString('base64')}` const { frames, elapsed, state } = await captureInChrome(t, { routes: { '/': html(``) }, inspect: () => document.querySelector('video').readyState }) t.is(frames, 15) t.true(state > 0, String(state)) t.true(elapsed < 5000, String(elapsed)) }) test('an iframe that has not loaded does not hold the clock', async t => { const { frames, elapsed, state } = await captureInChrome(t, { routes: { '/': html(`
`), '/child': html('child') }, inspect: () => window.drawn }) t.is(frames, 15) t.true(state >= 14, String(state)) t.true(elapsed < 5000, String(elapsed)) }) for (const [name, next] of [ ['the same site', "'/next'"], [ 'another site', "location.href.replace(location.hostname, location.hostname === 'localhost' ? '127.0.0.1' : 'localhost') + 'next'" ] ]) { test(`a page that leaves for ${name} goes on with the next page`, async t => { const { frames, state } = await captureInChrome(t, { duration: 1000, routes: { '/': html(`

first

${BOX}`), '/next': html('

next

') }, inspect: () => ({ path: window.location.pathname, late: window.late, duringGoto: window.loaded === true }) }) t.is(frames, 30) t.deepEqual(state, { path: '/next', late: true, duringGoto: false }) }) } test('an iframe that navigates does not restart the clock of the page', async t => { const { frames, state } = await captureInChrome(t, { routes: { '/': html(``), '/child': html('child'), '/other': html('other') }, inspect: () => window.times }) t.is(frames, 15) t.true(state.every((time, i) => i === 0 || time >= state[i - 1])) }) test('a navigation inside the document does not restart its clock', async t => { const { frames, state } = await captureInChrome(t, { routes: { '/': html(``) }, inspect: () => ({ hash: window.location.hash, times: window.times }) }) t.is(frames, 15) t.is(state.hash, '#there') t.true(state.times.every((time, i) => i === 0 || time >= state.times[i - 1])) }) const WAV = `data:audio/wav;base64,${silentWav({ seconds: 5 }).toString('base64')}` test('`video.play()` answers a promise, as in a browser', async t => { const { frames, state } = await captureInChrome(t, { duration: 1000, routes: { '/': html(``) }, inspect: () => ({ finished: window.finished, results: window.results.sort(), time: document.querySelector('#good').currentTime }) }) t.is(frames, 30) t.true(state.finished) t.deepEqual(state.results, ['bad:NotSupportedError', 'good:ok']) t.true(state.time > 0.5, String(state.time)) }) test('pausing a video that has not started rejects its `play()`', async t => { const { state } = await captureInChrome(t, { routes: { '/': html(``) }, inspect: () => ({ reason: window.reason, playing: window.playing, ready: window.ready }) }) t.true(state.ready >= 3, String(state.ready)) t.is(state.reason, 'AbortError') t.is(state.playing, 0) }) test('a `play` listener that pauses rejects that `play()`', async t => { const { state } = await captureInChrome(t, { routes: { '/': html(``), '/hang': () => {} }, inspect: () => window.reason }) t.is(state, 'AbortError') }) test('a `pause` listener that plays again keeps the new `play()`', async t => { const { state } = await captureInChrome(t, { routes: { '/': html(``), '/hang': () => {} }, inspect: () => window.results }) t.deepEqual(state, ['first:AbortError']) }) const serveAudio = (audio, delay = 0) => ({ req, res }) => { const [, from = '0'] = (req.headers.range || '').match(/bytes=(\d+)-/) || [] const body = audio.subarray(Number(from)) setTimeout(() => { res.writeHead(req.headers.range ? 206 : 200, { 'content-type': 'audio/wav', 'accept-ranges': 'bytes', 'content-length': body.length, 'content-range': `bytes ${from}-${audio.length - 1}/${audio.length}` }) res.end(body) }, delay) } for (const preload of ['none', 'metadata']) { test(`\`play()\` loads a video that preloads ${preload}`, async t => { const audio = silentWav({ seconds: 600 }) const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``), '/audio.wav': serveAudio(audio) }, inspect: () => window.played }) t.true(state) }) } for (const [name, script] of [ ['right after its `src`', `video.src = '${WAV}'; video.pause()`], [ 'after adding a `source`', `const source = document.createElement('source'); source.src = '${WAV}'; video.append(source); video.load(); video.pause()` ], [ 'when its metadata loads', `video.addEventListener('loadedmetadata', () => video.pause()); video.src = '${WAV}'` ], [ 'after a new `src` while it plays', `video.src = '${WAV}'; ${whenLoaded(`video.src = '${WAV}#again'; video.pause()`)}` ] ]) { test(`an autoplay video paused ${name} stays paused`, async t => { const { state } = await captureInChrome(t, { duration: 1000, routes: { '/': html( `` ) }, inspect: () => { const video = document.querySelector('video') return { paused: video.paused, time: video.currentTime } } }) t.true(state.paused) t.true(state.time < 0.2, String(state.time)) }) } test('a video keeps the position set right after its new source', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``), '/slow.wav': serveAudio(silentWav({ seconds: 5 }), 300) }, inspect: () => document.querySelector('video').currentTime }) t.true(state >= 2, String(state)) }) test('playing a video that already plays sends no event and loses no time', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``) }, inspect: () => ({ ...window.events, early: window.early, time: document.querySelector('video').currentTime }) }) t.true(state.time > 1, String(state.time)) t.deepEqual({ ...state, time: 0 }, { play: 1, playing: 1, early: 0, time: 0 }) }) test('playing a video that ended starts it again', async t => { const short = `data:audio/wav;base64,${silentWav({ seconds: 1 }).toString('base64')}` const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``) }, inspect: () => { const { currentTime, ended } = document.querySelector('video') return { ends: window.ends, currentTime, ended } } }) t.true(state.ends >= 1) t.false(state.ended) t.true(state.currentTime < 1, String(state.currentTime)) }) for (const [name, script] of [ ['seeks and plays', 'video.currentTime = 2; video.play()'], ['seeks and plays later', 'video.currentTime = 2; setTimeout(() => video.play(), 100)'], [ 'sets a new source, seeks and plays', `video.src = '${WAV}#next'; video.currentTime = 2; video.play()` ] ]) { test(`a video that ${name} when it ends keeps that position`, async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``) }, inspect: () => ({ ended: window.ended, time: document.querySelector('video').currentTime }) }) t.true(state.ended) t.true(state.time > 2.2 && state.time < 4, String(state.time)) }) } test('a pause that beats the event of a native autoplay wins', async t => { const { state } = await captureInChrome(t, { duration: 1000, routes: { '/': html(``) }, inspect: () => { const { paused, currentTime } = document.querySelector('video') return { forced: window.forced, paused, currentTime } } }) t.true(state.forced) t.true(state.paused) t.true(state.currentTime < 0.2, String(state.currentTime)) }) test('`playing` comes before `play()` resolves', async t => { const { state } = await captureInChrome(t, { duration: 1000, routes: { '/': html(``) }, inspect: () => window.order }) t.deepEqual(state, ['playing', 'resolved']) }) test('a `playing` listener that pauses still resolves that `play()`', async t => { const { state } = await captureInChrome(t, { duration: 1000, routes: { '/': html(``) }, inspect: () => ({ reason: window.reason, paused: document.querySelector('video').paused }) }) t.is(state.reason, 'ok') t.true(state.paused) }) for (const [name, restart, expected] of [ ['reverses', 'animation.reverse()', 1], ['plays again', 'animation.play()', 0] ]) { test(`an animation that ${name} once it finished moves again`, async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(`${BOX}`) }, inspect: () => ({ finishes: window.finishes, moved: window.samples.some(value => value > 0.1 && value < 0.9), opacity: Number(window.getComputedStyle(document.querySelector('#box')).opacity) }) }) t.true(state.moved, JSON.stringify(state)) t.true(state.finishes <= 3, String(state.finishes)) t.true(Math.abs(state.opacity - expected) < 0.05, String(state.opacity)) }) } test('a video taken out of the page stops where it was', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``) }, inspect: () => ({ atRemoval: window.atRemoval, time: window.video.currentTime }) }) t.true(state.atRemoval > 0.2, JSON.stringify(state)) t.true(state.time - state.atRemoval < 0.3, JSON.stringify(state)) }) test('loading again rejects the `play()` that was waiting', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``), '/slow.wav': serveAudio(silentWav({ seconds: 5 }), 5000) }, inspect: () => window.reason }) t.is(state, 'AbortError') }) test('a new source rejects the `play()` that was waiting', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``), '/slow.wav': serveAudio(silentWav({ seconds: 5 }), 5000) }, inspect: () => window.reason }) t.is(state, 'AbortError') }) test('a `play()` after the new source is the one that runs', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``) }, inspect: () => ({ reason: window.reason, time: document.querySelector('video').currentTime }) }) t.is(state.reason, 'ok') t.true(state.time > 0.4, JSON.stringify(state)) }) test('a play announced before a new load does not resolve the next one', async t => { const { state } = await captureInChrome(t, { duration: 1000, routes: { '/': html(``), '/hang': () => {} }, inspect: () => ({ ready: window.ready, first: window.first, second: window.second || 'pending' }) }) t.true(state.ready >= 3, String(state.ready)) t.is(state.first, 'AbortError') t.is(state.second, 'pending') }) test('a play announced before load() does not play the next one early', async t => { const audio = silentWav({ seconds: 5 }) const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``), '/clip.wav': serveAudio(audio) }, inspect: () => ({ ready: window.ready, trace: window.trace }) }) t.true(state.ready >= 3, String(state.ready)) t.true(state.trace.some(item => item.startsWith('first-AbortError'))) t.false(state.trace.some(item => item.startsWith('playing'))) t.true(state.trace.some(item => Number(item.split(':')[1]) >= 3 && item.startsWith('second-ok'))) }) test('a play after a cancelled announcement still resolves once the new source can play', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``) }, inspect: () => ({ ready: window.ready, first: window.first, second: window.second || 'pending', time: document.querySelector('video').currentTime }) }) t.true(state.ready >= 3, String(state.ready)) t.is(state.first, 'AbortError') t.is(state.second, 'ok') t.true(state.time > 0.4, JSON.stringify(state)) }) test('a video moved in the page keeps playing', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(`
`) }, inspect: () => document.querySelector('video').currentTime - window.movedAt }) t.true(state > 0.5, String(state)) }) test('a caller that handles dialogs decides what to answer', async t => { const browserless = await getBrowserContext(t) const url = await runServer(t, ({ res }) => { res.setHeader('content-type', 'text/html') res.end(html(``)) }) const run = browserless.withPage((page, goto) => async () => { const loadedGoto = Object.assign(async (...args) => { const result = await goto(...args) page.on('dialog', async dialog => { await new Promise(resolve => setTimeout(resolve, 20)) await dialog.accept() }) await page.evaluate(() => { window.loaded = true }) return result }, goto) await createFramesCapture({ goto: loadedGoto })(page)(url, { duration: 500, fps: 30, viewport: { width: 320, height: 240, deviceScaleFactor: 1 }, ffmpegPath: test.ffmpegPath }) return page.evaluate(() => window.answer) }) t.true(await run()) }) test('an abort wins while the page does not answer and goto waits', async t => { const controller = new AbortController() const reason = new Error('over budget') const page = createPage() page.mainFrame().evaluate = () => { setImmediate(() => controller.abort(reason)) return new Promise(() => {}) } const capture = createFramesCapture({ goto: createGoto(() => new Promise(() => {})) }) const error = await t.throwsAsync(() => rejectIfRunning( capture(page)('https://example.com', { duration: 100, fps: 30, signal: controller.signal, ffmpegPath: test.ffmpegPath }), 1000 ) ) t.is(error, reason) }) test('a video that changes its source starts the new one at zero', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(``) }, inspect: () => ({ time: document.querySelector('video').currentTime * 1000, elapsed: performance.now() - window.changedAt }) }) t.true(state.time > 0 && state.time <= state.elapsed + 50, JSON.stringify(state)) }) test.serial('an abort leaves no frame timer behind', async t => { const frameTimeout = 54321 const timers = new Set() const { setTimeout: realSetTimeout, clearTimeout: realClearTimeout } = globalThis globalThis.setTimeout = (callback, ms, ...args) => { const timer = realSetTimeout(callback, ms, ...args) if (ms === frameTimeout) timers.add(timer) return timer } globalThis.clearTimeout = timer => { timers.delete(timer) return realClearTimeout(timer) } t.teardown(() => { Object.assign(globalThis, { setTimeout: realSetTimeout, clearTimeout: realClearTimeout }) for (const timer of timers) realClearTimeout(timer) }) const controller = new AbortController() const reason = new Error('over budget') const page = createPage({ renders: () => { setImmediate(() => controller.abort(reason)) return false } }) const capture = createFramesCapture({ goto: createGoto() }) const error = await t.throwsAsync(() => rejectIfRunning( capture(page)('https://example.com', { duration: 100, fps: 30, frameTimeout, signal: controller.signal, ffmpegPath: test.ffmpegPath }), 2000 ) ) t.is(error, reason) t.is(timers.size, 0) }) for (const [name, script] of [ ['`src` set later', `addEventListener('DOMContentLoaded', () => { video.src = '${WAV}' })`], [ 'a `source` added later', `const source = document.createElement('source'); source.src = '${WAV}'; video.append(source); video.load()` ], ['`src` set mid-capture', whenLoaded(`video.src = '${WAV}'`, 50)], [ '`src` changed while it plays', `video.src = '${WAV}'; ${whenLoaded(`video.src = '${WAV}#again'`, 50)}` ] ]) { test(`an autoplay video with ${name} plays`, async t => { const { frames, state } = await captureInChrome(t, { duration: 1500, routes: { '/': html( `` ) }, inspect: () => { const video = document.querySelector('video') return { time: video.currentTime, paused: video.paused } } }) t.is(frames, 45) t.false(state.paused) t.true(state.time > 0.5, String(state.time)) }) } test('an animation that becomes driven by scroll follows it, and back', async t => { const { frames, state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(`
a
b
`) }, inspect: () => ({ opacity: window.getComputedStyle(document.querySelector('#stays')).opacity, before: window.before, after: document.querySelector('#returns').getAnimations()[0]?.currentTime, nativeRate: document.querySelector('#returns').getAnimations()[0]?._timeweb_oldPlaybackRate }) }) t.is(frames, 45) t.is(state.opacity, '0') t.true(typeof state.before === 'number') t.true(state.after - state.before > 300, JSON.stringify(state)) t.is(state.nativeRate, 0) }) test('a scroll-driven animation keeps a playback rate of zero', async t => { const { state } = await captureInChrome(t, { duration: 1500, routes: { '/': html(`
a
`) }, inspect: () => ({ engaged: window.engaged, nativeRate: window.nativeRate, before: window.before, afterRate: window.afterRate, after: window.after }) }) t.is(state.engaged, 1) t.true(state.before > 10, JSON.stringify(state)) t.is(state.afterRate, state.before) t.is(state.nativeRate, 0) t.is(state.after, state.before) }) test('a playback rate outside scroll mode leaves the native rate alone', async t => { const { state } = await captureInChrome(t, { duration: 800, routes: { '/': html(`
a
`) }, inspect: () => window.nativeRate }) t.is(state, 0) }) test('delays, dates and unknown elements work as in a browser', async t => { const { state } = await captureInChrome(t, { routes: { '/': html(``) }, inspect: () => { const { ticks, text, isDate, finished } = window return { ticks, text, isDate, finished } } }) t.true(state.ticks >= 8, String(state.ticks)) t.deepEqual({ ...state, ticks: 0 }, { ticks: 0, text: 'string', isDate: true, finished: true }) }) for (const [name, code, answer] of [ ['alert', 'alert(1)', undefined], ['confirm', 'window.answer = confirm("sure?")', false], ['prompt', 'window.answer = prompt("name?")', null] ]) { test(`a page that calls ${name} goes on`, async t => { const { frames, elapsed, state } = await captureInChrome(t, { routes: { '/': html(``) }, inspect: () => ({ after: window.after, answer: window.answer }) }) t.is(frames, 15) t.true(state.after) t.is(state.answer, answer) t.true(elapsed < 5000, String(elapsed)) }) } test('an animation that refuses its time only stops itself', async t => { const { frames, state } = await captureInChrome(t, { routes: { '/': html(`${BOX}`) }, inspect: () => window.drawn }) t.is(frames, 15) t.true(state >= 14, String(state)) }) const captureStuckPage = async (t, routes) => { const browserless = await getBrowserContext(t) const url = await runServer(t, ({ req, res }) => { const route = routes[new URL(req.url, 'http://localhost').pathname] if (typeof route !== 'string') return route?.({ req, res }) res.setHeader('content-type', 'text/html') res.end(route) }) const startedAt = Date.now() const run = browserless.withPage((page, goto) => async () => { const loadedGoto = Object.assign(async (...args) => { const result = await goto(...args) await page.evaluate(() => { window.loaded = true }) return result }, goto) const stream = await createFramesCapture({ goto: loadedGoto })(page)(url, { duration: 1000, fps: 30, frameTimeout: 1000, viewport: { width: 320, height: 240, deviceScaleFactor: 1 }, ffmpegPath: test.ffmpegPath }) return { frames: jpegSizes(stream).length, elapsed: Date.now() - startedAt } }) return run() } const leave = `

first

` for (const [name, next] of [ ['never answers', () => {}], ['never finishes its styles', '

next

'] ]) { test(`a page that leaves for one that ${name} keeps its last frame`, async t => { const { frames, elapsed } = await captureStuckPage(t, { '/': html(leave), '/next': next, '/hang': () => {} }) t.is(frames, 30) t.true(elapsed < 12000, String(elapsed)) }) } test('a page that stops answering keeps its last frame, without waiting for each one', async t => { const page = createPage({ renders: screenshot => screenshot < 1 }) const capture = createFramesCapture({ goto: createGoto() }) const startedAt = Date.now() const stream = await capture(page)('https://example.com', { duration: 1000, fps: 30, frameTimeout: 200, ffmpegPath: test.ffmpegPath }) t.is(stream.toString('latin1').split('frame-0').length - 1, 30) t.true(Date.now() - startedAt < 2000) }) test('removing the injected script never holds the result', async t => { const page = createPage() page.removeScriptToEvaluateOnNewDocument = () => new Promise(() => {}) const capture = createFramesCapture({ goto: createGoto() }) const stream = await rejectIfRunning( capture(page)('https://example.com', { duration: 100, fps: 30, ffmpegPath: test.ffmpegPath }), 4000 ) t.deepEqual(stream, expectedStream({ frames: 3, fps: 30 })) })