diff --git a/.github/scripts/packed-consumer.mjs b/.github/scripts/packed-consumer.mjs index f9528a457..5fb4d736b 100644 --- a/.github/scripts/packed-consumer.mjs +++ b/.github/scripts/packed-consumer.mjs @@ -119,6 +119,41 @@ async function run(command, args, cwd, env = environment) { } } +const packedOgRoute = `import { html } from 'void/html'; +import { OgImageResponse } from '@void/image/generate'; +import { defineHandler } from 'void'; +export const GET = defineHandler((c) => new OgImageResponse(html\`
\${Promise.resolve('Packed Привет Ελληνικά Łódź')}
\`, { fallbackFonts: false, defaultFont: c.req.query('font') === 'Geist' ? 'Geist' : 'Inter' })); +`; +const packedImageRoute = `import { html } from 'void/html'; +import { ImageResponse } from '@void/image/generate'; +import { defineHandler } from 'void'; +export const GET = defineHandler((c) => new ImageResponse(html\`
\${'Packed Привет Ελληνικά Łódź'}
\`, { width: 600, height: 600, fallbackFonts: false, defaultFont: c.req.query('font') === 'Geist' ? 'Geist' : 'Inter' })); +`; + +/** Fetches an image route and checks its PNG signature and dimensions. */ +async function assertPackedImage(url, dimensions, failure) { + const inter = await readPackedImage(url, dimensions, failure); + const geist = await readPackedImage(`${url}?font=Geist`, dimensions, failure); + assert(!Buffer.from(inter).equals(Buffer.from(geist)), 'Inter and Geist must render differently'); + const again = await readPackedImage(url, dimensions, failure); + assert( + Buffer.from(inter).equals(Buffer.from(again)), + 'Font selection must not leak across renders', + ); +} + +async function readPackedImage(url, dimensions, failure) { + const response = await fetch(url); + assert.equal(response.status, 200, failure()); + assert.equal(response.headers.get('content-type'), 'image/png', failure()); + // A render error arrives after the status, as a failed body. + const bytes = new Uint8Array(await response.arrayBuffer()); + assert.deepEqual([...bytes.subarray(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10], failure()); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + assert.deepEqual([view.getUint32(16), view.getUint32(20)], dimensions, failure()); + return bytes; +} + const packages = []; for (const entry of readdirSync(join(root, 'packages'), { withFileTypes: true })) { if (!entry.isDirectory()) { @@ -146,7 +181,9 @@ writeFileSync( environment.npm_config_registry = registry.origin; environment.NPM_CONFIG_REGISTRY = registry.origin; environment.PNPM_CONFIG_REGISTRY = registry.origin; -const version = packages.find((pkg) => pkg.manifest.name === 'void').manifest.version; +const voidManifest = packages.find((pkg) => pkg.manifest.name === 'void').manifest; +const version = voidManifest.version; +const imageVersion = packages.find((pkg) => pkg.manifest.name === '@void/image').manifest.version; const managers = process.env.VOID_PACKED_PM ? [process.env.VOID_PACKED_PM] : ['npm', 'pnpm']; assert(managers.every((manager) => ['npm', 'pnpm'].includes(manager))); const frameworks = process.env.VOID_PACKED_FRAMEWORK @@ -251,6 +288,35 @@ try { ); const cli = join(fixture, 'node_modules/void/dist/cli/cli.mjs'); await run(process.execPath, [cli, '--help'], fixture); + await run( + manager, + manager === 'npm' + ? ['install', `@void/image@${imageVersion}`] + : ['add', `@void/image@${imageVersion}`], + fixture, + ); + assert(existsSync(join(fixture, 'node_modules/@void/image/licenses/Inter.txt'))); + writeFileSync( + join(fixture, 'check-image.mjs'), + `import assert from 'node:assert/strict'; +import { ImageResponse, OgImageResponse } from '@void/image/generate'; +import { html } from 'void/html'; +await assert.rejects(import('@void/image')); +for (const path of ['void/image', 'void/og']) await assert.rejects(import(path)); +for (const response of [ + new ImageResponse(html\`
Hello
\`, { width: 320, height: 168, fallbackFonts: false }), + new OgImageResponse(html\`
Hello
\`, { fallbackFonts: false }), +]) { + const bytes = new Uint8Array(await response.arrayBuffer()); + assert.equal(response.headers.get('content-type'), 'image/png'); + assert.deepEqual([...bytes.slice(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10]); +} +`, + ); + await run(process.execPath, ['check-image.mjs'], fixture); + if (process.env.CI || spawnSync('bun', ['--version']).status === 0) { + await run('bun', ['check-image.mjs'], fixture); + } if (full && framework === 'react') { await run( manager, @@ -341,6 +407,9 @@ try { join(fixture, 'routes/api/packed-email.ts'), `import { defineHandler } from 'void';\nimport { sendEmail } from 'void/email';\nexport const GET = defineHandler(async () => { return sendEmail({ from: 'packed@example.com', to: 'inbox@example.com', subject: 'Packed', text: 'ok' }); });\n`, ); + // Both response classes use the generate subpath and React only when the app has it. + writeFileSync(join(fixture, 'routes/api/packed-og.ts'), packedOgRoute); + writeFileSync(join(fixture, 'routes/api/packed-image.ts'), packedImageRoute); mkdirSync(join(fixture, 'public'), { recursive: true }); writeFileSync(join(fixture, 'public/packed.txt'), label); const vite = join( @@ -433,6 +502,8 @@ if (runtime.manifest.platformVersion !== ${JSON.stringify(version)}) throw new E } else { assert.equal(email.error?.code, 'BINDING_MISSING', emailBody); } + await assertPackedImage(`${base}/api/packed-og`, [1200, 630], task.failure); + await assertPackedImage(`${base}/api/packed-image`, [600, 600], task.failure); if (full && framework === 'react') { const markdown = await fetch(`${base}/markdown`); assert.equal(markdown.status, 200, task.failure()); @@ -475,17 +546,16 @@ if (runtime.manifest.platformVersion !== ${JSON.stringify(version)}) throw new E if (framework === 'react') { // The Node target bundles the installed void into its build, so a ValidationError from // void/handler is the class that page actions check, as in dev. - await run( - manager, - manager === 'npm' ? ['install', '@hono/node-server'] : ['add', '@hono/node-server'], - fixture, - ); + await run(manager, [manager === 'npm' ? 'install' : 'add', '@hono/node-server'], fixture); writeFileSync( join(fixture, 'void.config.ts'), "import { defineConfig } from 'void/config';\nexport default defineConfig({ target: 'node' });\n", ); // KV and email are Cloudflare bindings. rmSync(join(fixture, 'routes'), { recursive: true }); + mkdirSync(join(fixture, 'routes/api'), { recursive: true }); + writeFileSync(join(fixture, 'routes/api/packed-og.ts'), packedOgRoute); + writeFileSync(join(fixture, 'routes/api/packed-image.ts'), packedImageRoute); writeFileSync( join(fixture, 'pages/form.tsx'), 'export default function Form() {\n return

Form

;\n}\n', @@ -519,12 +589,14 @@ if (runtime.manifest.platformVersion !== ${JSON.stringify(version)}) throw new E const body = await response.text(); assert.equal(response.status, 200, `${body}\n${task.failure()}`); assert(body.includes('Email already taken'), body); + await assertPackedImage(`${base}/api/packed-og`, [1200, 630], task.failure); + await assertPackedImage(`${base}/api/packed-image`, [600, 600], task.failure); } finally { await task.stop(); } } console.log( - `Passed packed ${label} (${suite}): init, frozen install, ${useVitePlus ? 'Vite+ build/typecheck/test' : 'public Vite build/typecheck'}, assets, KV, email, runtime integrity${full ? ', dev/preview, hydration/navigation' : ', dev HTTP'}${framework === 'react' ? ', Node target' : ''}`, + `Passed packed ${label} (${suite}): init, frozen install, ${useVitePlus ? 'Vite+ build/typecheck/test' : 'public Vite build/typecheck'}, assets, KV, email, OG/image rendering, runtime integrity${full ? ', dev/preview, hydration/navigation' : ', dev HTTP'}${framework === 'react' ? ', Node target' : ''}`, ); } catch (error) { failures.push({ fixture: label, error: String(error.stack ?? error) }); diff --git a/.github/scripts/packed-registry.mjs b/.github/scripts/packed-registry.mjs index e078989f6..04e833475 100644 --- a/.github/scripts/packed-registry.mjs +++ b/.github/scripts/packed-registry.mjs @@ -28,7 +28,11 @@ export function inspectPackage(tarball) { assert(isHttpsUrl(manifest.homepage), `${manifest.name}: homepage must be an HTTPS URL`); assert(isHttpsUrl(manifest.bugs?.url), `${manifest.name}: bugs.url must be an HTTPS URL`); assert(files.has('package/LICENSE'), `${manifest.name}: missing packaged LICENSE`); + if (manifest.name === 'void') { + assert.equal(manifest.dependencies?.['takumi-js'], undefined); + assert.equal(manifest.exports['./image'], undefined); + assert.equal(manifest.exports['./og'], undefined); for (const file of [ 'docs/guide/quickstart.md', 'docs/reference/cli.md', @@ -43,6 +47,20 @@ export function inspectPackage(tarball) { 'void: docs must be bundled at the package root', ); } + + if (manifest.name === '@void/image') { + assert(files.has('package/licenses/Inter.txt'), '@void/image: missing Inter license'); + assert.equal(manifest.exports['.'], undefined, '@void/image: root must not export generation'); + assert(manifest.exports['./generate'], '@void/image: missing generate export'); + assert(manifest.peerDependencies?.void, '@void/image: missing void peer dependency'); + assert(manifest.dependencies?.['takumi-js'], '@void/image: missing Takumi dependency'); + const output = execFileSync('tar', ['-xOf', tarball, 'package/dist/generate.mjs'], { + encoding: 'utf8', + }); + assert.match(output, /from ["']takumi-js["']/, '@void/image: Takumi must stay external'); + assert.match(output, /import\(["']takumi-js\/wasm["']\)/); + } + for (const field of [ 'dependencies', 'optionalDependencies', diff --git a/.github/scripts/packed-registry.test.mjs b/.github/scripts/packed-registry.test.mjs index dc3ec6ceb..8aca28ede 100644 --- a/.github/scripts/packed-registry.test.mjs +++ b/.github/scripts/packed-registry.test.mjs @@ -2,11 +2,11 @@ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path/posix'; +import { dirname, join } from 'node:path/posix'; import { test } from 'node:test'; import { inspectPackage } from './packed-registry.mjs'; -function createPackage(t, overrides = {}, includeLicense = true) { +function createPackage(t, overrides = {}, includeLicense = true, extraFiles = {}) { const root = mkdtempSync(join(tmpdir(), 'void-packed-metadata-')); t.after(() => rmSync(root, { recursive: true, force: true })); const directory = join(root, 'package'); @@ -26,6 +26,11 @@ function createPackage(t, overrides = {}, includeLicense = true) { if (includeLicense) { writeFileSync(join(directory, 'LICENSE'), 'MIT License\n'); } + for (const [path, content] of Object.entries(extraFiles)) { + const file = join(directory, path); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content); + } const tarball = join(root, 'package.tgz'); execFileSync('tar', ['-czf', tarball, '-C', root, 'package']); return tarball; @@ -62,3 +67,38 @@ void test('rejects blank descriptions and invalid package links', (t) => { void test('requires the license file as well as its manifest field', (t) => { assert.throws(() => inspectPackage(createPackage(t, {}, false)), /missing packaged LICENSE/); }); + +const imageManifest = { + name: '@void/image', + exports: { './generate': './dist/generate.mjs' }, + dependencies: { 'takumi-js': '~2.20.0' }, + peerDependencies: { void: '^1.8.0' }, +}; +const imageFiles = { + 'dist/generate.mjs': 'import { render } from "takumi-js";\nimport("takumi-js/wasm");\n', + 'licenses/Inter.txt': 'SIL Open Font License\n', +}; + +void test('accepts the image subpath with external Takumi and its font license', (t) => { + inspectPackage(createPackage(t, imageManifest, true, imageFiles)); +}); + +void test('rejects image packages that expose the root or omit the void peer', (t) => { + for (const overrides of [ + { exports: { ...imageManifest.exports, '.': './dist/generate.mjs' } }, + { peerDependencies: {} }, + ]) { + assert.throws(() => + inspectPackage(createPackage(t, { ...imageManifest, ...overrides }, true, imageFiles)), + ); + } +}); + +void test('rejects image packages that omit the font license or bundle Takumi', (t) => { + for (const files of [ + { 'dist/generate.mjs': imageFiles['dist/generate.mjs'] }, + { ...imageFiles, 'dist/generate.mjs': 'export class ImageResponse {}\n' }, + ]) { + assert.throws(() => inspectPackage(createPackage(t, imageManifest, true, files))); + } +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8bff11231..1795cbeda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,11 @@ jobs: - run: vp run build if: ${{ matrix.shard != 'unit' }} + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + if: ${{ matrix.shard != 'unit' }} + with: + bun-version: '1.4.4' + - run: vp test run --project parallel-integration --shard=${{ matrix.shard }} if: ${{ matrix.shard != 'unit' }} diff --git a/.github/workflows/prepublish-test.yml b/.github/workflows/prepublish-test.yml index 931adcb64..0eae9da35 100644 --- a/.github/workflows/prepublish-test.yml +++ b/.github/workflows/prepublish-test.yml @@ -76,6 +76,9 @@ jobs: with: node-version-file: .node-version cache: true + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: '1.4.4' # The npm bundled with Node can lag behind fixes that fresh installs need. - run: npm i -g npm && npm --version if: ${{ matrix.pm == 'npm' }} diff --git a/AGENTS.md b/AGENTS.md index df51d782c..8f2d65e31 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,6 +68,7 @@ pnpm workspaces managed through Vite+. Shared dependency versions use the **pnpm | [`packages/deploy-cloudflare`](./packages/deploy-cloudflare) | `@void/deploy-cloudflare` | Direct Cloudflare config and verified upload primitives | | [`packages/edge`](./packages/edge) | `@void/edge` | Shared routing, headers, and static edge runtime | | [`packages/isr`](./packages/isr) | `@void/isr` | Shared ISR protocol, core logic, and direct runtime | +| [`packages/image`](./packages/image) | `@void/image` | Image generation and Open Graph image responses | | [`packages/platform`](./packages/platform/README.md) | `@void/platform` | Self-hosted installation contracts and packaged platform runtime | | [`packages/void`](./packages/void/AGENTS.md) | `void` | Core Vite plugin — routing, inference, migrations, CLI | | [`packages/react`](./packages/react/README.md) | `@void/react` | React framework adapter for Pages mode (SSR, Link, useForm) | diff --git a/README.md b/README.md index bc8244e80..428d9a31d 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Read the [Void documentation](https://void.cloud) online or use the Markdown gui - [Server routes](https://void.cloud/guide/server-routing), [pages](https://void.cloud/guide/pages-routing/overview), and [error components](https://void.cloud/guide/pages-routing/errors) - [Database](https://void.cloud/guide/database) and [type safety](https://void.cloud/guide/type-safety) +- [Image generation](https://void.cloud/guide/image-generation) and [Open Graph images](https://void.cloud/guide/og-images) with `@void/image` - [Deployment](https://void.cloud/guide/deployment) - [Framework integrations](https://void.cloud/integrations/frameworks/overview) - [API](https://void.cloud/reference/api) and [CLI](https://void.cloud/reference/cli) reference diff --git a/TESTING.md b/TESTING.md index c92f9fbda..0550811f3 100644 --- a/TESTING.md +++ b/TESTING.md @@ -245,7 +245,9 @@ workspace links can hide. They do not publish packages or deploy applications. Smoke coverage checks package contents and exports, real initialization, CLI help, a frozen reinstall, public Vite builds, TypeScript, and development HTTP requests for pages, assets, and -KV. It uses no browser. Full coverage adds Vue, Svelte, Solid, Markdown, production preview, +KV. It also renders images through the installed `@void/image/generate` module on Node.js and, +when available locally, Bun. CI installs Bun and requires both runtimes. It uses no browser. +Full coverage adds Vue, Svelte, Solid, Markdown, production preview, and browser hydration/navigation. Superseded PR/main runs are cancelled; release runs are not. The selector reads all PR file pages or the complete pushed commit range. Renames consider both diff --git a/benchmark/.gitignore b/benchmark/.gitignore new file mode 100644 index 000000000..b7dd2f275 --- /dev/null +++ b/benchmark/.gitignore @@ -0,0 +1 @@ +*/artifacts/ diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 000000000..7b8f7a24d --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,235 @@ +# Workers performance benchmark + +Benchmarks build and deployment performance, bundle sizes, and the latency of +deployed Cloudflare Workers. The apps compare direct Workers, Void, and +`@void/image`. + +## Usage + +Run a single benchmark from the repository root: + +```sh +vp install +vp run build +vp run --filter ./benchmark benchmark baseline-workers +``` + +Available benchmarks: `baseline-workers`, `baseline-void`, `image-response-bare`, +and `image-response`. + +Install `oha` and supply `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` through +your environment or credential wrapper. The token needs Workers deployment, +Access Edit, and Account Analytics Read permissions. The package provides `cf`. +Protected requests open employee Access login unless `CF_ACCESS_TOKEN` is set. + +The complete flow deploys, measures latency, retrieves Worker metrics, and writes: + +- **`benchmark//report.md`** — readable results. +- **`benchmark//report.json`** — portable measurements used to generate the report. + +Commit both files. Detailed local logs and request samples remain in the ignored +`benchmark//artifacts/` directory. Failed runs preserve the previous report. + +Generate the cross-benchmark overview from saved reports: + +```sh +vp run --filter ./benchmark compare +``` + +The overview is **[`benchmark/report.md`](./report.md)**, with Mermaid charts and +links to the individual reports. Commit it alongside the source reports. + +An optional `benchmark//benchmark.json` configures deployment count and latency +workloads. Missing fields use defaults: 30 deployments, then 10 latency rounds of +500 requests with 50 warmup requests per round. CLI options override configuration; +`--path` selects one ad-hoc workload. Set `"latency": []` for deployment only. + +## Scripts + +All examples run from the repository root. Each command supports `-h` / `--help`, +except the `test` and `typecheck` package tasks. + +### `benchmark` + +Runs the complete benchmark. All latency workloads use the final deployment. + +```sh +vp run --filter ./benchmark benchmark image-response +vp run --filter ./benchmark benchmark image-response --path '/run?width=64&height=64' --deploy-runs 5 -n 200 +``` + +| Argument | Description | +| --------------------------- | ------------------------------------------------------------------ | +| `` | Benchmark directory name; required. | +| `--path ` | Replace configured workloads with one app-relative path and query. | +| `--deploy-runs ` | Deployment count, 1–1000; default 30. | +| `-n, --requests ` | Measured requests per latency round; default 500. | +| `--latency-runs ` | Latency rounds, 1–1000; default 10. | +| `--warmup-requests ` | Warmup requests per round; default 50; 0 disables. | +| `-c, --connections ` | Concurrent connections; default 1. | +| `-z, --duration