Skip to content

Commit 6164a3f

Browse files
committed
docs: define the deployment contract for provider plugins
Start mode ships no platform adapters, so provider Vite plugins (Nitro, Cloudflare) build on the plugin's environments, the ssr environment's index handler entry, build ordering, output locations and dev handover. The README now states those in one section as stable from 3.0, and everything else as internal. A test builds an SSR and a client-mode app through a stand-in provider that moves both outputs and builds the server first, then serves the index entry from a separate Node process.
1 parent 9dabc25 commit 6164a3f

3 files changed

Lines changed: 172 additions & 0 deletions

File tree

‎.changeset/deployment-contract.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@solidjs/vite-plugin': patch
3+
---
4+
5+
Document the deployment contract provider plugins can rely on from 3.0: the `client` and `ssr` environments, the `ssr` environment's `index` handler entry with its `{ fetch }` and `handleRequest` exports, client-first build order, output locations, client-mode output, and the dev handover. A test builds an app through a stand-in provider that relies on it.

‎README.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1250,6 +1250,50 @@ modules compile with no option. The plugin loads the package's `/vite`
12501250
front end the first time it meets an `.rx` module, so a project without
12511251
`.rx` files never loads it. A `.rx` entry in `frontends` replaces it.
12521252

1253+
## Deployment contract
1254+
1255+
Start mode ships no platform adapters. An app deploys through a provider
1256+
Vite plugin (Nitro's `nitro/vite`, `@cloudflare/vite-plugin`, and others) or
1257+
through the Node server `start.nodeServer` emits. From 3.0, providers can
1258+
rely on the following; virtual modules and generated files not documented
1259+
in this README are internal.
1260+
1261+
1. **Environments.** The app builds as two Vite environments, `client` and
1262+
`ssr` (consumer `server`).
1263+
2. **Server entry.** The `ssr` environment's build input `index` is the
1264+
app's handler (`dist/server/server.js` by default). Its default export is
1265+
`{ fetch(request) }`; its named `handleRequest(request, options)` takes
1266+
per-call options, such as `event: { nativeEvent }` to hand the platform's
1267+
raw request to `getRequestEvent()`. It answers pages, `start.middleware`
1268+
and the server-function endpoint. With `ssr: true`, the `ssr` dev
1269+
environment has the same `index` input.
1270+
3. **Build order.** The client builds before the server, which embeds the
1271+
client manifest. The plugin builds the client from its own `buildApp`
1272+
hook, so a provider that builds from a later one (`order: 'post'`, as
1273+
Nitro does) may take the environments in any order.
1274+
4. **Output.** Client files go to the `client` environment's `outDir`
1275+
(default `dist/client`): content-hashed files under `build.assetsDir`,
1276+
safe to cache forever, and Vite's manifest under `.vite/`, which is not
1277+
for serving. The server bundle goes to the `ssr` environment's `outDir`.
1278+
A provider may move either directory; the plugin follows the configured
1279+
`outDir`.
1280+
5. **Modes.** With `ssr: true`, every request that isn't a static file goes
1281+
to the handler. In client mode, `dist/client` is a static site with a
1282+
prerendered `index.html`, the fallback for page navigations. Its server
1283+
bundle stays when `serverFunctions` needs it for their endpoint
1284+
(`/_server`, joined with `base`) or when a provider's `buildApp` hook
1285+
orchestrates the build; a standalone build drops it.
1286+
6. **Dev.** When a provider replaces the `ssr` dev environment with one that
1287+
can't run in Vite's process (workerd, for example), the plugin's dev
1288+
middlewares stand down and the provider dispatches requests to `index`;
1289+
dev CSS reaches that runtime over HTTP from the dev server, with nothing
1290+
to configure. `start.externalServer` hands over the whole server
1291+
environment, and `serverFunctions.devMiddleware: false` only the
1292+
endpoint.
1293+
1294+
The provider owns the rest: the runtime, serving static files and routing
1295+
other requests to the handler, platform configuration, and bindings.
1296+
12531297
## Asset URLs in JSX
12541298

12551299
Static asset URLs in `src`, `srcset` and `poster` on `<img>`, `<source>` and

‎src/deployment-contract.test.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// The deployment contract (README, "Deployment contract"), as a stand-in
2+
// provider relies on it: it moves both outputs, builds the server first
3+
// from a `post` buildApp hook, and serves the `ssr` environment's `index`
4+
// entry from a separate Node process, as a host would. The dev half (point
5+
// 6) runs in examples/start-ssr's `external` and `detect` modes.
6+
import { spawnSync } from 'node:child_process';
7+
import { existsSync, readFileSync } from 'node:fs';
8+
import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises';
9+
import { tmpdir } from 'node:os';
10+
import path from 'node:path';
11+
import { fileURLToPath, pathToFileURL } from 'node:url';
12+
import { createBuilder, type Plugin } from 'vite';
13+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
14+
import solidPlugin from './index.js';
15+
16+
let root: string;
17+
18+
beforeAll(async () => {
19+
root = await realpath(await mkdtemp(path.join(tmpdir(), 'solid-deployment-contract-')));
20+
await symlink(
21+
fileURLToPath(new URL('../node_modules', import.meta.url)),
22+
path.join(root, 'node_modules'),
23+
'dir',
24+
);
25+
await mkdir(path.join(root, 'src'));
26+
await writeFile(
27+
path.join(root, 'src/App.tsx'),
28+
[
29+
"import { getRequestEvent } from '@solidjs/web';",
30+
'export default function App() {',
31+
' const event = getRequestEvent() as { nativeEvent?: { marker?: string } } | undefined;',
32+
" return <h1>native event: {event?.nativeEvent?.marker ?? 'none'}</h1>;",
33+
'}',
34+
].join('\n'),
35+
);
36+
});
37+
38+
afterAll(async () => {
39+
await rm(root, { recursive: true, force: true });
40+
});
41+
42+
function provider(output: string): Plugin {
43+
return {
44+
name: 'stand-in-provider',
45+
configEnvironment(name) {
46+
if (name === 'client') return { build: { outDir: `${output}/public` } };
47+
if (name === 'ssr') return { build: { outDir: `${output}/server` } };
48+
},
49+
buildApp: {
50+
order: 'post',
51+
async handler(builder) {
52+
// Server first, as orchestrators that build their workers first do.
53+
for (const name of ['ssr', 'client']) {
54+
const environment = builder.environments[name];
55+
if (environment && !environment.isBuilt) await builder.build(environment);
56+
}
57+
},
58+
},
59+
};
60+
}
61+
62+
async function buildApp(output: string, options: Parameters<typeof solidPlugin>[0]) {
63+
const builder = await createBuilder({
64+
root,
65+
configFile: false,
66+
// Own optimizer cache: node_modules is a symlink to the repo's.
67+
cacheDir: path.join(root, '.vite'),
68+
logLevel: 'silent',
69+
plugins: [solidPlugin(options), provider(output)],
70+
});
71+
await builder.buildApp();
72+
}
73+
74+
// The client entry a page loads, which must exist in the client output.
75+
function clientEntry(html: string, publicDir: string) {
76+
const src = html.match(/<script[^>]*type="?module"?[^>]*src="([^"]+)"/)?.[1];
77+
return { src, exists: !!src && existsSync(path.join(publicDir, src)) };
78+
}
79+
80+
describe('deployment contract', () => {
81+
it('serves an SSR app through the index entry a provider builds', async () => {
82+
await buildApp('.ssr-output', { start: true, ssr: true });
83+
const publicDir = path.join(root, '.ssr-output/public');
84+
expect(existsSync(path.join(publicDir, '.vite/manifest.json'))).toBe(true);
85+
const serverEntry = path.join(root, '.ssr-output/server/server.js');
86+
expect(existsSync(serverEntry)).toBe(true);
87+
88+
const script = `
89+
const app = await import(${JSON.stringify(pathToFileURL(serverEntry).href)});
90+
const request = () => new Request('http://localhost/', { headers: { accept: 'text/html' } });
91+
const page = await app.default.fetch(request());
92+
const hosted = await app.handleRequest(request(), {
93+
event: { nativeEvent: { marker: 'from-host' } },
94+
});
95+
console.log(JSON.stringify({
96+
status: page.status,
97+
type: page.headers.get('content-type'),
98+
page: await page.text(),
99+
hosted: await hosted.text(),
100+
}));
101+
`;
102+
const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
103+
cwd: root,
104+
encoding: 'utf8',
105+
});
106+
expect(result.stderr).toBe('');
107+
const served = JSON.parse(result.stdout.trim().split('\n').pop()!);
108+
expect(served.status).toBe(200);
109+
expect(served.type).toMatch(/^text\/html/);
110+
expect(served.page).toMatch(/native event: (<!--[^>]*-->)*none/);
111+
expect(served.hosted).toMatch(/native event: (<!--[^>]*-->)*from-host/);
112+
// Built client-first, whatever order the provider asks for.
113+
expect(clientEntry(served.page, publicDir)).toEqual({ src: expect.any(String), exists: true });
114+
}, 120_000);
115+
116+
it('builds a client-mode app to a static site, keeping the service for the host', async () => {
117+
await buildApp('.client-output', { start: true });
118+
const publicDir = path.join(root, '.client-output/public');
119+
const html = readFileSync(path.join(publicDir, 'index.html'), 'utf-8');
120+
expect(clientEntry(html, publicDir)).toEqual({ src: expect.any(String), exists: true });
121+
expect(existsSync(path.join(root, '.client-output/server/server.js'))).toBe(true);
122+
}, 120_000);
123+
});

0 commit comments

Comments
 (0)