Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

ci(a11y): the accessibility audit answers a story's remote images locally (#9715)

Cindy Zhangd67b808cdeda
diff --git a/.github/scripts/accessibility-audit.integration.test.mjs b/.github/scripts/accessibility-audit.integration.test.mjs
index 1a001590ad..676039a2f6 100644
--- a/.github/scripts/accessibility-audit.integration.test.mjs
+++ b/.github/scripts/accessibility-audit.integration.test.mjs
@@ -23,6 +23,8 @@ const originalLoad = Module._load;
let requestedUrl = '';
let reads = 0;
let selectorResolved = false;
+// The audit answers remote images locally before it opens any story.
+let remoteImagesRouted = false;
// The layout-settle step waits two frames before sampling geometry.
global.requestAnimationFrame = callback => setTimeout(callback, 0);
@@ -87,6 +89,9 @@ const page = {
// A real request, so a run only passes when the audit opens the port its
// server actually holds.
goto: async url => {
+ if (!remoteImagesRouted) {
+ throw new Error('a story opened before remote images were routed locally');
+ }
requestedUrl = url;
const response = await fetch(url);
if (!response.ok) {
@@ -110,6 +115,11 @@ const page = {
};
const context = {
addInitScript: async () => {},
+ route: async (pattern, handler) => {
+ if (pattern === '**/*' && typeof handler === 'function') {
+ remoteImagesRouted = true;
+ }
+ },
newPage: async () => page,
close: async () => {},
};
diff --git a/.github/scripts/accessibility-audit.js b/.github/scripts/accessibility-audit.js
index 8f0f5fabfd..92607665ea 100644
--- a/.github/scripts/accessibility-audit.js
+++ b/.github/scripts/accessibility-audit.js
@@ -38,6 +38,7 @@ const {
storyKey,
} = require('./lib/a11y-baseline');
const {waitForStoryReadiness} = require('./lib/a11y-story-readiness');
+const {routeRemoteImages} = require('./lib/offline-media');
const {
mergeA11yShards,
parseShard,
@@ -387,6 +388,10 @@ async function runAccessibilityAudit() {
: null;
// Animations are frozen from the page's first script on, however far the
// document has parsed: an adopted stylesheet needs no <head>.
+ // A story's remote photos (picsum.photos and the like) are answered with
+ // a local image, so no scan depends on a remote image host. The audit
+ // reads the same DOM: the image elements stay, only their bytes are local.
+ if (context) await routeRemoteImages(context, origin);
if (context) {
await context.addInitScript(css => {
const sheet = new CSSStyleSheet();
diff --git a/.github/scripts/lib/offline-media.js b/.github/scripts/lib/offline-media.js
new file mode 100644
index 0000000000..6f5d176690
--- /dev/null
+++ b/.github/scripts/lib/offline-media.js
@@ -0,0 +1,76 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use strict';
+/* global Buffer, module */
+
+/**
+ * @file Answers a page's remote images locally, so no Storybook scan
+ * depends on a remote image host.
+ * @input A Playwright page or browser context, and the origin it serves
+ * stories from.
+ * @output Every image request to another host is answered with a small local
+ * image. Requests to the story origin, and remote requests that are not
+ * images, pass unchanged.
+ * @position Used by the accessibility audit. A browser spec that loads remote
+ * photos may use it in place of its own stand-in.
+ */
+
+/** A neutral stand-in: a transparent 400 × 400 SVG. */
+const STAND_IN_IMAGE = Buffer.from(
+ "<svg xmlns='http://www.w3.org/2000/svg' width='400' height='400'/>",
+);
+
+const IMAGE_PATH = /\.(?:avif|bmp|gif|ico|jpe?g|png|svg|webp)$/i;
+
+/**
+ * Whether a request is a remote image: an image fetch to a host other than
+ * the story origin. A request the browser makes for an `<img>`, a CSS
+ * background or an `<image>` has resource type `image`; a fetch() of an image
+ * URL is matched by its extension.
+ *
+ * @param {{url: string, resourceType: string}} request
+ * @param {string} storyOrigin
+ */
+function isRemoteImage({url, resourceType}, storyOrigin) {
+ let parsed;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
+ if (parsed.origin === storyOrigin) return false;
+ if (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1')
+ return false;
+ return resourceType === 'image' || IMAGE_PATH.test(parsed.pathname);
+}
+
+/**
+ * Answers every remote image on `target` (a page or a browser context)
+ * locally. Await it before the first navigation.
+ *
+ * @param {{route: Function}} target
+ * @param {string} storyOrigin
+ * @returns {Promise<void>}
+ */
+async function routeRemoteImages(target, storyOrigin) {
+ await target.route('**/*', async route => {
+ const request = route.request();
+ if (
+ isRemoteImage(
+ {url: request.url(), resourceType: request.resourceType()},
+ storyOrigin,
+ )
+ ) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'image/svg+xml',
+ body: STAND_IN_IMAGE,
+ });
+ return;
+ }
+ await route.continue();
+ });
+}
+
+module.exports = {STAND_IN_IMAGE, isRemoteImage, routeRemoteImages};
diff --git a/.github/scripts/lib/offline-media.test.mjs b/.github/scripts/lib/offline-media.test.mjs
new file mode 100644
index 0000000000..c630451158
--- /dev/null
+++ b/.github/scripts/lib/offline-media.test.mjs
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import http from 'node:http';
+import {createRequire} from 'node:module';
+import {afterAll, beforeAll, describe, expect, it} from 'vitest';
+
+const require = createRequire(import.meta.url);
+const {isRemoteImage, routeRemoteImages} = require('./offline-media.js');
+
+const ORIGIN = 'http://localhost:6006';
+
+describe('isRemoteImage', () => {
+ it.each([
+ [{url: 'https://picsum.photos/400', resourceType: 'image'}, true],
+ [{url: 'https://images.unsplash.com/photo-1', resourceType: 'image'}, true],
+ // A fetch() of an image URL, matched by its extension.
+ [{url: 'https://placehold.co/600x400.png', resourceType: 'fetch'}, true],
+ // The story origin and the loopback host pass.
+ [{url: `${ORIGIN}/assets/photo.png`, resourceType: 'image'}, false],
+ [{url: 'http://127.0.0.1:9000/a.png', resourceType: 'image'}, false],
+ // A remote request that is not an image passes unchanged.
+ [
+ {url: 'https://fonts.example.com/font.woff2', resourceType: 'font'},
+ false,
+ ],
+ [{url: 'https://api.example.com/data', resourceType: 'fetch'}, false],
+ [{url: 'data:image/png;base64,AAAA', resourceType: 'image'}, false],
+ ])('%j → %s', (request, expected) => {
+ expect(isRemoteImage(request, ORIGIN)).toBe(expected);
+ });
+});
+
+// The Node test legs install no browser; this proof runs wherever Chromium is
+// installed (a workstation, or any job that installs Playwright's Chromium).
+const chromiumInstalled = (() => {
+ try {
+ return fs.existsSync(require('playwright').chromium.executablePath());
+ } catch {
+ return false;
+ }
+})();
+
+describe.runIf(chromiumInstalled)('routeRemoteImages in a real browser', () => {
+ let server;
+ let stalled;
+ let origin;
+ let chromium;
+ // The remote image host resolves to a local server that accepts the
+ // connection and never answers: a host that stalls, on every machine.
+ const REMOTE_HOST = 'photos.example.test';
+ const launch = () =>
+ chromium.launch({
+ args: [
+ `--host-resolver-rules=MAP ${REMOTE_HOST} 127.0.0.1:${stalled.address().port}`,
+ // A local sandboxed shell cannot start Chromium's own sandbox; CI can.
+ ...(process.env.ASTRYX_NO_BROWSER_SANDBOX === '1'
+ ? ['--no-sandbox', '--single-process', '--no-zygote']
+ : []),
+ ],
+ });
+
+ beforeAll(async () => {
+ ({chromium} = require('playwright'));
+ stalled = http.createServer(() => {});
+ await new Promise(resolve => stalled.listen(0, '127.0.0.1', resolve));
+ // A story page whose only image lives on the stalling host.
+ server = http.createServer((request, response) => {
+ response.setHeader('content-type', 'text/html');
+ response.end(
+ `<!doctype html><img id="photo" alt="photo" src="http://${REMOTE_HOST}/photo.jpg">`,
+ );
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ origin = `http://127.0.0.1:${server.address().port}`;
+ });
+
+ afterAll(async () => {
+ stalled?.closeAllConnections();
+ await new Promise(resolve => stalled?.close(resolve));
+ await new Promise(resolve => server?.close(resolve));
+ });
+
+ it('a page whose image host is unreachable still loads at once, with the image drawn locally', async () => {
+ const browser = await launch();
+ try {
+ const context = await browser.newContext();
+ await routeRemoteImages(context, origin);
+ const page = await context.newPage();
+ const started = Date.now();
+ await page.goto(`${origin}/`, {waitUntil: 'load', timeout: 10_000});
+ const elapsed = Date.now() - started;
+ const image = await page.evaluate(() => {
+ const element = document.getElementById('photo');
+ return {complete: element.complete, width: element.naturalWidth};
+ });
+ expect(elapsed).toBeLessThan(5_000);
+ expect(image).toEqual({complete: true, width: 400});
+ } finally {
+ await browser.close();
+ }
+ }, 30_000);
+
+ it('without the route, the same page waits on the unreachable host', async () => {
+ const browser = await launch();
+ try {
+ const page = await (await browser.newContext()).newPage();
+ await expect(
+ page.goto(`${origin}/`, {waitUntil: 'load', timeout: 3_000}),
+ ).rejects.toThrow(/Timeout/);
+ } finally {
+ await browser.close();
+ }
+ }, 30_000);
+});