Skip to content
Draft
5 changes: 5 additions & 0 deletions .changeset/kit-vite-respond.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

feat: add `virtual:sveltekit/server` and the `respond` option of `adapter.vite`, so that adapters can render requests in their platform's runtime during `vite dev`
14 changes: 14 additions & 0 deletions documentation/docs/25-build-and-deploy/99-writing-adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ export default function (options) {
}
},
vite: {
respond(request, { getClientAddress, resolve }) {
// during `vite dev`, render the request in your platform's runtime,
// or call `resolve` to render it in Node as usual
return resolve(request);
},
getRequest(options) {
const request = getRequest(options);
// modify the Request object here if needed
Expand Down Expand Up @@ -79,3 +84,12 @@ Within the `adapt` method, there are a number of things that an adapter should d
- Put the user's static files and the generated JS/CSS in the correct location for the target platform

Where possible, we recommend putting the adapter output under the `build/` directory with any intermediate output placed under `.svelte-kit/[adapter-name]`.

## Rendering in your platform's runtime during development

By default, `vite dev` renders requests in Node. If your platform's runtime can run in a [Vite environment](https://vite.dev/guide/api-environment), for example through a Vite plugin that your platform provides, you can render requests there instead, so that development behaves like production:

- In the code that runs in that environment, import `server` from `virtual:sveltekit/server`. It has the same API as the `server` that `builder.generateServerInstance` writes for production: call `await server.init({ env })` and `server.respond(request, { getClientAddress })`
- Add a `respond` function to your adapter's `vite` config that sends each request to that code and returns its response. SvelteKit calls it after serving static files, imported assets and the service worker, and logs the response as usual. It also sends its own requests through it, such as to find what a remote module exports, so that your app's modules only run in your platform's runtime

During development, `server` reads imported assets from the Vite dev server, so it doesn't need a `read` function.
3 changes: 2 additions & 1 deletion packages/kit/scripts/generate-dts.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ await createBundle({
'$app/paths': 'src/runtime/app/paths/public.d.ts',
'$app/server': 'src/runtime/app/server/public.d.ts',
'$app/service-worker': 'src/runtime/app/service-worker/index.js',
'$app/state': 'src/runtime/app/state/public.d.ts'
'$app/state': 'src/runtime/app/state/public.d.ts',
'virtual:sveltekit/server': 'src/exports/virtual/server/public.d.ts'
},
include: ['src'],
exclude: ['**/test/**', '**/fixtures/**', '**/*.spec.js'],
Expand Down
24 changes: 24 additions & 0 deletions packages/kit/src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@
*/
export const SVELTE_KIT_ASSETS = '/_svelte_kit_assets';

/** dev server path that returns the css a module depends on */
export const DEV_INLINE_STYLES_PATH = '/@sveltejs/kit/dev/inline-styles';

/** dev server path that returns the sizes of the assets a module imports */
export const DEV_SERVER_ASSETS_PATH = '/@sveltejs/kit/dev/server-assets';

/**
* response header that reports the features and remote function a request used
*/
export const DEV_INFO_HEADER = 'x-sveltekit-dev-info';

/**
* request header that asks the dev server for the exports of a remote module
*/
export const DEV_REMOTE_EXPORTS_HEADER = 'x-sveltekit-dev-remote-exports';

export const DEV_SERVER_ID = 'virtual:sveltekit/server';

/** exports the origin of the vite dev server */
export const DEV_HOST_ID = '__sveltekit/dev/host';

/** id prefix of the modules that load a remote module by its hash */
export const DEV_REMOTE_PREFIX = '__sveltekit/dev/remote/';

export const GENERATED_COMMENT = '// this file is generated — do not edit it';

export const ENDPOINT_METHODS = [
Expand Down
18 changes: 18 additions & 0 deletions packages/kit/src/exports/public.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,24 @@ export interface Adapter {
}

export interface AdapterViteConfig {
/**
* During `vite dev`, SvelteKit calls this function with each request it would render, after
* serving static files, imported assets and the service worker. Use it to render requests in
* your platform's runtime instead of Node: send them to code that runs there, which imports
* `server` from `virtual:sveltekit/server` and calls `server.respond`.
* Call `resolve` to render a request in Node, as SvelteKit does without this function.
* SvelteKit also sends its own requests through it, such as to find what a remote module exports.
* @since 3.3.0
*/
respond?: (
request: Request,
options: {
/** Returns the IP address of the client that sent the request */
getClientAddress: () => string;
/** Renders the request in Node */
resolve: (request: Request) => Promise<Response>;
}
) => Promise<Response>;
/**
* This function overrides the default behavior during Vite's dev and preview modes
* to convert an `http.IncomingMessage` to a `Request` object.
Expand Down
18 changes: 18 additions & 0 deletions packages/kit/src/exports/virtual/server/public.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Server } from '@sveltejs/kit';

/**
* SvelteKit's server during `vite dev`, for code that renders requests in a Vite environment
* outside the Vite process, such as an adapter's Worker in workerd. It has the same API as the
* [server](https://svelte.dev/docs/kit/@sveltejs-kit#Server) that `builder.generateServerInstance`
* writes for production. It reads imported assets from the Vite dev server, so `init` doesn't need
* a `read` function. See [`respond`](https://svelte.dev/docs/kit/@sveltejs-kit#AdapterViteConfig).
*
* ```js
* import { server } from 'virtual:sveltekit/server';
*
* await server.init({ env });
* const response = await server.respond(request, { getClientAddress: () => address });
* ```
* @since 3.3.0
*/
export const server: Server;
14 changes: 7 additions & 7 deletions packages/kit/src/exports/vite/dev/generate_manifest.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** @import { EnvironmentModuleNode, ErrorPayload, ViteDevServer } from 'vite' */
/** @import { DevEnvironment, EnvironmentModuleNode, ErrorPayload, ViteDevServer } from 'vite' */
/** @import { ModuleRunner } from 'vite/module-runner' */
/** @import { ManifestData, SSRManifest, SSRNode, RemoteChunk, UniversalNode, ValidatedConfig } from 'types' */
import fs from 'node:fs';
Expand All @@ -10,7 +10,7 @@ import * as e from '../../../messages/build-errors.js';
import { styleText } from 'node:util';

// vite-specifc queries that we should skip handling for css urls
const vite_css_query_regex = /(?:\?|&)(?:raw|url|inline)(?:&|$)/;
export const vite_css_query_regex = /(?:\?|&)(?:raw|url|inline)(?:&|$)/;

/**
* @param {typeof import('vite')} vite
Expand Down Expand Up @@ -137,7 +137,7 @@ export function generate_manifest(
const deps = new Set();

for (const module_node of module_nodes) {
await find_deps(vite_dev_server, module_node, deps);
await find_deps(vite_dev_server.environments.ssr, module_node, deps);
}

/** @type {Record<string, string>} */
Expand Down Expand Up @@ -266,11 +266,11 @@ async function resolve(vite, vite_dev_server, runner, id) {
}

/**
* @param {ViteDevServer} vite
* @param {DevEnvironment} environment the vite environment whose module graph to walk
* @param {EnvironmentModuleNode} node
* @param {Set<EnvironmentModuleNode>} deps
*/
async function find_deps(vite, node, deps) {
export async function find_deps(environment, node, deps) {
// since `transformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
// instead of using `await`, we resolve all branches in parallel.
/** @type {Promise<void>[]} */
Expand All @@ -280,13 +280,13 @@ async function find_deps(vite, node, deps) {
async function add(node) {
if (!deps.has(node)) {
deps.add(node);
await find_deps(vite, node, deps);
await find_deps(environment, node, deps);
}
}

/** @param {string} url */
async function add_by_url(url) {
const node = await vite.environments.ssr.moduleGraph.getModuleByUrl(url);
const node = await environment.moduleGraph.getModuleByUrl(url);

if (node) {
await add(node);
Expand Down
Loading
Loading