Skip to content

Commit 71691c4

Browse files
committed
fix: Serve Class A framework assets after 404s.
1 parent 96b2255 commit 71691c4

3 files changed

Lines changed: 150 additions & 50 deletions

File tree

‎packages/void/src/index.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import { restartPlugin } from './plugin-restart.ts';
6767
import { routingPlugin } from './plugin-routing.ts';
6868
import { assertNoRootSourceConventionConflicts, resolveProjectPaths } from './project-paths.ts';
6969
import { scanQueuesSync } from './queues/scan.ts';
70+
import { compileAssetFallbackHelper } from './router/compile.ts';
7071
import { scanMiddlewareSync, scanRoutePatternsSync } from './router/scan.ts';
7172
import { scanWebSocketRoutesSync } from './router/websocket.ts';
7273
import { SANDBOX_MIGRATION_TAG, isSandboxEnabled, resolveSandboxConfig } from './sandbox/config.ts';
@@ -254,6 +255,7 @@ function generateClassATriggerWrapper(
254255
framework: Framework,
255256
original: string,
256257
isBuild: boolean,
258+
assetsDir = 'assets',
257259
): string {
258260
const outDir = join(root, '.void');
259261
mkdirSync(outDir, { recursive: true });
@@ -265,9 +267,10 @@ import original from ${JSON.stringify(original)};
265267
export default {
266268
...original,
267269
async fetch(request, env, ctx) {
268-
return original.fetch(request, env, ctx);
270+
return serveWithAssets(request, env, await original.fetch(request, env, ctx));
269271
},
270272
};
273+
${compileAssetFallbackHelper(assetsDir)}
271274
`
272275
: `// @ts-nocheck — Auto-generated by Void in dev. Do NOT edit.
273276
import original from ${JSON.stringify(original)};
@@ -1385,6 +1388,21 @@ export function voidPlugin(options?: {
13851388

13861389
if (framework) {
13871390
workerConfig.main = getFrameworkEntry(framework, root, devTriggerToken);
1391+
const frameworkBuildWrapperPlugin: Plugin = {
1392+
name: 'void:framework-build-wrapper',
1393+
configResolved(resolved) {
1394+
if (resolved.command !== 'build') {
1395+
return;
1396+
}
1397+
generateClassATriggerWrapper(
1398+
root,
1399+
framework,
1400+
getOriginalFrameworkEntry(framework, root),
1401+
true,
1402+
resolved.build.assetsDir,
1403+
);
1404+
},
1405+
};
13881406
const existingFlags = (workerConfig.compatibility_flags as Array<string> | undefined) ?? [];
13891407
if (!existingFlags.includes('nodejs_compat')) {
13901408
workerConfig.compatibility_flags = [...existingFlags, 'nodejs_compat'];
@@ -1452,6 +1470,7 @@ export function voidPlugin(options?: {
14521470
}),
14531471
migrationPlugin(root, getDatabaseDialect(config)),
14541472
...(vinextCompat ? [vinextCompat] : []),
1473+
frameworkBuildWrapperPlugin,
14551474
frameworkTriggersPlugin(root, { devTriggerToken }),
14561475
devTriggersHintPlugin(root, { framework: true, devTriggerToken }),
14571476
...cloudflare({

‎packages/void/src/router/compile.ts‎

Lines changed: 49 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -2329,6 +2329,54 @@ function compilePageRoutes(
23292329
lines.push('');
23302330
}
23312331

2332+
/**
2333+
* Generate the asset fallthrough helper shared by native Void workers and
2334+
* Class A framework wrappers. If the app returns 404, check ASSETS binding
2335+
* for static files and set cache headers. Edge caching of hashed assets
2336+
* happens at the dispatch layer (see design doc 0042).
2337+
*/
2338+
export function compileAssetFallbackHelper(assetsDir = 'assets', serveSpaFallback = false): string {
2339+
const spaFallbackCode = serveSpaFallback
2340+
? ` // SPA fallback: when HTML-owning features make
2341+
// assetConfig.not_found_handling = 'none', the asset binding returns 404
2342+
// instead of falling back to index.html itself. Do that fallback here, after
2343+
// user routes/middleware have run, so auth gates and OAuth callbacks see the request first.
2344+
// Pages and SSR apps leave this disabled so intentional HTML 404s stay 404.
2345+
const accept = request.headers.get("accept") ?? "";
2346+
if (accept.includes("text/html")) {
2347+
const indexUrl = new URL("/index.html", request.url);
2348+
const indexAsset = await env.ASSETS.fetch(new Request(indexUrl, { method: request.method }));
2349+
if (indexAsset.status === 200) {
2350+
const res = new Response(indexAsset.body, {
2351+
status: 200,
2352+
headers: indexAsset.headers,
2353+
});
2354+
res.headers.set("Cache-Control", "no-store");
2355+
res.headers.set("Content-Type", "text/html; charset=utf-8");
2356+
return res;
2357+
}
2358+
}
2359+
return response;`
2360+
: ` return response;`;
2361+
2362+
return `
2363+
async function serveWithAssets(request, env, response) {
2364+
if (response.status !== 404 || !env.ASSETS || (request.method !== "GET" && request.method !== "HEAD")) return response;
2365+
const asset = await env.ASSETS.fetch(new Request(request.url, { method: request.method, headers: request.headers }));
2366+
if (asset.status !== 404) {
2367+
const res = new Response(asset.body, asset);
2368+
if (new URL(request.url).pathname.startsWith(${JSON.stringify('/' + assetsDir + '/')})) {
2369+
res.headers.set("Cache-Control", "public, max-age=31536000, immutable");
2370+
} else {
2371+
res.headers.set("Cache-Control", "no-store");
2372+
}
2373+
return res;
2374+
}
2375+
${spaFallbackCode}
2376+
}
2377+
`;
2378+
}
2379+
23322380
/**
23332381
* Generate the Worker entry module code.
23342382
* Re-exports the Hono app from the virtual module with an asset-serving
@@ -2438,55 +2486,7 @@ function __filterInternalBindings(env) {
24382486
}
24392487
`;
24402488

2441-
// Asset fallthrough helper — if the app returns 404, check ASSETS binding
2442-
// for static files and set cache headers. Edge caching of hashed assets
2443-
// happens at the dispatch layer (see design doc 0042).
2444-
// Safe for workers without ASSETS binding (env.ASSETS check short-circuits).
2445-
//
2446-
// Hashed assets under assetsDir get long immutable caching (content-addressed).
2447-
// Non-hashed asset responses are stamped no-store: a stale entry there would
2448-
// shadow routes that are added or fixed in subsequent deploys across the edge
2449-
// cache boundary, which the platform's deploy-scoped cache keys (dispatch
2450-
// layer) can't reach once CF's managed edge has cached the response.
2451-
const spaFallbackCode = serveSpaFallback
2452-
? ` // SPA fallback: when HTML-owning features make
2453-
// assetConfig.not_found_handling = 'none', the asset binding returns 404
2454-
// instead of falling back to index.html itself. Do that fallback here, after
2455-
// user routes/middleware have run, so auth gates and OAuth callbacks see the request first.
2456-
// Pages and SSR apps leave this disabled so intentional HTML 404s stay 404.
2457-
const accept = request.headers.get("accept") ?? "";
2458-
if (accept.includes("text/html")) {
2459-
const indexUrl = new URL("/index.html", request.url);
2460-
const indexAsset = await env.ASSETS.fetch(new Request(indexUrl, { method: request.method }));
2461-
if (indexAsset.status === 200) {
2462-
const res = new Response(indexAsset.body, {
2463-
status: 200,
2464-
headers: indexAsset.headers,
2465-
});
2466-
res.headers.set("Cache-Control", "no-store");
2467-
res.headers.set("Content-Type", "text/html; charset=utf-8");
2468-
return res;
2469-
}
2470-
}
2471-
return response;`
2472-
: ` return response;`;
2473-
2474-
const assetHelper = `
2475-
async function serveWithAssets(request, env, response) {
2476-
if (response.status !== 404 || !env.ASSETS || (request.method !== "GET" && request.method !== "HEAD")) return response;
2477-
const asset = await env.ASSETS.fetch(new Request(request.url, { method: request.method, headers: request.headers }));
2478-
if (asset.status !== 404) {
2479-
const res = new Response(asset.body, asset);
2480-
if (new URL(request.url).pathname.startsWith(${JSON.stringify('/' + assetsDir + '/')})) {
2481-
res.headers.set("Cache-Control", "public, max-age=31536000, immutable");
2482-
} else {
2483-
res.headers.set("Cache-Control", "no-store");
2484-
}
2485-
return res;
2486-
}
2487-
${spaFallbackCode}
2488-
}
2489-
`;
2489+
const assetHelper = compileAssetFallbackHelper(assetsDir, serveSpaFallback);
24902490

24912491
const fetchHandler = remotePath
24922492
? `async (request, env, ctx) => {
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2+
import { tmpdir } from 'node:os';
3+
import { join } from 'pathe';
4+
import type { Plugin, ResolvedConfig } from 'vite';
5+
import { afterEach, describe, expect, it, vi } from 'vite-plus/test';
6+
7+
type MockCloudflarePluginConfig = {
8+
config: (resolved: Record<string, unknown>) => Record<string, unknown>;
9+
};
10+
11+
vi.mock('@cloudflare/vite-plugin', () => ({
12+
cloudflare(pluginConfig: MockCloudflarePluginConfig): Array<Plugin> {
13+
return [{ name: 'mock:cloudflare', api: { pluginConfig } } as Plugin];
14+
},
15+
}));
16+
17+
const roots: Array<string> = [];
18+
19+
function createTanStackRoot(): string {
20+
const root = mkdtempSync(join(tmpdir(), 'void-class-a-wrapper-'));
21+
roots.push(root);
22+
writeFileSync(
23+
join(root, 'package.json'),
24+
JSON.stringify({
25+
type: 'module',
26+
dependencies: {
27+
'@tanstack/react-start': '^1.168.19',
28+
},
29+
}),
30+
);
31+
writeFileSync(
32+
join(root, 'void.json'),
33+
JSON.stringify({ worker: { compatibility_date: '2026-02-24' } }),
34+
);
35+
return root;
36+
}
37+
38+
function callConfigResolved(plugin: Plugin, config: Partial<ResolvedConfig>) {
39+
const hook = plugin.configResolved;
40+
const fn = typeof hook === 'function' ? hook : hook?.handler;
41+
if (typeof fn !== 'function') {
42+
throw new Error('configResolved not callable');
43+
}
44+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
45+
(fn as any)(config);
46+
}
47+
48+
afterEach(() => {
49+
vi.restoreAllMocks();
50+
vi.resetModules();
51+
while (roots.length > 0) {
52+
rmSync(roots.pop()!, { recursive: true, force: true });
53+
}
54+
});
55+
56+
describe('Class A framework build wrapper', () => {
57+
it('falls through framework 404 responses to ASSETS for uploaded client assets', async () => {
58+
const root = createTanStackRoot();
59+
vi.spyOn(process, 'cwd').mockReturnValue(root);
60+
61+
const { voidPlugin } = await import('../../src/index.ts');
62+
const plugins = voidPlugin();
63+
const wrapperPlugin = plugins.find((plugin) => plugin.name === 'void:framework-build-wrapper');
64+
if (!wrapperPlugin) {
65+
throw new Error('Expected Class A wrapper plugin.');
66+
}
67+
68+
callConfigResolved(wrapperPlugin, {
69+
command: 'build',
70+
build: { assetsDir: 'static' } as ResolvedConfig['build'],
71+
} as Partial<ResolvedConfig>);
72+
73+
const code = readFileSync(join(root, '.void', 'tanstack-start-trigger-wrapper.ts'), 'utf-8');
74+
expect(code).toContain('return serveWithAssets(request, env, await original.fetch');
75+
expect(code).toContain('async function serveWithAssets(request, env, response)');
76+
expect(code).toContain('env.ASSETS.fetch(new Request(request.url');
77+
expect(code).toContain('request.method !== "GET" && request.method !== "HEAD"');
78+
expect(code).toContain('"public, max-age=31536000, immutable"');
79+
expect(code).toContain('"/static/"');
80+
});
81+
});

0 commit comments

Comments
 (0)