From 64b5040e37d21d453eb8314cebb082e570db3af4 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Thu, 3 Dec 2026 17:46:11 -0500 Subject: [PATCH 1/3] Run CI's e2e suite against the production build A build job builds the site once and uploads .vercel/output. Each browser's job serves it with scripts/serve-vercel-output.ts, which follows the output's config.json routes, runs the on-demand _render function, and resizes /_vercel/image. The dev server's slow paths are gone: the router's hidden-frame wait for client-only components and on-demand image resizing. Locally the suite keeps the dev server; E2E_PRODUCTION=1 serves a build. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 42 +++++ CLAUDE.md | 5 + playwright.config.ts | 11 +- scripts/serve-vercel-output.ts | 273 +++++++++++++++++++++++++++++++++ tests/e2e/index.spec.ts | 14 +- tests/e2e/shell.spec.ts | 3 +- 6 files changed, 341 insertions(+), 7 deletions(-) create mode 100644 scripts/serve-vercel-output.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d1660df..16bf85c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,8 +55,45 @@ jobs: - name: Run unit tests run: pnpm test:unit run + # One production build, which every e2e job serves the way Vercel would. + build: + timeout-minutes: 15 + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: pnpm/action-setup@v4 + - name: Get pnpm store directory + shell: bash + run: echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + - uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Install dependencies + run: pnpm install + - name: Build the site + run: pnpm exec astro build + env: + ASTRO_DB_REMOTE_URL: ${{ secrets.ASTRO_DB_REMOTE_URL }} + ASTRO_DB_APP_TOKEN: ${{ secrets.ASTRO_DB_APP_TOKEN }} + # A tarball keeps the function bundle's node_modules symlinks. + - name: Pack the build output + run: tar -czf vercel-output.tgz .vercel/output + - uses: actions/upload-artifact@v4 + with: + name: vercel-output + path: vercel-output.tgz + retention-days: 1 + e2e: name: e2e (${{ matrix.project }}) + needs: build timeout-minutes: 30 runs-on: ubuntu-24.04 strategy: @@ -97,6 +134,11 @@ jobs: - name: Install Playwright system dependencies if: steps.playwright-cache.outputs.cache-hit == 'true' run: pnpm exec playwright install-deps ${{ matrix.project }} + - uses: actions/download-artifact@v4 + with: + name: vercel-output + - name: Unpack the build output + run: tar -xzf vercel-output.tgz - name: Run Playwright tests run: pnpm exec playwright test --project=${{ matrix.project }} env: diff --git a/CLAUDE.md b/CLAUDE.md index 90b28852..67abd254 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,6 +26,11 @@ Whatnot podcast). - **E2E tests only:** `pnpm test:e2e` (Playwright, auto-starts dev server) - **E2E on another port:** `E2E_PORT=4340 pnpm test:e2e` (default 4321, where outside CI Playwright reuses whatever server is running; use a free port in a worktree) +- **E2E against the production build:** `pnpm exec astro build`, then + `E2E_PRODUCTION=1 pnpm test:e2e`. CI always does this: a build job uploads + `.vercel/output`, and each browser's job serves it with + `scripts/serve-vercel-output.ts`, which follows the output's `config.json` + routes, runs the on-demand `_render` function, and resizes `/_vercel/image` - **Seed remote DB:** `pnpm db:seed` - **Push schema to DB:** `pnpm db:push` - **Drizzle Studio:** `pnpm db:studio` diff --git a/playwright.config.ts b/playwright.config.ts index 59c186d2..81f55954 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -2,6 +2,10 @@ import { defineConfig, devices } from '@playwright/test'; const port = process.env.E2E_PORT || '4321'; const baseURL = `http://localhost:${port}`; +/* CI tests the production build, which a build job leaves in .vercel/output. + Locally the dev server is quicker to iterate against; E2E_PRODUCTION=1 + serves an existing build instead. */ +const production = !!(process.env.CI || process.env.E2E_PRODUCTION); /** * Read environment variables from file. @@ -21,7 +25,7 @@ export default defineConfig({ /* Retry on CI only */ retries: process.env.CI ? 2 : 0, /* CI runs one browser per job; two workers fit its four cores beside the - dev server. */ + server. */ workers: process.env.CI ? 2 : undefined, /* Reporter to use. See https://playwright.dev/docs/test-reporters */ reporter: 'html', @@ -72,9 +76,10 @@ export default defineConfig({ // }, ], - /* Run your local dev server before starting the tests */ webServer: { - command: `pnpm exec astro dev --port ${port}`, + command: production + ? `pnpm exec tsx scripts/serve-vercel-output.ts --port ${port}` + : `pnpm exec astro dev --port ${port}`, url: baseURL, reuseExistingServer: !process.env.CI, timeout: 180 * 1000 diff --git a/scripts/serve-vercel-output.ts b/scripts/serve-vercel-output.ts new file mode 100644 index 00000000..c14237ec --- /dev/null +++ b/scripts/serve-vercel-output.ts @@ -0,0 +1,273 @@ +/** + * Serves `.vercel/output` the way Vercel does, closely enough for the e2e + * suite: the routes in `config.json` (redirects, `Accept: text/markdown` + * negotiation, the on-demand `_render` function) over the static files, plus + * `/_vercel/image`. + * + * Usage: pnpm exec astro build && pnpm tsx scripts/serve-vercel-output.ts --port 4321 + */ + +import { createReadStream } from 'node:fs'; +import { readFile, stat } from 'node:fs/promises'; +import { + createServer, + type IncomingMessage, + type ServerResponse +} from 'node:http'; +import { extname, join, normalize, resolve } from 'node:path'; +import { Readable } from 'node:stream'; +import { pathToFileURL } from 'node:url'; +import { parseArgs } from 'node:util'; +import sharp from 'sharp'; + +type Route = + | { handle: 'filesystem' } + | { + src: string; + dest?: string; + headers?: Record; + status?: number; + continue?: boolean; + has?: { type: 'header'; key: string; value: string }[]; + }; + +type Resolution = + | { kind: 'redirect'; status: number; location: string } + | { kind: 'file'; file: string; status: number; headers: Headers } + | { kind: 'function'; headers: Headers }; + +type Handler = { fetch(request: Request): Promise }; + +const { values } = parseArgs({ + options: { port: { type: 'string', default: '4321' } } +}); +const output = resolve('.vercel/output'); +const staticDir = join(output, 'static'); +const config = JSON.parse( + await readFile(join(output, 'config.json'), 'utf8') +) as { routes: Route[] }; +const split = config.routes.findIndex((route) => 'handle' in route); +const beforeFilesystem = config.routes.slice(0, split); +const afterFilesystem = config.routes.slice(split + 1); +const render = ( + (await import( + pathToFileURL(join(output, 'functions/_render.func/dist/server/entry.mjs')) + .href + )) as { default: Handler } +).default; + +const contentTypes: Record = { + '.css': 'text/css; charset=utf-8', + '.html': 'text/html; charset=utf-8', + '.ico': 'image/x-icon', + '.jpeg': 'image/jpeg', + '.jpg': 'image/jpeg', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.md': 'text/markdown; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.txt': 'text/plain; charset=utf-8', + '.webmanifest': 'application/manifest+json', + '.woff2': 'font/woff2', + '.xml': 'application/xml; charset=utf-8' +}; + +function substitute(template: string, match: RegExpExecArray) { + return template.replace(/\$(\d+)/g, (_, index) => match[Number(index)] ?? ''); +} + +function matches( + route: Exclude, + path: string, + request: IncomingMessage +) { + const match = new RegExp(route.src).exec(path); + if (!match) return null; + const satisfied = (route.has ?? []).every(({ key, value }) => { + const header = request.headers[key.toLowerCase()]; + return typeof header === 'string' && new RegExp(`^${value}$`).test(header); + }); + return satisfied ? match : null; +} + +async function staticFile(path: string) { + const file = normalize(join(staticDir, path)); + if (!file.startsWith(staticDir)) return null; + for (const candidate of [file, join(file, 'index.html')]) { + const info = await stat(candidate).catch(() => null); + if (info?.isFile()) return candidate; + } + return null; +} + +async function resolveRoute( + request: IncomingMessage, + pathname: string +): Promise { + const headers = new Headers(); + let path = pathname; + for (const route of beforeFilesystem) { + if ('handle' in route) continue; + const match = matches(route, path, request); + if (!match) continue; + for (const [key, value] of Object.entries(route.headers ?? {})) { + headers.set(key, substitute(value, match)); + } + const location = headers.get('location'); + if (route.status && location) { + return { kind: 'redirect', status: route.status, location }; + } + if (route.dest) path = substitute(route.dest, match); + if (!route.continue) break; + } + + const file = await staticFile(path); + if (file) return { kind: 'file', file, status: 200, headers }; + + for (const route of afterFilesystem) { + if ('handle' in route) continue; + const match = matches(route, path, request); + if (!match || !route.dest) continue; + if (route.dest === '_render') return { kind: 'function', headers }; + const fallback = await staticFile(route.dest); + if (fallback) { + return { + kind: 'file', + file: fallback, + status: route.status ?? 200, + headers + }; + } + } + throw new Error(`No route for ${pathname}`); +} + +const images = new Map>(); + +// The site's own images come as paths, such as `_astro/host.jpg`. +async function source(url: string) { + if (!/^https?:/.test(url)) { + const file = await staticFile(`/${url.replace(/^\//, '')}`); + if (!file) throw new Error(`No static file for ${url}`); + return readFile(file); + } + const upstream = await fetch(url, { signal: AbortSignal.timeout(30_000) }); + if (!upstream.ok) throw new Error(`${upstream.status} fetching ${url}`); + return Buffer.from(await upstream.arrayBuffer()); +} + +async function optimize( + url: string, + width: number, + quality: number, + webp: boolean +) { + const resized = sharp(await source(url)).resize({ + width, + withoutEnlargement: true + }); + return webp + ? { type: 'image/webp', body: await resized.webp({ quality }).toBuffer() } + : { type: 'image/jpeg', body: await resized.jpeg({ quality }).toBuffer() }; +} + +async function image( + request: IncomingMessage, + query: URLSearchParams, + response: ServerResponse +) { + const url = query.get('url'); + if (!url) { + response.writeHead(400).end('Missing url'); + return; + } + const webp = (request.headers.accept ?? '').includes('image/webp'); + const key = `${query}|${webp}`; + let pending = images.get(key); + if (!pending) { + pending = optimize( + url, + Number(query.get('w') ?? 640), + Number(query.get('q') ?? 75), + webp + ); + images.set(key, pending); + pending.catch(() => images.delete(key)); + } + const { type, body } = await pending; + response.writeHead(200, { + 'content-type': type, + 'cache-control': 'public, max-age=3600' + }); + response.end(body); +} + +async function callFunction( + request: IncomingMessage, + response: ServerResponse, + headers: Headers +) { + const hasBody = request.method !== 'GET' && request.method !== 'HEAD'; + const result = await render.fetch( + new Request(`http://${request.headers.host}${request.url}`, { + method: request.method, + headers: Object.entries(request.headers).flatMap(([key, value]) => + value === undefined ? [] : [[key, String(value)] as [string, string]] + ), + ...(hasBody + ? { body: Readable.toWeb(request) as ReadableStream, duplex: 'half' } + : {}) + } as RequestInit) + ); + headers.forEach((value, key) => { + if (!result.headers.has(key)) result.headers.set(key, value); + }); + response.writeHead(result.status, Object.fromEntries(result.headers)); + if (result.body && request.method !== 'HEAD') { + Readable.fromWeb(result.body as never).pipe(response); + } else { + response.end(); + } +} + +async function handle(request: IncomingMessage, response: ServerResponse) { + const url = new URL(request.url ?? '/', 'http://localhost'); + if (url.pathname === '/_vercel/image') { + await image(request, url.searchParams, response); + return; + } + const resolution = await resolveRoute( + request, + decodeURIComponent(url.pathname) + ); + switch (resolution.kind) { + case 'redirect': + response + .writeHead(resolution.status, { location: resolution.location }) + .end(); + return; + case 'function': + await callFunction(request, response, resolution.headers); + return; + case 'file': { + const type = contentTypes[extname(resolution.file)]; + response.writeHead(resolution.status, { + ...Object.fromEntries(resolution.headers), + ...(type ? { 'content-type': type } : {}) + }); + if (request.method === 'HEAD') response.end(); + else createReadStream(resolution.file).pipe(response); + } + } +} + +createServer((request, response) => { + handle(request, response).catch((error: unknown) => { + console.error(request.url, error); + if (!response.headersSent) response.writeHead(502); + response.end(); + }); +}).listen(Number(values.port), () => { + console.log(`Serving ${output} on http://localhost:${values.port}`); +}); diff --git a/tests/e2e/index.spec.ts b/tests/e2e/index.spec.ts index 99db8bb1..2742e720 100644 --- a/tests/e2e/index.spec.ts +++ b/tests/e2e/index.spec.ts @@ -8,6 +8,14 @@ const indexMeta = { 'https://assets.flightcast.com/workspaces/w3c9dshmqkhqsgbaue0txwq5/podcasts/w7bqgc792i30fd43a32uawx0/fx4npv5dbjrucewh4372wfv9.jpg' }; +// The adapter's image endpoint: Vercel's in the build, Astro's under astro dev. +function optimized(src: string, width: number) { + const href = encodeURIComponent(src).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return RegExp( + `^/_(?:vercel/image[?]url|image[?]href)=${href}&w=${width}&q=75$` + ); +} + test('index page has correct meta', async ({ page }) => { await page.goto('/'); @@ -25,13 +33,13 @@ test('index page has correct meta', async ({ page }) => { const ogImage = page.locator('meta[property="og:image"]'); await expect(ogImage).toHaveAttribute( 'content', - `/_image?href=${encodeURIComponent(indexMeta.image)}&w=640&q=75` + optimized(indexMeta.image, 640) ); const twitterImage = page.locator('meta[name="twitter:image:src"]'); await expect(twitterImage).toHaveAttribute( 'content', - `/_image?href=${encodeURIComponent(indexMeta.image)}&w=640&q=75` + optimized(indexMeta.image, 640) ); const firstEpisodeThumbnail = page.locator( @@ -39,6 +47,6 @@ test('index page has correct meta', async ({ page }) => { ); await expect(firstEpisodeThumbnail).toHaveAttribute( 'src', - RegExp('^/_image[?]href=.*w=320&q=75$') + RegExp('^/_(?:vercel/image[?]url|image[?]href)=.*&w=320&q=75$') ); }); diff --git a/tests/e2e/shell.spec.ts b/tests/e2e/shell.spec.ts index a3458270..81e7bc7b 100644 --- a/tests/e2e/shell.spec.ts +++ b/tests/e2e/shell.spec.ts @@ -828,7 +828,8 @@ test.describe('search palette', () => { // shortcut has been pressed. let loaded!: () => void; const held = new Promise((done) => (loaded = done)); - await page.route(/SearchDialog\.tsx/, async (route) => { + // Its module: SearchDialog.tsx under astro dev, a hashed chunk in the build. + await page.route(/\/SearchDialog\.(tsx|[\w-]+\.js)/, async (route) => { await held; await route.continue(); }); From af4346d9c9e9f2d27fa679852352ffdd470b3dfe Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Thu, 3 Dec 2026 21:05:54 -0500 Subject: [PATCH 2/3] Serve CI's e2e build with the Node adapter instead of a Vercel mimic Vercel's adapter has no preview server, which is why #124 carried scripts/serve-vercel-output.ts. With E2E_PRODUCTION set, astro.config.mjs builds with @astrojs/node (a devDependency) and Playwright serves dist/ with node dist/server/entry.mjs. The script is gone. The e2e build keeps Vercel's image service, which only writes /_vercel/image URLs. Astro's own service would resize all 1,293 remote artworks at build time: 2m 4s of AVIF encoding locally on its own. Nothing serves those URLs under Node, so the images 404; no test reads their bytes. A plain build still uses the Vercel adapter unchanged. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 15 +- CLAUDE.md | 11 +- astro.config.mjs | 48 +++--- package.json | 1 + playwright.config.ts | 4 +- pnpm-lock.yaml | 133 ++++++++++++++++ scripts/serve-vercel-output.ts | 273 --------------------------------- 7 files changed, 178 insertions(+), 307 deletions(-) delete mode 100644 scripts/serve-vercel-output.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16bf85c2..566dd60c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,7 +55,7 @@ jobs: - name: Run unit tests run: pnpm test:unit run - # One production build, which every e2e job serves the way Vercel would. + # One production build for Node, which every e2e job serves. build: timeout-minutes: 15 runs-on: ubuntu-24.04 @@ -80,15 +80,13 @@ jobs: - name: Build the site run: pnpm exec astro build env: + E2E_PRODUCTION: 1 ASTRO_DB_REMOTE_URL: ${{ secrets.ASTRO_DB_REMOTE_URL }} ASTRO_DB_APP_TOKEN: ${{ secrets.ASTRO_DB_APP_TOKEN }} - # A tarball keeps the function bundle's node_modules symlinks. - - name: Pack the build output - run: tar -czf vercel-output.tgz .vercel/output - uses: actions/upload-artifact@v4 with: - name: vercel-output - path: vercel-output.tgz + name: dist + path: dist/ retention-days: 1 e2e: @@ -136,9 +134,8 @@ jobs: run: pnpm exec playwright install-deps ${{ matrix.project }} - uses: actions/download-artifact@v4 with: - name: vercel-output - - name: Unpack the build output - run: tar -xzf vercel-output.tgz + name: dist + path: dist/ - name: Run Playwright tests run: pnpm exec playwright test --project=${{ matrix.project }} env: diff --git a/CLAUDE.md b/CLAUDE.md index 67abd254..53627b64 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,11 +26,12 @@ Whatnot podcast). - **E2E tests only:** `pnpm test:e2e` (Playwright, auto-starts dev server) - **E2E on another port:** `E2E_PORT=4340 pnpm test:e2e` (default 4321, where outside CI Playwright reuses whatever server is running; use a free port in a worktree) -- **E2E against the production build:** `pnpm exec astro build`, then - `E2E_PRODUCTION=1 pnpm test:e2e`. CI always does this: a build job uploads - `.vercel/output`, and each browser's job serves it with - `scripts/serve-vercel-output.ts`, which follows the output's `config.json` - routes, runs the on-demand `_render` function, and resizes `/_vercel/image` +- **E2E against the production build:** `E2E_PRODUCTION=1 pnpm exec astro build`, + then `E2E_PRODUCTION=1 pnpm test:e2e`. CI always does this. `E2E_PRODUCTION` + swaps in `@astrojs/node` (Vercel's adapter has no preview server), and + Playwright serves `dist/` with `node dist/server/entry.mjs`. The build keeps + Vercel's image service, so pages carry the same `/_vercel/image` URLs, but + nothing resizes them and those images 404 - **Seed remote DB:** `pnpm db:seed` - **Push schema to DB:** `pnpm db:push` - **Drizzle Studio:** `pnpm db:studio` diff --git a/astro.config.mjs b/astro.config.mjs index 9ffe8404..a4589591 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -1,31 +1,43 @@ +import process from 'node:process'; + +import node from '@astrojs/node'; import vercel from '@astrojs/vercel'; import { defineConfig } from 'astro/config'; import starpod from 'starpod'; import starpodConfig from './starpod.config'; +const imagesConfig = { + formats: ['image/avif'], + minimumCacheTTL: 3600, + remotePatterns: [{ protocol: 'https' }, { protocol: 'http' }], + sizes: [160, 320, 640, 1280] +}; + +// CI's e2e suite builds for Node, which `astro preview` serves. +const e2e = !!process.env.E2E_PRODUCTION; + // https://astro.build/config export default defineConfig({ output: 'static', - adapter: vercel({ - imageService: true, - imagesConfig: { - formats: ['image/avif'], - minimumCacheTTL: 3600, - remotePatterns: [ - { - protocol: 'https' + adapter: e2e + ? node({ mode: 'standalone' }) + : vercel({ + imageService: true, + imagesConfig, + webAnalytics: { enabled: true } + }), + /* Vercel's image service writes the same /_vercel/image URLs, so the e2e + build resizes no images, which takes minutes with sharp. */ + image: e2e + ? { + service: { + entrypoint: '@astrojs/vercel/build-image-service', + config: imagesConfig }, - { - protocol: 'http' - } - ], - sizes: [160, 320, 640, 1280] - }, - webAnalytics: { - enabled: true - } - }), + breakpoints: imagesConfig.sizes + } + : undefined, site: 'https://whiskey.fm', integrations: [starpod(starpodConfig, { database: true })], // These were specific redirects we needed for our podcast, if you do not have any routes to redirect, you can safely remove this. diff --git a/package.json b/package.json index 6258e478..627c9229 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ }, "devDependencies": { "@astrojs/check": "^0.9.9", + "@astrojs/node": "^10.1.4", "@eslint/js": "^9.39.4", "@playwright/test": "^1.60.0", "@testing-library/jest-dom": "^6.9.1", diff --git a/playwright.config.ts b/playwright.config.ts index 81f55954..bd855482 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -2,7 +2,7 @@ import { defineConfig, devices } from '@playwright/test'; const port = process.env.E2E_PORT || '4321'; const baseURL = `http://localhost:${port}`; -/* CI tests the production build, which a build job leaves in .vercel/output. +/* CI tests a production build for Node, which a build job leaves in dist/. Locally the dev server is quicker to iterate against; E2E_PRODUCTION=1 serves an existing build instead. */ const production = !!(process.env.CI || process.env.E2E_PRODUCTION); @@ -78,7 +78,7 @@ export default defineConfig({ webServer: { command: production - ? `pnpm exec tsx scripts/serve-vercel-output.ts --port ${port}` + ? `PORT=${port} node dist/server/entry.mjs` : `pnpm exec astro dev --port ${port}`, url: baseURL, reuseExistingServer: !process.env.CI, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bf78cfb0..b6b0b141 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -42,6 +42,9 @@ importers: '@astrojs/check': specifier: ^0.9.9 version: 0.9.9(prettier-plugin-astro@0.14.1)(prettier@3.8.3)(typescript@5.9.3) + '@astrojs/node': + specifier: ^10.1.4 + version: 10.1.4(astro@6.4.2(@types/node@24.12.4)(@vercel/functions@3.6.1)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.4)(tsx@4.22.4)(yaml@2.9.0)) '@eslint/js': specifier: ^9.39.4 version: 9.39.4 @@ -241,6 +244,11 @@ packages: '@astrojs/markdown-remark@7.2.0': resolution: {integrity: sha512-+YxmVQu1Bd+MFfSzjq1rOJvD9+nIOJzz5YIIhdIH01RrxRkKbyKoEgyIqP3yv51MhzMDgd79QaPv+kCVPT8vHw==} + '@astrojs/node@10.1.4': + resolution: {integrity: sha512-itV568ttlrpwNsutO+KPziqKfzTPlAIXMADlpBi3VeQ3liivRKKKG+jm+IjLMKvYGkxd0QnClKVCBP4i3gpwQQ==} + peerDependencies: + astro: ^6.3.0 + '@astrojs/preact@5.1.4': resolution: {integrity: sha512-KqP1oNWYUc4ljf8zlWWuZ8RGpTfqS7vX/cNheyJegqZ+KV0uMZy8NIoGi0L1++slhHN4ci/IRiVjoDq6oUJtZg==} engines: {node: '>=22.12.0'} @@ -2470,6 +2478,10 @@ packages: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} + depd@2.0.0: + resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} + engines: {node: '>= 0.8'} + dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -2625,6 +2637,9 @@ packages: eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + ee-first@1.1.1: + resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + electron-to-chromium@1.5.364: resolution: {integrity: sha512-G/dYE3+AYhyHwzTwg8UbnXf7zqMERYh7l2jJ3QujhFsH8agSYwtnGAR2aZ7f0AakIKJXd5En/Hre4igIUrdlYw==} @@ -2637,6 +2652,10 @@ packages: emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + encodeurl@2.0.3: + resolution: {integrity: sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==} + engines: {node: '>= 0.8'} + encoding@0.1.13: resolution: {integrity: sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==} @@ -2709,6 +2728,9 @@ packages: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} + escape-html@1.0.3: + resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} + escape-string-regexp@4.0.0: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} @@ -2782,6 +2804,10 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} + etag@1.8.1: + resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} + engines: {node: '>= 0.6'} + eventemitter3@5.0.4: resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} @@ -2902,6 +2928,10 @@ packages: resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==} engines: {node: '>= 6'} + fresh@2.0.0: + resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} + engines: {node: '>= 0.8'} + fs-extra@11.4.0: resolution: {integrity: sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==} engines: {node: '>=14.14'} @@ -3101,6 +3131,10 @@ packages: http-cache-semantics@4.2.0: resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==} + http-errors@2.0.1: + resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} + engines: {node: '>= 0.8'} + http-proxy-agent@4.0.1: resolution: {integrity: sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==} engines: {node: '>= 6'} @@ -3659,10 +3693,18 @@ packages: resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} engines: {node: '>= 0.6'} + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + mime-types@2.1.35: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} + mime-types@3.0.2: + resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} + engines: {node: '>=18'} + mimic-fn@2.1.0: resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} engines: {node: '>=6'} @@ -3860,6 +3902,10 @@ packages: ohash@2.0.11: resolution: {integrity: sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==} + on-finished@2.4.2: + resolution: {integrity: sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==} + engines: {node: '>= 0.8'} + once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} @@ -4160,6 +4206,10 @@ packages: radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} + range-parser@1.3.0: + resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} + engines: {node: '>= 0.6'} + rc@1.2.8: resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} hasBin: true @@ -4336,6 +4386,13 @@ packages: engines: {node: '>=10'} hasBin: true + send@1.2.1: + resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} + engines: {node: '>= 18'} + + server-destroy@1.0.1: + resolution: {integrity: sha512-rb+9B5YBIEzYcD6x2VKidaa+cqYBJQKnU4oe4E3ANwRRN56yk/ua1YCJT1n21NTS8w6CcOclAKNP3PhdCXKYtQ==} + set-function-length@1.2.2: resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} engines: {node: '>= 0.4'} @@ -4344,6 +4401,9 @@ packages: resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==} engines: {node: '>= 0.4'} + setprototypeof@1.2.0: + resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} + sharp@0.34.5: resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} @@ -4458,6 +4518,10 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + statuses@2.0.2: + resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} + engines: {node: '>= 0.8'} + std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} @@ -4593,6 +4657,10 @@ packages: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} + toidentifier@1.0.1: + resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} + engines: {node: '>=0.6'} + tough-cookie@6.0.1: resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==} engines: {node: '>=16'} @@ -5264,6 +5332,15 @@ snapshots: transitivePeerDependencies: - supports-color + '@astrojs/node@10.1.4(astro@6.4.2(@types/node@24.12.4)(@vercel/functions@3.6.1)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.4)(tsx@4.22.4)(yaml@2.9.0))': + dependencies: + '@astrojs/internal-helpers': 0.10.0 + astro: 6.4.2(@types/node@24.12.4)(@vercel/functions@3.6.1)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.4)(tsx@4.22.4)(yaml@2.9.0) + send: 1.2.1 + server-destroy: 1.0.1 + transitivePeerDependencies: + - supports-color + '@astrojs/preact@5.1.4(@babel/core@7.29.7)(@types/node@24.12.4)(jiti@2.7.0)(lightningcss@1.32.0)(preact@10.29.2)(rollup@4.60.4)(tsx@4.22.4)(yaml@2.9.0)': dependencies: '@astrojs/internal-helpers': 0.10.0 @@ -7379,6 +7456,8 @@ snapshots: delayed-stream@1.0.0: {} + depd@2.0.0: {} + dequal@2.0.3: {} destr@2.0.5: {} @@ -7440,6 +7519,8 @@ snapshots: eastasianwidth@0.2.0: {} + ee-first@1.1.1: {} + electron-to-chromium@1.5.364: {} emmet@2.4.11: @@ -7451,6 +7532,8 @@ snapshots: emoji-regex@9.2.2: {} + encodeurl@2.0.3: {} + encoding@0.1.13: dependencies: iconv-lite: 0.6.3 @@ -7614,6 +7697,8 @@ snapshots: escalade@3.2.0: {} + escape-html@1.0.3: {} + escape-string-regexp@4.0.0: {} escape-string-regexp@5.0.0: {} @@ -7713,6 +7798,8 @@ snapshots: esutils@2.0.3: {} + etag@1.8.1: {} + eventemitter3@5.0.4: {} execa@5.1.1: @@ -7841,6 +7928,8 @@ snapshots: hasown: 2.0.4 mime-types: 2.1.35 + fresh@2.0.0: {} + fs-extra@11.4.0: dependencies: graceful-fs: 4.2.11 @@ -8117,6 +8206,14 @@ snapshots: http-cache-semantics@4.2.0: {} + http-errors@2.0.1: + dependencies: + depd: 2.0.0 + inherits: 2.0.4 + setprototypeof: 1.2.0 + statuses: 2.0.2 + toidentifier: 1.0.1 + http-proxy-agent@4.0.1: dependencies: '@tootallnate/once': 1.1.2 @@ -8839,10 +8936,16 @@ snapshots: mime-db@1.52.0: {} + mime-db@1.54.0: {} + mime-types@2.1.35: dependencies: mime-db: 1.52.0 + mime-types@3.0.2: + dependencies: + mime-db: 1.54.0 + mimic-fn@2.1.0: {} min-indent@1.0.1: {} @@ -9020,6 +9123,10 @@ snapshots: ohash@2.0.11: {} + on-finished@2.4.2: + dependencies: + ee-first: 1.1.1 + once@1.4.0: dependencies: wrappy: 1.0.2 @@ -9244,6 +9351,8 @@ snapshots: radix3@1.1.2: {} + range-parser@1.3.0: {} + rc@1.2.8: dependencies: deep-extend: 0.6.0 @@ -9503,6 +9612,24 @@ snapshots: semver@7.8.1: {} + send@1.2.1: + dependencies: + debug: 4.4.3 + encodeurl: 2.0.3 + escape-html: 1.0.3 + etag: 1.8.1 + fresh: 2.0.0 + http-errors: 2.0.1 + mime-types: 3.0.2 + ms: 2.1.3 + on-finished: 2.4.2 + range-parser: 1.3.0 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + + server-destroy@1.0.1: {} + set-function-length@1.2.2: dependencies: define-data-property: 1.1.4 @@ -9519,6 +9646,8 @@ snapshots: functions-have-names: 1.2.3 has-property-descriptors: 1.0.2 + setprototypeof@1.2.0: {} + sharp@0.34.5: dependencies: '@img/colour': 1.1.0 @@ -9668,6 +9797,8 @@ snapshots: stackback@0.0.2: {} + statuses@2.0.2: {} + std-env@4.1.0: {} stop-iteration-iterator@1.1.0: @@ -9800,6 +9931,8 @@ snapshots: dependencies: is-number: 7.0.0 + toidentifier@1.0.1: {} + tough-cookie@6.0.1: dependencies: tldts: 7.4.2 diff --git a/scripts/serve-vercel-output.ts b/scripts/serve-vercel-output.ts deleted file mode 100644 index c14237ec..00000000 --- a/scripts/serve-vercel-output.ts +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Serves `.vercel/output` the way Vercel does, closely enough for the e2e - * suite: the routes in `config.json` (redirects, `Accept: text/markdown` - * negotiation, the on-demand `_render` function) over the static files, plus - * `/_vercel/image`. - * - * Usage: pnpm exec astro build && pnpm tsx scripts/serve-vercel-output.ts --port 4321 - */ - -import { createReadStream } from 'node:fs'; -import { readFile, stat } from 'node:fs/promises'; -import { - createServer, - type IncomingMessage, - type ServerResponse -} from 'node:http'; -import { extname, join, normalize, resolve } from 'node:path'; -import { Readable } from 'node:stream'; -import { pathToFileURL } from 'node:url'; -import { parseArgs } from 'node:util'; -import sharp from 'sharp'; - -type Route = - | { handle: 'filesystem' } - | { - src: string; - dest?: string; - headers?: Record; - status?: number; - continue?: boolean; - has?: { type: 'header'; key: string; value: string }[]; - }; - -type Resolution = - | { kind: 'redirect'; status: number; location: string } - | { kind: 'file'; file: string; status: number; headers: Headers } - | { kind: 'function'; headers: Headers }; - -type Handler = { fetch(request: Request): Promise }; - -const { values } = parseArgs({ - options: { port: { type: 'string', default: '4321' } } -}); -const output = resolve('.vercel/output'); -const staticDir = join(output, 'static'); -const config = JSON.parse( - await readFile(join(output, 'config.json'), 'utf8') -) as { routes: Route[] }; -const split = config.routes.findIndex((route) => 'handle' in route); -const beforeFilesystem = config.routes.slice(0, split); -const afterFilesystem = config.routes.slice(split + 1); -const render = ( - (await import( - pathToFileURL(join(output, 'functions/_render.func/dist/server/entry.mjs')) - .href - )) as { default: Handler } -).default; - -const contentTypes: Record = { - '.css': 'text/css; charset=utf-8', - '.html': 'text/html; charset=utf-8', - '.ico': 'image/x-icon', - '.jpeg': 'image/jpeg', - '.jpg': 'image/jpeg', - '.js': 'text/javascript; charset=utf-8', - '.json': 'application/json; charset=utf-8', - '.md': 'text/markdown; charset=utf-8', - '.png': 'image/png', - '.svg': 'image/svg+xml', - '.txt': 'text/plain; charset=utf-8', - '.webmanifest': 'application/manifest+json', - '.woff2': 'font/woff2', - '.xml': 'application/xml; charset=utf-8' -}; - -function substitute(template: string, match: RegExpExecArray) { - return template.replace(/\$(\d+)/g, (_, index) => match[Number(index)] ?? ''); -} - -function matches( - route: Exclude, - path: string, - request: IncomingMessage -) { - const match = new RegExp(route.src).exec(path); - if (!match) return null; - const satisfied = (route.has ?? []).every(({ key, value }) => { - const header = request.headers[key.toLowerCase()]; - return typeof header === 'string' && new RegExp(`^${value}$`).test(header); - }); - return satisfied ? match : null; -} - -async function staticFile(path: string) { - const file = normalize(join(staticDir, path)); - if (!file.startsWith(staticDir)) return null; - for (const candidate of [file, join(file, 'index.html')]) { - const info = await stat(candidate).catch(() => null); - if (info?.isFile()) return candidate; - } - return null; -} - -async function resolveRoute( - request: IncomingMessage, - pathname: string -): Promise { - const headers = new Headers(); - let path = pathname; - for (const route of beforeFilesystem) { - if ('handle' in route) continue; - const match = matches(route, path, request); - if (!match) continue; - for (const [key, value] of Object.entries(route.headers ?? {})) { - headers.set(key, substitute(value, match)); - } - const location = headers.get('location'); - if (route.status && location) { - return { kind: 'redirect', status: route.status, location }; - } - if (route.dest) path = substitute(route.dest, match); - if (!route.continue) break; - } - - const file = await staticFile(path); - if (file) return { kind: 'file', file, status: 200, headers }; - - for (const route of afterFilesystem) { - if ('handle' in route) continue; - const match = matches(route, path, request); - if (!match || !route.dest) continue; - if (route.dest === '_render') return { kind: 'function', headers }; - const fallback = await staticFile(route.dest); - if (fallback) { - return { - kind: 'file', - file: fallback, - status: route.status ?? 200, - headers - }; - } - } - throw new Error(`No route for ${pathname}`); -} - -const images = new Map>(); - -// The site's own images come as paths, such as `_astro/host.jpg`. -async function source(url: string) { - if (!/^https?:/.test(url)) { - const file = await staticFile(`/${url.replace(/^\//, '')}`); - if (!file) throw new Error(`No static file for ${url}`); - return readFile(file); - } - const upstream = await fetch(url, { signal: AbortSignal.timeout(30_000) }); - if (!upstream.ok) throw new Error(`${upstream.status} fetching ${url}`); - return Buffer.from(await upstream.arrayBuffer()); -} - -async function optimize( - url: string, - width: number, - quality: number, - webp: boolean -) { - const resized = sharp(await source(url)).resize({ - width, - withoutEnlargement: true - }); - return webp - ? { type: 'image/webp', body: await resized.webp({ quality }).toBuffer() } - : { type: 'image/jpeg', body: await resized.jpeg({ quality }).toBuffer() }; -} - -async function image( - request: IncomingMessage, - query: URLSearchParams, - response: ServerResponse -) { - const url = query.get('url'); - if (!url) { - response.writeHead(400).end('Missing url'); - return; - } - const webp = (request.headers.accept ?? '').includes('image/webp'); - const key = `${query}|${webp}`; - let pending = images.get(key); - if (!pending) { - pending = optimize( - url, - Number(query.get('w') ?? 640), - Number(query.get('q') ?? 75), - webp - ); - images.set(key, pending); - pending.catch(() => images.delete(key)); - } - const { type, body } = await pending; - response.writeHead(200, { - 'content-type': type, - 'cache-control': 'public, max-age=3600' - }); - response.end(body); -} - -async function callFunction( - request: IncomingMessage, - response: ServerResponse, - headers: Headers -) { - const hasBody = request.method !== 'GET' && request.method !== 'HEAD'; - const result = await render.fetch( - new Request(`http://${request.headers.host}${request.url}`, { - method: request.method, - headers: Object.entries(request.headers).flatMap(([key, value]) => - value === undefined ? [] : [[key, String(value)] as [string, string]] - ), - ...(hasBody - ? { body: Readable.toWeb(request) as ReadableStream, duplex: 'half' } - : {}) - } as RequestInit) - ); - headers.forEach((value, key) => { - if (!result.headers.has(key)) result.headers.set(key, value); - }); - response.writeHead(result.status, Object.fromEntries(result.headers)); - if (result.body && request.method !== 'HEAD') { - Readable.fromWeb(result.body as never).pipe(response); - } else { - response.end(); - } -} - -async function handle(request: IncomingMessage, response: ServerResponse) { - const url = new URL(request.url ?? '/', 'http://localhost'); - if (url.pathname === '/_vercel/image') { - await image(request, url.searchParams, response); - return; - } - const resolution = await resolveRoute( - request, - decodeURIComponent(url.pathname) - ); - switch (resolution.kind) { - case 'redirect': - response - .writeHead(resolution.status, { location: resolution.location }) - .end(); - return; - case 'function': - await callFunction(request, response, resolution.headers); - return; - case 'file': { - const type = contentTypes[extname(resolution.file)]; - response.writeHead(resolution.status, { - ...Object.fromEntries(resolution.headers), - ...(type ? { 'content-type': type } : {}) - }); - if (request.method === 'HEAD') response.end(); - else createReadStream(resolution.file).pipe(response); - } - } -} - -createServer((request, response) => { - handle(request, response).catch((error: unknown) => { - console.error(request.url, error); - if (!response.headersSent) response.writeHead(502); - response.end(); - }); -}).listen(Number(values.port), () => { - console.log(`Serving ${output} on http://localhost:${values.port}`); -}); From c8722f57d8161e3035f2e6810f71b8a73cc73b96 Mon Sep 17 00:00:00 2001 From: Robert Wagner Date: Thu, 3 Dec 2026 21:44:38 -0500 Subject: [PATCH 3/3] Build CI's e2e site against a seeded local database Astro inlines ASTRO_DB_REMOTE_URL and ASTRO_DB_APP_TOKEN into the server bundle, and CI uploads that bundle as a public artifact. The build job now pushes the schema to a local SQLite file, seeds it from db/data, and builds against it. A guard step fails the job if dist/ holds a libsql:// URL or a JWT-shaped string. The e2e jobs download ci.db with dist/ to the path the build inlined. No CI job here references the database secrets. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 26 +++++++++++++++++++------- CLAUDE.md | 4 +++- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 566dd60c..09825e5f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -77,16 +77,32 @@ jobs: ${{ runner.os }}-pnpm-store- - name: Install dependencies run: pnpm install + # The build inlines the database URL and token into dist/, which is a + # public artifact, so it gets a local database seeded from db/data, never + # the production one. The e2e jobs need it at this same path. + - name: Seed a local database + run: | + pnpm exec drizzle-kit push + pnpm db:seed + env: + ASTRO_DB_REMOTE_URL: file:${{ github.workspace }}/ci.db - name: Build the site run: pnpm exec astro build env: E2E_PRODUCTION: 1 - ASTRO_DB_REMOTE_URL: ${{ secrets.ASTRO_DB_REMOTE_URL }} - ASTRO_DB_APP_TOKEN: ${{ secrets.ASTRO_DB_APP_TOKEN }} + ASTRO_DB_REMOTE_URL: file:${{ github.workspace }}/ci.db + - name: Check the build holds no credentials + run: | + if grep -rElI 'libsql://|eyJ[A-Za-z0-9_-]{10,}\.' dist/; then + echo "::error::dist/ contains a database URL or a JWT" + exit 1 + fi - uses: actions/upload-artifact@v4 with: name: dist - path: dist/ + path: | + dist/ + ci.db retention-days: 1 e2e: @@ -135,12 +151,8 @@ jobs: - uses: actions/download-artifact@v4 with: name: dist - path: dist/ - name: Run Playwright tests run: pnpm exec playwright test --project=${{ matrix.project }} - env: - ASTRO_DB_REMOTE_URL: ${{ secrets.ASTRO_DB_REMOTE_URL }} - ASTRO_DB_APP_TOKEN: ${{ secrets.ASTRO_DB_APP_TOKEN }} - uses: actions/upload-artifact@v4 if: always() with: diff --git a/CLAUDE.md b/CLAUDE.md index 53627b64..54f587c8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,9 @@ Whatnot podcast). swaps in `@astrojs/node` (Vercel's adapter has no preview server), and Playwright serves `dist/` with `node dist/server/entry.mjs`. The build keeps Vercel's image service, so pages carry the same `/_vercel/image` URLs, but - nothing resizes them and those images 404 + nothing resizes them and those images 404. CI builds against a local SQLite + database seeded from `db/data`, never the production one, because the build inlines + the database URL and token into `dist/`, which CI uploads as a public artifact - **Seed remote DB:** `pnpm db:seed` - **Push schema to DB:** `pnpm db:push` - **Drizzle Studio:** `pnpm db:studio`