An open source design system that's fully customizable and agent ready
TypeScript
fix(ci): prime the CDN assets a starter page needs before the browser asks (#7821)
Aashish Mahatoc37d716cf053
diff --git a/.github/scripts/cdn-template-smoke-test.mjs b/.github/scripts/cdn-template-smoke-test.mjsindex c2c2605e0c..107ea5bc77 100644--- a/.github/scripts/cdn-template-smoke-test.mjs+++ b/.github/scripts/cdn-template-smoke-test.mjs@@ -29,6 +29,7 @@ import * as http from 'node:http';import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath} from 'node:url';+import {pageAssetUrls, primeCdnAssets} from './lib/cdn-asset-priming.mjs';import {resolvePublishedCdnVersion} from './lib/cdn-version.mjs';const ROOT = path.resolve(@@ -95,7 +96,49 @@ if (rendered !== pinned) {);}-// ── 3. Serve it, so the page loads the way a deployed one would ──────────────+// ── 3. Prime the CDN, so the browser's requests hit a built asset ───────────+// Both CDNs build a package on the first request that reaches them for it, and a+// request that arrives mid-build is answered with an error document that is then+// cached. A page pinned to a version published minutes ago therefore loads its+// CSS as `text/plain`, which Chromium rejects as an opaque response+// (net::ERR_BLOCKED_BY_ORB) and `networkidle` never settles on. Asking for the+// same URLs over plain HTTP starts and finishes the build first, and turns the+// remaining case into a line that names the asset instead of a navigation+// timeout at the end of a 17-minute run.+const PRIME_DEADLINE_MS = 120_000;+const assets = pageAssetUrls(fs.readFileSync(pagePath, 'utf8'));+const {cold} = await primeCdnAssets(assets, {deadlineMs: PRIME_DEADLINE_MS});+if (cold.length > 0) {+ fail(+ `${cold.length} page asset(s) did not serve within ${PRIME_DEADLINE_MS / 1000}s`,+ [+ ' Every URL below is one the starter page requests, so the page cannot render',+ ' without it. The text after :: is what the last request observed, and it',+ ' takes one of three shapes.',+ '',+ ' HTTP <status> with a sentence after it: the CDN answered and its own words',+ ' name what it could not find — jsDelivr separates the file from the release',+ ' version from the package, and esm.sh words a missing release its own way.',+ ' A release published minutes ago can still be building at that edge, so weigh',+ ' the sentence against the version this run resolved before reading it as a',+ ' URL a change broke.',+ '',+ ' HTTP <status> with nothing after it: it answered, and the error document did',+ ' not read, so the number is all there is to report.',+ '',+ ' An error name, with the transport reason in parentheses when there is one',+ ' (TypeError (ECONNREFUSED), or a bare TimeoutError when the request hung):',+ ' nobody answered at all, so the asset may be fine and the DNS, the route or',+ ' the CDN itself is the problem.',+ '',+ ...cold.map(({url, reason}) => ` ${url} :: ${reason}`),+ ].join('\n'),+ );+ fs.rmSync(tmpDir, {recursive: true, force: true});+ process.exit(1);+}++// ── 4. Serve it, so the page loads the way a deployed one would ─────────────const server = http.createServer((req, res) => {const body = fs.readFileSync(pagePath);res.writeHead(200, {'content-type': 'text/html; charset=utf-8'});@@ -139,7 +182,7 @@ async function render() {}}-// ── 4. Render, retrying once so a blip at a CDN is not a red build ───────────+// ── 5. Render, retrying once so a blip at a CDN is not a red build ───────────let result;for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {result = await render();@@ -153,7 +196,7 @@ for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {}server.close();-// ── 5. Report ────────────────────────────────────────────────────────────────+// ── 6. Report ────────────────────────────────────────────────────────────────console.log(`\n${PAGE} @ ${rendered}`);for (const [label, entries] of [['console error', result.consoleErrors],diff --git a/.github/scripts/lib/cdn-asset-priming.mjs b/.github/scripts/lib/cdn-asset-priming.mjsnew file mode 100644index 0000000000..8cda0a89c8--- /dev/null+++ b/.github/scripts/lib/cdn-asset-priming.mjs@@ -0,0 +1,264 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Prime the CDN assets a starter page asks for, before a browser does.+ *+ * Both CDNs the starter page uses build a package on the first request that+ * reaches them for it, and a request that arrives while that build is running is+ * answered with an error document. For CSS that is the worst case: Chromium+ * refuses a stylesheet served as `text/plain` (`net::ERR_BLOCKED_BY_ORB`), the+ * page never goes idle, and a smoke test that launches a browser sees only a+ * navigation timeout — minutes later, on a lane every contributor's pull+ * request runs, with nothing in the output naming the cause.+ *+ * A plain `fetch` starts the same build and keeps polling it, so the page's own+ * asset URLs are requested here first, and the ones that still do not serve are+ * reported by URL with what the CDN answered — a status alone cannot tell an+ * unbuilt version apart from a path that does not exist in it.+ */++/** True for an answer that means the asset is there: 2xx, or a redirect to it. */+function isServable(status) {+ return status >= 200 && status < 400;+}++/** Absolute http(s) URLs only; a relative or protocol-relative link is not ours to prime. */+function isAbsoluteHttp(value) {+ return /^https?:\/\//i.test(value ?? '');+}++/**+ * `rel` is a set of space-separated tokens, and the ones that make the browser+ * fetch a file while loading the page are these. Everything else a `<link>` can+ * carry — `icon`, `manifest`, `canonical`, `prefetch`, `preconnect` — names a+ * resource the page load does not request, so priming it would report a+ * perfectly good starter page as broken over a file nobody asked for.+ */+const LOAD_TIME_RELS = new Set(['stylesheet', 'modulepreload', 'preload']);++/**+ * Every URL the page itself fetches, in document order and deduplicated.+ *+ * Only load-time requests: `stylesheet`/`modulepreload`/`preload` links, script+ * `src`s, and the import map's module entries — both the top-level `imports` and+ * the targets nested under `scopes`.+ *+ * @param {string} html the scaffolded page+ * @returns {string[]}+ */+export function pageAssetUrls(html) {+ const urls = [];++ for (const tag of html.match(/<link\b[^>]*>/gi) ?? []) {+ const rel = /\brel="([^"]*)"/i.exec(tag)?.[1] ?? '';+ if (!rel.split(/\s+/).some(token => LOAD_TIME_RELS.has(token))) continue;+ const href = /\bhref="([^"]*)"/i.exec(tag)?.[1];+ if (isAbsoluteHttp(href)) urls.push(href);+ }++ for (const tag of html.match(/<script\b[^>]*\bsrc="[^"]*"[^>]*>/gi) ?? []) {+ const src = /\bsrc="([^"]*)"/i.exec(tag)?.[1];+ if (isAbsoluteHttp(src)) urls.push(src);+ }++ for (const block of html.match(+ /<script\b[^>]*type="importmap"[^>]*>([\s\S]*?)<\/script>/gi,+ ) ?? []) {+ const json = />([\s\S]*?)<\/script>/i.exec(block)?.[1];+ let map;+ try {+ map = JSON.parse(json ?? '');+ } catch {+ // The browser will report a malformed import map far better than this+ // probe can, and priming is only a precondition for that report.+ continue;+ }+ // `scopes` maps each scope prefix to its own specifier→URL object, so its+ // values are objects rather than URLs: flatten that one level to reach the+ // targets. Spreading it beside `imports` collected nothing and let a scope+ // prefix silently overwrite an equally named top-level specifier.+ const targets = [+ ...Object.values(map?.imports ?? {}),+ ...Object.values(map?.scopes ?? {}).flatMap(scope =>+ Object.values(scope ?? {}),+ ),+ ];+ for (const target of targets) {+ if (isAbsoluteHttp(target)) urls.push(target);+ }+ }++ return [...new Set(urls)];+}++/**+ * What a failed request actually was. `undici` reports every transport failure+ * as `TypeError: fetch failed` and puts the real reason one level down on+ * `error.cause` — as a `code` (`UND_ERR_CONNECT_TIMEOUT`, `ECONNREFUSED`,+ * `ENOTFOUND`, …) or, when the request never reached a socket, as a message like+ * `bad port`. The wrapper name alone sends a contributor to a generic error.+ *+ * @param {unknown} error+ * @returns {string}+ */+function requestFailureLabel(error) {+ const name = error instanceof Error ? error.name : String(error);+ const cause = error?.cause;+ if (!cause) return name;+ const detail = cause.code ?? cause.message;+ return detail ? `${name} (${String(detail).trim()})` : name;+}++/**+ * How far into an error document the probe reads. A CDN refusal is one short+ * sentence, so this is well past what it says, while still bounding what a+ * server that answers with a full page can cost a failing asset check.+ */+const ERROR_BODY_MAX_CHARS = 400;++/**+ * The shape `primeCdnAssets` reads out of whatever answered its request.+ *+ * @typedef {{status: number, body?: unknown, text?: () => Promise<string>}} ResponseLike+ */++/**+ * The start of an error document, read without pulling the whole body.+ *+ * @param {ResponseLike} response+ * @returns {Promise<string|null>} null when it carries nothing readable+ */+async function readErrorBody(response) {+ const stream = response?.body;+ if (typeof stream?.getReader !== 'function') {+ return typeof response?.text === 'function' ? await response.text() : null;+ }+ const reader = stream.getReader();+ const decoder = new TextDecoder();+ let text = '';+ try {+ while (text.length < ERROR_BODY_MAX_CHARS) {+ const {done, value} = await reader.read();+ if (done) break;+ text += decoder.decode(value, {stream: true});+ }+ } finally {+ // Nothing wants the rest of the document, and an abandoned body keeps the+ // connection open past the round that read it.+ await reader.cancel().catch(() => {});+ }+ return text;+}++/**+ * What the CDN said, as one line: markup removed, whitespace collapsed, the+ * first remaining line kept and bounded.+ *+ * @param {string|null} body+ * @returns {string|null} null when the document says nothing readable+ */+function describeErrorBody(body) {+ if (!body) return null;+ const withoutMarkup = body+ .replace(/<!--[\s\S]*?-->/g, '')+ .replace(/<[^>]*>/g, ' ');+ for (const line of withoutMarkup.split(/\r?\n/)) {+ const summary = line.replace(/\s+/g, ' ').trim();+ if (summary === '') continue;+ return summary.length > ERROR_BODY_MAX_CHARS+ ? `${summary.slice(0, ERROR_BODY_MAX_CHARS - 1).trimEnd()}…`+ : summary;+ }+ return null;+}++/**+ * Why an answered request still did not serve the asset.+ *+ * Every refusal these CDNs make is a `404` with a sentence that names the thing+ * it could not find, so the status on its own reports three different failures+ * as one string. The document is a bonus on top of the status though: a body+ * that will not read must never cost the report of the status that did answer.+ *+ * @param {ResponseLike} response+ * @returns {Promise<string>}+ */+async function nonServableReason(response) {+ const status = `HTTP ${response?.status}`;+ let said;+ try {+ said = describeErrorBody(await readErrorBody(response));+ } catch {+ return status;+ }+ return said === null ? status : `${status} — ${said}`;+}++/**+ * Request each URL until it serves, sharing one deadline across all of them.+ *+ * The first round asks for everything once, which is what starts a cold build;+ * only URLs that did not serve are asked again, so a page whose assets are+ * already cached costs one round trip per asset.+ *+ * @param {string[]} urls+ * @param {object} [options]+ * @param {(url: string, init: object) => Promise<ResponseLike>} [options.fetchImpl]+ * @param {number} [options.deadlineMs] total budget for every retry round+ * @param {number} [options.retryDelayMs] pause between rounds+ * @param {number} [options.probeTimeoutMs] per-request timeout, so a hanging CDN cannot spend the budget+ * @param {() => number} [options.now]+ * @param {(ms: number) => Promise<void>} [options.sleep]+ * @returns {Promise<{ready: string[], cold: Array<{url: string, reason: string}>}>}+ */+export async function primeCdnAssets(+ urls,+ {+ fetchImpl = globalThis.fetch,+ deadlineMs = 120_000,+ retryDelayMs = 5_000,+ probeTimeoutMs = 10_000,+ now = Date.now,+ sleep = ms => new Promise(resolve => setTimeout(resolve, ms)),+ } = {},+) {+ const ready = new Set();+ const reasons = new Map();+ let pending = [...new Set(urls)];+ const deadline = now() + deadlineMs;++ while (pending.length > 0) {+ const stillPending = [];+ await Promise.all(+ pending.map(async url => {+ let reason;+ try {+ const response = await fetchImpl(url, {+ redirect: 'follow',+ signal: AbortSignal.timeout(probeTimeoutMs),+ });+ reason = isServable(response.status)+ ? null+ : await nonServableReason(response);+ } catch (error) {+ reason = requestFailureLabel(error);+ }+ if (reason === null) {+ ready.add(url);+ } else {+ reasons.set(url, reason);+ stillPending.push(url);+ }+ }),+ );+ pending = stillPending;+ if (pending.length === 0) break;+ if (now() >= deadline) break;+ await sleep(retryDelayMs);+ }++ return {+ ready: [...ready],+ cold: pending.map(url => ({url, reason: reasons.get(url) ?? 'unknown'})),+ };+}diff --git a/.github/scripts/lib/cdn-asset-priming.test.mjs b/.github/scripts/lib/cdn-asset-priming.test.mjsnew file mode 100644index 0000000000..7903f2267b--- /dev/null+++ b/.github/scripts/lib/cdn-asset-priming.test.mjs@@ -0,0 +1,557 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it, vi} from 'vitest';+import {pageAssetUrls, primeCdnAssets} from './cdn-asset-priming.mjs';++const PAGE = `+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/src/reset.css" />+ <link rel="stylesheet" href="/local.css" />+ <script src="https://esm.sh/@astryxdesign/[email protected]" type="module"></script>+ <script type="importmap">+ {"imports": {+ "react": "https://esm.sh/[email protected]",+ "core": "https://esm.sh/@astryxdesign/[email protected]?external=react,react-dom",+ "local": "./local.js"+ }}+ </script>+ <p>Docs: https://astryx.dev/docs/button</p>+`;++describe('pageAssetUrls', () => {+ it('collects what the page fetches, in document order', () => {+ expect(pageAssetUrls(PAGE)).toEqual([+ 'https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/src/reset.css',+ 'https://esm.sh/@astryxdesign/[email protected]',+ 'https://esm.sh/[email protected]',+ 'https://esm.sh/@astryxdesign/[email protected]?external=react,react-dom',+ ]);+ });++ it('leaves out preconnect hints, relative paths and links in prose', () => {+ const urls = pageAssetUrls(PAGE);+ expect(urls).not.toContain('https://fonts.googleapis.com');+ expect(urls).not.toContain('https://fonts.gstatic.com');+ expect(urls).not.toContain('https://astryx.dev/docs/button');+ expect(urls).not.toContain('./local.js');+ });++ it('names a URL once when the page asks for it twice', () => {+ const resetCss =+ 'https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/src/reset.css';+ const twice = `${PAGE}\n<link rel="stylesheet" href="${resetCss}" />`;+ expect(pageAssetUrls(twice).filter(u => u === resetCss)).toHaveLength(1);+ expect(pageAssetUrls(twice)).toHaveLength(pageAssetUrls(PAGE).length);+ });++ it('survives an import map that is not JSON', () => {+ const broken = PAGE.replace(/"imports": \{[\s\S]*?\}\}/, 'not json');+ expect(() => pageAssetUrls(broken)).not.toThrow();+ expect(pageAssetUrls(broken)).toContain(+ 'https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/src/reset.css',+ );+ });++ it('collects a scoped import-map target, not only the top-level ones', () => {+ const scoped = `+ <script type="importmap">+ {"imports": {"react": "https://esm.sh/[email protected]"},+ "scopes": {"./app/": {"react": "https://esm.sh/[email protected]",+ "lodash": "https://esm.sh/[email protected]"}}}+ </script>+ `;+ const urls = pageAssetUrls(scoped);+ expect(urls).toContain('https://esm.sh/[email protected]');+ expect(urls).toContain('https://esm.sh/[email protected]');+ expect(urls).toContain('https://esm.sh/[email protected]');+ // A scope prefix is a key, never a value, and must not displace the+ // top-level entry that happens to share its specifier name.+ expect(urls).not.toContain('./app/');+ });++ it('tolerates a scope whose map is missing or malformed', () => {+ expect(+ pageAssetUrls(+ '<script type="importmap">{"scopes": {"./a/": null, "./b/": {"x": 42}}}</script>',+ ),+ ).toEqual([]);+ });++ it('primes only the links a page load actually fetches', () => {+ const page = `+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/dist/astryx.css" />+ <link rel="modulepreload" href="https://esm.sh/[email protected]" />+ <link rel="preload" as="script" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/htm.js" />+ <link rel="preload stylesheet" as="style" href="https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/dist/theme.css" />+ <link rel="icon" href="https://astryx.dev/favicon.ico" />+ <link rel="manifest" href="https://astryx.dev/site.webmanifest" />+ <link rel="canonical" href="https://astryx.dev/docs/button" />+ <link rel="prefetch" href="https://astryx.dev/docs/input" />+ `;+ const urls = pageAssetUrls(page);+ expect(urls).toEqual([+ 'https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/dist/astryx.css',+ 'https://esm.sh/[email protected]',+ // A bare `rel="preload"` is fetched during the load like any other asset,+ // and a multi-token `rel` matches on any load-time token it carries.+ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/htm.js',+ 'https://cdn.jsdelivr.net/npm/@astryxdesign/[email protected]/dist/theme.css',+ ]);+ // A 404 on any of these is not a broken starter page: the page never asks+ // for them while it loads.+ expect(urls).not.toContain('https://astryx.dev/favicon.ico');+ expect(urls).not.toContain('https://astryx.dev/site.webmanifest');+ expect(urls).not.toContain('https://astryx.dev/docs/button');+ expect(urls).not.toContain('https://astryx.dev/docs/input');+ });+});++/**+ * A fetch that answers from a script, one entry per call, and keeps answering+ * with its last entry afterwards. `calls` records which URL each answer went to.+ * A number answers with a bare status — no body to read, the way a stubbed+ * transport behaves — and `{status, …}` answers with whatever the response+ * object is given.+ */+function scriptedFetch(results) {+ const calls = [];+ return {+ calls,+ fetchImpl: async url => {+ calls.push(url);+ const result = results[Math.min(calls.length - 1, results.length - 1)];+ if (result instanceof Error) throw result;+ return typeof result === 'number' ? {status: result} : result;+ },+ };+}++/** A response whose body is text, as both CDNs serve an error document. */+function textResponse(status, body) {+ return {status, text: async () => body};+}++/**+ * A streamed body, chunked and watched, so a test can see how far the probe read+ * and whether it gave the rest of the document back.+ */+function streamBody(text, chunkSize = 24) {+ const encoder = new TextEncoder();+ const chunks = [];+ for (let i = 0; i < text.length; i += chunkSize) {+ chunks.push(encoder.encode(text.slice(i, i + chunkSize)));+ }+ let reads = 0;+ const state = {reads: () => reads, cancelled: false};+ return {+ state,+ getReader() {+ return {+ async read() {+ const chunk = chunks[reads];+ reads += 1;+ return chunk === undefined+ ? {done: true, value: undefined}+ : {done: false, value: chunk};+ },+ async cancel() {+ state.cancelled = true;+ },+ };+ },+ };+}++describe('primeCdnAssets', () => {+ it('returns every asset as ready when the CDN already serves it', async () => {+ const {calls, fetchImpl} = scriptedFetch([200]);+ const sleep = vi.fn();+ const res = await primeCdnAssets(['a.css', 'b.css'], {+ fetchImpl,+ sleep,+ now: () => 0,+ deadlineMs: 1_000,+ });+ expect(res).toEqual({ready: ['a.css', 'b.css'], cold: []});+ expect(calls).toEqual(['a.css', 'b.css']);+ expect(sleep).not.toHaveBeenCalled();+ });++ it('retries only what did not serve, and reports it once it does', async () => {+ const {calls, fetchImpl} = scriptedFetch([404, 200, 200]);+ const sleep = vi.fn();+ const res = await primeCdnAssets(['building.css', 'served.css'], {+ fetchImpl,+ sleep,+ now: () => 0,+ deadlineMs: 1_000,+ });+ expect(calls).toEqual(['building.css', 'served.css', 'building.css']);+ expect(res.cold).toEqual([]);+ expect(res.ready.sort()).toEqual(['building.css', 'served.css']);+ expect(sleep).toHaveBeenCalledOnce();+ });++ it('reports an asset the CDN never serves, with the answer it gave', async () => {+ const {calls, fetchImpl} = scriptedFetch([404]);+ const res = await primeCdnAssets(['still-building.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(calls).toEqual(['still-building.css']);+ expect(res.ready).toEqual([]);+ expect(res.cold).toEqual([{url: 'still-building.css', reason: 'HTTP 404'}]);+ });++ it('names a request that fails outright rather than answering', async () => {+ const timeout = new Error('The operation was aborted due to timeout');+ timeout.name = 'TimeoutError';+ const {fetchImpl} = scriptedFetch([timeout]);+ const res = await primeCdnAssets(['hanging.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold).toEqual([{url: 'hanging.css', reason: 'TimeoutError'}]);+ });++ it('carries a socket-level cause into the reason, not just the wrapper name', async () => {+ // undici reports every transport failure as `TypeError: fetch failed` and+ // puts the real code on error.cause — without it every network problem+ // reads as the same one word.+ const wrapped = new TypeError('fetch failed');+ wrapped.cause = Object.assign(new Error('connect ETIMEDOUT'), {+ code: 'UND_ERR_CONNECT_TIMEOUT',+ });+ const {fetchImpl} = scriptedFetch([wrapped]);+ const res = await primeCdnAssets(['unreachable.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold).toEqual([+ {+ url: 'unreachable.css',+ reason: 'TypeError (UND_ERR_CONNECT_TIMEOUT)',+ },+ ]);+ });++ it('treats a redirect as served and a server error as not', async () => {+ const {fetchImpl} = scriptedFetch([302, 500]);+ const res = await primeCdnAssets(['redirected.js', 'broken.js'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.ready).toEqual(['redirected.js']);+ expect(res.cold).toEqual([{url: 'broken.js', reason: 'HTTP 500'}]);+ });++ it('stops retrying once the deadline is spent', async () => {+ const {calls, fetchImpl} = scriptedFetch([404]);+ let elapsed = 0;+ const res = await primeCdnAssets(['a.css', 'b.css'], {+ fetchImpl,+ sleep: async () => {+ elapsed += 5_000;+ },+ now: () => elapsed,+ deadlineMs: 5_000,+ });+ expect(calls).toEqual(['a.css', 'b.css', 'a.css', 'b.css']);+ expect(res.cold.map(entry => entry.url)).toEqual(['a.css', 'b.css']);+ });++ it('deduplicates a URL the page names twice', async () => {+ const {calls, fetchImpl} = scriptedFetch([200]);+ const res = await primeCdnAssets(['same.css', 'same.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 1_000,+ });+ expect(calls).toEqual(['same.css']);+ expect(res.ready).toEqual(['same.css']);+ });++ it('names a cause that has a message but no code', async () => {+ // Measured on Node 24: `fetch('http://127.0.0.1:1/a.css')` rejects with a+ // `TypeError: fetch failed` whose cause is a bare `Error: bad port`, with no+ // `code` anywhere, so a code-only label printed the wrapper name alone.+ const wrapped = new TypeError('fetch failed');+ wrapped.cause = new Error('bad port');+ const {fetchImpl} = scriptedFetch([wrapped]);+ const res = await primeCdnAssets(['bad-port.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold).toEqual([+ {url: 'bad-port.css', reason: 'TypeError (bad port)'},+ ]);+ });++ it('carries the CDN sentence for a missing version into the reason', async () => {+ // Verbatim from jsDelivr: `curl https://cdn.jsdelivr.net/npm/+ // @astryxdesign/[email protected]/package.json` answers text/plain with this.+ const {fetchImpl} = scriptedFetch([+ textResponse(404, "Couldn't find the requested release version 9.9.9.\n"),+ ]);+ const res = await primeCdnAssets(['core.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold).toEqual([+ {+ url: 'core.css',+ reason: "HTTP 404 — Couldn't find the requested release version 9.9.9.",+ },+ ]);+ });++ it('separates the refusals that all answer 404', async () => {+ // Three real answers, each measured against the live CDN, and the status+ // alone reported all three as the same `HTTP 404`. A contributor has to be+ // able to tell them apart: only one of them is a file this repo broke.+ const {fetchImpl} = scriptedFetch([+ textResponse(+ 404,+ "Couldn't find the requested file /dist/nope.css in @astryxdesign/core.\n",+ ),+ textResponse(+ 404,+ 'Failed to fetch version info for @astryxdesign/no-such-zz.\n',+ ),+ // esm.sh words a missing release differently again.+ textResponse(404, "version 9.9.9 of 'react' not found\n"),+ ]);+ const res = await primeCdnAssets(+ ['bad-path.css', 'bad-package.js', 'bad-version.js'],+ {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ },+ );+ expect(Object.fromEntries(res.cold.map(e => [e.url, e.reason]))).toEqual({+ 'bad-path.css':+ "HTTP 404 — Couldn't find the requested file /dist/nope.css in @astryxdesign/core.",+ 'bad-package.js':+ 'HTTP 404 — Failed to fetch version info for @astryxdesign/no-such-zz.',+ 'bad-version.js': "HTTP 404 — version 9.9.9 of 'react' not found",+ });+ });++ it('reads a streamed body and gives the rest of the document back', async () => {+ const body = streamBody('Sorry, the requested resource does not exist.');+ const {fetchImpl} = scriptedFetch([{status: 404, body}]);+ const res = await primeCdnAssets(['a.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold[0].reason).toBe(+ 'HTTP 404 — Sorry, the requested resource does not exist.',+ );+ // An abandoned body holds the connection, and the next round would pay for it.+ expect(body.state.cancelled).toBe(true);+ });++ it('bounds the read of a document that is not an error message', async () => {+ const body = streamBody('<!doctype html><html><body>' + 'x'.repeat(9_000));+ const {fetchImpl} = scriptedFetch([{status: 500, body}]);+ const res = await primeCdnAssets(['a.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold[0].reason.length).toBeLessThan(440);+ // Stops at the cap instead of draining 9 KB it will never print.+ expect(body.state.reads()).toBeLessThan(20);+ expect(body.state.cancelled).toBe(true);+ });++ it('bounds the summary when the document arrived in one piece', async () => {+ // The streamed read bounds itself where it reads; a response that only+ // offers `text()` has no such place, so the printed line is what gets cut.+ const {fetchImpl} = scriptedFetch([textResponse(500, 'x'.repeat(9_000))]);+ const res = await primeCdnAssets(['a.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold[0].reason).toMatch(/^HTTP 500 — x{399}…$/);+ expect(res.cold[0].reason.length).toBeLessThan(420);+ });++ it('reports the first readable line of an HTML error page', async () => {+ const {fetchImpl} = scriptedFetch([+ textResponse(+ 404,+ '<html>\n <body>\n <h1>Not Found</h1>\n <p>No package by that name.</p>\n </body>\n</html>\n',+ ),+ ]);+ const res = await primeCdnAssets(['a.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold[0].reason).toBe('HTTP 404 — Not Found');+ });++ it('skips a blank leading line to reach the message', async () => {+ const {fetchImpl} = scriptedFetch([+ textResponse(+ 404,+ '\n\n Package @astryxdesign/[email protected] is still being built.\n Try again shortly.\n',+ ),+ ]);+ const res = await primeCdnAssets(['a.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold[0].reason).toBe(+ 'HTTP 404 — Package @astryxdesign/[email protected] is still being built.',+ );+ });++ it('reports the status alone when the body says nothing readable', async () => {+ const {fetchImpl} = scriptedFetch([+ textResponse(404, ''),+ textResponse(404, '\n \n \n'),+ textResponse(404, '<div></div>'),+ ]);+ const res = await primeCdnAssets(['a.css', 'b.css', 'c.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(res.cold.map(entry => entry.reason)).toEqual([+ 'HTTP 404',+ 'HTTP 404',+ 'HTTP 404',+ ]);+ });++ it('keeps the status when the body will not read', async () => {+ // A transport that answers the headers and then drops the body must still+ // report the answer, not the read failure that came after it.+ const {fetchImpl} = scriptedFetch([+ {+ status: 404,+ text: async () => {+ throw new TypeError('terminated');+ },+ },+ {+ status: 503,+ body: {+ getReader() {+ return {+ read: async () => {+ throw new Error('stream reset');+ },+ cancel: async () => {},+ };+ },+ },+ },+ ]);+ const res = await primeCdnAssets(['dropped.css', 'reset.css'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ expect(Object.fromEntries(res.cold.map(e => [e.url, e.reason]))).toEqual({+ 'dropped.css': 'HTTP 404',+ 'reset.css': 'HTTP 503',+ });+ });++ it('does not read the body of an asset that serves', async () => {+ let textReads = 0;+ const {fetchImpl} = scriptedFetch([+ {status: 200, text: async () => ((textReads += 1), 'asset bytes')},+ {status: 302, text: async () => ((textReads += 1), 'redirecting')},+ ]);+ const res = await primeCdnAssets(['a.css', 'b.js'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 1_000,+ });+ expect(res.ready.sort()).toEqual(['a.css', 'b.js']);+ expect(res.cold).toEqual([]);+ expect(textReads).toBe(0);+ });+});++// The smoke test prints each cold asset as `<url> :: <reason>` under a legend+// that explains the three shapes a reason can take+// (`.github/scripts/cdn-template-smoke-test.mjs`, the `fail(...)` call after+// `primeCdnAssets`). The legend is only true while `primeCdnAssets` produces+// exactly those shapes, so the promise is pinned here rather than left to a+// reader who cannot tell a status from a socket error.+describe('the shapes the smoke test legend describes', () => {+ const probe = results => {+ const {fetchImpl} = scriptedFetch(results);+ return primeCdnAssets(['a', 'b', 'c'], {+ fetchImpl,+ sleep: async () => {},+ now: () => 0,+ deadlineMs: 0,+ });+ };++ it('answers every asset with one of the three shapes', async () => {+ const {cold} = await probe([+ textResponse(404, "Couldn't find the requested release version 9.9.9.\n"),+ textResponse(500, ''),+ new Error('boom'),+ ]);+ // Keyed by URL, because the assets settle in whatever order they fail.+ expect(Object.fromEntries(cold.map(e => [e.url, e.reason]))).toEqual({+ // 1. status + the CDN's own sentence+ a: "HTTP 404 — Couldn't find the requested release version 9.9.9.",+ // 2. status alone+ b: 'HTTP 500',+ // 3. a bare error name+ c: 'Error',+ });+ });++ it('keeps the shapes distinguishable from each other', () => {+ // What the legend asserts, stated as the test: a status means the CDN+ // answered, a sentence after it names the thing it could not find, and the+ // absence of a status means no answer arrived at all.+ const withSentence =+ "HTTP 404 — Couldn't find the requested release version 9.9.9.";+ const statusOnly = 'HTTP 500';+ const noAnswer = 'TypeError (UND_ERR_CONNECT_TIMEOUT)';+ for (const answered of [withSentence, statusOnly]) {+ expect(answered).toMatch(/^HTTP \d{3}( — .+)?$/);+ }+ expect(noAnswer).not.toMatch(/^HTTP /);+ expect(withSentence.split(' — ')[1].length).toBeGreaterThan(0);+ expect(statusOnly).not.toContain(' — ');+ });+});