From e38059e94725aacc4f1f02b4d22ab74086a5717f Mon Sep 17 00:00:00 2001 From: "svelte-docs-bot[bot]" <196124396+svelte-docs-bot[bot]@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:42:49 +0000 Subject: [PATCH] sync Kit next docs --- .../20-core-concepts/60-remote-functions.md | 35 +- .../25-build-and-deploy/30-adapter-auto.md | 1 + .../60-adapter-cloudflare.md | 56 +-- .../25-build-and-deploy/80-adapter-netlify.md | 2 - .../25-build-and-deploy/90-adapter-vercel.md | 11 +- .../99-writing-adapters.md | 15 +- .../docs/kit/30-advanced/68-observability.md | 2 + .../kit/40-best-practices/05-performance.md | 20 +- .../35-migrating-to-sveltekit-3.md | 95 +++- .../docs/kit/98-reference/10-@sveltejs-kit.md | 303 ++++++++---- .../kit/98-reference/15-@sveltejs-kit-vite.md | 453 +++++++++--------- .../docs/kit/98-reference/20-$app-server.md | 120 ++--- 12 files changed, 649 insertions(+), 464 deletions(-) diff --git a/apps/svelte.dev/content/docs/kit/20-core-concepts/60-remote-functions.md b/apps/svelte.dev/content/docs/kit/20-core-concepts/60-remote-functions.md index c9687e4fe1..309a28c128 100644 --- a/apps/svelte.dev/content/docs/kit/20-core-concepts/60-remote-functions.md +++ b/apps/svelte.dev/content/docs/kit/20-core-concepts/60-remote-functions.md @@ -417,7 +417,7 @@ A form is composed of a set of _fields_, which are defined by the schema. In the These attributes allow SvelteKit to set the correct input type, set a `name` that is used to construct the `data` passed to the handler, populate the `value` of the form (for example following a failed submission, to save the user having to re-enter everything), and set the [`aria-invalid`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-invalid) state. -Passing a second argument to `.as(...)` is useful when rendering a form from existing data, such as an edit form or multiple instances created with [`for(...)`](#form-Multiple-instances-of-a-form). As well as setting the value of the element when it is rendered, it controls the value of the element when the form is reset. `radio`, `submit` and `hidden` inputs always need this value, and `checkbox` inputs need it when they represent one option in an array field. `file` inputs cannot be populated this way. +Passing a second argument to `.as(...)` is useful when rendering a form from existing data, such as an edit form or multiple instances created with [`for(...)`](#form-Multiple-instances-of-a-form). As well as setting the value of the element when it is rendered, it controls the value of the element when the form is reset. `radio`, `submit` and `hidden` inputs always need this value, and `checkbox` inputs need it when they represent one option in an array field. For these `radio` and `checkbox` inputs the second argument identifies the option, so whether it is currently checked goes in a third argument, e.g. `.as('radio', option, settings.visibility === option)` or `.as('checkbox', tag, settings.tags.includes(tag))`. `file` inputs cannot be populated this way. > [!NOTE] The generated `name` attribute uses JS object notation (e.g. `nested.array[0].value`). String keys that require quotes such as `object['nested-array'][0].value` are not supported. Under the hood, boolean checkbox and number field names are prefixed with `b:` and `n:`, respectively, to signal SvelteKit to coerce the values from strings prior to validation. @@ -1106,7 +1106,27 @@ export const createPost = form( ); ``` -`requested` gives you access to the queries the client requested to refresh. Each entry is an `{ arg, query }` object: `arg` is the value the query's implementation function received — i.e. the argument *after* the schema has validated and (where applicable) transformed it — and `query` is a `RemoteQuery` already bound to the client's original cache key, so calling `query.refresh()` / `query.set(...)` updates the correct client instance. If parsing an argument fails, that query will error, but the entire command will not fail. `requested`'s second parameter, `limit`, is the maximum number of items it will return. Any refresh requests beyond this limit will fail. +`requested` gives you access to the queries the client requested to refresh. Each entry is an `{ arg, query, ignore }` object: `arg` is the value the query's implementation function received — i.e. the argument *after* the schema has validated and (where applicable) transformed it — and `query` is a `RemoteQuery` already bound to the client's original cache key, so calling `query.refresh()` / `query.set(...)` updates the correct client instance. Call `ignore()` if you intentionally do not want to update a particular instance: + +```js +import { requested, query } from '$app/server'; + +export const getPosts = query('unchecked', ({ filter }) => { + return ['foo', 'bar']; +}); +---cut--- +for (const { arg, query, ignore } of requested(getPosts, 10)) { + if (arg.filter === 'author:santa') { + void query.refresh(); + } else { + ignore(); + } +} +``` + +Every requested update must be refreshed, set, reconnected (for a live query), or explicitly ignored. Otherwise, the corresponding query will enter an error state on the client. If parsing or validating an argument fails, that query will also error, but the entire command will not fail. + +`requested`'s second parameter, `limit`, is the maximum number of items it will return. Any refresh requests beyond this limit will fail on the client. > [!NOTE] `limit` is required because the list of refresh requests is controlled by the client — each entry causes the server to validate an argument and usually re-fetch data, so an unbounded list is a denial-of-service risk. Choose a limit that reflects the worst case you're willing to handle per request. You _can_ pass `Infinity` if you have explicitly decided to accept any number of refreshes, but it is not recommended. @@ -1121,6 +1141,17 @@ declare const getPosts: RemoteQueryFunction; await requested(getPosts, 1).refreshAll(); ``` +If you want to intentionally ignore every selected update, use `ignoreAll`: + +```js +import { requested } from '$app/server'; + +---cut--- +await requested(getPosts, 10).ignoreAll(); +``` + +`ignoreAll` only ignores entries within the specified `limit`. Any excess entries still fail on the client. + > [!NOTE] Why does the command have to name every query it's willing to refresh? Two reasons: > > - **Bundle size.** If a command could implicitly refresh *any* query in your app, SvelteKit would have to include every query's code in the command's server bundle, because it can't know ahead of time which ones will be called. diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md index 71bd8bd4d1..bc3320414e 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md @@ -11,6 +11,7 @@ When you create a new SvelteKit project with `npx sv create`, it installs [`adap - [`svelte-adapter-azure-swa`](https://github.com/geoffrich/svelte-adapter-azure-swa) for [Azure Static Web Apps](https://docs.microsoft.com/en-us/azure/static-web-apps/) - [`svelte-kit-sst`](https://github.com/sst/v2/tree/master/packages/svelte-kit-sst) for [AWS via SST](https://sst.dev/docs/start/aws/svelte) - [`@sveltejs/adapter-node`](adapter-node) for [Google Cloud Run](https://cloud.google.com/run) +- [`@sveltejs/adapter-node`](adapter-node) for [Render](https://render.com) It's recommended to install the appropriate adapter to your `devDependencies` once you've settled on a target environment, since this will add the adapter to your lockfile and slightly improve install times on CI. diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md index 957b24f846..58a265a6bf 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md @@ -5,7 +5,7 @@ title: Cloudflare To deploy to [Cloudflare Workers](https://workers.cloudflare.com/) or [Cloudflare Pages](https://pages.cloudflare.com/), use [`adapter-cloudflare`](https://github.com/sveltejs/kit/tree/main/packages/adapter-cloudflare). -This adapter will be installed by default when you use [`adapter-auto`](adapter-auto). If you plan on staying with Cloudflare, you can switch from [`adapter-auto`](adapter-auto) to using this adapter directly so that `event.platform` is emulated during local development, type declarations are automatically applied, and the ability to set Cloudflare-specific options is provided. +This adapter will be installed by default when you use [`adapter-auto`](adapter-auto). If you plan on staying with Cloudflare, you can switch from [`adapter-auto`](adapter-auto) to using this adapter directly so that `cloudflare:workers` is emulated during local development, type declarations are automatically applied, and the ability to set Cloudflare-specific options is provided. ## Comparisons @@ -54,7 +54,7 @@ Path to your [Wrangler configuration file](https://developers.cloudflare.com/wor ### platformProxy -Preferences for the emulated `platform.env` local bindings. See the [getPlatformProxy](https://developers.cloudflare.com/workers/wrangler/api/#parameters-1) Wrangler API documentation for a full list of options. +Preferences for the emulated `env` local bindings. See the [getPlatformProxy](https://developers.cloudflare.com/workers/wrangler/api/#parameters-1) Wrangler API documentation for a full list of options. ### fallback @@ -131,62 +131,34 @@ Functions contained in the [`/functions` directory](https://developers.cloudflar ## Runtime APIs -The [`env`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#parameters) object contains your project's [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/), which consist of KV/DO namespaces, etc. It is passed to SvelteKit via the `platform` property, along with [`ctx`](https://developers.cloudflare.com/workers/runtime-apis/context/), [`caches`](https://developers.cloudflare.com/workers/runtime-apis/cache/), and [`cf`](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties), meaning that you can access it in hooks and endpoints: +The [`env`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#parameters) object contains your project's [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/), which consist of KV/DO namespaces, etc. It is available on the [`cloudflare:workers`](https://developers.cloudflare.com/workers/runtime-apis/bindings/#importing-env-as-a-global) module. ```js +/// file: +server.js // @filename: ambient.d.ts -import { DurableObjectNamespace } from '@cloudflare/workers-types'; - -declare global { - namespace App { - interface Platform { - env: { - YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace; - }; - } - } +declare module 'cloudflare:workers' { + export const env: { + YOUR_DURABLE_OBJECT_NAMESPACE: import('@cloudflare/workers-types').DurableObjectNamespace; + }; } // @filename: +server.js // ---cut--- // @errors: 2355 2322 -/// file: +server.js +import { env } from 'cloudflare:workers'; + /** @type {import('./$types').RequestHandler} */ -export async function POST({ request, platform }) { - const x = platform?.env.YOUR_DURABLE_OBJECT_NAMESPACE.idFromName('x'); +export async function POST() { + const x = env.YOUR_DURABLE_OBJECT_NAMESPACE.idFromName('x'); } ``` > [!NOTE] SvelteKit's built-in [`$app/env/*` modules](environment-variables) should be preferred for environment variables. -To make these types available to your app, install [`wrangler`](https://www.npmjs.com/package/wrangler), run [`wrangler types`](https://developers.cloudflare.com/workers/languages/typescript/), and reference them in your `src/app.d.ts`: - -```ts -// @filename: ambient.d.ts -import { KVNamespace, DurableObjectNamespace } from '@cloudflare/workers-types'; - -namespace Cloudflare { - export interface Env { - YOUR_KV_NAMESPACE: KVNamespace; - YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace; - } -} -/// file: src/app.d.ts -// ---cut--- - -declare global { - namespace App { - interface Platform { -+++ env: Cloudflare.Env;+++ - } - } -} - -export {}; -``` +To make these types available to your app, install [`wrangler`](https://www.npmjs.com/package/wrangler) and run [`wrangler types`](https://developers.cloudflare.com/workers/languages/typescript/). ### Testing locally -Cloudflare specific values in the `platform` property are emulated during dev and preview modes. Local [bindings](https://developers.cloudflare.com/workers/wrangler/configuration/#bindings) are created based on your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/) and are used to populate `platform.env` during development and preview. Use the adapter config [`platformProxy` option](#Options-platformProxy) to change your preferences for the bindings. +Cloudflare specific values are emulated during dev and preview modes. Local [bindings](https://developers.cloudflare.com/workers/wrangler/configuration/#bindings) are created based on your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/) and are used to populate `env` during development and preview. Use the adapter config [`platformProxy` option](#Options-platformProxy) to change your preferences for the bindings. > [!NOTE] [Durable Objects](https://developers.cloudflare.com/durable-objects/) and [Workflows](https://developers.cloudflare.com/workflows/), which require custom classes to be exported from your worker, are not currently supported. diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md index 372189b48a..dbfd526a8c 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md @@ -53,8 +53,6 @@ If `true`, your app will be deployed as a [Netlify Edge Function](https://docs.n If `true`, your app will be split into multiple functions instead of a single one for the entire app. -If `edge` is `true`, this option cannot be used. - ## Netlify alternatives to SvelteKit functionality You may build your app using functionality provided directly by SvelteKit without relying on any Netlify functionality. Using the SvelteKit versions of these features will allow them to be used in dev mode, tested with integration tests, and to work with other adapters should you ever decide to switch away from Netlify. However, in some scenarios you may find it beneficial to use the Netlify versions of these features. One example would be if you're migrating an app that's already hosted on Netlify to SvelteKit. diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md index 82877184e3..767cf40bc8 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md @@ -120,9 +120,12 @@ The expiration time (in seconds) before the cached asset will be re-generated by ### bypassToken -A random token that can be provided in the URL to bypass the cached version of the asset, by requesting the asset with a `__prerender_bypass=` cookie. +A random token that can be used for two things: -Making a `GET` or `HEAD` request with `x-prerender-revalidate: ` will force the asset to be re-validated. +- Draft mode, which bypasses the cache so that you can, for example, view live content from your CMS as you edit it. Send the token in a `__prerender_bypass=` cookie to render the route at request time. See [Vercel's Draft Mode documentation](https://vercel.com/docs/draft-mode?framework=sveltekit) for more details. +- Revalidation, which empties the route's ISR cache and repopulates it for future visitors. To do so, send a `GET` or `HEAD` request with a `x-prerender-revalidate: ` header. + +The `BYPASS_TOKEN` is saved at build time; setting or changing it after the application has been built requires a new deployment. Note that the `BYPASS_TOKEN` string must be at least 32 characters long. You could generate one using the JavaScript console like so: @@ -200,6 +203,10 @@ If you have Vercel functions contained in the `api` directory at the project's r Projects created before a certain date may default to using an older Node version than what SvelteKit currently requires. You can [change the Node version in your project settings](https://vercel.com/docs/concepts/functions/serverless-functions/runtimes/node-js#node.js-version). +### More information + +You can find more information on how to use SvelteKit on Vercel [in the Vercel documentation](https://vercel.com/docs/frameworks/full-stack/sveltekit). + ## Troubleshooting ### Accessing the file system diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md index 01890d5b8f..dbe38b4fb9 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md @@ -14,6 +14,8 @@ type AdapterSpecificOptions = any; // @filename: index.js // ---cut--- +import { getRequest, setResponse } from '@sveltejs/kit/node'; + /** @param {AdapterSpecificOptions} options */ export default function (options) { /** @type {import('@sveltejs/kit').Adapter} */ @@ -42,6 +44,15 @@ export default function (options) { } }, vite: { + getRequest(options) { + const request = getRequest(options); + // modify the Request object here if needed + return request; + }, + setResponse(res, response) { + // handle WebSockets here, for example + setResponse(res, response); + }, plugins: { // add plugins here to integrate with Vite pre: [], @@ -61,8 +72,8 @@ Within the `adapt` method, there are a number of things that an adapter should d - Clear out the build directory - Write SvelteKit output with `builder.writeClient`, `builder.writeServer`, and `builder.writePrerendered` - Output code that: - - Imports `Server` from `${builder.getServerDirectory()}/index.js` - - Instantiates the app with a manifest generated with `builder.generateManifest({ relativePath })` + - Imports a `server` instance generated by `${builder.generateServerInstance()}` + - Runs `await server.init({ env, read })` - Listens for requests from the platform, converts them to a standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) if necessary, calls the `server.respond(request, { getClientAddress })` function to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) and responds with it - expose any platform-specific information to SvelteKit via the `platform` option passed to `server.respond` - Bundle the output to avoid needing to install dependencies on the target platform, if necessary diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/68-observability.md b/apps/svelte.dev/content/docs/kit/30-advanced/68-observability.md index 7e0c78f816..92b9d12299 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/68-observability.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/68-observability.md @@ -140,6 +140,8 @@ Bundling can disrupt this in two ways. First, a bundler may place code imported by `instrumentation.server.js` and application code in the same shared chunk. Importing that chunk to initialize instrumentation can then evaluate application code before the interceptor has been installed. By the time the application is dynamically imported, the module is already in the ESM module cache and it is too late to instrument it. +There is also an unavoidable chicken-and-egg limitation: importing [`$app/env/*` modules](environment-variables) evaluates your `src/env.js` module and its dependencies. Because of this, instrumentation cannot intercept a module imported by `src/env`, because that imported module must run before `instrumentation.server.js` can start. Therefore, you should avoid importing anything from `src/env.js` that you need to instrument. + Second, a bundler may inline or transform the module you want to instrument. For example, it could replace this: ```js diff --git a/apps/svelte.dev/content/docs/kit/40-best-practices/05-performance.md b/apps/svelte.dev/content/docs/kit/40-best-practices/05-performance.md index 7d167b2719..628f4b61bf 100644 --- a/apps/svelte.dev/content/docs/kit/40-best-practices/05-performance.md +++ b/apps/svelte.dev/content/docs/kit/40-best-practices/05-performance.md @@ -50,7 +50,25 @@ Video files can be very large, so extra care should be taken to ensure that they ### Fonts -SvelteKit automatically preloads critical `.js` and `.css` files when the user visits a page, but it does _not_ preload fonts by default, since this may cause unnecessary files (such as font weights that are referenced by your CSS but not actually used on the current page) to be downloaded. Having said that, preloading fonts correctly can make a big difference to how fast your site feels. In your [`handle`](hooks#handle) hook, you can call `resolve` with a `preload` filter that includes your fonts. +SvelteKit automatically preloads critical `.js` and `.css` files when the user visits a page, but it does _not_ preload fonts by default, since this may cause unnecessary files (such as font weights that are referenced by your CSS but not actually used on the current page) to be downloaded. Having said that, preloading fonts correctly can make a big difference to how fast your site feels. In your [`handle`](hooks#handle) hook, you can call `resolve` with a `preload` filter that includes your fonts: + +```js +/// file: src/hooks.server.js +/** @type {import('@sveltejs/kit/hooks').Handle} */ +export async function handle({ event, resolve }) { + return resolve(event, { + preload: (asset) => { + if (asset.type === 'font') { + return asset.filename === 'node_modules/@fontsource/inter/files/inter-latin-400-normal.woff2'; + } + + return true; + } + }); +} +``` + +`filename` is the source filename relative to the project root, and is only available when `asset.type === 'font'` since JS and CSS assets are bundled by Vite. You can reduce the size of font files by [subsetting](https://web.dev/learn/performance/optimize-web-fonts#subset_your_web_fonts) your fonts. diff --git a/apps/svelte.dev/content/docs/kit/60-appendix/35-migrating-to-sveltekit-3.md b/apps/svelte.dev/content/docs/kit/60-appendix/35-migrating-to-sveltekit-3.md index 914cfd86bf..cfe5c02c03 100644 --- a/apps/svelte.dev/content/docs/kit/60-appendix/35-migrating-to-sveltekit-3.md +++ b/apps/svelte.dev/content/docs/kit/60-appendix/35-migrating-to-sveltekit-3.md @@ -454,9 +454,47 @@ All first-party adapters now require SvelteKit 3, alongside these adapter-specif ### `adapter-cloudflare` +Cloudflare-specific APIs are no longer available on `platform`. Instead, find them where you would expect on a Cloudflare worker: + +- `env`, `ctx.waitUntil`, and other `ctx` properties should be imported from `cloudflare:workers`: +```js +// @filename: ambient.d.ts +declare module 'cloudflare:workers' { + export const env: { KV: { get(): Promise } }; + export function waitUntil(promise: Promise): void; +} +// ---cut--- +import { env, waitUntil } from 'cloudflare:workers'; + +const value = await env.KV.get('key'); +``` +- `cf` is now a property of the `Request` object: +```js +/// file: src/routes/cf/+server.js +// @filename: ambient.d.ts +interface Request { + cf: import('@cloudflare/workers-types').IncomingRequestCfProperties; +} +// @filename: index.js +// @errors: 7031 +// ---cut--- +export async function GET({ request }) { + const { country } = request.cf; +} +``` +- `caches` is now a global variable: +```js +/// file: src/routes/cache/+server.js +let request = new Request(''); +// ---cut--- +const myCache = await caches.open('foo'); +await myCache.match(request); +``` + +- To make these types available to your app, install [`wrangler`](https://www.npmjs.com/package/wrangler) and run [`wrangler types`](https://developers.cloudflare.com/workers/languages/typescript/). + - minimum `wrangler` is now `^4.67.0` - `@cloudflare/workers-types` upgraded -- `platform.context` removed in favour of `platform.ctx` ### `adapter-node` @@ -482,6 +520,61 @@ For adapter authors, there are some additional changes: - `builder.createEntries` has been removed — use `builder.writeClient`, `builder.writeServer` and `builder.writePrerendered` directly - `builder.compress` returns a list of compressed files - `builder.mkdirp` and `builder.rimraf` are deprecated in favour of `node:fs` methods +- `builder.generateManifest` has been removed — use `builder.generateServerInstance` to replace it, and `builder.manifest` to access the manifest + +#### Server instrumentation + +Adapters that use `builder.instrument` must now generate an environment initializer before any +bundling step, include the returned module as an entrypoint in that step, and pass its final path to +`builder.instrument`: + +```js +// @filename: ambient.d.ts +import { Builder } from '@sveltejs/kit'; + +declare global { + const builder: Builder; + const temporary_directory: string; + const entrypoint: string; + const instrumentation: string; +} + +export {}; + +// @filename: index.js +// ---cut--- +const initializer = builder.createInstrumentationInitializer({ outputDirectory: temporary_directory }); + +// Include `initializer` in any bundling or file tracing here + +builder.instrument({ + entrypoint, + instrumentation, + initializer +}); +``` + +For runtimes that do not expose environment variables through `process.env`, pass the contents of +a module whose default export is the platform environment: + +```js +// @filename: ambient.d.ts +import { Builder } from '@sveltejs/kit'; + +declare global { + const builder: Builder; + const temporary_directory: string; +} + +export {}; + +// @filename: index.js +// ---cut--- +const initializer = builder.createInstrumentationInitializer({ + outputDirectory: temporary_directory, + environment: `import { env } from 'cloudflare:workers';\nexport default env;` +}); +``` ## Responses diff --git a/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md b/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md index 0e68b43b96..1bd8dce083 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md @@ -8,7 +8,6 @@ title: @sveltejs/kit ```js // @noErrors import { - Server, VERSION, error, fail, @@ -24,43 +23,6 @@ import { } from '@sveltejs/kit'; ``` -## Server - -
- -```dts -class Server {/*…*/} -``` - -
- -```dts -constructor(manifest: SSRManifest); -``` - -
-
- -
- -```dts -init(options: ServerInitOptions): Promise; -``` - -
-
- -
- -```dts -respond(request: Request, options: RequestOptions): Promise; -``` - -
-
- - - ## VERSION
@@ -564,23 +526,103 @@ during dev, build and prerendering.
```dts -vite?: { - plugins?: { - /** - * Vite plugins placed before any of SvelteKit's own plugins. - * @since 3.0.0 - */ - pre?: Plugin[]; - /** - * Vite plugins placed after any of SvelteKit's own plugins. - * @since 3.0.0 - */ - post?: Plugin[]; - }; -}; +vite?: AdapterViteConfig | ((ctx: { config: ValidatedConfig }) => AdapterViteConfig); ``` -
+
+ +
+ +- available since v3.0.0 + +
+ +Options for configuring and interacting with Vite + +
+
+ +## AdapterViteConfig + +
+ +```dts +interface AdapterViteConfig {/*…*/} +``` + +
+ +```dts +getRequest?: typeof getRequest; +``` + +
+ +
+ +- available since v3.0.0 + +
+ +This function overrides the default behavior during Vite's dev and preview modes +to convert an `http.IncomingMessage` to a `Request` object. +To call the original `setRequest` function, import it from `@sveltejs/kit/node`. + +
+
+ +
+ +```dts +setResponse?: typeof setResponse; +``` + +
+ +
+ +- available since v3.0.0 + +
+ +This function overrides the default behavior in Vite's dev and preview modes +to write a `Response` object to a `http.ServerResponse`. +To call the original `setResponse` function, import it from `@sveltejs/kit/node`. + +
+
+ +
+ +```dts +plugins?: + | Plugin[] + | { + /** + * Vite plugins placed before any of SvelteKit's own plugins. + * @since 3.0.0 + */ + pre?: Plugin[]; + /** + * Vite plugins placed after any of SvelteKit's own plugins. + * @since 3.0.0 + */ + post?: Plugin[]; + }; +``` + +
+ +
+ +- available since v3.0.0 + +
+ +Vite plugins injected by the adapter. By default, +they are placed before SvelteKit's plugins. + +
## AwaitedActions @@ -704,6 +746,45 @@ An array of all routes (including prerendered)
+```dts +manifest: typeof import('$app/manifest'); +``` + +
+ +
+ +- available since v3.0.0 + +
+ +The value of the `$app/manifest` module. +The only difference is `manifest.assets` also includes the service worker, if it exists. + +
+
+ +
+ +```dts +mimeTypes: Record; +``` + +
+ +
+ +- available since v3.0.0 + +
+ +A record of file extensions to MIME types + +
+
+ +
+ ```dts createEntries?: (fn: (route: RouteDefinition) => AdapterEntry) => Promise; ``` @@ -764,7 +845,7 @@ Generate a module exposing public environment variables as `$app/env/public` if
```dts -generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string; +generateManifest?: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string; ```
@@ -772,6 +853,7 @@ generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) =
- `opts.relativePath` A relative path to the base directory of the server build output +- deprecated removed in 3.0. Use `builder.generateServerInstance` or `builder.manifest` instead
@@ -840,6 +922,33 @@ Get the application path including any configured `base` path, e.g. `my-base-pat
+```dts +generateServerInstance: ( + dest: string, + opts?: { + routes?: RouteDefinition[]; + serverDirectory?: string; + } +) => void; +``` + +
+ +
+ +- `opts.routes` A subset of the routes to include in the server's manifest +- `opts.serverDirectory` The directory containing the server code. Defaults to `getServerDirectory()`. +- available since v3.0.0 + +
+ +Generates a module exposing a SvelteKit [Server](/docs/kit/@sveltejs-kit#Server) instance. + +
+
+ +
+ ```dts writeClient: (dest: string) => string[]; ``` @@ -900,6 +1009,35 @@ Write server-side code to `dest`.
+```dts +createInstrumentationInitializer: (options: { + outputDirectory: string; + environment?: string; + serverDirectory?: string; +}) => string; +``` + +
+ +
+ +- `options` an object containing the following properties: +- `options.outputDirectory` the directory in which to create the initializer. +- `options.environment` the contents of a module whose default export contains the platform's environment variables. If omitted, `process.env` is used. +- `options.serverDirectory` the directory containing the server build output. Defaults to `getServerDirectory()`. +- returns the filesystem path to the generated initializer. +- available since v3.0.0 + +
+ +Generate an initializer that populates `$env/dynamic/private` before server instrumentation +runs. Include the returned module in any subsequent bundling or tracing step. + +
+
+ +
+ ```dts copy: ( from: string, @@ -955,12 +1093,17 @@ instrument: (args: { entrypoint: string; instrumentation: string; start?: string; + initializer: string; module?: | { exports: string[]; } | { - generateText: (args: { instrumentation: string; start: string }) => string; + generateText: (args: { + instrumentation: string; + start: string; + initializer: string; + }) => string; }; }) => void; ``` @@ -973,9 +1116,10 @@ instrument: (args: { - `options.entrypoint` the path to the entrypoint to trace. - `options.instrumentation` the path to the instrumentation file. - `options.start` the name of the start file. This is what `entrypoint` will be renamed to. +- `options.initializer` the filesystem path to the bundled or copied instrumentation initializer. - `options.module` configuration for the resulting entrypoint module. -- `options.module.generateText` a function that receives the relative paths to the instrumentation and start files, and generates the text of the module to be traced. If not provided, the default implementation will be used, which uses top-level await. -- available since v2.31.0 +- `options.module.generateText` a function that receives the relative paths to the initializer, instrumentation and start files, and generates the text of the module to be traced. It must import `initializer` before `instrumentation`, and dynamically import `start` after instrumentation has run. If not provided, the default implementation will be used, which uses top-level await. +- available since v3.0.0
@@ -985,6 +1129,9 @@ Renames `entrypoint` to `start` and creates a new module at `entrypoint` which imports `instrumentation` and then dynamically imports `start`. This allows the module hooks necessary for instrumentation libraries to be loaded prior to any application code. +`initializer` is a module generated by `createInstrumentationInitializer`. It must be included +in any bundling or tracing step before calling this method. + Caveats: - "Live exports" will not work. If your adapter uses live exports, your users will need to manually import the server instrumentation on startup. - If `tla` is `false`, OTEL auto-instrumentation may not work properly. Use it if your environment supports it. @@ -2017,59 +2164,27 @@ config: Config;
-## SSRManifest - -Information required to instantiate a new `Server` instance. +## Server
```dts -interface SSRManifest {/*…*/} -``` - -
- -```dts -appDir: string; +interface Server {/*…*/} ``` -
- -The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes. - -
-
-
```dts -appPath: string; -``` - -
- -The `base` and `appDir` settings combined without a leading slash. - -
-
- -
- -```dts -assets: Set; +init(options: ServerInitOptions): Promise; ``` -
- -Static files from `config.files.assets` and the service worker (if any). - -
+
```dts -mimeTypes: Record; +respond(request: Request, options: RequestOptions): Promise; ```
diff --git a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md index 903fc94e4b..70731ae323 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md @@ -3,13 +3,6 @@ NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-doc title: @sveltejs/kit/vite --- - - -```js -// @noErrors -import { sveltekit } from '@sveltejs/kit/vite'; -``` - ## sveltekit The SvelteKit Vite plugin, which must be added to your `vite.config.js` file along with your project's configuration: @@ -57,21 +50,7 @@ function sveltekit(config?: Config): Promise; ## Config -An extension of [`vite-plugin-svelte`'s options](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options). - -
- -```dts -interface Config extends VitePluginSvelteOptions {/*…*/} -``` - -
- -```dts -adapter?: Adapter; -``` - -
+An extension of [`vite-plugin-svelte`'s options](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options).## adapter
@@ -81,16 +60,13 @@ adapter?: Adapter; Your [adapter](/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. -
-
+
-
-```dts -alias?: Record; -``` -
+
+ +## alias
@@ -105,16 +81,13 @@ This option is deprecated. Use [subpath imports](/docs/kit/$lib) instead. > [!NOTE] You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. -
-
+
-
-```dts -appDir?: string; -``` -
+
+ +## appDir
@@ -126,16 +99,19 @@ The directory where SvelteKit keeps its stuff, including static assets (such as If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`. -
+
+ + +
-
+## csp -```dts -csp?: {/*…*/} -``` +
-
+ + +
[Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this... @@ -173,9 +149,12 @@ When pages are prerendered, the CSP header is added via a `` ta If this level of configuration is insufficient and you have more dynamic requirements, you can use the [`handle` hook](/docs/kit/hooks#handle) to roll your own CSP. -
+
-```dts +
+ +```ts +// @noErrors mode?: 'hash' | 'nonce' | 'auto'; ``` @@ -187,7 +166,8 @@ Whether to use hashes or nonces to restrict `