From 2d7a76f1be8151426938ae9ae3da061ca5480a3a Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 8 Nov 2026 15:28:27 -0600 Subject: [PATCH 1/3] test(navigation) Ignore pending badge images why: External README badges can hold the load event after the Ruby legacy URL has reached its destination article. The shared assertion affects multiple port integrations. what: - Check the destination URL, parsed article heading and title - Hold badge responses in a regression without raising timeouts - Add the focused --guide-redirect browser mode Isolated samples with staged Ruby guides compared main 9a01505fc with the Perl integration ca13fe555: cold GET 7.13s versus 7.34s, final server RSS 2675 versus 2716 MiB, and warm redirects 0.30s versus 0.34s. This sample showed little integration growth; it did not establish the cause of the separate hosted ECONNRESET. On this main-based branch, held badge responses reproduce the old load timeout. Document readiness completes within the existing deadline. Appearance checks retain their image-completion contract. --- site/scripts/check-dev.mjs | 7 ++++++- site/scripts/check-navigation.mjs | 30 ++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/site/scripts/check-dev.mjs b/site/scripts/check-dev.mjs index e07ac0cf3..cd50eca6c 100644 --- a/site/scripts/check-dev.mjs +++ b/site/scripts/check-dev.mjs @@ -24,6 +24,7 @@ import { checkBlockLinksUndecorated, checkKindBadgeLinks, checkKindBadgeLinksFai import { checkTypeParameters } from './check-type-parameters.mjs' import { checkTmuxKeys, TMUX_KEY_PAGES } from './check-tmux-keys.mjs' import { checkSidebarDemo } from './check-sidebar-demo.mjs' +import { checkGuideRedirect } from './check-navigation.mjs' const apiNavigationOnly = process.argv.includes('--api-navigation') const apiAnchorsOnly = process.argv.includes('--api-anchors') @@ -53,6 +54,7 @@ assert(requestedBrowserPort === undefined || /^\d+$/.test(requestedBrowserPort) && Number(requestedBrowserPort) >= 1 && Number(requestedBrowserPort) <= 65535, 'LIBTMUX_DOCS_BROWSER_PORT must be an integer from 1 to 65535') const documentationNavigationOnly = process.argv.includes('--documentation-navigation') +const guideRedirectOnly = process.argv.includes('--guide-redirect') const workspacePortCount = PORTS.filter((port) => productAvailable(port, 'workspace')).length Object.assign(process.env, { @@ -785,6 +787,7 @@ try { // Compile the initial pages during setup; navigation assertions measure // the running app. The outer loop still budgets this initial compilation. const firstPage = homeLauncherOnly || homeControlsOnly ? '/' + : guideRedirectOnly ? '/ruby/latest/guides/overview/' : keywordHelpOnly ? '/kotlin/latest/reference/io-github-libtmux-kotlin-withserver/' : apiStickyOnly || permalinkRevealOnly ? '/swift/latest/reference/server/' : badgeCentringOnly ? '/py/v0.46.2/guides/attaching-to-tmux/' @@ -793,7 +796,7 @@ try { : apiNavigationOnly ? '/lua/latest/reference/libtmux-server/' : typeParametersOnly ? '/ts/latest/reference/selection-selection-where/' : '/tmux/concepts/server-session-window-pane/' const fullRun = ![homeLauncherOnly, homeControlsOnly, keywordHelpOnly, apiSignaturesOnly, referenceLayoutOnly, globalHeaderOnly, headerMenuSectionsOnly, statusBadgesOnly, badgeCentringOnly, referencePreviewsOnly, - referencePreferencesOnly, documentationNavigationOnly, apiNavigationOnly, apiAnchorsOnly, typeParametersOnly, permalinkRevealOnly, requiredAppearanceOnly].some(Boolean) + referencePreferencesOnly, documentationNavigationOnly, guideRedirectOnly, apiNavigationOnly, apiAnchorsOnly, typeParametersOnly, permalinkRevealOnly, requiredAppearanceOnly].some(Boolean) const setupPages = sampleOnly ? [firstPage, '/demo/widgets/pickers/', ...TMUX_KEY_PAGES] : [firstPage, ...(fullRun ? TMUX_KEY_PAGES : [])] const ready = Promise.all(setupPages.map(async (path) => { @@ -863,6 +866,8 @@ try { } else if (referencePreferencesOnly) { await retryReload(() => checkReferencePreferences(browser, base)) await retryReload(() => checkGlobalHeader(browser, base)) + } else if (guideRedirectOnly) { + await checkGuideRedirect(browser, base) } else if (documentationNavigationOnly) { await retryReload(() => checkDocumentationNavigation(browser, base, true)) } else if (apiNavigationOnly) { diff --git a/site/scripts/check-navigation.mjs b/site/scripts/check-navigation.mjs index be7df6b38..caccb9b52 100644 --- a/site/scripts/check-navigation.mjs +++ b/site/scripts/check-navigation.mjs @@ -7,6 +7,33 @@ import { checkPickerFilters } from './check-picker-filters.mjs' /** The version the dev build mounts a port's prose pages at: its default, as check-dev sets it. */ const defaultVersion = (port) => JSON.parse(process.env.LIBTMUX_DOCS_PORT_DEFAULTS || '{}')[port] ?? 'latest' +/** A legacy guide reaches its article while external README badges remain pending. */ +export async function checkGuideRedirect(browser, base) { + const page = await browser.newPage({ reducedMotion: 'reduce' }) + page.setDefaultTimeout(process.env.CI ? 20000 : 10000) + let release + let requested = 0 + const pending = new Promise((resolve) => { release = resolve }) + await page.route('https://img.shields.io/**', async (route) => { + requested += 1 + await pending + await route.fulfill({ contentType: 'image/svg+xml', body: '' }) + }) + try { + await page.goto(`${base}/ruby/latest/guides/overview/`, { waitUntil: 'domcontentloaded' }) + await page.waitForURL(`${base}/ruby/latest/guides/getting-started/`, { waitUntil: 'domcontentloaded' }) + assert.equal((await page.locator('main h1').textContent()).trim(), 'Getting started') + assert.equal(await page.title(), 'Getting started | libtmux-ruby') + assert(requested > 0, 'The real guide requested external badges') + assert.equal(await page.evaluate(() => document.readyState), 'interactive', 'The destination document is parsed before external badges complete') + console.log('Guide redirect: the legacy Ruby URL reaches its article with external badges still pending') + } finally { + release() + await page.unrouteAll({ behavior: 'wait' }) + await page.close() + } +} + /** Optional scripts injected at the end of the body cannot gate navigation. */ export async function checkNavigationBeforeAnalytics(browser, base) { const page = await browser.newPage({ viewport: { width: 390, height: 900 }, reducedMotion: 'reduce' }) @@ -297,8 +324,7 @@ export async function checkDocumentationNavigation(browser, base, complete = fal await page.waitForURL(`${base}/fsharp/latest/reference/?from=bookmark`) assert.equal((await page.locator('main h1').textContent()).trim(), 'API reference') assert.equal(await page.title(), 'F# API reference | libtmux-fsharp') - await page.goto(`${base}/ruby/latest/guides/overview/`, { waitUntil: 'load' }) - await page.waitForURL(`${base}/ruby/latest/guides/getting-started/`) + await checkGuideRedirect(browser, base) console.log(`Documentation surfaces: ${ports.length} ports retain real section links; Ruby/F# setup, cards and legacy links pass`) } finally { await page.close() From 547ee120c281f53364da63012f9f89f91a1d0286 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 8 Nov 2026 16:43:36 -0600 Subject: [PATCH 2/3] test(browser) Isolate checks from external requests why: Remote README badges can keep document load pending across browser checks. Context routing alone misses redirects and can be bypassed by later request decorators. what: - Create shared check contexts with an owned origin-restricted proxy - Fulfil foreign images locally and constrain existing decorators - Preserve load and visible-readiness assertions for legacy guides - Exercise redirects, popups, WebSockets and failed stream cleanup - Close owned contexts when policy registration fails --- site/scripts/.probe-core-tabs.mjs | 3 +- site/scripts/browser-context.mjs | 113 +++++++++++ site/scripts/check-badge-centring.mjs | 9 +- site/scripts/check-browser-network.mjs | 193 +++++++++++++++++++ site/scripts/check-clipboard.mjs | 5 +- site/scripts/check-color-scheme.mjs | 9 +- site/scripts/check-dev-sample.mjs | 5 +- site/scripts/check-dev.mjs | 19 +- site/scripts/check-fonts.mjs | 3 +- site/scripts/check-header-menu-sections.mjs | 3 +- site/scripts/check-home-example-options.mjs | 5 +- site/scripts/check-home-hover.mjs | 3 +- site/scripts/check-home-launcher.mjs | 9 +- site/scripts/check-home-task-reset.mjs | 17 +- site/scripts/check-language-icon-scheme.mjs | 5 +- site/scripts/check-mobile-nav.mjs | 3 +- site/scripts/check-native-layout.mjs | 8 +- site/scripts/check-native-navigation.mjs | 7 +- site/scripts/check-native-shell.mjs | 5 +- site/scripts/check-navigation.mjs | 54 +++--- site/scripts/check-page-readiness.mjs | 26 +-- site/scripts/check-picker-filters.mjs | 8 +- site/scripts/check-reference-preferences.mjs | 13 +- site/scripts/check-ruby-lua.mjs | 3 +- site/scripts/check-sidebar-demo.mjs | 3 +- site/scripts/check-status-badges.mjs | 5 +- site/scripts/check-style-parity.mjs | 3 +- site/scripts/check-tables.mjs | 3 +- site/scripts/check-tmux-keys.mjs | 3 +- site/scripts/check-type-parameters.mjs | 3 +- site/scripts/check-visual.mjs | 3 +- site/scripts/check-workspace-hover.mjs | 3 +- site/scripts/check-workspace-shift.mjs | 3 +- 33 files changed, 448 insertions(+), 109 deletions(-) create mode 100644 site/scripts/browser-context.mjs create mode 100644 site/scripts/check-browser-network.mjs diff --git a/site/scripts/.probe-core-tabs.mjs b/site/scripts/.probe-core-tabs.mjs index 2b2757999..f90783402 100644 --- a/site/scripts/.probe-core-tabs.mjs +++ b/site/scripts/.probe-core-tabs.mjs @@ -1,8 +1,9 @@ +import { newCheckPage } from './browser-context.mjs' import { chromium } from 'playwright' const url = process.argv[2] ?? 'http://127.0.0.1:53972/' const browser = await chromium.launch() -const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' }) +const page = await newCheckPage(browser, url, { viewport: { width: 1280, height: 900 }, colorScheme: 'dark' }) await page.addInitScript(() => { window.__shifts = [] window.__phase = 'load' diff --git a/site/scripts/browser-context.mjs b/site/scripts/browser-context.mjs new file mode 100644 index 000000000..bf555a8a8 --- /dev/null +++ b/site/scripts/browser-context.mjs @@ -0,0 +1,113 @@ +/** Own a forwarding proxy per check context; redirects and route.fetch share its origin boundary. */ +import { once } from 'node:events' +import { Agent, createServer, request as httpRequest } from 'node:http' +import { connect } from 'node:net' +import { pipeline } from 'node:stream' + +async function proxyFor(base) { + const own = new URL(base) + const allowed = own.origin + const agent = new Agent({ keepAlive: true, maxSockets: 32 }) + const sockets = new Set() + const track = (socket) => { + if (sockets.has(socket)) return socket + sockets.add(socket) + socket.once('close', () => sockets.delete(socket)) + return socket + } + const targetFor = (raw, tunnel = false) => { + const target = new URL(tunnel ? `${own.protocol}//${raw}` : raw) + const origin = target.origin.replace(/^ws:/, 'http:').replace(/^wss:/, 'https:') + return origin === allowed ? target : undefined + } + const server = createServer((incoming, outgoing) => { + let target + try { target = targetFor(incoming.url) } catch {} + if (!target || target.protocol !== 'http:') { incoming.socket.destroy(); return } + const headers = { ...incoming.headers, host: target.host } + delete headers['proxy-connection'] + delete headers['proxy-authorization'] + const upstream = httpRequest(target, { method: incoming.method, headers, agent }, (response) => { + outgoing.writeHead(response.statusCode, response.headers) + pipeline(response, outgoing, (error) => { if (error) upstream.destroy() }) + }) + upstream.on('socket', track) + upstream.on('error', () => outgoing.destroy()) + incoming.on('error', () => upstream.destroy()) + incoming.on('aborted', () => upstream.destroy()) + outgoing.on('close', () => { if (!outgoing.writableFinished) upstream.destroy() }) + incoming.pipe(upstream) + }) + server.on('connection', track) + server.on('connect', (request, client, head) => { + let target + try { target = targetFor(request.url, true) } catch {} + if (!target) { client.destroy(); return } + const upstream = track(connect(Number(target.port || (own.protocol === 'https:' ? 443 : 80)), target.hostname)) + upstream.once('connect', () => { + client.write('HTTP/1.1 200 Connection Established\r\n\r\n') + if (head.length) upstream.write(head) + client.pipe(upstream).pipe(client) + }) + client.on('error', () => upstream.destroy()) + upstream.on('error', () => client.destroy()) + client.on('close', () => upstream.destroy()) + upstream.on('close', () => client.destroy()) + }) + server.on('upgrade', (request, client, head) => { + let target + try { target = targetFor(request.url) } catch {} + if (!target || !['http:', 'ws:'].includes(target.protocol)) { client.destroy(); return } + const upstream = track(connect(Number(target.port || 80), target.hostname)) + upstream.once('connect', () => { + const headers = Object.entries(request.headers).filter(([key]) => key !== 'proxy-connection') + .map(([key, value]) => `${key}: ${value}`).join('\r\n') + upstream.write(`${request.method} ${target.pathname}${target.search} HTTP/${request.httpVersion}\r\n${headers}\r\n\r\n`) + if (head.length) upstream.write(head) + client.pipe(upstream).pipe(client) + }) + client.on('error', () => upstream.destroy()) + upstream.on('error', () => client.destroy()) + client.on('close', () => upstream.destroy()) + upstream.on('close', () => client.destroy()) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + return { + server: `http://127.0.0.1:${server.address().port}`, + close() { + server.close() + agent.destroy() + for (const socket of sockets) socket.destroy() + }, + } +} + +async function mockForeignImages(context, base) { + const origin = new URL(base).origin + await context.route((url) => url.origin !== origin, (route) => route.request().resourceType() === 'image' + ? route.fulfill({ contentType: 'image/svg+xml', body: '' }) + : route.abort()) +} + +export async function newCheckContext(browser, base, options = {}) { + const proxy = await proxyFor(base) + let context + try { + context = await browser.newContext({ ...options, serviceWorkers: 'block', proxy: { server: proxy.server, bypass: '<-loopback>' } }) + context.once('close', () => proxy.close()) + await mockForeignImages(context, base) + return context + } catch (error) { proxy.close(); await context?.close().catch(() => {}); throw error } +} + +export async function newCheckPage(browser, base, options = {}) { + const proxy = await proxyFor(base) + let page + try { + page = await browser.newPage({ ...options, serviceWorkers: 'block', proxy: { server: proxy.server, bypass: '<-loopback>' } }) + page.context().once('close', () => proxy.close()) + await mockForeignImages(page.context(), base) + return page + } catch (error) { proxy.close(); await page?.close().catch(() => {}); throw error } +} diff --git a/site/scripts/check-badge-centring.mjs b/site/scripts/check-badge-centring.mjs index c566cf8ec..f7b52191f 100644 --- a/site/scripts/check-badge-centring.mjs +++ b/site/scripts/check-badge-centring.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PNG } from 'pngjs' import { chromium } from 'playwright' @@ -590,7 +591,7 @@ export async function checkBadgeCentring(browser, base, { sample: bounded = fals const hi = await chromium.launch({ args: ['--force-device-scale-factor=2', '--window-size=1440,1000'] }) try { for (const [engine, factor] of [[browser, 1], [hi, 2]]) { - const context = await engine.newContext(factor === 1 ? { viewport: { width: 1440, height: 1000 }, reducedMotion: 'reduce' } : { viewport: null, reducedMotion: 'reduce' }) + const context = await newCheckContext(engine, base, factor === 1 ? { viewport: { width: 1440, height: 1000 }, reducedMotion: 'reduce' } : { viewport: null, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) // The first request for a reference page compiles it in the dev server, and the index and tool pages are large. @@ -616,7 +617,7 @@ export async function checkBadgeCentring(browser, base, { sample: bounded = fals * carries the mark and a later one is a plain link that keeps its kind. */ export async function checkMentionDensity(browser, base) { - const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }) + const context = await newCheckContext(browser, base, { viewport: { width: 1440, height: 1000 } }) const page = await context.newPage() page.setDefaultNavigationTimeout(60000) try { @@ -666,7 +667,7 @@ const CHIP_PAGES = ['server', 'session', 'window', 'pane', 'client'].map((name) */ export async function checkChipGrowth(browser, base) { // The contents column, and the Related APIs in it, show from 85rem. - const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultNavigationTimeout(60000) const open = async (path) => { @@ -712,7 +713,7 @@ const USAGE = { list: '.tmux-usage', where: 'usage table', ink: true } * a chip squeezed by its qualifier and one chip moved onto another. */ export async function checkUsageChips(browser, base) { - const context = await browser.newContext({ viewport: { width: 1134, height: 900 } }) + const context = await newCheckContext(browser, base, { viewport: { width: 1134, height: 900 } }) const page = await context.newPage() page.setDefaultNavigationTimeout(60000) const ready = () => page.waitForFunction(() => document.documentElement.dataset.pageReadiness === 'ready', null, { timeout: 30000 }).catch(() => {}) diff --git a/site/scripts/check-browser-network.mjs b/site/scripts/check-browser-network.mjs new file mode 100644 index 000000000..f89b4d85c --- /dev/null +++ b/site/scripts/check-browser-network.mjs @@ -0,0 +1,193 @@ +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' +import { once } from 'node:events' +import { createServer } from 'node:http' +import { pathToFileURL } from 'node:url' +import { chromium } from 'playwright' +import { newCheckContext, newCheckPage } from './browser-context.mjs' + +/** A held image on another origin must never reach its server or delay load. */ +export async function checkBrowserNetwork(browser) { + let result = Promise.withResolvers() + let escaped = 0 + const foreign = createServer(() => { + // Deliberately leave this image response pending until fixture teardown. + }) + foreign.on('connection', () => { + escaped += 1 + result.resolve('escaped') + }) + foreign.listen(0, '127.0.0.1') + await once(foreign, 'listening') + const remote = `http://127.0.0.1:${foreign.address().port}` + let truncated + let pendingClosed = Promise.withResolvers() + const local = createServer((request, response) => { + if (['/truncated', '/pending'].includes(request.url)) { + response.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Length': '65536', 'X-Content-Type-Options': 'nosniff' }) + response.write('x'.repeat(16384)) + if (request.url === '/truncated') truncated = response + else response.once('close', () => { pendingClosed.resolve(); local.emit('pending-closed') }) + } else if (request.url === '/release-truncated') { + response.end('released') + truncated.destroy() + } else if (request.url === '/pending-state') { + void pendingClosed.promise.then(() => { if (!response.destroyed) response.end('closed') }) + } else if (request.url === '/local.js') { + response.writeHead(200, { 'Content-Type': 'application/javascript' }) + response.end('window.localScript = true') + } else if (request.url === '/local.css') { + response.writeHead(200, { 'Content-Type': 'text/css' }) + response.end('h1 { color: rgb(1, 2, 3) }') + } else if (request.url === '/redirected.svg') { + response.writeHead(302, { Location: `${remote}/held.svg` }) + response.end() + } else { + response.writeHead(200, { 'Content-Type': 'text/html' }) + const image = request.url === '/redirect-case' ? '/redirected.svg' : `${remote}/held.svg` + response.end(`Local fixture

Local fixture

`) + } + }) + const localSockets = new Set() + local.on('connection', (socket) => { + localSockets.add(socket) + socket.once('close', () => localSockets.delete(socket)) + socket.on('error', () => socket.destroy()) + }) + local.on('upgrade', (request, socket) => { + const accept = createHash('sha1').update(request.headers['sec-websocket-key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64') + socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`) + socket.once('data', () => socket.end()) + }) + try { + local.listen(0, '127.0.0.1') + await once(local, 'listening') + const base = `http://127.0.0.1:${local.address().port}` + for (const factory of ['page', 'context', 'redirect', 'continued']) { + const page = factory === 'page' + ? await newCheckPage(browser, base, { viewport: { width: 640, height: 480 } }) + : await (await newCheckContext(browser, base, { viewport: { width: 640, height: 480 } })).newPage() + const context = page.context() + context.setDefaultNavigationTimeout(5000) + context.on('requestfailed', (request) => { + if (new URL(request.url()).origin === remote) result.resolve('blocked') + }) + context.on('response', (response) => { + if (new URL(response.url()).origin === remote) result.resolve('blocked') + }) + try { + if (factory === 'continued') await page.route('**/*', (route) => route.continue()) + result = Promise.withResolvers() + let loaded = false + const navigation = page.goto(base + (factory === 'redirect' ? '/redirect-case' : '/'), { waitUntil: 'load' }).then(() => { loaded = true }, (error) => { result.reject(error) }) + const outcome = await result.promise + if (outcome === 'escaped') assert.equal(loaded, false, 'The held image delays document load') + assert.equal(outcome, 'blocked', `${factory}: held image reached the foreign server`) + await navigation + assert.equal(await page.title(), 'Local fixture') + assert.deepEqual(await page.evaluate(() => [window.localScript, getComputedStyle(document.querySelector('h1')).color]), [true, 'rgb(1, 2, 3)']) + assert.equal(page.viewportSize().width, 640, 'Browser options survive the request policy') + if (['page', 'context'].includes(factory)) { + assert.equal(await page.evaluate(async () => { + await Promise.all(Array.from(document.images, (image) => image.decode())) + return document.images[0].naturalWidth + }), 1, 'Off-origin image fixtures decode without contacting their server') + } + if (factory === 'context') { + assert.equal(await page.evaluate((url) => new Promise((resolve, reject) => { + const socket = new WebSocket(url) + socket.onopen = () => { socket.close(); resolve('open') } + socket.onerror = () => reject(new Error('The owned server WebSocket did not open')) + }), base.replace('http:', 'ws:') + '/socket'), 'open') + result = Promise.withResolvers() + const incoming = page.waitForEvent('popup') + await page.evaluate(() => window.open('/popup')) + const popup = await incoming + assert.equal(await result.promise, 'blocked', 'Popup requests inherit the context policy') + await popup.waitForLoadState('load') + assert.equal(await popup.title(), 'Local fixture') + assert.equal(await popup.evaluate(async () => { await document.images[0].decode(); return document.images[0].naturalWidth }), 1) + await popup.close() + result = Promise.withResolvers() + const fetched = context.request.get(`${remote}/api`, { timeout: 1000 }) + .then(() => 'responded', () => 'blocked') + assert.equal(await Promise.race([result.promise, fetched]), 'blocked', 'Context request/fetch cannot escape through a decorator') + } + assert.equal(escaped, 0, 'No off-origin request reached the held-image server') + } finally { + if (factory === 'page') await page.close() + else await context.close() + } + } + const page = await newCheckPage(browser, base) + try { + await page.goto(base) + const truncation = await page.evaluate(async () => { + const controller = new AbortController() + const limit = setTimeout(() => controller.abort(), 1000) + try { + const response = await fetch('/truncated', { signal: controller.signal }) + const reader = response.body.getReader() + await reader.read() + await fetch('/release-truncated') + try { + let chunk = await reader.read() + while (!chunk.done) chunk = await reader.read() + return { failed: false } + } + catch { return { failed: true, deadline: controller.signal.aborted } } + } finally { clearTimeout(limit) } + }) + assert.deepEqual(truncation, { failed: true, deadline: false }, 'Truncated upstream fails before the fixture deadline') + pendingClosed = Promise.withResolvers() + assert.equal(await page.evaluate(async () => { + const controller = new AbortController() + const response = await fetch('/pending', { signal: controller.signal }) + await response.body.getReader().read() + controller.abort() + return (await fetch('/pending-state', { signal: AbortSignal.timeout(1000) })).text() + }), 'closed', 'Cancelling a client closes its owned upstream request') + } finally { await page.close() } + const context = await newCheckContext(browser, base) + try { + const page = await context.newPage() + await page.goto(base) + await page.evaluate(async () => { await (await fetch('/pending')).body.getReader().read() }) + await Promise.all([once(local, 'pending-closed', { signal: AbortSignal.timeout(1000) }), context.close()]) + } finally { await context.close() } + const before = browser.contexts().length + const failure = new Error('Image policy registration failed') + const broken = { + async newContext(options) { + const context = await browser.newContext(options) + context.route = async () => { throw failure } + return context + }, + async newPage(options) { + const page = await browser.newPage(options) + page.context().route = async () => { throw failure } + return page + }, + } + await assert.rejects(newCheckContext(broken, base), (error) => error === failure) + assert.equal(browser.contexts().length, before, 'Failed context policy registration closes its context') + await assert.rejects(newCheckPage(broken, base), (error) => error === failure) + assert.equal(browser.contexts().length, before, 'Failed page policy registration closes its context') + const driver = browser.browserType() + const closed = await driver.launch(driver.name() === 'chromium' ? { channel: process.env.LIBTMUX_DOCS_BROWSER_CHANNEL } : {}) + await closed.close() + await assert.rejects(newCheckContext(closed, base)) + await assert.rejects(newCheckPage(closed, base)) + console.log('Browser network: local assets load; off-origin images, redirects, decorators and popup requests cannot escape') + } finally { + local.closeAllConnections() + foreign.closeAllConnections() + for (const socket of localSockets) socket.destroy() + await Promise.all([new Promise((resolve) => local.close(resolve)), new Promise((resolve) => foreign.close(resolve))]) + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const browser = await chromium.launch() + try { await checkBrowserNetwork(browser) } finally { await browser.close() } +} diff --git a/site/scripts/check-clipboard.mjs b/site/scripts/check-clipboard.mjs index caecd5fbf..da8a2cec6 100644 --- a/site/scripts/check-clipboard.mjs +++ b/site/scripts/check-clipboard.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' @@ -36,7 +37,7 @@ export function assertCompleteApiExample(rendered, example) { /** Inspect rendered API examples against their native execution receipts. */ export async function checkCompleteApiExamples(browser, base) { const examples = JSON.parse(readFileSync(new URL('../test/fixtures/api-examples.json', import.meta.url), 'utf8')).examples - const page = await browser.newPage() + const page = await newCheckPage(browser, base) try { for (const example of examples) { const path = example.page.replace(`ports/${example.port}/`, `${example.port}/latest/`) @@ -217,7 +218,7 @@ export async function checkClipboard(page, base) { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const browser = await chromium.launch() try { - const page = await browser.newPage() + const page = await newCheckPage(browser, base) page.setDefaultTimeout(1000) await checkClipboard(page, (process.argv[2] ?? 'http://localhost:8080/en').replace(/\/$/, '')) } finally { diff --git a/site/scripts/check-color-scheme.mjs b/site/scripts/check-color-scheme.mjs index 78288b657..9a700fa22 100644 --- a/site/scripts/check-color-scheme.mjs +++ b/site/scripts/check-color-scheme.mjs @@ -1,12 +1,13 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Compact cycling and wide radios share the same saved preference. */ export async function checkColorScheme(browser, base) { for (const blocked of [false, true]) { - const context = await browser.newContext({ viewport: { width: 596, height: 777 }, colorScheme: 'light', reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 596, height: 777 }, colorScheme: 'light', reducedMotion: 'reduce' }) try { if (blocked) { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) await context.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) @@ -58,7 +59,7 @@ export async function checkColorScheme(browser, base) { await context.close() } } - const reader = await browser.newContext({ viewport: { width: 1062, height: 789 }, colorScheme: 'light', reducedMotion: 'reduce' }) + const reader = await newCheckContext(browser, base, { viewport: { width: 1062, height: 789 }, colorScheme: 'light', reducedMotion: 'reduce' }) try { const page = await reader.newPage() await page.goto(`${base}/code-tabs-probe/`) @@ -99,7 +100,7 @@ export async function checkColorScheme(browser, base) { } finally { await reader.close() } - const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 596, height: 777 } }) + const context = await newCheckContext(browser, base, { javaScriptEnabled: false, viewport: { width: 596, height: 777 } }) try { const page = await context.newPage() await page.goto(`${base}/`) diff --git a/site/scripts/check-dev-sample.mjs b/site/scripts/check-dev-sample.mjs index f46b57c78..561c2733e 100644 --- a/site/scripts/check-dev-sample.mjs +++ b/site/scripts/check-dev-sample.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { checkHomeResponsiveLayout } from './check-home-launcher.mjs' import { checkPickerFilters } from './check-picker-filters.mjs' @@ -96,7 +97,7 @@ function revealedContrast(id) { export async function checkRowPermalinks(browser, base, pages = ROW_PERMALINK_PAGES) { let rows = 0 for (const colorScheme of ['light', 'dark']) { - const context = await browser.newContext({ colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -174,7 +175,7 @@ export async function checkDevSample(browser, base) { await checkKindBadgeLinks(browser, base, { sample: true }) await checkBlockLinksUndecorated(browser, base, { sample: true }) await checkTmuxKeys(browser, base) - const context = await browser.newContext({ reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) diff --git a/site/scripts/check-dev.mjs b/site/scripts/check-dev.mjs index cd50eca6c..4b5dbea2d 100644 --- a/site/scripts/check-dev.mjs +++ b/site/scripts/check-dev.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckContext, newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { join } from 'node:path' @@ -309,7 +310,7 @@ async function retryReload(check, page) { } async function checkSignatureLayouts(browser, base) { - const page = await browser.newPage({ javaScriptEnabled: false }) + const page = await newCheckPage(browser, base, { javaScriptEnabled: false }) try { await page.goto(`${base}/api-signature-probe/`, { waitUntil: 'load' }) const entries = page.locator('[data-signature-port]') @@ -450,7 +451,7 @@ async function checkSignatureLayouts(browser, base) { async function checkKeywordHelp(browser, base) { const fullMatrix = apiSignaturesOnly || keywordHelpOnly for (const javaScriptEnabled of [false, true]) { - const page = await browser.newPage({ javaScriptEnabled }) + const page = await newCheckPage(browser, base, { javaScriptEnabled }) const errors = [] page.on('pageerror', (error) => errors.push(error.message)) page.setDefaultTimeout(5000) @@ -542,7 +543,7 @@ async function checkMemberBodies(browser, base) { } async function checkReferenceAndHeroes(browser, base) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { await page.goto(`${base}/api-body-probe/`) @@ -871,7 +872,7 @@ try { } else if (documentationNavigationOnly) { await retryReload(() => checkDocumentationNavigation(browser, base, true)) } else if (apiNavigationOnly) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) await retryReload(() => checkApiNavigation(page, base)) await checkApiNavigationFail(browser, base) @@ -917,15 +918,15 @@ try { // Cold API indexes occupy the same development server as the page walk. // Finish that initial compilation before starting timed browser navigation. await apiExamples - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const manifest = await page.request.get(`${base}/page-links.json`) assert(manifest.ok(), `Native navigation manifest: HTTP ${manifest.status()}`) assert.equal((await manifest.json()).schema, 1) - const clipboardPage = await browser.newPage() + const clipboardPage = await newCheckPage(browser, base) clipboardPage.setDefaultTimeout(process.env.CI ? 20000 : 10000) const clipboard = schedule(() => checkClipboard(clipboardPage, base).finally(() => clipboardPage.close())) - const navigationPage = await browser.newPage({ reducedMotion: 'reduce' }) + const navigationPage = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) navigationPage.setDefaultTimeout(process.env.CI ? 20000 : 10000) const navigation = schedule(() => retryReload(() => checkNavigation(navigationPage, base)).finally(() => navigationPage.close()) .then(() => retryReload(() => checkMcpInstallRevisit(browser, base)))) @@ -943,7 +944,7 @@ try { .then(() => checkStatusBadgesFail(browser, base))) const homeLauncher = schedule(() => checkHomeLauncher(browser, base)) const documentationNavigation = schedule(() => retryReload(() => checkDocumentationNavigation(browser, base))) - const apiNavigationPage = await browser.newPage({ reducedMotion: 'reduce' }) + const apiNavigationPage = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) apiNavigationPage.setDefaultTimeout(process.env.CI ? 20000 : 10000) const apiNavigation = schedule(() => retryReload(() => checkApiNavigation(apiNavigationPage, base)).then(() => checkApiNavigationFail(browser, base)).finally(() => apiNavigationPage.close())) const apiAnchors = schedule(() => retryReload(() => checkApiAnchorArrival(browser, base))) @@ -1201,7 +1202,7 @@ try { }) assert.equal(toolbar.background, toolbar.page, `${colorScheme}: toolbar uses the page surface before theme initialization`) assert.equal(toolbar.icon, toolbar.text, `${colorScheme}: toolbar icons use the page text color`) - const context = await browser.newContext({ javaScriptEnabled: false, colorScheme, viewport: { width: 390, height: 844 } }) + const context = await newCheckContext(browser, base, { javaScriptEnabled: false, colorScheme, viewport: { width: 390, height: 844 } }) const noScript = await context.newPage() await noScript.goto(`${base}/tmux/concepts/server-session-window-pane/`, { waitUntil: 'load' }) const checkContrast = async (scheme, selectors = ['h1', '.prose h2', '.prose p']) => { diff --git a/site/scripts/check-fonts.mjs b/site/scripts/check-fonts.mjs index da8033c40..770b3351b 100755 --- a/site/scripts/check-fonts.mjs +++ b/site/scripts/check-fonts.mjs @@ -22,6 +22,7 @@ * * Usage: node scripts/check-fonts.mjs [--site DIR] [--url BASE] [--json] */ +import { newCheckPage } from './browser-context.mjs' import { existsSync, readFileSync } from 'node:fs' import { globSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' @@ -169,7 +170,7 @@ try { const browser = await chromium.launch() usage = [] for (const [name, path, ours] of ARCHETYPES) { - const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }) + const page = await newCheckPage(browser, BASE, { viewport: { width: 1440, height: 900 } }) const response = await page.goto(BASE + path, { waitUntil: 'networkidle' }).catch(() => null) if (!response?.ok()) { failures.push(`${name}: ${path} returned ${response?.status() ?? 'no response'}`) diff --git a/site/scripts/check-header-menu-sections.mjs b/site/scripts/check-header-menu-sections.mjs index 2a384e772..dbbb6d2a6 100644 --- a/site/scripts/check-header-menu-sections.mjs +++ b/site/scripts/check-header-menu-sections.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** @@ -252,7 +253,7 @@ export async function checkHeaderMenuSections(browser, base, options = {}) { kinds = KINDS, behavior = true, sabotage } = options let menus = 0 for (const scheme of schemes) { - const context = await browser.newContext({ colorScheme: scheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme: scheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) // The first load of each port compiles its page in the development server. diff --git a/site/scripts/check-home-example-options.mjs b/site/scripts/check-home-example-options.mjs index 7622c8e2e..e83bef817 100644 --- a/site/scripts/check-home-example-options.mjs +++ b/site/scripts/check-home-example-options.mjs @@ -1,13 +1,14 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PORTS } from '../src/lib/ports.ts' import { chooseHomeTask } from './check-home-task-reset.mjs' export async function checkHomeExampleOptions(browser, base) { for (const blocked of [false, true]) { - const context = await browser.newContext({ viewport: { width: 944, height: 777 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 944, height: 777 }, reducedMotion: 'reduce' }) try { if (blocked) { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) await context.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) diff --git a/site/scripts/check-home-hover.mjs b/site/scripts/check-home-hover.mjs index c89b4b734..3b42e7e47 100644 --- a/site/scripts/check-home-hover.mjs +++ b/site/scripts/check-home-hover.mjs @@ -1,9 +1,10 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PORTS } from '../src/lib/ports.ts' /** Real pointer events, with the clock advanced instead of sleeping per option. */ export async function checkHomeHover(browser, base) { - const context = await browser.newContext({ viewport: { width: 914, height: 777 }, colorScheme: 'light', reducedMotion: 'no-preference' }) + const context = await newCheckContext(browser, base, { viewport: { width: 914, height: 777 }, colorScheme: 'light', reducedMotion: 'no-preference' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) diff --git a/site/scripts/check-home-launcher.mjs b/site/scripts/check-home-launcher.mjs index 0f14ca68c..b23844476 100644 --- a/site/scripts/check-home-launcher.mjs +++ b/site/scripts/check-home-launcher.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PORTS } from '../src/lib/ports.ts' import HOME_PROOF from '../test/fixtures/home-examples.json' with { type: 'json' } @@ -119,7 +120,7 @@ async function checkSolutionHome(page, solution, port) { /** Exercise the real homepage, including the prompt controlled by its picker. */ export async function checkHomeLauncher(browser, base) { - const context = await browser.newContext({ reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const errors = [] @@ -375,10 +376,10 @@ export async function checkHomeLauncher(browser, base) { } finally { await context.close() } - const blockedStorage = await browser.newContext() + const blockedStorage = await newCheckContext(browser, base) try { // Astro's development toolbar reads storage unguarded; it is absent from published pages. - await blockedStorage.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await blockedStorage.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) await blockedStorage.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) @@ -399,7 +400,7 @@ export async function checkHomeLauncher(browser, base) { } finally { await blockedStorage.close() } - const noScript = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 390, height: 777 } }) + const noScript = await newCheckContext(browser, base, { javaScriptEnabled: false, viewport: { width: 390, height: 777 } }) try { const page = await noScript.newPage() await page.goto(`${base}/`) diff --git a/site/scripts/check-home-task-reset.mjs b/site/scripts/check-home-task-reset.mjs index 76cb8ba2a..a946b9374 100644 --- a/site/scripts/check-home-task-reset.mjs +++ b/site/scripts/check-home-task-reset.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' async function checkTaskFirstPaint(browser, base) { @@ -7,16 +8,19 @@ async function checkTaskFirstPaint(browser, base) { { slug: 'v0.1.0-alpha.12', label: 'v0.1.0-alpha.12', kind: 'prerelease', supported: true }, ] } } for (const width of [853, 390, 280]) { - const context = await browser.newContext({ viewport: { width, height: 789 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 789 }, reducedMotion: 'reduce' }) let releaseWidget const widgetReady = new Promise((resolve) => { releaseWidget = resolve }) try { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin === new URL(base).origin + ? route.fulfill({ contentType: 'application/javascript', body: 'export {}' }) : route.fallback()) await context.route('**/*AgentPrompt*', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() if (route.request().resourceType() === 'script') await widgetReady - await route.continue() + await route.fallback() }) - await context.route('**/versions.json', (route) => route.fulfill({ json: versions })) + await context.route('**/versions.json', (route) => new URL(route.request().url()).origin === new URL(base).origin + ? route.fulfill({ json: versions }) : route.fallback()) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const response = await page.goto(`${base}/?port=ts&errors=1&cleanup=1`, { waitUntil: 'commit' }) @@ -72,10 +76,11 @@ export async function chooseHomeTask(page, topic) { export async function checkHomeTaskReset(browser, base) { await checkTaskFirstPaint(browser, base) for (const blocked of [false, true]) { - const context = await browser.newContext({ viewport: { width: 914, height: 777 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 914, height: 777 }, reducedMotion: 'reduce' }) try { if (blocked) { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin === new URL(base).origin + ? route.fulfill({ contentType: 'application/javascript', body: 'export {}' }) : route.fallback()) await context.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) diff --git a/site/scripts/check-language-icon-scheme.mjs b/site/scripts/check-language-icon-scheme.mjs index afff84c3f..7971c04ad 100644 --- a/site/scripts/check-language-icon-scheme.mjs +++ b/site/scripts/check-language-icon-scheme.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PNG } from 'pngjs' @@ -56,7 +57,7 @@ export function readPlate(buffer) { async function readIcon(browser, url, icon, { device, site, css, replacement, forced = false, read = readMark }) { // A null site is a visit without JavaScript: no saved choice, so the page follows the device. - const context = await browser.newContext({ colorScheme: device, forcedColors: forced ? 'active' : 'none', reducedMotion: 'reduce', javaScriptEnabled: site !== null, viewport: { width: 1280, height: 777 } }) + const context = await newCheckContext(browser, url, { colorScheme: device, forcedColors: forced ? 'active' : 'none', reducedMotion: 'reduce', javaScriptEnabled: site !== null, viewport: { width: 1280, height: 777 } }) try { if (site !== null) await context.addInitScript((choice) => localStorage.setItem('color-scheme', choice), site) // Added before the page parses, so an image is first drawn with it. @@ -66,7 +67,7 @@ async function readIcon(browser, url, icon, { device, site, css, replacement, fo else new MutationObserver((_, observer) => { if (document.documentElement) { observer.disconnect(); add() } }).observe(document, { childList: true }) }, css) const page = await context.newPage() - if (replacement) await page.route('**/brand/languages/rs/icon.svg', (route) => route.fulfill({ contentType: 'image/svg+xml', body: replacement })) + if (replacement) await page.route('**/brand/languages/rs/icon.svg', (route) => new URL(route.request().url()).origin !== new URL(url).origin ? route.fallback() : route.fulfill({ contentType: 'image/svg+xml', body: replacement })) await page.goto(url) const image = page.locator(icon) await image.waitFor({ state: 'visible' }) diff --git a/site/scripts/check-mobile-nav.mjs b/site/scripts/check-mobile-nav.mjs index 8a1679183..840d45e8a 100755 --- a/site/scripts/check-mobile-nav.mjs +++ b/site/scripts/check-mobile-nav.mjs @@ -21,6 +21,7 @@ * * Usage: node scripts/check-mobile-nav.mjs [base-url] */ +import { newCheckContext } from './browser-context.mjs' import { chromium } from 'playwright' import { checkApiNavigation } from './check-navigation.mjs' const BASE = (process.argv[2] ?? 'http://localhost:8080').replace(/\/$/, '') @@ -28,7 +29,7 @@ const b = await chromium.launch() const fails = [], ok = [] const note = (pass, msg) => (pass ? ok : fails).push(msg) const WITH_TOC = '/tmux/topics/traversal/', NO_TOC = '/tmux/concepts/' -const ctx = await b.newContext() +const ctx = await newCheckContext(b, BASE) const apiPage = await ctx.newPage() try { await checkApiNavigation(apiPage, BASE) diff --git a/site/scripts/check-native-layout.mjs b/site/scripts/check-native-layout.mjs index 76f476f0e..2aeb6f02c 100644 --- a/site/scripts/check-native-layout.mjs +++ b/site/scripts/check-native-layout.mjs @@ -1,3 +1,4 @@ +import { newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' /** Controls beside a signature may sit this far from the centre of its first line. */ @@ -198,7 +199,7 @@ const DECLARATION_SAMPLES = [ * names, or the check would pass without measuring anything. */ export async function checkDeclarationControlAlignment(browser, base, widths = [1440, 768, 500, 390]) { - const page = await browser.newPage({ javaScriptEnabled: false }) + const page = await newCheckPage(browser, base, { javaScriptEnabled: false }) const beside = new Map(widths.map((width) => [width, 0])) const measured = [] try { @@ -363,7 +364,8 @@ export async function checkNativeFirstPaint(page, url) { const delayedScript = new Promise((resolve) => { release = resolve }) const pendingRoutes = [] const routeScript = (route) => { - const pending = delayedScript.then(() => route.continue()) + if (new URL(route.request().url()).origin !== new URL(url).origin) return route.fallback() + const pending = delayedScript.then(() => route.fallback()) pendingRoutes.push(pending) return pending } @@ -480,7 +482,7 @@ const MEMBER_BODY_PAGES = [ /** A body's padding alone sets its inset: top and bottom match each other and the padding. */ export async function checkMemberBodyInsets(browser, base) { const tolerance = 1 - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const failures = [] let measured = 0 diff --git a/site/scripts/check-native-navigation.mjs b/site/scripts/check-native-navigation.mjs index 8d1f2f6ba..937b5cbee 100644 --- a/site/scripts/check-native-navigation.mjs +++ b/site/scripts/check-native-navigation.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { chromium } from 'playwright' @@ -103,7 +104,7 @@ async function checkMetadata(page) { try { for (const [width, colorScheme, reducedMotion] of [[1027, 'light', 'no-preference'], [390, 'dark', 'reduce']]) { - const context = await browser.newContext({ viewport: { width, height: 900 }, colorScheme, reducedMotion, permissions: ['clipboard-read', 'clipboard-write'] }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, colorScheme, reducedMotion, permissions: ['clipboard-read', 'clipboard-write'] }) try { const page = await context.newPage() const errors = [], documents = [] @@ -159,7 +160,7 @@ try { } finally { await context.close() } } for (const width of [1027, 390]) { - const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, reducedMotion: 'reduce' }) try { const page = await context.newPage() const current = 'internals/api/libtmux._internal.query_list/' @@ -172,7 +173,7 @@ try { } finally { await context.close() } } for (const javaScriptEnabled of [false, true]) { - const context = await browser.newContext({ javaScriptEnabled, viewport: { width: 1027, height: 1450 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, viewport: { width: 1027, height: 1450 }, reducedMotion: 'reduce' }) try { const page = await context.newPage() await page.goto(root) diff --git a/site/scripts/check-native-shell.mjs b/site/scripts/check-native-shell.mjs index a961d2f01..c975032cc 100644 --- a/site/scripts/check-native-shell.mjs +++ b/site/scripts/check-native-shell.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckContext, newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { chromium } from 'playwright' import { checkNativeFirstPaint, checkNativeHeader } from './check-native-layout.mjs' @@ -8,7 +9,7 @@ const version = process.argv.find((arg) => arg.startsWith('--version='))?.slice( const browser = await chromium.launch({ channel: process.env.LIBTMUX_DOCS_BROWSER_CHANNEL }) try { for (const javaScriptEnabled of [true, false]) { - const context = await browser.newContext({ javaScriptEnabled, reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) try { const page = await context.newPage() const id = 'libtmux._internal.query_list.QueryList' @@ -24,7 +25,7 @@ try { await context.close() } } - const page = await browser.newPage() + const page = await newCheckPage(browser, base) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const loaded = new Set() page.on('response', (response) => { diff --git a/site/scripts/check-navigation.mjs b/site/scripts/check-navigation.mjs index caccb9b52..9254c7e59 100644 --- a/site/scripts/check-navigation.mjs +++ b/site/scripts/check-navigation.mjs @@ -1,3 +1,5 @@ +import { newCheckContext, newCheckPage } from './browser-context.mjs' +import { checkBrowserNetwork } from './check-browser-network.mjs' import assert from 'node:assert/strict' import { PORTS, productAvailable, productStatus } from '../src/lib/ports.ts' import registry from '../src/data/registry.json' with { type: 'json' } @@ -7,36 +9,28 @@ import { checkPickerFilters } from './check-picker-filters.mjs' /** The version the dev build mounts a port's prose pages at: its default, as check-dev sets it. */ const defaultVersion = (port) => JSON.parse(process.env.LIBTMUX_DOCS_PORT_DEFAULTS || '{}')[port] ?? 'latest' -/** A legacy guide reaches its article while external README badges remain pending. */ +/** A legacy guide loads with third-party requests blocked by its context. */ export async function checkGuideRedirect(browser, base) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + await checkBrowserNetwork(browser) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) - let release - let requested = 0 - const pending = new Promise((resolve) => { release = resolve }) - await page.route('https://img.shields.io/**', async (route) => { - requested += 1 - await pending - await route.fulfill({ contentType: 'image/svg+xml', body: '' }) - }) try { - await page.goto(`${base}/ruby/latest/guides/overview/`, { waitUntil: 'domcontentloaded' }) - await page.waitForURL(`${base}/ruby/latest/guides/getting-started/`, { waitUntil: 'domcontentloaded' }) + await page.goto(`${base}/ruby/latest/guides/overview/`, { waitUntil: 'load' }) + await page.waitForURL(`${base}/ruby/latest/guides/getting-started/`, { waitUntil: 'load' }) + await page.locator('html[data-page-readiness="ready"]').waitFor({ state: 'attached' }) assert.equal((await page.locator('main h1').textContent()).trim(), 'Getting started') + assert(await page.locator('main h1').isVisible(), 'The loaded guide is readable') assert.equal(await page.title(), 'Getting started | libtmux-ruby') - assert(requested > 0, 'The real guide requested external badges') - assert.equal(await page.evaluate(() => document.readyState), 'interactive', 'The destination document is parsed before external badges complete') - console.log('Guide redirect: the legacy Ruby URL reaches its article with external badges still pending') + assert.equal(await page.evaluate(() => document.readyState), 'complete') + console.log('Guide redirect: the legacy Ruby URL loads its article without third-party requests') } finally { - release() - await page.unrouteAll({ behavior: 'wait' }) await page.close() } } /** Optional scripts injected at the end of the body cannot gate navigation. */ export async function checkNavigationBeforeAnalytics(browser, base) { - const page = await browser.newPage({ viewport: { width: 390, height: 900 }, reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { viewport: { width: 390, height: 900 }, reducedMotion: 'reduce' }) page.setDefaultTimeout(5000) await page.clock.install({ time: 0 }) await page.clock.pauseAt(1000) @@ -205,7 +199,7 @@ export async function checkDocumentationNavigation(browser, base, complete = fal await checkPickerFilters(browser, base, complete) await checkNavigationBeforeAnalytics(browser, base) const ports = complete ? PORTS : PORTS.filter((port) => ['fsharp', 'ruby'].includes(port.slug)) - const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) await observeInitialPageLoad(page) const desktopPicker = (reader) => reader.locator('[data-documentation-context] [data-surface-picker]') @@ -333,7 +327,7 @@ export async function checkDocumentationNavigation(browser, base, complete = fal if (!complete) return for (const javaScriptEnabled of [true, false]) { for (const colorScheme of ['light', 'dark']) { - const context = await browser.newContext({ javaScriptEnabled, colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, colorScheme, reducedMotion: 'reduce' }) const reader = await context.newPage() reader.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -566,7 +560,7 @@ export async function checkApiNavigation(page, base, { sabotage } = {}) { const nav = document.querySelector('.api-nav') sessionStorage.removeItem(`libtmux:api-tree:${nav.dataset.base}`) }) - await page.route('**/tree.json', (route) => route.fulfill({ status: 503, body: 'Unavailable' })) + await page.route('**/tree.json', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ status: 503, body: 'Unavailable' })) await page.reload({ waitUntil: 'commit' }) await page.waitForFunction(() => window.__docsPageLoaded) await page.locator('[data-api-nav-toggle]').click() @@ -630,7 +624,7 @@ export async function checkApiNavigation(page, base, { sabotage } = {}) { await page.keyboard.press('Escape') assert.equal(await page.locator('.api-nav').evaluate((nav) => nav.inert), true, 'The CLI drawer dismisses with Escape') await page.setViewportSize({ width: 1440, height: 900 }) - await page.route('**/tree.json', (route) => route.fulfill({ status: 503, body: 'Unavailable' })) + await page.route('**/tree.json', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ status: 503, body: 'Unavailable' })) await page.goto(`${base}/lua/latest/reference/`, { waitUntil: 'commit' }) await page.waitForFunction(() => window.__docsPageLoaded) assert.equal(await page.locator('.api-nav__tree [role="treeitem"][tabindex="0"]').count(), 1, 'The server-rendered index remains keyboard reachable when its inventory cannot load') @@ -641,7 +635,7 @@ export async function checkApiNavigation(page, base, { sabotage } = {}) { /** Public symbol fragments and earlier declaration links reach the same bar. */ export async function checkApiAnchorArrival(browser, base) { const paths = new Set([`${base}/py/latest/reference/libtmux-_internal-query_list-querylist/`]) - const catalog = await browser.newPage() + const catalog = await newCheckPage(browser, base) try { for (const port of PORTS) { await catalog.goto(`${base}/${port.slug}/latest/reference/`, { waitUntil: 'load' }) @@ -656,7 +650,7 @@ export async function checkApiAnchorArrival(browser, base) { [390, 'light', true], [1280, 'dark', true], [390, 'dark', false], [1280, 'light', false], ]) { - const context = await browser.newContext({ viewport: { width, height: 1000 }, colorScheme, + const context = await newCheckContext(browser, base, { viewport: { width, height: 1000 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) @@ -714,7 +708,7 @@ export async function checkPermalinkReveal(browser, base, { only, sabotage } = { ['a parameter line', 'ul.api-parameters > li[id] > p > a.api-heading-link']]], ] const open = async (options) => { - const context = await browser.newContext({ reducedMotion: 'reduce', ...options }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', ...options }) if (sabotage?.css) await context.addInitScript((css) => document.addEventListener('DOMContentLoaded', () => { document.head.append(Object.assign(document.createElement('style'), { textContent: css })) }), sabotage.css) @@ -947,7 +941,7 @@ export async function checkPermalinkRevealFail(browser, base) { /** The control for `checkApiNavigation`: a drawer whose close button does nothing must fail it. */ export async function checkApiNavigationFail(browser, base) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) try { await assert.rejects(() => checkApiNavigation(page, base, { sabotage: () => { document.addEventListener('click', (event) => { @@ -963,7 +957,7 @@ export async function checkApiNavigationFail(browser, base) { * style to the page, for the control below. */ export async function checkReferenceSidebarBounds(browser, base, { sabotage } = {}) { - const page = await browser.newPage({ viewport: { width: 1233, height: 1220 }, reducedMotion: 'reduce', colorScheme: 'dark' }) + const page = await newCheckPage(browser, base, { viewport: { width: 1233, height: 1220 }, reducedMotion: 'reduce', colorScheme: 'dark' }) try { await page.goto(`${base}/tmux/latest/manual/#options`) await page.locator('html[data-page-readiness="ready"]').waitFor() @@ -1024,7 +1018,7 @@ export async function checkApiStickyHeadings(browser, base, { only, sabotage } = const timeout = process.env.CI ? 20000 : 10000 const wants = (scenario) => !only || only.includes(scenario) const open = async (viewport) => { - const context = await browser.newContext({ viewport }) + const context = await newCheckContext(browser, base, { viewport }) if (sabotage?.script) await context.addInitScript(sabotage.script) const page = await context.newPage() page.setDefaultTimeout(timeout) @@ -1380,7 +1374,7 @@ export async function checkNavigation(page, base) { await page.goto(`${legacy}?from=legacy#where-this-comes-from`, { waitUntil: 'load' }) await page.waitForURL(`${current}?from=legacy#where-this-comes-from`) assert.equal(await page.locator('#where-this-comes-from').count(), 1, 'Legacy section still exists') - const fallback = await page.context().browser().newContext({ javaScriptEnabled: false }) + const fallback = await newCheckContext(page.context().browser(), base, { javaScriptEnabled: false }) try { const reader = await fallback.newPage() await reader.goto(legacy, { waitUntil: 'load' }) @@ -1412,7 +1406,7 @@ export async function checkApiExampleOwnership(page, base, path = 'ts/latest/ref * attributes that snippet set on , so the widget has to restore them. */ export async function checkMcpInstallRevisit(browser, base) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) try { const shown = () => page.evaluate(() => [...document.querySelectorAll('.lm-mcp-install__panel')] .filter((panel) => panel.checkVisibility()).length) diff --git a/site/scripts/check-page-readiness.mjs b/site/scripts/check-page-readiness.mjs index 81a6ef95e..d49f7ba71 100644 --- a/site/scripts/check-page-readiness.mjs +++ b/site/scripts/check-page-readiness.mjs @@ -1,3 +1,4 @@ +import { newCheckContext, newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import pixelmatch from 'pixelmatch' import { PNG } from 'pngjs' @@ -56,7 +57,7 @@ async function observeAppearance(context) { /** Optional policy and beacon requests cannot hold browser lifecycle events. */ export async function checkWebAnalytics(browser, base) { for (const kind of ['beacon', 'policy', 'excluded']) { - const context = await browser.newContext({ viewport: { width: 390, height: 900 } }) + const context = await newCheckContext(browser, base, { viewport: { width: 390, height: 900 } }) await observeAppearance(context) const page = await context.newPage() const errors = [] @@ -65,6 +66,7 @@ export async function checkWebAnalytics(browser, base) { const held = new Promise((resolve) => { release = resolve }) try { await page.route('**/_shell/web-analytics.json', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() if (kind === 'policy') { requested = true await held @@ -123,13 +125,14 @@ export async function checkWebAnalytics(browser, base) { /** Reproduce a late beacon arriving between an Astro swap and script execution. */ export async function checkWebAnalyticsTransitions(browser, base) { for (const markHandled of [true, false]) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) let release, requested = false const held = new Promise((resolve) => { release = resolve }) try { await page.route('**/_shell/web-analytics.json', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() const response = await route.fetch() await route.fulfill({ response, headers: { ...response.headers(), 'x-libtmux-analytics': 'allow' } }) }) @@ -186,7 +189,7 @@ export async function checkRequiredAppearance(browser, base) { ['module', '/java/latest/reference/io-github-libtmux-buffers-buffers-delete/', 1280], ['effect', '/prompts/?port=ts', 390], ]) { - const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, reducedMotion: 'reduce' }) await observeAppearance(context) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) @@ -214,6 +217,7 @@ export async function checkRequiredAppearance(browser, base) { : request.url() === module const incoming = page.waitForRequest(required) await page.route('**/*', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() if (required(route.request())) { requested = true; await hold } if (kind === 'effect' && required(route.request())) { // Exercise insertion even when a new preview's actual manifest has @@ -225,7 +229,7 @@ export async function checkRequiredAppearance(browser, base) { await route.fulfill({ json: { schema: 1, ports: { py: entries, ts: entries } } }) return } - await route.continue() + await route.fallback() }) await page.goto(`${base}${path}`, { waitUntil: 'commit' }) await incoming @@ -273,11 +277,11 @@ export async function checkRequiredAppearance(browser, base) { } finally { release(); await context.close() } } - const context = await browser.newContext({ reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { - await page.route('**/*', (route) => route.request().resourceType() === 'font' ? route.abort() : route.continue()) + await page.route('**/*', (route) => route.request().resourceType() === 'font' ? route.abort() : route.fallback()) await page.goto(`${base}/`, { waitUntil: 'commit' }) await page.getByRole('alert').waitFor({ state: 'visible' }) assert.equal(await page.locator('html').getAttribute('data-page-readiness'), 'failed') @@ -288,7 +292,7 @@ export async function checkRequiredAppearance(browser, base) { await page.locator('html[data-page-readiness="ready"]').waitFor({ state: 'attached' }) assert(await page.locator('main h1').isVisible(), 'Reload recovers after the required resource becomes available') } finally { await context.close() } - const legacy = await browser.newPage() + const legacy = await newCheckPage(browser, base) try { const probe = `${base}/legacy-shell-probe/` await legacy.route(probe, (route) => route.fulfill({ contentType: 'text/html', body: @@ -461,7 +465,7 @@ async function addBadgeLinkFixtures(page) { * name's text, and leads it by about a quarter em. */ export async function checkKindBadgeLinks(browser, base, { sample = false, entries = BADGE_LINKS } = {}) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1600, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1600, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const failures = [] @@ -564,7 +568,7 @@ function dottedDecorations() { * line; only inline text runs carry the dotted underline. */ export async function checkBlockLinksUndecorated(browser, base, { sample = false } = {}) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const failures = [] @@ -676,7 +680,7 @@ async function functionLinkMarked(page) { * taken away, and a page that never had the section. */ export async function checkTmuxReferencePreviewsFail(browser, base) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -700,7 +704,7 @@ const TMUX_FUNCTION_LINK = 'section.api-tmux-section:has(> #api-tmux-command) .t const TMUX_METHOD_PAGE = '/cxx/latest/reference/libtmux-server-panes/' export async function checkTmuxReferencePreviews(browser, base, { served: build } = {}) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const opened = () => page.evaluate(() => document.getElementById('reference-link-preview')?.matches(':popover-open') ?? false) diff --git a/site/scripts/check-picker-filters.mjs b/site/scripts/check-picker-filters.mjs index 3aa0c47bb..45eda7db9 100644 --- a/site/scripts/check-picker-filters.mjs +++ b/site/scripts/check-picker-filters.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' async function bounds(page, panel) { @@ -61,7 +62,7 @@ async function exercise(page, selector, query, count) { export async function checkPickerFilters(browser, base, complete = false) { const sizes = complete ? [{ width: 853, height: 789 }, { width: 320, height: 360 }, { width: 280, height: 320 }] : [{ width: 320, height: 360 }] for (const colorScheme of complete ? ['light', 'dark'] : ['light']) { - const context = await browser.newContext({ colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(5000) try { @@ -77,10 +78,11 @@ export async function checkPickerFilters(browser, base, complete = false) { } if (!complete) return - const context = await browser.newContext({ viewport: { width: 853, height: 789 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 853, height: 789 }, reducedMotion: 'reduce' }) let release const pending = new Promise((resolve) => { release = resolve }) await context.route('**/versions.json', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() await pending await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ schema: 1, ports: { kotlin: [ { slug: 'latest', label: 'latest', kind: 'trunk', supported: true }, @@ -120,7 +122,7 @@ export async function checkPickerFilters(browser, base, complete = false) { assert.equal(new URL(page.url()).hash, '#demo-versions', 'Sample versions use their own destination after choosing a sample language') } finally { release(); await context.unrouteAll({ behavior: 'wait' }); await context.close() } - const noScript = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 853, height: 789 } }) + const noScript = await newCheckContext(browser, base, { javaScriptEnabled: false, viewport: { width: 853, height: 789 } }) try { const page = await noScript.newPage() await page.goto(`${base}/demo/widgets/pickers/`) diff --git a/site/scripts/check-reference-preferences.mjs b/site/scripts/check-reference-preferences.mjs index b1da486c5..6d9e37c71 100644 --- a/site/scripts/check-reference-preferences.mjs +++ b/site/scripts/check-reference-preferences.mjs @@ -1,10 +1,11 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Exercise native disclosures and fragment navigation on a short API page. */ export async function checkReferencePreferences(browser, base) { const path = '/java/latest/reference/io-github-libtmux-buffers-buffers-delete/' const key = 'libtmux-docs.api-source-details' - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 784, height: 760 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 784, height: 760 } }) await context.addInitScript(() => { window.__sourceFrames = [] const seen = new WeakSet() @@ -82,7 +83,7 @@ export async function checkReferencePreferences(browser, base) { } for (const javaScriptEnabled of [false, true]) { - const fallback = await browser.newContext({ javaScriptEnabled, reducedMotion: 'reduce' }) + const fallback = await newCheckContext(browser, base, { javaScriptEnabled, reducedMotion: 'reduce' }) if (javaScriptEnabled) await fallback.addInitScript(() => { Object.defineProperty(window, 'localStorage', { get() { throw new Error('Storage blocked') } }) }) @@ -208,7 +209,7 @@ export async function checkHeaderLinks(page, path, width, scripted) { */ export async function checkHeaderLinksFail(browser, base) { const run = async ({ path = '/rs/latest/', width = 1440, css, script }) => { - const context = await browser.newContext({ javaScriptEnabled: true, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled: true, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -277,7 +278,7 @@ export async function checkHeaderLinksRender(browser, base, { path = '/rs/latest if ((script || css) && javaScript.includes(false)) throw new Error('checkHeaderLinksRender: script and css apply only where JavaScript is on') for (const colorScheme of schemes) for (const width of widths) for (const javaScriptEnabled of javaScript) { const where = `${path} at ${width}px, ${colorScheme}, ${javaScriptEnabled ? 'with' : 'without'} JavaScript` - const context = await browser.newContext({ viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) if (javaScriptEnabled) { await context.addInitScript(() => { window.__headerShift = 0 @@ -405,7 +406,7 @@ export async function checkHeaderLinksRenderFail(browser, base) { /** The global header has no repeated destination strip, including without JS. */ export async function checkGlobalHeader(browser, base) { for (const javaScriptEnabled of [false, true]) { - const context = await browser.newContext({ javaScriptEnabled, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, reducedMotion: 'reduce' }) const page = await context.newPage() const headerFrames = new Map() try { @@ -464,7 +465,7 @@ export async function checkScrollbarStability(browser, base) { }) try { for (const width of [280, 628, 1280]) for (const colorScheme of ['light', 'dark']) for (const javaScriptEnabled of [true, false]) { - const context = await classic.newContext({ viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) + const context = await newCheckContext(classic, base, { viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) const page = await context.newPage() const frame = () => page.evaluate(() => { const rect = (selector) => { diff --git a/site/scripts/check-ruby-lua.mjs b/site/scripts/check-ruby-lua.mjs index 558a7b533..7b9bf8fba 100644 --- a/site/scripts/check-ruby-lua.mjs +++ b/site/scripts/check-ruby-lua.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node /** Browser coverage for the Ruby and Lua documentation surfaces. */ +import { newCheckContext } from './browser-context.mjs' import { chromium } from 'playwright' const BASE = (process.argv[2] ?? 'http://localhost:8080/en').replace(/\/$/, '') @@ -33,7 +34,7 @@ const check = (condition, message) => { for (const scheme of ['light', 'dark']) { for (const [viewport, width, height] of VIEWPORTS) { - const context = await browser.newContext({ + const context = await newCheckContext(browser, base, { viewport: { width, height }, colorScheme: scheme, }) diff --git a/site/scripts/check-sidebar-demo.mjs b/site/scripts/check-sidebar-demo.mjs index 3ceb43692..4ac27f13d 100644 --- a/site/scripts/check-sidebar-demo.mjs +++ b/site/scripts/check-sidebar-demo.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node // Outer loop: real browser interactions across sidebar modes, themes, and viewports. +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { mkdir } from 'node:fs/promises' import { resolve } from 'node:path' @@ -10,7 +11,7 @@ import { chromium } from 'playwright' export async function checkSidebarDemo(browser, url, options = {}) { const values = { url, screenshots: options.screenshots, 'negative-control': options.negativeControl } const started = performance.now() - const context = await browser.newContext({ viewport: { width: 1600, height: 1150 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1600, height: 1150 }, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(1000) const navigationTimeout = process.env.CI ? 20000 : 10000 diff --git a/site/scripts/check-status-badges.mjs b/site/scripts/check-status-badges.mjs index 8b920199a..899986589 100644 --- a/site/scripts/check-status-badges.mjs +++ b/site/scripts/check-status-badges.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { CONCEPT_DESCRIPTION, PICKER_GROUP_SUMMARY, PORT_BY_SLUG, PRODUCT_STATUS_GUIDE, PRODUCT_STATUS_LINK, productStatusLine, productAvailable, productStatus } from '../src/lib/ports.ts' import registry from '../src/data/registry.json' with { type: 'json' } @@ -222,7 +223,7 @@ export async function checkStatusBadges(browser, base, options = {}) { touch = true, timeout, sabotage } = options let rows = 0 for (const scheme of schemes) { - const context = await browser.newContext({ colorScheme: scheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme: scheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(timeout ?? (process.env.CI ? 20000 : 10000)) page.setDefaultNavigationTimeout(60000) @@ -269,7 +270,7 @@ export async function checkStatusBadges(browser, base, options = {}) { } } if (touch && !sabotage) { - const context = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) page.setDefaultNavigationTimeout(60000) diff --git a/site/scripts/check-style-parity.mjs b/site/scripts/check-style-parity.mjs index ead796b35..09c48e390 100755 --- a/site/scripts/check-style-parity.mjs +++ b/site/scripts/check-style-parity.mjs @@ -17,6 +17,7 @@ * * Usage: node scripts/check-style-parity.mjs [base-url] */ +import { newCheckPage } from './browser-context.mjs' import { chromium } from 'playwright' const base = process.argv[2] ?? 'http://localhost:8080' @@ -163,7 +164,7 @@ async function styles(page, url, cases, side) { } const browser = await chromium.launch() -const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }) +const page = await newCheckPage(browser, base, { viewport: { width: 1440, height: 900 } }) const sphinx = await styles(page, SPHINX, CASES, 'sphinx') /* * Two visits, one array. diff --git a/site/scripts/check-tables.mjs b/site/scripts/check-tables.mjs index 254eea1f6..f5b5bb2c7 100644 --- a/site/scripts/check-tables.mjs +++ b/site/scripts/check-tables.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { globSync, readFileSync } from 'node:fs' import { join } from 'node:path' @@ -31,7 +32,7 @@ const browser = await chromium.launch({ channel: process.env.LIBTMUX_DOCS_BROWSE let checked = 0 try { for (const width of [1440, 768, 390]) { - const page = await browser.newPage({ viewport: { width, height: 1000 } }) + const page = await newCheckPage(browser, base, { viewport: { width, height: 1000 } }) for (const path of paths) { const response = await page.goto(base + path) assert(response?.ok(), `${path}: HTTP ${response?.status()}`) diff --git a/site/scripts/check-tmux-keys.mjs b/site/scripts/check-tmux-keys.mjs index 20d3d05f0..fadc9d09c 100644 --- a/site/scripts/check-tmux-keys.mjs +++ b/site/scripts/check-tmux-keys.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Contrast of a rendered element's text against what is painted behind it. */ @@ -53,7 +54,7 @@ export const TMUX_KEY_PAGES = [ */ export async function checkTmuxKeys(browser, base) { for (const colorScheme of ['light', 'dark']) { - const context = await browser.newContext({ colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const errors = [] diff --git a/site/scripts/check-type-parameters.mjs b/site/scripts/check-type-parameters.mjs index a7ffe4637..d7bbbf330 100644 --- a/site/scripts/check-type-parameters.mjs +++ b/site/scripts/check-type-parameters.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** @@ -18,7 +19,7 @@ export const TYPE_PARAMETER_PAGES = [ * declaration exists on the owner's page, and the Markdown twin says the same. */ export async function checkTypeParameters(browser, base, pages = TYPE_PARAMETER_PAGES) { - const context = await browser.newContext({ viewport: { width: 1280, height: 1000 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1280, height: 1000 }, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { diff --git a/site/scripts/check-visual.mjs b/site/scripts/check-visual.mjs index 10e9e16da..9caa7b658 100755 --- a/site/scripts/check-visual.mjs +++ b/site/scripts/check-visual.mjs @@ -17,6 +17,7 @@ * * Usage: node scripts/check-visual.mjs [--update] [base-url] */ +import { newCheckPage } from './browser-context.mjs' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' @@ -60,7 +61,7 @@ let written = 0 for (const [scheme] of [['light'], ['dark']]) { for (const [vname, width, height] of VIEWPORTS) { - const page = await browser.newPage({ viewport: { width, height }, colorScheme: scheme }) + const page = await newCheckPage(browser, base, { viewport: { width, height }, colorScheme: scheme }) for (const [pname, path] of PAGES) { const name = `${pname}-${vname}-${scheme}.png` const file = join(dir, name) diff --git a/site/scripts/check-workspace-hover.mjs b/site/scripts/check-workspace-hover.mjs index 5bdcf5c6d..8ed8274fe 100644 --- a/site/scripts/check-workspace-hover.mjs +++ b/site/scripts/check-workspace-hover.mjs @@ -1,8 +1,9 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Real pointer events on the preset picker, with the clock advanced instead of sleeping. */ export async function checkWorkspaceHover(browser, base) { - const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) diff --git a/site/scripts/check-workspace-shift.mjs b/site/scripts/check-workspace-shift.mjs index 3575d55f9..db8d68211 100644 --- a/site/scripts/check-workspace-shift.mjs +++ b/site/scripts/check-workspace-shift.mjs @@ -1,8 +1,9 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** A cold deep link into the preset picker lands in one scroll and shifts nothing. */ export async function checkWorkspaceShift(browser, base) { - const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) From a437e971a32fdb36662e921af74ca1ff9d81f393 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 8 Nov 2026 17:32:36 -0600 Subject: [PATCH 3/3] fix(browser) Preserve migrated origin bindings why: The shared context factory needs each caller's site URL. Undefined base variables stopped the sidebar audit and two standalone checks. what: - Preserve the sidebar, clipboard and Ruby/Lua URL bindings - Reject undefined names in browser-check preflight - Exercise sidebar context admission and add a focused browser mode --- site/scripts/browser-scope.json | 4 ++++ site/scripts/check-browser-network.mjs | 10 +++++++++- site/scripts/check-clipboard.mjs | 3 ++- site/scripts/check-dev.mjs | 6 +++++- site/scripts/check-ruby-lua.mjs | 2 +- site/scripts/check-sidebar-demo.mjs | 2 +- 6 files changed, 22 insertions(+), 5 deletions(-) create mode 100644 site/scripts/browser-scope.json diff --git a/site/scripts/browser-scope.json b/site/scripts/browser-scope.json new file mode 100644 index 000000000..ef13225e3 --- /dev/null +++ b/site/scripts/browser-scope.json @@ -0,0 +1,4 @@ +{ + "env": { "browser": true, "node": true, "builtin": true }, + "rules": { "no-undef": "error" } +} diff --git a/site/scripts/check-browser-network.mjs b/site/scripts/check-browser-network.mjs index f89b4d85c..d1cedb111 100644 --- a/site/scripts/check-browser-network.mjs +++ b/site/scripts/check-browser-network.mjs @@ -1,13 +1,18 @@ import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' import { once } from 'node:events' import { createServer } from 'node:http' -import { pathToFileURL } from 'node:url' +import { fileURLToPath, pathToFileURL } from 'node:url' import { chromium } from 'playwright' import { newCheckContext, newCheckPage } from './browser-context.mjs' +import { checkSidebarDemo } from './check-sidebar-demo.mjs' /** A held image on another origin must never reach its server or delay load. */ export async function checkBrowserNetwork(browser) { + execFileSync(fileURLToPath(new URL('../node_modules/.bin/oxlint', import.meta.url)), + ['--config', fileURLToPath(new URL('./browser-scope.json', import.meta.url)), + fileURLToPath(new URL('.', import.meta.url))], { stdio: 'inherit' }) let result = Promise.withResolvers() let escaped = 0 const foreign = createServer(() => { @@ -63,6 +68,9 @@ export async function checkBrowserNetwork(browser) { local.listen(0, '127.0.0.1') await once(local, 'listening') const base = `http://127.0.0.1:${local.address().port}` + const sidebarAdmission = new Error('Sidebar context admitted') + await assert.rejects(checkSidebarDemo({ async newContext() { throw sidebarAdmission } }, base), + (error) => error === sidebarAdmission, 'The sidebar check passes its URL into the shared context factory') for (const factory of ['page', 'context', 'redirect', 'continued']) { const page = factory === 'page' ? await newCheckPage(browser, base, { viewport: { width: 640, height: 480 } }) diff --git a/site/scripts/check-clipboard.mjs b/site/scripts/check-clipboard.mjs index da8a2cec6..dcc1dfc31 100644 --- a/site/scripts/check-clipboard.mjs +++ b/site/scripts/check-clipboard.mjs @@ -218,9 +218,10 @@ export async function checkClipboard(page, base) { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const browser = await chromium.launch() try { + const base = (process.argv[2] ?? 'http://localhost:8080/en').replace(/\/$/, '') const page = await newCheckPage(browser, base) page.setDefaultTimeout(1000) - await checkClipboard(page, (process.argv[2] ?? 'http://localhost:8080/en').replace(/\/$/, '')) + await checkClipboard(page, base) } finally { await browser.close() } diff --git a/site/scripts/check-dev.mjs b/site/scripts/check-dev.mjs index 4b5dbea2d..1fd279fc6 100644 --- a/site/scripts/check-dev.mjs +++ b/site/scripts/check-dev.mjs @@ -56,6 +56,7 @@ assert(requestedBrowserPort === undefined || /^\d+$/.test(requestedBrowserPort) 'LIBTMUX_DOCS_BROWSER_PORT must be an integer from 1 to 65535') const documentationNavigationOnly = process.argv.includes('--documentation-navigation') const guideRedirectOnly = process.argv.includes('--guide-redirect') +const sidebarDemoOnly = process.argv.includes('--sidebar-demo') const workspacePortCount = PORTS.filter((port) => productAvailable(port, 'workspace')).length Object.assign(process.env, { @@ -788,6 +789,7 @@ try { // Compile the initial pages during setup; navigation assertions measure // the running app. The outer loop still budgets this initial compilation. const firstPage = homeLauncherOnly || homeControlsOnly ? '/' + : sidebarDemoOnly ? '/demo/sidebar/' : guideRedirectOnly ? '/ruby/latest/guides/overview/' : keywordHelpOnly ? '/kotlin/latest/reference/io-github-libtmux-kotlin-withserver/' : apiStickyOnly || permalinkRevealOnly ? '/swift/latest/reference/server/' @@ -797,7 +799,7 @@ try { : apiNavigationOnly ? '/lua/latest/reference/libtmux-server/' : typeParametersOnly ? '/ts/latest/reference/selection-selection-where/' : '/tmux/concepts/server-session-window-pane/' const fullRun = ![homeLauncherOnly, homeControlsOnly, keywordHelpOnly, apiSignaturesOnly, referenceLayoutOnly, globalHeaderOnly, headerMenuSectionsOnly, statusBadgesOnly, badgeCentringOnly, referencePreviewsOnly, - referencePreferencesOnly, documentationNavigationOnly, guideRedirectOnly, apiNavigationOnly, apiAnchorsOnly, typeParametersOnly, permalinkRevealOnly, requiredAppearanceOnly].some(Boolean) + referencePreferencesOnly, documentationNavigationOnly, guideRedirectOnly, sidebarDemoOnly, apiNavigationOnly, apiAnchorsOnly, typeParametersOnly, permalinkRevealOnly, requiredAppearanceOnly].some(Boolean) const setupPages = sampleOnly ? [firstPage, '/demo/widgets/pickers/', ...TMUX_KEY_PAGES] : [firstPage, ...(fullRun ? TMUX_KEY_PAGES : [])] const ready = Promise.all(setupPages.map(async (path) => { @@ -869,6 +871,8 @@ try { await retryReload(() => checkGlobalHeader(browser, base)) } else if (guideRedirectOnly) { await checkGuideRedirect(browser, base) + } else if (sidebarDemoOnly) { + await checkSidebarDemo(browser, `${base}/demo/sidebar/`) } else if (documentationNavigationOnly) { await retryReload(() => checkDocumentationNavigation(browser, base, true)) } else if (apiNavigationOnly) { diff --git a/site/scripts/check-ruby-lua.mjs b/site/scripts/check-ruby-lua.mjs index 7b9bf8fba..2805915ca 100644 --- a/site/scripts/check-ruby-lua.mjs +++ b/site/scripts/check-ruby-lua.mjs @@ -34,7 +34,7 @@ const check = (condition, message) => { for (const scheme of ['light', 'dark']) { for (const [viewport, width, height] of VIEWPORTS) { - const context = await newCheckContext(browser, base, { + const context = await newCheckContext(browser, BASE, { viewport: { width, height }, colorScheme: scheme, }) diff --git a/site/scripts/check-sidebar-demo.mjs b/site/scripts/check-sidebar-demo.mjs index 4ac27f13d..dc26afb5b 100644 --- a/site/scripts/check-sidebar-demo.mjs +++ b/site/scripts/check-sidebar-demo.mjs @@ -11,7 +11,7 @@ import { chromium } from 'playwright' export async function checkSidebarDemo(browser, url, options = {}) { const values = { url, screenshots: options.screenshots, 'negative-control': options.negativeControl } const started = performance.now() - const context = await newCheckContext(browser, base, { viewport: { width: 1600, height: 1150 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, url, { viewport: { width: 1600, height: 1150 }, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(1000) const navigationTimeout = process.env.CI ? 20000 : 10000