diff --git a/apps/svelte.dev/.prettierrc b/apps/svelte.dev/.prettierrc index 4dd7e46351..f91c4a7d52 100644 --- a/apps/svelte.dev/.prettierrc +++ b/apps/svelte.dev/.prettierrc @@ -16,6 +16,12 @@ "options": { "requirePragma": true } + }, + { + "files": "includes/**", + "options": { + "requirePragma": true + } } ] } 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 3c7d7bb230..e89510f253 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 @@ -2,3433 +2,4 @@ title: @sveltejs/kit --- - - -```js -// @noErrors -import { - VERSION, - error, - fail, - isHttpError, - isRedirect, - json, - redirect, - text -} from '@sveltejs/kit'; -``` - -## VERSION - - - -
- -```ts -// @noErrors -const VERSION: string; -``` - -
- -## error - -Throws an error with a HTTP status code and an optional message. -When called during request handling, this will cause SvelteKit to -return an error response without invoking `handleError`. -Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. - -
- -```ts -// @noErrors -function error(status: number, body: App.Error): never; -``` - -
- -## error - -Throws an error with a HTTP status code and an optional message. -When called during request handling, this will cause SvelteKit to -return an error response without invoking `handleError`. -Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. - -
- -```ts -// @noErrors -function error( - status: number, - body?: { - message: string; - } extends App.Error - ? App.Error | string | undefined - : never -): never; -``` - -
- -## fail - -Create an `ActionFailure` object. - -
- -```ts -// @noErrors -function fail(status: number): ActionFailure; -``` - -
- -## fail - -Create an `ActionFailure` object. - -
- -```ts -// @noErrors -function fail< - T extends Record | undefined = undefined ->(status: number, data: T): ActionFailure; -``` - -
- -## isHttpError - -Checks whether this is an error thrown by `error`. - -
- -```ts -// @noErrors -function isHttpError( - e: unknown, - status?: T | undefined -): e is HttpError_1 & { - status: T extends undefined ? never : T; -}; -``` - -
- -## isRedirect - -Checks whether this is a redirect thrown by `redirect`. - -
- -```ts -// @noErrors -function isRedirect(e: unknown): e is Redirect_1; -``` - -
- -## json - -Create a JSON `Response` object from the supplied data. - -
- -```ts -// @noErrors -function json( - data: any, - init?: ResponseInit | undefined -): Response; -``` - -
- -## redirect - -Redirect a request. When called during request handling, SvelteKit will return a redirect response. -Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. - -
- -```ts -// @noErrors -function redirect( - status: - | 300 - | 301 - | 302 - | 303 - | 304 - | 305 - | 306 - | 307 - | 308 - | ({} & number), - location: string | URL -): never; -``` - -
- -## text - -Create a `Response` object from the supplied body. - -
- -```ts -// @noErrors -function text( - body: string, - init?: ResponseInit | undefined -): Response; -``` - -
- -## Action - -Shape of a form action method that is part of `export const actions = {..}` in `+page.server.js`. -See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. - -
- -```dts -type Action< - Params extends Partial> = Partial< - Record - >, - OutputData extends Record | void = Record< - string, - any - > | void, - RouteId extends string | null = string | null -> = ( - event: RequestEvent -) => MaybePromise; -``` - - -
- -## ActionFailure - -
- -```dts -interface ActionFailure< - T extends Record | undefined = undefined -> {/*…*/} -``` - -
- -```dts -status: number; -``` - -
-
- -
- -```dts -data: T; -``` - -
-
- -
- -```dts -[uniqueSymbol]: true; -``` - -
-
-
- -## ActionResult - -When calling a form action via fetch, the response will be one of these shapes. -```svelte -
{ - return ({ result }) => { - // result is of type ActionResult - }; -}} -``` - -
- -```dts -type ActionResult< - Success extends - | Record - | undefined = Record, - Failure extends - | Record - | undefined = Record -> = - | { type: 'success'; status: number; data?: Success } - | { type: 'failure'; status: number; data?: Failure } - | { type: 'redirect'; status: number; location: string } - | { type: 'error'; status?: number; error: any }; -``` - - -
- -## Actions - -Shape of the `export const actions = {..}` object in `+page.server.js`. -See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. - -
- -```dts -type Actions< - Params extends Partial> = Partial< - Record - >, - OutputData extends Record | void = Record< - string, - any - > | void, - RouteId extends string | null = string | null -> = Record>; -``` - - -
- -## Adapter - -[Adapters](https://kit.svelte.dev/docs/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing. - -
- -```dts -interface Adapter {/*…*/} -``` - -
- -```dts -name: string; -``` - -
- -The name of the adapter, using for logging. Will typically correspond to the package name. - -
-
- -
- -```dts -adapt(builder: Builder): MaybePromise; -``` - -
- -
- -- `builder` An object provided by SvelteKit that contains methods for adapting the app - -
- -This function is called after SvelteKit has built your app. - -
-
- -
- -```dts -supports?: {/*…*/} -``` - -
- -Checks called during dev and build to determine whether specific features will work in production with this adapter - -
- -```dts -read?: (details: { config: any; route: { id: string } }) => boolean; -``` - -
- -
- -- `config` The merged route config - -
- -Test support for `read` from `$app/server` - -
-
- -
-
- -
- -```dts -emulate?(): MaybePromise; -``` - -
- -Creates an `Emulator`, which allows the adapter to influence the environment -during dev, build and prerendering - -
-
-
- -## AfterNavigate - -The argument passed to [`afterNavigate`](/docs/kit/reference/$app-navigation#afternavigate) callbacks. - -
- -```dts -interface AfterNavigate extends Omit {/*…*/} -``` - -
- -```dts -type: Exclude; -``` - -
- -The type of navigation: -- `enter`: The app has hydrated -- `form`: The user submitted a `` -- `link`: Navigation was triggered by a link click -- `goto`: Navigation was triggered by a `goto(...)` call or a redirect -- `popstate`: Navigation was triggered by back/forward navigation - -
-
- -
- -```dts -willUnload: false; -``` - -
- -Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page. - -
-
-
- -## AwaitedActions - -
- -```dts -type AwaitedActions< - T extends Record any> -> = OptionalUnion< - { - [Key in keyof T]: UnpackValidationError< - Awaited> - >; - }[keyof T] ->; -``` - - -
- -## BeforeNavigate - -The argument passed to [`beforeNavigate`](/docs/kit/reference/$app-navigation#beforenavigate) callbacks. - -
- -```dts -interface BeforeNavigate extends Navigation {/*…*/} -``` - -
- -```dts -cancel(): void; -``` - -
- -Call this to prevent the navigation from starting. - -
-
-
- -## Builder - -This object is passed to the `adapt` function of adapters. -It contains various methods and properties that are useful for adapting the app. - -
- -```dts -interface Builder {/*…*/} -``` - -
- -```dts -log: Logger; -``` - -
- -Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. - -
-
- -
- -```dts -rimraf(dir: string): void; -``` - -
- -Remove `dir` and all its contents. - -
-
- -
- -```dts -mkdirp(dir: string): void; -``` - -
- -Create `dir` and any required parent directories. - -
-
- -
- -```dts -config: ValidatedConfig; -``` - -
- -The fully resolved `svelte.config.js`. - -
-
- -
- -```dts -prerendered: Prerendered; -``` - -
- -Information about prerendered pages and assets, if any. - -
-
- -
- -```dts -routes: RouteDefinition[]; -``` - -
- -An array of all routes (including prerendered) - -
-
- -
- -```dts -createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; -``` - -
- -
- -- `fn` A function that groups a set of routes into an entry point -- deprecated Use `builder.routes` instead - -
- -Create separate functions that map to one or more routes of your app. - -
-
- -
- -```dts -findServerAssets(routes: RouteDefinition[]): string[]; -``` - -
- -Find all the assets imported by server files belonging to `routes` - -
-
- -
- -```dts -generateFallback(dest: string): Promise; -``` - -
- -Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. - -
-
- -
- -```dts -generateEnvModule(): void; -``` - -
- -Generate a module exposing build-time environment variables as `$env/dynamic/public`. - -
-
- -
- -```dts -generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; -``` - -
- -
- -- `opts` a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated - -
- -Generate a server-side manifest to initialise the SvelteKit [server](/docs/kit/reference/types#public-types-server) with. - -
-
- -
- -```dts -getBuildDirectory(name: string): string; -``` - -
- -
- -- `name` path to the file, relative to the build directory - -
- -Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. - -
-
- -
- -```dts -getClientDirectory(): string; -``` - -
- -Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. - -
-
- -
- -```dts -getServerDirectory(): string; -``` - -
- -Get the fully resolved path to the directory containing server-side code. - -
-
- -
- -```dts -getAppPath(): string; -``` - -
- -Get the application path including any configured `base` path, e.g. `my-base-path/_app`. - -
-
- -
- -```dts -writeClient(dest: string): string[]; -``` - -
- -
- -- `dest` the destination folder -- returns an array of files written to `dest` - -
- -Write client assets to `dest`. - -
-
- -
- -```dts -writePrerendered(dest: string): string[]; -``` - -
- -
- -- `dest` the destination folder -- returns an array of files written to `dest` - -
- -Write prerendered files to `dest`. - -
-
- -
- -```dts -writeServer(dest: string): string[]; -``` - -
- -
- -- `dest` the destination folder -- returns an array of files written to `dest` - -
- -Write server-side code to `dest`. - -
-
- -
- -```dts -copy( - from: string, - to: string, - opts?: { - filter?(basename: string): boolean; - replace?: Record; - } -): string[]; -``` - -
- -
- -- `from` the source file or directory -- `to` the destination file or directory -- `opts.filter` a function to determine whether a file or directory should be copied -- `opts.replace` a map of strings to replace -- returns an array of files that were copied - -
- -Copy a file or directory. - -
-
- -
- -```dts -compress(directory: string): Promise; -``` - -
- -
- -- `directory` The directory containing the files to be compressed - -
- -Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. - -
-
-
- -## Config - -See the [configuration reference](/docs/kit/configuration) for details. - -## Cookies - -
- -```dts -interface Cookies {/*…*/} -``` - -
- -```dts -get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; -``` - -
- -
- -- `name` the name of the cookie -- `opts` the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) - -
- -Gets a cookie that was previously set with `cookies.set`, or from the request headers. - -
-
- -
- -```dts -getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; -``` - -
- -
- -- `opts` the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) - -
- -Gets all cookies that were previously set with `cookies.set`, or from the request headers. - -
-
- -
- -```dts -set( - name: string, - value: string, - opts: import('cookie').CookieSerializeOptions & { path: string } -): void; -``` - -
- -
- -- `name` the name of the cookie -- `value` the cookie value -- `opts` the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) - -
- -Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request. - -The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. - -You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children - -
-
- -
- -```dts -delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void; -``` - -
- -
- -- `name` the name of the cookie -- `opts` the options, passed directly to `cookie.serialize`. The `path` must match the path of the cookie you want to delete. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) - -
- -Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. - -You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children - -
-
- -
- -```dts -serialize( - name: string, - value: string, - opts: import('cookie').CookieSerializeOptions & { path: string } -): string; -``` - -
- -
- -- `name` the name of the cookie -- `value` the cookie value -- `opts` the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) - -
- -Serialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response. - -The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. - -You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children - -
-
-
- -## Emulator - -A collection of functions that influence the environment during dev, build and prerendering - -
- -```dts -interface Emulator {/*…*/} -``` - -
- -```dts -platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise; -``` - -
- -A function that is called with the current route `config` and `prerender` option -and returns an `App.Platform` object - -
-
-
- -## Handle - -The [`handle`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) hook runs every time the SvelteKit server receives a [request](https://kit.svelte.dev/docs/web-standards#fetch-apis-request) and -determines the [response](https://kit.svelte.dev/docs/web-standards#fetch-apis-response). -It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. -This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example). - -
- -```dts -type Handle = (input: { - event: RequestEvent; - resolve( - event: RequestEvent, - opts?: ResolveOptions - ): MaybePromise; -}) => MaybePromise; -``` - - -
- -## HandleClientError - -The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. - -If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. -Make sure that this function _never_ throws an error. - -
- -```dts -type HandleClientError = (input: { - error: unknown; - event: NavigationEvent; - status: number; - message: string; -}) => MaybePromise; -``` - - -
- -## HandleFetch - -The [`handleFetch`](https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch) hook allows you to modify (or replace) a `fetch` request that happens inside a `load` function that runs on the server (or during pre-rendering) - -
- -```dts -type HandleFetch = (input: { - event: RequestEvent; - request: Request; - fetch: typeof fetch; -}) => MaybePromise; -``` - - -
- -## HandleServerError - -The server-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while responding to a request. - -If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. -Make sure that this function _never_ throws an error. - -
- -```dts -type HandleServerError = (input: { - error: unknown; - event: RequestEvent; - status: number; - message: string; -}) => MaybePromise; -``` - - -
- -## HttpError - -The object returned by the [`error`](/docs/kit/reference/@sveltejs-kit#error) function. - -
- -```dts -interface HttpError {/*…*/} -``` - -
- -```dts -status: number; -``` - -
- -The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. - -
-
- -
- -```dts -body: App.Error; -``` - -
- -The content of the error. - -
-
-
- -## KitConfig - -See the [configuration reference](/docs/kit/configuration) for details. - -## LessThan - -
- -```dts -type LessThan< - TNumber extends number, - TArray extends any[] = [] -> = TNumber extends TArray['length'] - ? TArray[number] - : LessThan; -``` - - -
- -## Load - -The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](/docs/kit/reference/types#generated-types)) -rather than using `Load` directly. - -
- -```dts -type Load< - Params extends Partial> = Partial< - Record - >, - InputData extends Record | null = Record< - string, - any - > | null, - ParentData extends Record = Record< - string, - any - >, - OutputData extends Record< - string, - unknown - > | void = Record | void, - RouteId extends string | null = string | null -> = ( - event: LoadEvent -) => MaybePromise; -``` - - -
- -## LoadEvent - -The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](/docs/kit/reference/types#generated-types)) -rather than using `LoadEvent` directly. - -
- -```dts -interface LoadEvent< - Params extends Partial> = Partial< - Record - >, - Data extends Record | null = Record< - string, - any - > | null, - ParentData extends Record = Record< - string, - any - >, - RouteId extends string | null = string | null -> extends NavigationEvent {/*…*/} -``` - -
- -```dts -fetch: typeof fetch; -``` - -
- -`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: - -- It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. -- It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). -- Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. -- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) -- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. - -You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) - -
-
- -
- -```dts -data: Data; -``` - -
- -Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. - -
-
- -
- -```dts -setHeaders(headers: Record): void; -``` - -
- -If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: - -```js -// @errors: 7031 -/// file: src/routes/blog/+page.js -export async function load({ fetch, setHeaders }) { - const url = `https://cms.example.com/articles.json`; - const response = await fetch(url); - - setHeaders({ - age: response.headers.get('age'), - 'cache-control': response.headers.get('cache-control') - }); - - return response.json(); -} -``` - -Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. - -You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/reference/types#public-types-cookies) API in a server-only `load` function instead. - -`setHeaders` has no effect when a `load` function runs in the browser. - -
-
- -
- -```dts -parent(): Promise; -``` - -
- -`await parent()` returns data from parent `+layout.js` `load` functions. -Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files. - -Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. - -
-
- -
- -```dts -depends(...deps: Array<`${string}:${string}`>): void; -``` - -
- -This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/reference/$app-navigation#invalidate) to cause `load` to rerun. - -Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. - -URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). - -Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). - -The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. - -```js -// @errors: 7031 -/// file: src/routes/+page.js -let count = 0; -export async function load({ depends }) { - depends('increase:count'); - - return { count: count++ }; -} -``` - -```html -/// file: src/routes/+page.svelte - - -

{data.count}

- -``` - -

-
- -
- -```dts -untrack(fn: () => T): T; -``` - -
- -Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: - -```js -// @errors: 7031 -/// file: src/routes/+page.server.js -export async function load({ untrack, url }) { - // Untrack url.pathname so that path changes don't trigger a rerun - if (untrack(() => url.pathname === '/')) { - return { message: 'Welcome!' }; - } -} -``` - -
-
-
- -## LoadProperties - -
- -```dts -type LoadProperties< - input extends Record | void -> = input extends void - ? undefined // needs to be undefined, because void will break intellisense - : input extends Record - ? input - : unknown; -``` - - -
- -## Navigation - -
- -```dts -interface Navigation {/*…*/} -``` - -
- -```dts -from: NavigationTarget | null; -``` - -
- -Where navigation was triggered from - -
-
- -
- -```dts -to: NavigationTarget | null; -``` - -
- -Where navigation is going to/has gone to - -
-
- -
- -```dts -type: Exclude; -``` - -
- -The type of navigation: -- `form`: The user submitted a `` -- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring -- `link`: Navigation was triggered by a link click -- `goto`: Navigation was triggered by a `goto(...)` call or a redirect -- `popstate`: Navigation was triggered by back/forward navigation - -
-
- -
- -```dts -willUnload: boolean; -``` - -
- -Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) - -
-
- -
- -```dts -delta?: number; -``` - -
- -In case of a history back/forward navigation, the number of steps to go back/forward - -
-
- -
- -```dts -complete: Promise; -``` - -
- -A promise that resolves once the navigation is complete, and rejects if the navigation -fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve - -
-
-
- -## NavigationEvent - -
- -```dts -interface NavigationEvent< - Params extends Partial> = Partial< - Record - >, - RouteId extends string | null = string | null -> {/*…*/} -``` - -
- -```dts -params: Params; -``` - -
- -The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object - -
-
- -
- -```dts -route: {/*…*/} -``` - -
- -Info about the current route - -
- -```dts -id: RouteId; -``` - -
- -The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` - -
-
- -
-
- -
- -```dts -url: URL; -``` - -
- -The URL of the current page - -
-
-
- -## NavigationTarget - -Information about the target of a specific navigation. - -
- -```dts -interface NavigationTarget {/*…*/} -``` - -
- -```dts -params: Record | null; -``` - -
- -Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. -Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). - -
-
- -
- -```dts -route: { id: string | null }; -``` - -
- -Info about the target route - -
-
- -
- -```dts -url: URL; -``` - -
- -The URL that is navigated to - -
-
-
- -## NavigationType - -- `enter`: The app has hydrated -- `form`: The user submitted a `` with a GET method -- `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document -- `link`: Navigation was triggered by a link click -- `goto`: Navigation was triggered by a `goto(...)` call or a redirect -- `popstate`: Navigation was triggered by back/forward navigation - -
- -```dts -type NavigationType = - | 'enter' - | 'form' - | 'leave' - | 'link' - | 'goto' - | 'popstate'; -``` - - -
- -## NumericRange - -
- -```dts -type NumericRange< - TStart extends number, - TEnd extends number -> = Exclude, LessThan>; -``` - - -
- -## OnNavigate - -The argument passed to [`onNavigate`](/docs/kit/reference/$app-navigation#onnavigate) callbacks. - -
- -```dts -interface OnNavigate extends Navigation {/*…*/} -``` - -
- -```dts -type: Exclude; -``` - -
- -The type of navigation: -- `form`: The user submitted a `` -- `link`: Navigation was triggered by a link click -- `goto`: Navigation was triggered by a `goto(...)` call or a redirect -- `popstate`: Navigation was triggered by back/forward navigation - -
-
- -
- -```dts -willUnload: false; -``` - -
- -Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page. - -
-
-
- -## Page - -The shape of the `$page` store - -
- -```dts -interface Page< - Params extends Record = Record< - string, - string - >, - RouteId extends string | null = string | null -> {/*…*/} -``` - -
- -```dts -url: URL; -``` - -
- -The URL of the current page - -
-
- -
- -```dts -params: Params; -``` - -
- -The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object - -
-
- -
- -```dts -route: {/*…*/} -``` - -
- -Info about the current route - -
- -```dts -id: RouteId; -``` - -
- -The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` - -
-
- -
-
- -
- -```dts -status: number; -``` - -
- -Http status code of the current page - -
-
- -
- -```dts -error: App.Error | null; -``` - -
- -The error object of the current page, if any. Filled from the `handleError` hooks. - -
-
- -
- -```dts -data: App.PageData & Record; -``` - -
- -The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. - -
-
- -
- -```dts -state: App.PageState; -``` - -
- -The page state, which can be manipulated using the [`pushState`](/docs/kit/reference/$app-navigation#pushstate) and [`replaceState`](/docs/kit/reference/$app-navigation#replacestate) functions from `$app/navigation`. - -
-
- -
- -```dts -form: any; -``` - -
- -Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. - -
-
-
- -## ParamMatcher - -The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. - -
- -```dts -type ParamMatcher = (param: string) => boolean; -``` - - -
- -## PrerenderOption - -
- -```dts -type PrerenderOption = boolean | 'auto'; -``` - - -
- -## Redirect - -The object returned by the [`redirect`](/docs/kit/reference/@sveltejs-kit#redirect) function - -
- -```dts -interface Redirect {/*…*/} -``` - -
- -```dts -status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; -``` - -
- -The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. - -
-
- -
- -```dts -location: string; -``` - -
- -The location to redirect to. - -
-
-
- -## RequestEvent - -
- -```dts -interface RequestEvent< - Params extends Partial> = Partial< - Record - >, - RouteId extends string | null = string | null -> {/*…*/} -``` - -
- -```dts -cookies: Cookies; -``` - -
- -Get or set cookies related to the current request - -
-
- -
- -```dts -fetch: typeof fetch; -``` - -
- -`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: - -- It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. -- It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). -- Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. -- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) -- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. - -You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) - -
-
- -
- -```dts -getClientAddress(): string; -``` - -
- -The client's IP address, set by the adapter. - -
-
- -
- -```dts -locals: App.Locals; -``` - -
- -Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). - -
-
- -
- -```dts -params: Params; -``` - -
- -The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object - -
-
- -
- -```dts -platform: Readonly | undefined; -``` - -
- -Additional data made available through the adapter. - -
-
- -
- -```dts -request: Request; -``` - -
- -The original request object - -
-
- -
- -```dts -route: {/*…*/} -``` - -
- -Info about the current route - -
- -```dts -id: RouteId; -``` - -
- -The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` - -
-
- -
-
- -
- -```dts -setHeaders(headers: Record): void; -``` - -
- -If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: - -```js -// @errors: 7031 -/// file: src/routes/blog/+page.js -export async function load({ fetch, setHeaders }) { - const url = `https://cms.example.com/articles.json`; - const response = await fetch(url); - - setHeaders({ - age: response.headers.get('age'), - 'cache-control': response.headers.get('cache-control') - }); - - return response.json(); -} -``` - -Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. - -You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/reference/types#public-types-cookies) API instead. - -
-
- -
- -```dts -url: URL; -``` - -
- -The requested URL. - -
-
- -
- -```dts -isDataRequest: boolean; -``` - -
- -`true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information -related to the data request in this case. Use this property instead if the distinction is important to you. - -
-
- -
- -```dts -isSubRequest: boolean; -``` - -
- -`true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server. - -
-
-
- -## RequestHandler - -A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method. - -It receives `Params` as the first generic argument, which you can skip by using [generated types](/docs/kit/reference/types#generated-types) instead. - -
- -```dts -type RequestHandler< - Params extends Partial> = Partial< - Record - >, - RouteId extends string | null = string | null -> = ( - event: RequestEvent -) => MaybePromise; -``` - - -
- -## Reroute - -The [`reroute`](https://kit.svelte.dev/docs/hooks#universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render. - -
- -```dts -type Reroute = (event: { url: URL }) => void | string; -``` - - -
- -## ResolveOptions - -
- -```dts -interface ResolveOptions {/*…*/} -``` - -
- -```dts -transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; -``` - -
- -
- -- `input` the html chunk and the info if this is the last chunk - -
- -Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML -(they could include an element's opening tag but not its closing tag, for example) -but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components. - -
-
- -
- -```dts -filterSerializedResponseHeaders?(name: string, value: string): boolean; -``` - -
- -
- -- `name` header name -- `value` header value - -
- -Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. -By default, none will be included. - -
-
- -
- -```dts -preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; -``` - -
- -
- -- `input` the type of the file and its path - -
- -Determines what should be added to the `` tag to preload it. -By default, `js` and `css` files will be preloaded. - -
-
-
- -## RouteDefinition - -
- -```dts -interface RouteDefinition {/*…*/} -``` - -
- -```dts -id: string; -``` - -
-
- -
- -```dts -api: { - methods: Array; -}; -``` - -
-
- -
- -```dts -page: { - methods: Array>; -}; -``` - -
-
- -
- -```dts -pattern: RegExp; -``` - -
-
- -
- -```dts -prerender: PrerenderOption; -``` - -
-
- -
- -```dts -segments: RouteSegment[]; -``` - -
-
- -
- -```dts -methods: Array; -``` - -
-
- -
- -```dts -config: Config; -``` - -
-
-
- -## SSRManifest - -
- -```dts -interface SSRManifest {/*…*/} -``` - -
- -```dts -appDir: string; -``` - -
-
- -
- -```dts -appPath: string; -``` - -
-
- -
- -```dts -assets: Set; -``` - -
-
- -
- -```dts -mimeTypes: Record; -``` - -
-
- -
- -```dts -_: {/*…*/} -``` - -
- -private fields - -
- -```dts -client: NonNullable; -``` - -
-
-
- -```dts -nodes: SSRNodeLoader[]; -``` - -
-
-
- -```dts -routes: SSRRoute[]; -``` - -
-
-
- -```dts -matchers(): Promise>; -``` - -
-
-
- -```dts -server_assets: Record; -``` - -
- -A `[file]: size` map of all assets imported by server code - -
-
- -
-
-
- -## Server - -
- -```dts -class Server {/*…*/} -``` - -
- -```dts -constructor(manifest: SSRManifest); -``` - -
-
- -
- -```dts -init(options: ServerInitOptions): Promise; -``` - -
-
- -
- -```dts -respond(request: Request, options: RequestOptions): Promise; -``` - -
-
-
- -## ServerInitOptions - -
- -```dts -interface ServerInitOptions {/*…*/} -``` - -
- -```dts -env: Record; -``` - -
- -A map of environment variables - -
-
- -
- -```dts -read?: (file: string) => ReadableStream; -``` - -
- -A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work - -
-
-
- -## ServerLoad - -The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](/docs/kit/reference/types#generated-types)) -rather than using `ServerLoad` directly. - -
- -```dts -type ServerLoad< - Params extends Partial> = Partial< - Record - >, - ParentData extends Record = Record< - string, - any - >, - OutputData extends Record | void = Record< - string, - any - > | void, - RouteId extends string | null = string | null -> = ( - event: ServerLoadEvent -) => MaybePromise; -``` - - -
- -## ServerLoadEvent - -
- -```dts -interface ServerLoadEvent< - Params extends Partial> = Partial< - Record - >, - ParentData extends Record = Record< - string, - any - >, - RouteId extends string | null = string | null -> extends RequestEvent {/*…*/} -``` - -
- -```dts -parent(): Promise; -``` - -
- -`await parent()` returns data from parent `+layout.server.js` `load` functions. - -Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. - -
-
- -
- -```dts -depends(...deps: string[]): void; -``` - -
- -This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/reference/$app-navigation#invalidate) to cause `load` to rerun. - -Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. - -URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). - -Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). - -The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. - -```js -// @errors: 7031 -/// file: src/routes/+page.js -let count = 0; -export async function load({ depends }) { - depends('increase:count'); - - return { count: count++ }; -} -``` - -```html -/// file: src/routes/+page.svelte - - -

{data.count}

- -``` - -

-
- -
- -```dts -untrack(fn: () => T): T; -``` - -
- -Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: - -```js -// @errors: 7031 -/// file: src/routes/+page.js -export async function load({ untrack, url }) { - // Untrack url.pathname so that path changes don't trigger a rerun - if (untrack(() => url.pathname === '/')) { - return { message: 'Welcome!' }; - } -} -``` - -
-
-
- -## Snapshot - -The type of `export const snapshot` exported from a page or layout component. - -
- -```dts -interface Snapshot {/*…*/} -``` - -
- -```dts -capture: () => T; -``` - -
-
- -
- -```dts -restore: (snapshot: T) => void; -``` - -
-
-
- -## SubmitFunction - -
- -```dts -type SubmitFunction< - Success extends - | Record - | undefined = Record, - Failure extends - | Record - | undefined = Record -> = (input: { - action: URL; - formData: FormData; - formElement: HTMLFormElement; - controller: AbortController; - submitter: HTMLElement | null; - cancel(): void; -}) => MaybePromise< - | void - | ((opts: { - formData: FormData; - formElement: HTMLFormElement; - action: URL; - result: ActionResult; - /** - * Call this to get the default behavior of a form submission response. - * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. - * @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission. - */ - update(options?: { - reset?: boolean; - invalidateAll?: boolean; - }): Promise; - }) => void) ->; -``` - - -
- - - -## Private types - -The following are referenced by the public types documented above, but cannot be imported directly: - -## AdapterEntry - -
- -```dts -interface AdapterEntry {/*…*/} -``` - -
- -```dts -id: string; -``` - -
- -A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. -For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both -be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID - -
-
- -
- -```dts -filter(route: RouteDefinition): boolean; -``` - -
- -A function that compares the candidate route with the current route to determine -if it should be grouped with the current route. - -Use cases: -- Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes -- Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function - -
-
- -
- -```dts -complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise; -``` - -
- -A function that is invoked once the entry has been created. This is where you -should write the function to the filesystem and generate redirect manifests. - -
-
-
- -## Csp - -
- -```dts -namespace Csp { - type ActionSource = 'strict-dynamic' | 'report-sample'; - type BaseSource = - | 'self' - | 'unsafe-eval' - | 'unsafe-hashes' - | 'unsafe-inline' - | 'wasm-unsafe-eval' - | 'none'; - type CryptoSource = - `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`; - type FrameSource = - | HostSource - | SchemeSource - | 'self' - | 'none'; - type HostNameScheme = `${string}.${string}` | 'localhost'; - type HostSource = - `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`; - type HostProtocolSchemes = `${string}://` | ''; - type HttpDelineator = '/' | '?' | '#' | '\\'; - type PortScheme = `:${number}` | '' | ':*'; - type SchemeSource = - | 'http:' - | 'https:' - | 'data:' - | 'mediastream:' - | 'blob:' - | 'filesystem:'; - type Source = - | HostSource - | SchemeSource - | CryptoSource - | BaseSource; - type Sources = Source[]; -} -``` - - -
- -## CspDirectives - -
- -```dts -interface CspDirectives {/*…*/} -``` - -
- -```dts -'child-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'default-src'?: Array; -``` - -
-
- -
- -```dts -'frame-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'worker-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'connect-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'font-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'img-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'manifest-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'media-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'object-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'prefetch-src'?: Csp.Sources; -``` - -
-
- -
- -```dts -'script-src'?: Array; -``` - -
-
- -
- -```dts -'script-src-elem'?: Csp.Sources; -``` - -
-
- -
- -```dts -'script-src-attr'?: Csp.Sources; -``` - -
-
- -
- -```dts -'style-src'?: Array; -``` - -
-
- -
- -```dts -'style-src-elem'?: Csp.Sources; -``` - -
-
- -
- -```dts -'style-src-attr'?: Csp.Sources; -``` - -
-
- -
- -```dts -'base-uri'?: Array; -``` - -
-
- -
- -```dts -sandbox?: Array< -| 'allow-downloads-without-user-activation' -| 'allow-forms' -| 'allow-modals' -| 'allow-orientation-lock' -| 'allow-pointer-lock' -| 'allow-popups' -| 'allow-popups-to-escape-sandbox' -| 'allow-presentation' -| 'allow-same-origin' -| 'allow-scripts' -| 'allow-storage-access-by-user-activation' -| 'allow-top-navigation' -| 'allow-top-navigation-by-user-activation' ->; -``` - -
-
- -
- -```dts -'form-action'?: Array; -``` - -
-
- -
- -```dts -'frame-ancestors'?: Array; -``` - -
-
- -
- -```dts -'navigate-to'?: Array; -``` - -
-
- -
- -```dts -'report-uri'?: string[]; -``` - -
-
- -
- -```dts -'report-to'?: string[]; -``` - -
-
- -
- -```dts -'require-trusted-types-for'?: Array<'script'>; -``` - -
-
- -
- -```dts -'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; -``` - -
-
- -
- -```dts -'upgrade-insecure-requests'?: boolean; -``` - -
-
- -
- -```dts -'require-sri-for'?: Array<'script' | 'style' | 'script style'>; -``` - -
- -
- -- deprecated - -
- -
-
- -
- -```dts -'block-all-mixed-content'?: boolean; -``` - -
- -
- -- deprecated - -
- -
-
- -
- -```dts -'plugin-types'?: Array<`${string}/${string}` | 'none'>; -``` - -
- -
- -- deprecated - -
- -
-
- -
- -```dts -referrer?: Array< -| 'no-referrer' -| 'no-referrer-when-downgrade' -| 'origin' -| 'origin-when-cross-origin' -| 'same-origin' -| 'strict-origin' -| 'strict-origin-when-cross-origin' -| 'unsafe-url' -| 'none' ->; -``` - -
- -
- -- deprecated - -
- -
-
-
- -## HttpMethod - -
- -```dts -type HttpMethod = - | 'GET' - | 'HEAD' - | 'POST' - | 'PUT' - | 'DELETE' - | 'PATCH' - | 'OPTIONS'; -``` - - -
- -## Logger - -
- -```dts -interface Logger {/*…*/} -``` - -
- -```dts -(msg: string): void; -``` - -
-
- -
- -```dts -success(msg: string): void; -``` - -
-
- -
- -```dts -error(msg: string): void; -``` - -
-
- -
- -```dts -warn(msg: string): void; -``` - -
-
- -
- -```dts -minor(msg: string): void; -``` - -
-
- -
- -```dts -info(msg: string): void; -``` - -
-
-
- -## MaybePromise - -
- -```dts -type MaybePromise = T | Promise; -``` - - -
- -## PrerenderEntryGeneratorMismatchHandler - -
- -```dts -interface PrerenderEntryGeneratorMismatchHandler {/*…*/} -``` - -
- -```dts -(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; -``` - -
-
-
- -## PrerenderEntryGeneratorMismatchHandlerValue - -
- -```dts -type PrerenderEntryGeneratorMismatchHandlerValue = - | 'fail' - | 'warn' - | 'ignore' - | PrerenderEntryGeneratorMismatchHandler; -``` - - -
- -## PrerenderHttpErrorHandler - -
- -```dts -interface PrerenderHttpErrorHandler {/*…*/} -``` - -
- -```dts -(details: { -status: number; -path: string; -referrer: string | null; -referenceType: 'linked' | 'fetched'; -message: string; -}): void; -``` - -
-
-
- -## PrerenderHttpErrorHandlerValue - -
- -```dts -type PrerenderHttpErrorHandlerValue = - | 'fail' - | 'warn' - | 'ignore' - | PrerenderHttpErrorHandler; -``` - - -
- -## PrerenderMap - -
- -```dts -type PrerenderMap = Map; -``` - - -
- -## PrerenderMissingIdHandler - -
- -```dts -interface PrerenderMissingIdHandler {/*…*/} -``` - -
- -```dts -(details: { path: string; id: string; referrers: string[]; message: string }): void; -``` - -
-
-
- -## PrerenderMissingIdHandlerValue - -
- -```dts -type PrerenderMissingIdHandlerValue = - | 'fail' - | 'warn' - | 'ignore' - | PrerenderMissingIdHandler; -``` - - -
- -## PrerenderOption - -
- -```dts -type PrerenderOption = boolean | 'auto'; -``` - - -
- -## Prerendered - -
- -```dts -interface Prerendered {/*…*/} -``` - -
- -```dts -pages: Map< -string, -{ - /** The location of the .html file relative to the output directory */ - file: string; -} ->; -``` - -
- -A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`. - -
-
- -
- -```dts -assets: Map< -string, -{ - /** The MIME type of the asset */ - type: string; -} ->; -``` - -
- -A map of `path` to `{ type }` objects. - -
-
- -
- -```dts -redirects: Map< -string, -{ - status: number; - location: string; -} ->; -``` - -
- -A map of redirects encountered during prerendering. - -
-
- -
- -```dts -paths: string[]; -``` - -
- -An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) - -
-
-
- -## RequestOptions - -
- -```dts -interface RequestOptions {/*…*/} -``` - -
- -```dts -getClientAddress(): string; -``` - -
-
- -
- -```dts -platform?: App.Platform; -``` - -
-
-
- -## RouteSegment - -
- -```dts -interface RouteSegment {/*…*/} -``` - -
- -```dts -content: string; -``` - -
-
- -
- -```dts -dynamic: boolean; -``` - -
-
- -
- -```dts -rest: boolean; -``` - -
-
-
- -## TrailingSlash - -
- -```dts -type TrailingSlash = 'never' | 'always' | 'ignore'; -``` - - -
- - +@include kit/@sveltejs/kit/index.md diff --git a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md index 37f8d7c715..03b5c648a9 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md @@ -2,26 +2,4 @@ title: @sveltejs/kit/node/polyfills --- - - -```js -// @noErrors -import { installPolyfills } from '@sveltejs/kit/node/polyfills'; -``` - -## installPolyfills - -Make various web APIs available as globals: -- `crypto` -- `File` - -
- -```ts -// @noErrors -function installPolyfills(): void; -``` - -
- - +@include kit/@sveltejs/kit/node/polyfills/index.md diff --git a/apps/svelte.dev/content/docs/svelte/04-runtime/03-lifecycle-hooks.md b/apps/svelte.dev/content/docs/svelte/04-runtime/03-lifecycle-hooks.md index 05aa38ccbb..8dd345f091 100644 --- a/apps/svelte.dev/content/docs/svelte/04-runtime/03-lifecycle-hooks.md +++ b/apps/svelte.dev/content/docs/svelte/04-runtime/03-lifecycle-hooks.md @@ -45,13 +45,7 @@ If a function is returned from `onMount`, it will be called when the component i ## `onDestroy` -
- -```dts -function onDestroy(fn: () => any): void; -``` - -
+@include svelte/svelte/+exports/onDestroy.md Schedules a callback to run immediately before the component is unmounted. diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md b/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md index 12d685434e..a5362266d8 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md @@ -2,849 +2,4 @@ title: svelte --- - - -```js -// @noErrors -import { - afterUpdate, - beforeUpdate, - createEventDispatcher, - createRawSnippet, - flushSync, - getAllContexts, - getContext, - hasContext, - hydrate, - mount, - onDestroy, - onMount, - setContext, - tick, - unmount, - untrack -} from 'svelte'; -``` - -## afterUpdate - -Schedules a callback to run immediately after the component has been updated. - -The first time the callback runs will be after the initial `onMount`. - -In runes mode use `$effect` instead. - -https://svelte.dev/docs/svelte#afterupdate - -
- -```ts -// @noErrors -function afterUpdate(fn: () => void): void; -``` - -
- -## beforeUpdate - -Schedules a callback to run immediately before the component is updated after any state change. - -The first time the callback runs will be before the initial `onMount`. - -In runes mode use `$effect.pre` instead. - -https://svelte.dev/docs/svelte#beforeupdate - -
- -```ts -// @noErrors -function beforeUpdate(fn: () => void): void; -``` - -
- -## createEventDispatcher - -Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs#template-syntax-component-directives-on-eventname). -Event dispatchers are functions that can take two arguments: `name` and `detail`. - -Component events created with `createEventDispatcher` create a -[CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). -These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture). -The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) -property and can contain any type of data. - -The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument: -```ts -const dispatch = createEventDispatcher<{ - loaded: never; // does not take a detail argument - change: string; // takes a detail argument of type string, which is required - optional: number | null; // takes an optional detail argument of type number -}>(); -``` - -https://svelte.dev/docs/svelte#createeventdispatcher - -
- -```ts -// @noErrors -function createEventDispatcher< - EventMap extends Record = any ->(): EventDispatcher; -``` - -
- -## createRawSnippet - -Create a snippet programmatically - -
- -```ts -// @noErrors -function createRawSnippet( - fn: (...params: Getters) => { - render: () => string; - setup?: (element: Element) => void | (() => void); - } -): Snippet; -``` - -
- -## flushSync - -Synchronously flushes any pending state changes and those that result from it. - -
- -```ts -// @noErrors -function flushSync(fn?: (() => void) | undefined): void; -``` - -
- -## getAllContexts - -Retrieves the whole context map that belongs to the closest parent component. -Must be called during component initialisation. Useful, for example, if you -programmatically create a component and want to pass the existing context to it. - -https://svelte.dev/docs/svelte#getallcontexts - -
- -```ts -// @noErrors -function getAllContexts< - T extends Map = Map ->(): T; -``` - -
- -## getContext - -Retrieves the context that belongs to the closest parent component with the specified `key`. -Must be called during component initialisation. - -https://svelte.dev/docs/svelte#getcontext - -
- -```ts -// @noErrors -function getContext(key: any): T; -``` - -
- -## hasContext - -Checks whether a given `key` has been set in the context of a parent component. -Must be called during component initialisation. - -https://svelte.dev/docs/svelte#hascontext - -
- -```ts -// @noErrors -function hasContext(key: any): boolean; -``` - -
- -## hydrate - -Hydrates a component on the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component - -
- -```ts -// @noErrors -function hydrate< - Props extends Record, - Exports extends Record ->( - component: - | ComponentType> - | Component, - options: {} extends Props - ? { - target: Document | Element | ShadowRoot; - props?: Props; - events?: Record any>; - context?: Map; - intro?: boolean; - recover?: boolean; - } - : { - target: Document | Element | ShadowRoot; - props: Props; - events?: Record any>; - context?: Map; - intro?: boolean; - recover?: boolean; - } -): Exports; -``` - -
- -## mount - -Mounts a component to the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component. -Transitions will play during the initial render unless the `intro` option is set to `false`. - -
- -```ts -// @noErrors -function mount< - Props extends Record, - Exports extends Record ->( - component: - | ComponentType> - | Component, - options: {} extends Props - ? { - target: Document | Element | ShadowRoot; - anchor?: Node; - props?: Props; - events?: Record any>; - context?: Map; - intro?: boolean; - } - : { - target: Document | Element | ShadowRoot; - props: Props; - anchor?: Node; - events?: Record any>; - context?: Map; - intro?: boolean; - } -): Exports; -``` - -
- -## onDestroy - -Schedules a callback to run immediately before the component is unmounted. - -Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the -only one that runs inside a server-side component. - -https://svelte.dev/docs/svelte#ondestroy - -
- -```ts -// @noErrors -function onDestroy(fn: () => any): void; -``` - -
- -## onMount - -The `onMount` function schedules a callback to run as soon as the component has been mounted to the DOM. -It must be called during the component's initialisation (but doesn't need to live *inside* the component; -it can be called from an external module). - -If a function is returned _synchronously_ from `onMount`, it will be called when the component is unmounted. - -`onMount` does not run inside a [server-side component](https://svelte.dev/docs#run-time-server-side-component-api). - -https://svelte.dev/docs/svelte#onmount - -
- -```ts -// @noErrors -function onMount( - fn: () => - | NotFunction - | Promise> - | (() => any) -): void; -``` - -
- -## setContext - -Associates an arbitrary `context` object with the current component and the specified `key` -and returns that object. The context is then available to children of the component -(including slotted content) with `getContext`. - -Like lifecycle functions, this must be called during component initialisation. - -https://svelte.dev/docs/svelte#setcontext - -
- -```ts -// @noErrors -function setContext(key: any, context: T): T; -``` - -
- -## tick - -Returns a promise that resolves once any pending state changes have been applied. - -
- -```ts -// @noErrors -function tick(): Promise; -``` - -
- -## unmount - -Unmounts a component that was previously mounted using `mount` or `hydrate`. - -
- -```ts -// @noErrors -function unmount(component: Record): void; -``` - -
- -## untrack - -Use `untrack` to prevent something from being treated as an `$effect`/`$derived` dependency. - -https://svelte-5-preview.vercel.app/docs/functions#untrack - -
- -```ts -// @noErrors -function untrack(fn: () => T): T; -``` - -
- -## Component - -Can be used to create strongly typed Svelte components. - -#### Example: - -You have component library on npm called `component-library`, from which -you export a component called `MyComponent`. For Svelte+TypeScript users, -you want to provide typings. Therefore you create a `index.d.ts`: -```ts -import type { Component } from 'svelte'; -export declare const MyComponent: Component<{ foo: string }> {} -``` -Typing this makes it possible for IDEs like VS Code with the Svelte extension -to provide intellisense and to use the component like this in a Svelte file -with TypeScript: -```svelte - - -``` - -
- -```dts -interface Component< - Props extends Record = {}, - Exports extends Record = {}, - Bindings extends keyof Props | '' = string -> {/*…*/} -``` - -
- -```dts -( - this: void, - internals: ComponentInternals, - props: Props -): { - /** - * @deprecated This method only exists when using one of the legacy compatibility helpers, which - * is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes - * for more info. - */ - $on?(type: string, callback: (e: any) => void): () => void; - /** - * @deprecated This method only exists when using one of the legacy compatibility helpers, which - * is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes - * for more info. - */ - $set?(props: Partial): void; -} & Exports; -``` - -
- -
- -- `internal` An internal object used by Svelte. Do not use or modify. -- `props` The props passed to the component. - -
- -
-
- -
- -```dts -element?: typeof HTMLElement; -``` - -
- -The custom element version of the component. Only present if compiled with the `customElement` compiler option - -
-
-
- -## ComponentConstructorOptions - -
- -In Svelte 4, components are classes. In Svelte 5, they are functions. -Use `mount` instead to instantiate components. -See [breaking changes](https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes) -for more info. - -
- -
- -```dts -interface ComponentConstructorOptions< - Props extends Record = Record -> {/*…*/} -``` - -
- -```dts -target: Element | Document | ShadowRoot; -``` - -
-
- -
- -```dts -anchor?: Element; -``` - -
-
- -
- -```dts -props?: Props; -``` - -
-
- -
- -```dts -context?: Map; -``` - -
-
- -
- -```dts -hydrate?: boolean; -``` - -
-
- -
- -```dts -intro?: boolean; -``` - -
-
- -
- -```dts -recover?: boolean; -``` - -
-
- -
- -```dts -sync?: boolean; -``` - -
-
- -
- -```dts -$$inline?: boolean; -``` - -
-
-
- -## ComponentEvents - -
- -The new `Component` type does not have a dedicated Events type. Use `ComponentProps` instead. - -
- -
- -```dts -type ComponentEvents = - Comp extends SvelteComponent - ? Events - : never; -``` - - -
- -## ComponentInternals - -Internal implementation details that vary between environments - -
- -```dts -type ComponentInternals = Branded<{}, 'ComponentInternals'>; -``` - - -
- -## ComponentProps - -Convenience type to get the props the given component expects. - -Example: Ensure a variable contains the props expected by `MyComponent`: - -```ts -import type { ComponentProps } from 'svelte'; -import MyComponent from './MyComponent.svelte'; - -// Errors if these aren't the correct props expected by MyComponent. -const props: ComponentProps = { foo: 'bar' }; -``` - -Example: A generic function that accepts some component and infers the type of its props: - -```ts -import type { Component, ComponentProps } from 'svelte'; -import MyComponent from './MyComponent.svelte'; - -function withProps>( - component: TComponent, - props: ComponentProps -) {}; - -// Errors if the second argument is not the correct props expected by the component in the first argument. -withProps(MyComponent, { foo: 'bar' }); -``` - -
- -```dts -type ComponentProps< - Comp extends SvelteComponent | Component -> = - Comp extends SvelteComponent - ? Props - : Comp extends Component - ? Props - : never; -``` - - -
- -## ComponentType - -
- -This type is obsolete when working with the new `Component` type. - -
- -
- -```dts -type ComponentType< - Comp extends SvelteComponent = SvelteComponent -> = (new ( - options: ComponentConstructorOptions< - Comp extends SvelteComponent - ? Props - : Record - > -) => Comp) & { - /** The custom element version of the component. Only present if compiled with the `customElement` compiler option */ - element?: typeof HTMLElement; -}; -``` - - -
- -## EventDispatcher - -
- -```dts -interface EventDispatcher< - EventMap extends Record -> {/*…*/} -``` - -
- -```dts -( - ...args: null extends EventMap[Type] - ? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions] - : undefined extends EventMap[Type] - ? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions] - : [type: Type, parameter: EventMap[Type], options?: DispatchOptions] -): boolean; -``` - -
-
-
- -## Snippet - -The type of a `#snippet` block. You can use it to (for example) express that your component expects a snippet of a certain type: -```ts -let { banner }: { banner: Snippet<[{ text: string }]> } = $props(); -``` -You can only call a snippet through the `{@render ...}` tag. - -https://svelte-5-preview.vercel.app/docs/snippets - -
- -```dts -interface Snippet {/*…*/} -``` - -
- -```dts -( - this: void, - // this conditional allows tuples but not arrays. Arrays would indicate a - // rest parameter type, which is not supported. If rest parameters are added - // in the future, the condition can be removed. - ...args: number extends Parameters['length'] ? never : Parameters -): { - '{@render ...} must be called with a Snippet': "import type { Snippet } from 'svelte'"; -} & typeof SnippetReturn; -``` - -
-
-
- -## SvelteComponent - -This was the base class for Svelte components in Svelte 4. Svelte 5+ components -are completely different under the hood. For typing, use `Component` instead. -To instantiate components, use `mount` instead`. -See [breaking changes documentation](https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes) for more info. - -
- -```dts -class SvelteComponent< - Props extends Record = Record, - Events extends Record = any, - Slots extends Record = any -> {/*…*/} -``` - -
- -```dts -static element?: typeof HTMLElement; -``` - -
- -The custom element version of the component. Only present if compiled with the `customElement` compiler option - -
-
- -
- -```dts -[prop: string]: any; -``` - -
-
- -
- -```dts -constructor(options: ComponentConstructorOptions>); -``` - -
- -
- -- deprecated This constructor only exists when using the `asClassComponent` compatibility helper, which -is a stop-gap solution. Migrate towards using `mount` instead. See -https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info. - -
- -
-
- -
- -```dts -$destroy(): void; -``` - -
- -
- -- deprecated This method only exists when using one of the legacy compatibility helpers, which -is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes -for more info. - -
- -
-
- -
- -```dts -$on>( - type: K, - callback: (e: Events[K]) => void -): () => void; -``` - -
- -
- -- deprecated This method only exists when using one of the legacy compatibility helpers, which -is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes -for more info. - -
- -
-
- -
- -```dts -$set(props: Partial): void; -``` - -
- -
- -- deprecated This method only exists when using one of the legacy compatibility helpers, which -is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes -for more info. - -
- -
-
-
- -## SvelteComponentTyped - -
- -Use `Component` instead. See [breaking changes documentation](https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes) for more information. - -
- -
- -```dts -class SvelteComponentTyped< - Props extends Record = Record, - Events extends Record = any, - Slots extends Record = any -> extends SvelteComponent {} -``` - - -
- - +@include svelte/svelte/index.md diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md index 37ca65a283..542f70a565 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md @@ -2,109 +2,4 @@ title: svelte/action --- -## Action - -Actions are functions that are called when an element is created. -You can use this interface to type such actions. -The following example defines an action that only works on `
` elements -and optionally accepts a parameter which it has a default value for: -```ts -export const myAction: Action = (node, param = { someProperty: true }) => { - // ... -} -``` -`Action` and `Action` both signal that the action accepts no parameters. - -You can return an object with methods `update` and `destroy` from the function and type which additional attributes and events it has. -See interface `ActionReturn` for more details. - -Docs: https://svelte.dev/docs/svelte-action - -
- -```dts -interface Action< - Element = HTMLElement, - Parameter = undefined, - Attributes extends Record = Record< - never, - any - > -> {/*…*/} -``` - -
- -```dts -( - ...args: undefined extends Parameter - ? [node: Node, parameter?: Parameter] - : [node: Node, parameter: Parameter] -): void | ActionReturn; -``` - -
-
-
- -## ActionReturn - -Actions can return an object containing the two properties defined in this interface. Both are optional. -- update: An action can have a parameter. This method will be called whenever that parameter changes, - immediately after Svelte has applied updates to the markup. `ActionReturn` and `ActionReturn` both - mean that the action accepts no parameters. -- destroy: Method that is called after the element is unmounted - -Additionally, you can specify which additional attributes and events the action enables on the applied element. -This applies to TypeScript typings only and has no effect at runtime. - -Example usage: -```ts -interface Attributes { - newprop?: string; - 'on:event': (e: CustomEvent) => void; -} - -export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn { - // ... - return { - update: (updatedParameter) => {...}, - destroy: () => {...} - }; -} -``` - -Docs: https://svelte.dev/docs/svelte-action - -
- -```dts -interface ActionReturn< - Parameter = undefined, - Attributes extends Record = Record< - never, - any - > -> {/*…*/} -``` - -
- -```dts -update?: (parameter: Parameter) => void; -``` - -
-
- -
- -```dts -destroy?: () => void; -``` - -
-
-
- - +@include svelte/svelte/action/index.md diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md index 1760b94b3f..0c9e38e9b0 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md @@ -2,127 +2,4 @@ title: svelte/animate --- - - -```js -// @noErrors -import { flip } from 'svelte/animate'; -``` - -## flip - -The flip function calculates the start and end position of an element and animates between them, translating the x and y values. -`flip` stands for [First, Last, Invert, Play](https://aerotwist.com/blog/flip-your-animations/). - -https://svelte.dev/docs/svelte-animate#flip - -
- -```ts -// @noErrors -function flip( - node: Element, - { - from, - to - }: { - from: DOMRect; - to: DOMRect; - }, - params?: FlipParams -): AnimationConfig; -``` - -
- -## AnimationConfig - -
- -```dts -interface AnimationConfig {/*…*/} -``` - -
- -```dts -delay?: number; -``` - -
-
- -
- -```dts -duration?: number; -``` - -
-
- -
- -```dts -easing?: (t: number) => number; -``` - -
-
- -
- -```dts -css?: (t: number, u: number) => string; -``` - -
-
- -
- -```dts -tick?: (t: number, u: number) => void; -``` - -
-
-
- -## FlipParams - -
- -```dts -interface FlipParams {/*…*/} -``` - -
- -```dts -delay?: number; -``` - -
-
- -
- -```dts -duration?: number | ((len: number) => number); -``` - -
-
- -
- -```dts -easing?: (t: number) => number; -``` - -
-
-
- - +@include svelte/svelte/animate/index.md diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md index 4e7bb25652..6c59607315 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md @@ -2,1309 +2,4 @@ title: svelte/compiler --- - - -```js -// @noErrors -import { - VERSION, - compile, - compileModule, - migrate, - parse, - preprocess, - walk -} from 'svelte/compiler'; -``` - -## VERSION - -The current version, as set in package.json. - -https://svelte.dev/docs/svelte-compiler#svelte-version - -
- -```ts -// @noErrors -const VERSION: string; -``` - -
- -## compile - -`compile` converts your `.svelte` source code into a JavaScript module that exports a component - -https://svelte.dev/docs/svelte-compiler#svelte-compile - -
- -```ts -// @noErrors -function compile( - source: string, - options: CompileOptions -): CompileResult; -``` - -
- -## compileModule - -`compileModule` takes your JavaScript source code containing runes, and turns it into a JavaScript module. - -https://svelte.dev/docs/svelte-compiler#svelte-compile - -
- -```ts -// @noErrors -function compileModule( - source: string, - options: ModuleCompileOptions -): CompileResult; -``` - -
- -## migrate - -Does a best-effort migration of Svelte code towards using runes, event attributes and render tags. -May throw an error if the code is too complex to migrate automatically. - -
- -```ts -// @noErrors -function migrate(source: string): { - code: string; -}; -``` - -
- -## parse - -The parse function parses a component, returning only its abstract syntax tree. - -The `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST. -`modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7. - -https://svelte.dev/docs/svelte-compiler#svelte-parse - -
- -```ts -// @noErrors -function parse( - source: string, - options: { - filename?: string; - modern: true; - } -): AST.Root; -``` - -
- -## parse - -The parse function parses a component, returning only its abstract syntax tree. - -The `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST. -`modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7. - -https://svelte.dev/docs/svelte-compiler#svelte-parse - -
- -```ts -// @noErrors -function parse( - source: string, - options?: - | { - filename?: string; - modern?: false; - } - | undefined -): Record; -``` - -
- -## preprocess - -The preprocess function provides convenient hooks for arbitrarily transforming component source code. -For example, it can be used to convert a