diff --git a/.github/scripts/packed-consumer.mjs b/.github/scripts/packed-consumer.mjs index d3e04d8d2..5303ced55 100644 --- a/.github/scripts/packed-consumer.mjs +++ b/.github/scripts/packed-consumer.mjs @@ -119,6 +119,46 @@ async function run(command, args, cwd, env = environment) { } } +const packedOgRoute = `import { html } from 'void/html'; +import { takumiRenderer } from '@void/image-renderer-takumi'; +import { OgImageResponse } from 'void/image'; +import { defineHandler } from 'void'; +export const GET = defineHandler((c) => new OgImageResponse(html\`
\${Promise.resolve('Packed Привет Ελληνικά Łódź')}
\`, { renderer: [takumiRenderer, { fallbackFonts: false }], font: c.req.query('font') === 'Geist' ? 'Geist' : 'Roboto' })); +`; +const packedImageRoute = `import { html } from 'void/html'; +import { takumiRenderer } from '@void/image-renderer-takumi'; +import { ImageResponse } from 'void/image'; +import { defineHandler } from 'void'; +export const GET = defineHandler((c) => new ImageResponse(html\`
\${'Packed Привет Ελληνικά Łódź'}
\`, { width: 600, height: 600, renderer: [takumiRenderer, { fallbackFonts: false }], font: c.req.query('font') === 'Geist' ? 'Geist' : 'Roboto' })); +`; + +/** Fetches an image route and checks its PNG signature and dimensions. */ +async function assertPackedImage(url, dimensions, failure) { + const roboto = await readPackedImage(url, dimensions, failure); + const geist = await readPackedImage(`${url}?font=Geist`, dimensions, failure); + assert( + !Buffer.from(roboto).equals(Buffer.from(geist)), + 'Roboto and Geist must render differently', + ); + const again = await readPackedImage(url, dimensions, failure); + assert( + Buffer.from(roboto).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 +186,10 @@ 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 imagePackage = '@void/image-renderer-takumi'; +const imageVersion = packages.find((pkg) => pkg.manifest.name === imagePackage).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 +294,45 @@ try { ); const cli = join(fixture, 'node_modules/void/dist/cli/cli.mjs'); await run(process.execPath, [cli, '--help'], fixture); + await run( + process.execPath, + [ + '--input-type=module', + '-e', + "import { ImageResponse } from 'void/image'; if (!ImageResponse) throw new Error('Missing ImageResponse');", + ], + fixture, + ); + await run( + manager, + manager === 'npm' + ? ['install', `${imagePackage}@${imageVersion}`] + : ['add', `${imagePackage}@${imageVersion}`], + fixture, + ); + assert(existsSync(join(fixture, 'node_modules', imagePackage, 'licenses/Roboto.txt'))); + writeFileSync( + join(fixture, 'check-image.mjs'), + `import assert from 'node:assert/strict'; +import { takumiRenderer } from '@void/image-renderer-takumi'; +import { ImageResponse, OgImageResponse } from 'void/image'; +import { html } from 'void/html'; +await assert.rejects(import('@void/image')); +await assert.rejects(import('void/og')); +for (const response of [ + new ImageResponse(html\`
Hello
\`, { width: 320, height: 168, renderer: takumiRenderer, fallbackFonts: false }), + new OgImageResponse(html\`
Hello
\`, { renderer: takumiRenderer, 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 +423,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( @@ -448,6 +533,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()); @@ -490,17 +577,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', @@ -534,12 +620,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..ca583192c 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(manifest.exports['./image'], 'void: missing image export'); + assert.equal(manifest.exports['./og'], undefined); for (const file of [ 'docs/guide/quickstart.md', 'docs/reference/cli.md', @@ -43,6 +47,19 @@ export function inspectPackage(tarball) { 'void: docs must be bundled at the package root', ); } + + if (manifest.name === '@void/image-renderer-takumi') { + assert(files.has('package/licenses/Roboto.txt'), `${manifest.name}: missing Roboto license`); + assert(manifest.exports['.'], `${manifest.name}: missing renderer export`); + assert(manifest.peerDependencies?.void, `${manifest.name}: missing void peer dependency`); + assert(manifest.dependencies?.['takumi-js'], `${manifest.name}: missing Takumi dependency`); + const output = execFileSync('tar', ['-xOf', tarball, 'package/dist/index.mjs'], { + encoding: 'utf8', + }); + assert.match(output, /from ["']takumi-js["']/, `${manifest.name}: 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..634ea90a3 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,35 @@ 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-renderer-takumi', + exports: { '.': './dist/index.mjs' }, + dependencies: { 'takumi-js': '~2.20.0' }, + peerDependencies: { void: '^1.8.0' }, +}; +const imageFiles = { + 'dist/index.mjs': 'import { render } from "takumi-js";\nimport("takumi-js/wasm");\n', + 'licenses/Roboto.txt': 'SIL Open Font License\n', +}; + +void test('accepts the renderer entry with external Takumi and its font license', (t) => { + inspectPackage(createPackage(t, imageManifest, true, imageFiles)); +}); + +void test('rejects renderer packages that omit the root export or void peer', (t) => { + for (const overrides of [{ exports: {} }, { 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/index.mjs': imageFiles['dist/index.mjs'] }, + { ...imageFiles, 'dist/index.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 85f7203fa..c356187d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,21 +59,22 @@ vp run --filter ./packages/vue typecheck # Typecheck a specific package pnpm workspaces managed through Vite+. Shared dependency versions use the **pnpm catalog** in `pnpm-workspace.yaml` (`typescript`, `vite-plus`, Vite+/Vitest aliases, `@cloudflare/workers-types`, wrangler). Make sure to run `vp install` after making package structure changes. -| Package | npm name | Purpose | -| ------------------------------------------------------------ | ------------------------- | ----------------------------------------------------------------- | -| [`packages/deploy-core`](./packages/deploy-core) | `@void/deploy-core` | Shared deployment manifests, events, and target-neutral contracts | -| [`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/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) | -| [`packages/vue`](./packages/vue/README.md) | `@void/vue` | Vue framework adapter for Pages mode (SSR, Link, useForm) | -| [`packages/svelte`](./packages/svelte/README.md) | `@void/svelte` | Svelte 5 framework adapter for Pages mode (SSR, Link, useForm) | -| [`packages/solid`](./packages/solid/README.md) | `@void/solid` | SolidJS framework adapter for Pages mode (SSR, Link, useForm) | -| [`docs`](./docs) | (private) | Documentation site (VitePress) | -| [`platform`](./platform/README.md) | (private) | Self-hosted platform source, routing, proxy, logs, and dashboard | -| `playground/*` | (private) | local apps for testing | +| Package | npm name | Purpose | +| -------------------------------------------------------------------- | ----------------------------- | ----------------------------------------------------------------- | +| [`packages/deploy-core`](./packages/deploy-core) | `@void/deploy-core` | Shared deployment manifests, events, and target-neutral contracts | +| [`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-renderer-takumi`](./packages/image-renderer-takumi) | `@void/image-renderer-takumi` | Takumi renderer for `void/image` | +| [`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) | +| [`packages/vue`](./packages/vue/README.md) | `@void/vue` | Vue framework adapter for Pages mode (SSR, Link, useForm) | +| [`packages/svelte`](./packages/svelte/README.md) | `@void/svelte` | Svelte 5 framework adapter for Pages mode (SSR, Link, useForm) | +| [`packages/solid`](./packages/solid/README.md) | `@void/solid` | SolidJS framework adapter for Pages mode (SSR, Link, useForm) | +| [`docs`](./docs) | (private) | Documentation site (VitePress) | +| [`platform`](./platform/README.md) | (private) | Self-hosted platform source, routing, proxy, logs, and dashboard | +| `playground/*` | (private) | local apps for testing | The platform source is part of this repository. Its workspace-only packages keep `private: true` to prevent accidental npm publication; this does not mean the platform source is private. Use `docs/guide/platform-development.md` for contributor/fork setup and `docs/guide/self-hosted-platform.md` for installation. diff --git a/README.md b/README.md index bc8244e80..419db9c9f 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 9a6435eaa..79b4d00d2 100644 --- a/TESTING.md +++ b/TESTING.md @@ -263,7 +263,10 @@ 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 with `void/image` and the installed `@void/image-renderer-takumi` +package 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..93b0a9c9b --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,242 @@ +# 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` with Cloudflare Browser Run or Takumi. + +## 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` and `baseline-void`: Worker and Void baselines. +- `image-gen`: Cloudflare Browser Run, with native browser emoji. +- `image-gen-takumi`: the same image workloads with Takumi and Twemoji. + +The Browser Run benchmark requires Browser Run on the target Cloudflare account. +Its render requests count toward Browser Run usage. + +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.jsonc` configures deployment count and latency +workloads. Use `//` or `/* … */` comments to temporarily disable entries. 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-gen +vp run --filter ./benchmark benchmark image-gen --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