From 150612721268165c77e3499687bec9edfdd85fcd Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 25 Sep 2024 16:29:38 -0400 Subject: [PATCH 1/4] sync content from git --- .../docs/kit/50-reference/10-configuration.md | 1154 ++++++ .../content/docs/kit/50-reference/20-cli.md | 15 + .../docs/kit/50-reference/30-modules.md | 1186 ++++++ .../content/docs/kit/50-reference/40-types.md | 3468 +++++++++++++++++ .../content/docs/kit/50-reference/index.md | 3 + .../03-reactivity-fundamentals.md | 66 - .../02-template-syntax/02-basic-markup.md | 2 +- .../svelte/02-template-syntax/08-bindings.md | 25 +- .../02-template-syntax/09-special-elements.md | 22 +- .../docs/svelte/05-misc/03-typescript.md | 6 +- .../svelte/98-reference/21-svelte-events.md | 72 + .../svelte/98-reference/21-svelte-legacy.md | 174 +- 12 files changed, 6102 insertions(+), 91 deletions(-) create mode 100644 apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md create mode 100644 apps/svelte.dev/content/docs/kit/50-reference/20-cli.md create mode 100644 apps/svelte.dev/content/docs/kit/50-reference/30-modules.md create mode 100644 apps/svelte.dev/content/docs/kit/50-reference/40-types.md create mode 100644 apps/svelte.dev/content/docs/kit/50-reference/index.md diff --git a/apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md b/apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md new file mode 100644 index 0000000000..dde2f235d4 --- /dev/null +++ b/apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md @@ -0,0 +1,1154 @@ +--- +title: Configuration +--- + +Your project's configuration lives in a `svelte.config.js` file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions. + +```js +/// file: svelte.config.js +// @filename: ambient.d.ts +declare module '@sveltejs/adapter-auto' { + const plugin: () => import('@sveltejs/kit').Adapter; + export default plugin; +} + +// @filename: index.js +// ---cut--- +import adapter from '@sveltejs/adapter-auto'; + +/** @type {import('@sveltejs/kit').Config} */ +const config = { + kit: { + adapter: adapter() + } +}; + +export default config; +``` + +
+ +```dts +interface Config {/*…*/} +``` + +
+ +```dts +compilerOptions?: CompileOptions; +``` + +
+ +
+ +- default `{}` + +
+ +Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). + +
+
+ +
+ +```dts +extensions?: string[]; +``` + +
+ +
+ +- default `[".svelte"]` + +
+ +List of file extensions that should be treated as Svelte files. + +
+
+ +
+ +```dts +kit?: KitConfig; +``` + +
+ +SvelteKit options + +
+
+ +
+ +```dts +preprocess?: any; +``` + +
+ +Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. + +
+
+ +
+ +```dts +vitePlugin?: PluginOptions; +``` + +
+ +`vite-plugin-svelte` plugin options. + +
+
+ +
+ +```dts +[key: string]: any; +``` + +
+ +Any additional options required by tooling that integrates with Svelte. + +
+
+
+ + + +The `kit` property configures SvelteKit, and can have the following properties: + +## adapter + +
+ +- default `undefined` + +
+ +Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. + +
+ + + +
+ +## alias + +
+ +- default `{}` + +
+ +An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. + +```js +// @errors: 7031 +/// file: svelte.config.js +/** @type {import('@sveltejs/kit').Config} */ +const config = { + kit: { + alias: { + // this will match a file + 'my-file': 'path/to/my-file.js', + + // this will match a directory and its contents + // (`my-directory/x` resolves to `path/to/my-directory/x`) + 'my-directory': 'path/to/my-directory', + + // an alias ending /* will only match + // the contents of a directory, not the directory itself + 'my-directory/*': 'path/to/my-directory/*' + } + } +}; +``` + +> The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. + +> You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. + +
+ + + +
+ +## appDir + +
+ +- default `"_app"` + +
+ +The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes. + +If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`. + +
+ + + +
+ +## 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... + +```js +// @errors: 7031 +/// file: svelte.config.js +/** @type {import('@sveltejs/kit').Config} */ +const config = { + kit: { + csp: { + directives: { + 'script-src': ['self'] + }, + reportOnly: { + 'script-src': ['self'] + } + } + } +}; + +export default config; +``` + +...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. + +To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` +``` + +If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](/docs/kit/reference/$app-stores#updated) store to `true` when it detects one. + +
+ +
+ +```ts +// @noErrors +name?: string; +``` + +
+ +The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. + +For example, to use the current commit hash, you could do use `git rev-parse HEAD`: + +```js +// @errors: 7031 +/// file: svelte.config.js +import * as child_process from 'node:child_process'; + +export default { + kit: { + version: { + name: child_process.execSync('git rev-parse HEAD').toString().trim() + } + } +}; +``` + +
+
+
+ +```ts +// @noErrors +pollInterval?: number; +``` + +
+ +
+ +- default `0` + +
+ +The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. + +
+
+ +
\ No newline at end of file diff --git a/apps/svelte.dev/content/docs/kit/50-reference/20-cli.md b/apps/svelte.dev/content/docs/kit/50-reference/20-cli.md new file mode 100644 index 0000000000..d365c446f1 --- /dev/null +++ b/apps/svelte.dev/content/docs/kit/50-reference/20-cli.md @@ -0,0 +1,15 @@ +--- +title: Command Line Interface +--- + +SvelteKit projects use [Vite](https://vitejs.dev), meaning you'll mostly use its CLI (albeit via `npm run dev/build/preview` scripts): + +- `vite dev` — start a development server +- `vite build` — build a production version of your app +- `vite preview` — run the production version locally + +However SvelteKit includes its own CLI for initialising your project: + +## svelte-kit sync + +`svelte-kit sync` creates the `tsconfig.json` and all generated types (which you can import as `./$types` inside routing files) for your project. When you create a new project, it is listed as the `prepare` script and will be run automatically as part of the npm lifecycle, so you should not ordinarily have to run this command. diff --git a/apps/svelte.dev/content/docs/kit/50-reference/30-modules.md b/apps/svelte.dev/content/docs/kit/50-reference/30-modules.md new file mode 100644 index 0000000000..12bd86defe --- /dev/null +++ b/apps/svelte.dev/content/docs/kit/50-reference/30-modules.md @@ -0,0 +1,1186 @@ +--- +title: Modules +--- + +SvelteKit makes a number of modules available to your application. + +## $app/environment + + + +```js +// @noErrors +import { browser, building, dev, version } from '$app/environment'; +``` + + + + + +### browser + +`true` if the app is running in the browser. + +
+ +```ts +// @noErrors +const browser: boolean; +``` + +
+ +### building + +SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + +
+ +```ts +// @noErrors +const building: boolean; +``` + +
+ +### dev + +Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. + +
+ +```ts +// @noErrors +const dev: boolean; +``` + +
+ +### version + +The value of `config.kit.version.name`. + +
+ +```ts +// @noErrors +const version: string; +``` + +
+ +## $app/forms + + + +```js +// @noErrors +import { applyAction, deserialize, enhance } from '$app/forms'; +``` + + + + + +### applyAction + +This action updates the `form` property of the current page with the given data and updates `$page.status`. +In case of an error, it redirects to the nearest error page. + +
+ +```ts +// @noErrors +function applyAction< + Success extends Record | undefined, + Failure extends Record | undefined +>( + result: import('@sveltejs/kit').ActionResult< + Success, + Failure + > +): Promise; +``` + +
+ +### deserialize + +Use this function to deserialize the response from a form submission. +Usage: + +```js +// @errors: 7031 +import { deserialize } from '$app/forms'; + +async function handleSubmit(event) { + const response = await fetch('/form?/action', { + method: 'POST', + body: new FormData(event.target) + }); + + const result = deserialize(await response.text()); + // ... +} +``` + +
+ +```ts +// @noErrors +function deserialize< + Success extends Record | undefined, + Failure extends Record | undefined +>( + result: string +): import('@sveltejs/kit').ActionResult; +``` + +
+ +### enhance + +This action enhances a `
` element that otherwise would work without JavaScript. + +The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. +If `cancel` is called, the form will not be submitted. +You can use the abort `controller` to cancel the submission in case another one starts. +If a function is returned, that function is called with the response from the server. +If nothing is returned, the fallback will be used. + +If this function or its return value isn't set, it +- falls back to updating the `form` prop with the returned data if the action is on the same page as the form +- updates `$page.status` +- resets the `` element and invalidates all data in case of successful submission with no redirect response +- redirects in case of a redirect response +- redirects to the nearest error page in case of an unexpected error + +If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. + +
+ +```ts +// @noErrors +function enhance< + Success extends Record | undefined, + Failure extends Record | undefined +>( + form_element: HTMLFormElement, + submit?: import('@sveltejs/kit').SubmitFunction< + Success, + Failure + > +): { + destroy(): void; +}; +``` + +
+ +## $app/navigation + + + +```js +// @noErrors +import { + afterNavigate, + beforeNavigate, + disableScrollHandling, + goto, + invalidate, + invalidateAll, + onNavigate, + preloadCode, + preloadData, + pushState, + replaceState +} from '$app/navigation'; +``` + + + + + +### afterNavigate + +A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. + +`afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + +
+ +```ts +// @noErrors +function afterNavigate( + callback: ( + navigation: import('@sveltejs/kit').AfterNavigate + ) => void +): void; +``` + +
+ +### beforeNavigate + +A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. + +Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. + +When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`. + +If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`. + +`beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + +
+ +```ts +// @noErrors +function beforeNavigate( + callback: ( + navigation: import('@sveltejs/kit').BeforeNavigate + ) => void +): void; +``` + +
+ +### disableScrollHandling + +If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. +This is generally discouraged, since it breaks user expectations. + +
+ +```ts +// @noErrors +function disableScrollHandling(): void; +``` + +
+ +### goto + +Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. +For external URLs, use `window.location = url` instead of calling `goto(url)`. + +
+ +```ts +// @noErrors +function goto( + url: string | URL, + opts?: + | { + replaceState?: boolean | undefined; + noScroll?: boolean | undefined; + keepFocus?: boolean | undefined; + invalidateAll?: boolean | undefined; + state?: App.PageState | undefined; + } + | undefined +): Promise; +``` + +
+ +### invalidate + +Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. + +If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). +To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. + +The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. +This can be useful if you want to invalidate based on a pattern instead of a exact match. + +```ts +// Example: Match '/path' regardless of the query parameters +import { invalidate } from '$app/navigation'; + +invalidate((url) => url.pathname === '/path'); +``` + +
+ +```ts +// @noErrors +function invalidate( + resource: string | URL | ((url: URL) => boolean) +): Promise; +``` + +
+ +### invalidateAll + +Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + +
+ +```ts +// @noErrors +function invalidateAll(): Promise; +``` + +
+ +### onNavigate + +A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations. + +If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. + +If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated. + +`onNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + +
+ +```ts +// @noErrors +function onNavigate( + callback: ( + navigation: import('@sveltejs/kit').OnNavigate + ) => MaybePromise<(() => void) | void> +): void; +``` + +
+ +### preloadCode + +Programmatically imports the code for routes that haven't yet been fetched. +Typically, you might call this to speed up subsequent navigation. + +You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). + +Unlike `preloadData`, this won't call `load` functions. +Returns a Promise that resolves when the modules have been imported. + +
+ +```ts +// @noErrors +function preloadCode(pathname: string): Promise; +``` + +
+ +### preloadData + +Programmatically preloads the given page, which means + 1. ensuring that the code for the page is loaded, and + 2. calling the page's load function with the appropriate options. + +This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. +If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. +Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete. + +
+ +```ts +// @noErrors +function preloadData(href: string): Promise< + | { + type: 'loaded'; + status: number; + data: Record; + } + | { + type: 'redirect'; + location: string; + } +>; +``` + +
+ +### pushState + +Programmatically create a new history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). + +
+ +```ts +// @noErrors +function pushState( + url: string | URL, + state: App.PageState +): void; +``` + +
+ +### replaceState + +Programmatically replace the current history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). + +
+ +```ts +// @noErrors +function replaceState( + url: string | URL, + state: App.PageState +): void; +``` + +
+ +## $app/paths + + + +```js +// @noErrors +import { assets, base, resolveRoute } from '$app/paths'; +``` + + + + + +### assets + +An absolute path that matches [`config.kit.paths.assets`](/docs/kit/reference/configuration#paths). + +> If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. + +
+ +```ts +// @noErrors +let assets: + | '' + | `https://${string}` + | `http://${string}` + | '/_svelte_kit_assets'; +``` + +
+ +### base + +A string that matches [`config.kit.paths.base`](/docs/kit/reference/configuration#paths). + +Example usage: `
Link` + +
+ +```ts +// @noErrors +let base: '' | `/${string}`; +``` + +
+ +### resolveRoute + +Populate a route ID with params to resolve a pathname. + +
+ +```ts +// @noErrors +function resolveRoute( + id: string, + params: Record +): string; +``` + +
+ +## $app/server + + + +```js +// @noErrors +import { read } from '$app/server'; +``` + + + + + +### read + +Read the contents of an imported asset from the filesystem + +
+ +```ts +// @noErrors +function read(asset: string): Response; +``` + +
+ +## $app/stores + + + +```js +// @noErrors +import { getStores, navigating, page, updated } from '$app/stores'; +``` + + + + + +### getStores + + + +
+ +```ts +// @noErrors +function getStores(): { + page: typeof page; + + navigating: typeof navigating; + + updated: typeof updated; +}; +``` + +
+ +### navigating + +A readable store. +When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. +When navigating finishes, its value reverts to `null`. + +On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + +
+ +```ts +// @noErrors +const navigating: import('svelte/store').Readable< + import('@sveltejs/kit').Navigation | null +>; +``` + +
+ +### page + +A readable store whose value contains page data. + +On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + +
+ +```ts +// @noErrors +const page: import('svelte/store').Readable< + import('@sveltejs/kit').Page +>; +``` + +
+ +### updated + +A readable store whose initial value is `false`. If [`version.pollInterval`](/docs/kit/reference/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. + +On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + +
+ +```ts +// @noErrors +const updated: import('svelte/store').Readable & { + check(): Promise; +}; +``` + +
+ +## $env/dynamic/private + + + +This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](/docs/kit/reference/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/reference/configuration#env) (if configured). + +This module cannot be imported into client-side code. + +Dynamic environment variables cannot be used during prerendering. + +```ts +import { env } from '$env/dynamic/private'; +console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); +``` + +> In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. + + + + +## $env/dynamic/public + + + +Similar to [`$env/dynamic/private`](/docs/kit/reference/$env-all#$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + +Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead. + +Dynamic environment variables cannot be used during prerendering. + +```ts +import { env } from '$env/dynamic/public'; +console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); +``` + + + + +## $env/static/private + + + +Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](/docs/kit/reference/$env-all#$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/reference/configuration#env) (if configured). + +_Unlike_ [`$env/dynamic/private`](/docs/kit/reference/$env-all#$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination. + +```ts +import { API_KEY } from '$env/static/private'; +``` + +Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: + +``` +MY_FEATURE_FLAG="" +``` + +You can override `.env` values from the command line like so: + +```bash +MY_FEATURE_FLAG="enabled" npm run dev +``` + + + + +## $env/static/public + + + +Similar to [`$env/static/private`](/docs/kit/reference/$env-all#$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + +Values are replaced statically at build time. + +```ts +import { PUBLIC_BASE_URL } from '$env/static/public'; +``` + + + + +## $lib + + + +This is a simple alias to `src/lib`, or whatever directory is specified as [`config.kit.files.lib`](/docs/kit/reference/configuration#files). It allows you to access common components and utility modules without `../../../../` nonsense. + +### `$lib/server` + +A subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](/docs/server-only-modules). + + + + +## $service-worker + + + +```js +// @noErrors +import { base, build, files, prerendered, version } from '$service-worker'; +``` + + + +This module is only available to [service workers](/docs/service-workers). + +### base + +The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. +Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. + +
+ +```ts +// @noErrors +const base: string; +``` + +
+ +### build + +An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. +During development, this is an empty array. + +
+ +```ts +// @noErrors +const build: string[]; +``` + +
+ +### files + +An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](/docs/kit/reference/configuration) + +
+ +```ts +// @noErrors +const files: string[]; +``` + +
+ +### prerendered + +An array of pathnames corresponding to prerendered pages and endpoints. +During development, this is an empty array. + +
+ +```ts +// @noErrors +const prerendered: string[]; +``` + +
+ +### version + +See [`config.kit.version`](/docs/kit/reference/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. + +
+ +```ts +// @noErrors +const version: string; +``` + +
+ +## @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; +``` + +
+ +## @sveltejs/kit/hooks + + + +```js +// @noErrors +import { sequence } from '@sveltejs/kit/hooks'; +``` + + + + + +### sequence + +A helper function for sequencing multiple `handle` calls in a middleware-like manner. +The behavior for the `handle` options is as follows: +- `transformPageChunk` is applied in reverse order and merged +- `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called +- `filterSerializedResponseHeaders` behaves the same as `preload` + +```js +// @errors: 7031 +/// file: src/hooks.server.js +import { sequence } from '@sveltejs/kit/hooks'; + +/** @type {import('@sveltejs/kit').Handle} */ +async function first({ event, resolve }) { + console.log('first pre-processing'); + const result = await resolve(event, { + transformPageChunk: ({ html }) => { + // transforms are applied in reverse order + console.log('first transform'); + return html; + }, + preload: () => { + // this one wins as it's the first defined in the chain + console.log('first preload'); + } + }); + console.log('first post-processing'); + return result; +} + +/** @type {import('@sveltejs/kit').Handle} */ +async function second({ event, resolve }) { + console.log('second pre-processing'); + const result = await resolve(event, { + transformPageChunk: ({ html }) => { + console.log('second transform'); + return html; + }, + preload: () => { + console.log('second preload'); + }, + filterSerializedResponseHeaders: () => { + // this one wins as it's the first defined in the chain + console.log('second filterSerializedResponseHeaders'); + } + }); + console.log('second post-processing'); + return result; +} + +export const handle = sequence(first, second); +``` + +The example above would print: + +``` +first pre-processing +first preload +second pre-processing +second filterSerializedResponseHeaders +second transform +first transform +second post-processing +first post-processing +``` + +
+ +```ts +// @noErrors +function sequence( + ...handlers: import('@sveltejs/kit').Handle[] +): import('@sveltejs/kit').Handle; +``` + +
+ +## @sveltejs/kit/node + + + +```js +// @noErrors +import { + createReadableStream, + getRequest, + setResponse +} from '@sveltejs/kit/node'; +``` + + + + + +### createReadableStream + +Converts a file on disk to a readable stream + +
+ +```ts +// @noErrors +function createReadableStream(file: string): ReadableStream; +``` + +
+ +### getRequest + + + +
+ +```ts +// @noErrors +function getRequest({ + request, + base, + bodySizeLimit +}: { + request: import('http').IncomingMessage; + base: string; + bodySizeLimit?: number; +}): Promise; +``` + +
+ +### setResponse + + + +
+ +```ts +// @noErrors +function setResponse( + res: import('http').ServerResponse, + response: Response +): Promise; +``` + +
+ +## @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; +``` + +
+ +## @sveltejs/kit/vite + + + +```js +// @noErrors +import { sveltekit } from '@sveltejs/kit/vite'; +``` + + + + + +### sveltekit + +Returns the SvelteKit Vite plugins. + +
+ +```ts +// @noErrors +function sveltekit(): Promise; +``` + +
+ + + + diff --git a/apps/svelte.dev/content/docs/kit/50-reference/40-types.md b/apps/svelte.dev/content/docs/kit/50-reference/40-types.md new file mode 100644 index 0000000000..65f37d2521 --- /dev/null +++ b/apps/svelte.dev/content/docs/kit/50-reference/40-types.md @@ -0,0 +1,3468 @@ +--- +title: Types +--- + +## Public types + +The following types can be imported from `@sveltejs/kit`: + +## 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'; +``` + + +
+ + + +## Generated types + +The `RequestHandler` and `Load` types both accept a `Params` argument allowing you to type the `params` object. For example this endpoint expects `foo`, `bar` and `baz` params: + +```js +/// file: src/routes/[foo]/[bar]/[baz]/+page.server.js +// @errors: 2355 2322 1360 +/** @type {import('@sveltejs/kit').RequestHandler<{ + foo: string; + bar: string; + baz: string + }>} */ +export async function GET({ params }) { + // ... +} +``` + +Needless to say, this is cumbersome to write out, and less portable (if you were to rename the `[foo]` directory to `[qux]`, the type would no longer reflect reality). + +To solve this problem, SvelteKit generates `.d.ts` files for each of your endpoints and pages: + +```ts +/// file: .svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts +/// link: false +import type * as Kit from '@sveltejs/kit'; + +type RouteParams = { + foo: string; + bar: string; + baz: string; +} + +export type PageServerLoad = Kit.ServerLoad; +export type PageLoad = Kit.Load; +``` + +These files can be imported into your endpoints and pages as siblings, thanks to the [`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs) option in your TypeScript configuration: + +```js +/// file: src/routes/[foo]/[bar]/[baz]/+page.server.js +// @filename: $types.d.ts +import type * as Kit from '@sveltejs/kit'; + +type RouteParams = { + foo: string; + bar: string; + baz: string; +} + +export type PageServerLoad = Kit.ServerLoad; + +// @filename: index.js +// @errors: 2355 +// ---cut--- +/** @type {import('./$types').PageServerLoad} */ +export async function GET({ params }) { + // ... +} +``` + +```js +/// file: src/routes/[foo]/[bar]/[baz]/+page.js +// @filename: $types.d.ts +import type * as Kit from '@sveltejs/kit'; + +type RouteParams = { + foo: string; + bar: string; + baz: string; +} + +export type PageLoad = Kit.Load; + +// @filename: index.js +// @errors: 2355 +// ---cut--- +/** @type {import('./$types').PageLoad} */ +export async function load({ params, fetch }) { + // ... +} +``` + +> For this to work, your own `tsconfig.json` or `jsconfig.json` should extend from the generated `.svelte-kit/tsconfig.json` (where `.svelte-kit` is your [`outDir`](configuration#outdir)) and TypeScript should be installed as a dependency: +> +> `{ "extends": "./.svelte-kit/tsconfig.json" }` + +### Default tsconfig.json + +The generated `.svelte-kit/tsconfig.json` file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason: + +```json +/// file: .svelte-kit/tsconfig.json +{ + "compilerOptions": { + "baseUrl": "..", + "paths": { + "$lib": "src/lib", + "$lib/*": "src/lib/*" + }, + "rootDirs": ["..", "./types"] + }, + "include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"], + "exclude": ["../node_modules/**", "./**"] +} +``` + +Others are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing: + +```json +/// file: .svelte-kit/tsconfig.json +{ + "compilerOptions": { + // this ensures that types are explicitly + // imported with `import type`, which is + // necessary as svelte-preprocess cannot + // otherwise compile components correctly + "importsNotUsedAsValues": "error", + + // Vite compiles one TypeScript module + // at a time, rather than compiling + // the entire module graph + "isolatedModules": true, + + // TypeScript cannot 'see' when you + // use an imported value in your + // markup, so we need this + "preserveValueImports": true, + + // This ensures both `vite build` + // and `svelte-package` work correctly + "lib": ["esnext", "DOM", "DOM.Iterable"], + "moduleResolution": "node", + "module": "esnext", + "target": "esnext" + } +} +``` + +## App + +## Error + +Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. + +
+ +```dts +interface Error {/*…*/} +``` + +
+ +```dts +message: string; +``` + +
+
+
+ +## Locals + +The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. + +
+ +```dts +interface Locals {} +``` + + +
+ +## PageData + +Defines the common shape of the [$page.data store](/docs/kit/reference/$app-stores#page) - that is, the data that is shared between all pages. +The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. +Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). + +
+ +```dts +interface PageData {} +``` + + +
+ +## PageState + +The shape of the `$page.state` object, 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 +interface PageState {} +``` + + +
+ +## Platform + +If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. + +
+ +```dts +interface Platform {} +``` + + +
+ + diff --git a/apps/svelte.dev/content/docs/kit/50-reference/index.md b/apps/svelte.dev/content/docs/kit/50-reference/index.md new file mode 100644 index 0000000000..b98302768e --- /dev/null +++ b/apps/svelte.dev/content/docs/kit/50-reference/index.md @@ -0,0 +1,3 @@ +--- +title: Reference +--- diff --git a/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md b/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md index 1d165d46ac..0f1c8e0799 100644 --- a/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md +++ b/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md @@ -40,23 +40,6 @@ class Todo { } ``` -
-Legacy mode - -In Svelte 4, state was implicitly reactive if the variable was declared at the top level - -```svelte - - - -``` - -
- ## `$derived` Derived state is declared with the `$derived` rune: @@ -78,27 +61,6 @@ The expression inside `$derived(...)` should be free of side-effects. Svelte wil As with `$state`, you can mark class fields as `$derived`. -
-Legacy mode -In Svelte 4, you could use reactive statements for this. - -```svelte - - - - -

{count} doubled is {doubled}

-``` - -This only worked at the top level of a component. - -
- ## `$effect` To run _side-effects_ when the component is mounted to the DOM, and when values change, we can use the `$effect` rune ([demo](/#H4sIAAAAAAAAE31T24rbMBD9lUG7kAQ2sbdlX7xOYNk_aB_rQhRpbAsU2UiTW0P-vbrYubSlYGzmzMzROTPymdVKo2PFjzMzfIusYB99z14YnfoQuD1qQh-7bmdFQEonrOppVZmKNBI49QthCc-OOOH0LZ-9jxnR6c7eUpOnuv6KeT5JFdcqbvbcBcgDz1jXKGg6ncFyBedYR6IzLrAZwiN5vtSxaJA-EzadfJEjKw11C6GR22-BLH8B_wxdByWpvUYtqqal2XB6RVkG1CoHB6U1WJzbnYFDiwb3aGEdDa3Bm1oH12sQLTcNPp7r56m_00mHocSG97_zd7ICUXonA5fwKbPbkE2ZtMJGGVkEdctzQi4QzSwr9prnFYNk5hpmqVuqPQjNnfOJoMF22lUsrq_UfIN6lfSVyvQ7grB3X2mjMZYO3XO9w-U5iLx42qg29md3BP_ni5P4gy9ikTBlHxjLzAtPDlyYZmRdjAbGq7HprEQ7p64v4LU_guu0kvAkhBim3nMplWl8FreQD-CW20aZR0wq12t-KqDWeBywhvexKC3memmDwlHAv9q4Vo2ZK8KtK0CgX7u9J8wXbzdKv-nRnfF_2baTqlYoWUF2h5efl9-n0O6koAMAAA==)): @@ -124,31 +86,3 @@ To run _side-effects_ when the component is mounted to the DOM, and when values ``` The function passed to `$effect` will run when the component mounts, and will re-run after any changes to the values it reads that were declared with `$state` or `$derived` (including those passed in with `$props`). Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied. - -
-Legacy mode -In Svelte 4, you could use reactive statements for this. - -```svelte - - - -``` - -This only worked at the top level of a component. - -
diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md index 8bf9b2cf42..437e59eb14 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md @@ -112,7 +112,7 @@ Because events are just attributes, the same rules as for attributes apply: Timing-wise, event attributes always fire after events from bindings (e.g. `oninput` always fires after an update to `bind:value`). Under the hood, some event handlers are attached directly with `addEventListener`, while others are _delegated_. -When using `onwheel`, `onmousewheel`, `ontouchstart` and `ontouchmove` event attributes, the handlers are [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#using_passive_listeners) to align with browser defaults. This greatly improves responsiveness by allowing the browser to scroll the document immediately, rather than waiting to see if the event handler calls `event.preventDefault()`. +When using `ontouchstart` and `ontouchmove` event attributes, the handlers are [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#using_passive_listeners) for better performance. This greatly improves responsiveness by allowing the browser to scroll the document immediately, rather than waiting to see if the event handler calls `event.preventDefault()`. In the very rare cases that you need to prevent these event defaults, you should use [`on`](https://svelte-5-preview.vercel.app/docs/imports#svelte-events) instead (for example inside an action). diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md index 73b49cdd0e..cabbc45969 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md @@ -1,4 +1,4 @@ ---- +--- title: Bindings --- @@ -42,25 +42,34 @@ Numeric input values are coerced; even though `input.value` is a string as far a ``` -On `` elements with `type="file"`, you can use `bind:files` to get the [`FileList` of selected files](https://developer.mozilla.org/en-US/docs/Web/API/FileList). It is readonly. +On `` elements with `type="file"`, you can use `bind:files` to get the [`FileList` of selected files](https://developer.mozilla.org/en-US/docs/Web/API/FileList). When you want to update the files programmatically, you always need to use a `FileList` object. Currently `FileList` objects cannot be constructed directly, so you need to create a new [`DataTransfer`](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer) object and get `files` from there. ```svelte + + + ``` -If you're using `bind:` directives together with `on:` directives, the order that they're defined in affects the value of the bound variable when the event handler is called. +`FileList` objects also cannot be modified, so if you want to e.g. delete a single file from the list, you need to create a new `DataTransfer` object and add the files you want to keep. + +> `DataTransfer` may not be available in server-side JS runtimes. Leaving the state that is bound to `files` uninitialized prevents potential errors if components are server-side rendered. + +If you're using `bind:` directives together with `on` event attributes, the binding will always fire before the event attribute. ```svelte - console.log('Old value:', value)} - bind:value - on:input={() => console.log('New value:', value)} -/> + console.log('New value:', value)} bind:value /> ``` Here we were binding to the value of a text input, which uses the `input` event. Bindings on other elements may use different events such as `change`. diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/09-special-elements.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/09-special-elements.md index b2f6e1e134..86fad4fa18 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/09-special-elements.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/09-special-elements.md @@ -14,8 +14,7 @@ It cannot appear at the top level of your markup; it must be inside an if or eac ```svelte {#if count > 0} @@ -56,12 +55,12 @@ If `this` is the name of a [void element](https://developer.mozilla.org/en-US/do ```svelte -Foo +Foo ``` Svelte tries its best to infer the correct namespace from the element's surroundings, but it's not always possible. You can make it explicit with an `xmlns` attribute: @@ -73,7 +72,7 @@ Svelte tries its best to infer the correct namespace from the element's surround ## `` ```svelte - + ``` ```svelte @@ -86,13 +85,12 @@ Unlike ``, this element may only appear at the top level of your co ```svelte - + ``` You can also bind to the following properties: @@ -117,7 +115,7 @@ All except `scrollX` and `scrollY` are readonly. ## `` ```svelte - + ``` ```svelte @@ -129,7 +127,7 @@ Similarly to ``, this element allows you to add listeners to even As with ``, this element may only appear the top level of your component and must never be inside a block or element. ```svelte - + ``` You can also bind to the following properties: @@ -144,7 +142,7 @@ All are readonly. ## `` ```svelte - + ``` Similarly to ``, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave`, which don't fire on `window`. It also lets you use [actions](/docs/element-directives#use-action) on the `` element. @@ -152,7 +150,7 @@ Similarly to ``, this element allows you to add listeners to even As with `` and ``, this element may only appear the top level of your component and must never be inside a block or element. ```svelte - + ``` ## `` diff --git a/apps/svelte.dev/content/docs/svelte/05-misc/03-typescript.md b/apps/svelte.dev/content/docs/svelte/05-misc/03-typescript.md index eb58e89b5c..10f0dd30eb 100644 --- a/apps/svelte.dev/content/docs/svelte/05-misc/03-typescript.md +++ b/apps/svelte.dev/content/docs/svelte/05-misc/03-typescript.md @@ -118,7 +118,7 @@ Components can declare a generic relationship between their properties. One exam select: Item; } - let { items, select } = $props(); + let { items, select }: Props = $props(); {#each items as item} @@ -210,8 +210,8 @@ declare namespace svelteHTML { } // enhance attributes interface HTMLAttributes { - // If you want to use on:beforeinstallprompt - 'on:beforeinstallprompt'?: (event: any) => any; + // If you want to use the beforeinstallprompt event + 'onbeforeinstallprompt'?: (event: any) => any; // If you want to use myCustomAttribute={..} (note: all lowercase) mycustomattribute?: any; // You can replace any with something more specific if you like } diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-events.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-events.md index c9e55deb48..1078efa675 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-events.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-events.md @@ -11,6 +11,52 @@ import { on } from 'svelte/events'; ## on +Attaches an event handler to the window and returns a function that removes the handler. Using this +rather than `addEventListener` will preserve the correct order relative to handlers added declaratively +(with attributes like `onclick`), which use event delegation for performance reasons + +
+ +```ts +// @noErrors +function on( + window: Window, + type: Type, + handler: ( + this: Window, + event: WindowEventMap[Type] + ) => any, + options?: AddEventListenerOptions | undefined +): () => void; +``` + +
+ +## on + +Attaches an event handler to the document and returns a function that removes the handler. Using this +rather than `addEventListener` will preserve the correct order relative to handlers added declaratively +(with attributes like `onclick`), which use event delegation for performance reasons + +
+ +```ts +// @noErrors +function on( + document: Document, + type: Type, + handler: ( + this: Document, + event: DocumentEventMap[Type] + ) => any, + options?: AddEventListenerOptions | undefined +): () => void; +``` + +
+ +## on + Attaches an event handler to an element and returns a function that removes the handler. Using this rather than `addEventListener` will preserve the correct order relative to handlers added declaratively (with attributes like `onclick`), which use event delegation for performance reasons @@ -43,6 +89,32 @@ rather than `addEventListener` will preserve the correct order relative to handl
+```ts +// @noErrors +function on< + Element extends MediaQueryList, + Type extends keyof MediaQueryListEventMap +>( + element: Element, + type: Type, + handler: ( + this: Element, + event: MediaQueryListEventMap[Type] + ) => any, + options?: AddEventListenerOptions | undefined +): () => void; +``` + +
+ +## on + +Attaches an event handler to an element and returns a function that removes the handler. Using this +rather than `addEventListener` will preserve the correct order relative to handlers added declaratively +(with attributes like `onclick`), which use event delegation for performance reasons + +
+ ```ts // @noErrors function on( diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-legacy.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-legacy.md index e2c347fb6e..4497cf7de4 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-legacy.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-legacy.md @@ -6,7 +6,21 @@ title: svelte/legacy ```js // @noErrors -import { asClassComponent, createClassComponent, run } from 'svelte/legacy'; +import { + asClassComponent, + createBubbler, + createClassComponent, + handlers, + nonpassive, + once, + passive, + preventDefault, + run, + self, + stopImmediatePropagation, + stopPropagation, + trusted +} from 'svelte/legacy'; ``` ## asClassComponent @@ -33,6 +47,21 @@ function asClassComponent<
+## createBubbler + +Function to create a `bubble` function that mimic the behavior of `on:click` without handler available in svelte 4. + +
+ +```ts +// @noErrors +function createBubbler(): ( + type: string +) => (event: Event) => boolean; +``` + +
+ ## createClassComponent Takes the same options as a Svelte 4 component and the component function and returns a Svelte 4 compatible component. @@ -57,6 +86,89 @@ function createClassComponent< +## handlers + +Function to mimic the multiple listeners available in svelte 4 + +
+ +```ts +// @noErrors +function handlers( + ...handlers: EventListener[] +): EventListener; +``` + +
+ +## nonpassive + +Substitute for the `nonpassive` event modifier, implemented as an action + +
+ +```ts +// @noErrors +function nonpassive( + node: HTMLElement, + [event, handler]: [ + event: string, + handler: () => EventListener + ] +): void; +``` + +
+ +## once + +Substitute for the `once` event modifier + +
+ +```ts +// @noErrors +function once( + fn: (event: Event, ...args: Array) => void +): (event: Event, ...args: unknown[]) => void; +``` + +
+ +## passive + +Substitute for the `passive` event modifier, implemented as an action + +
+ +```ts +// @noErrors +function passive( + node: HTMLElement, + [event, handler]: [ + event: string, + handler: () => EventListener + ] +): void; +``` + +
+ +## preventDefault + +Substitute for the `preventDefault` event modifier + +
+ +```ts +// @noErrors +function preventDefault( + fn: (event: Event, ...args: Array) => void +): (event: Event, ...args: unknown[]) => void; +``` + +
+ ## run Runs the given function once immediately on the server, and works like `$effect.pre` on the client. @@ -70,4 +182,64 @@ function run(fn: () => void | (() => void)): void; +## self + +Substitute for the `self` event modifier + +
+ +```ts +// @noErrors +function self( + fn: (event: Event, ...args: Array) => void +): (event: Event, ...args: unknown[]) => void; +``` + +
+ +## stopImmediatePropagation + +Substitute for the `stopImmediatePropagation` event modifier + +
+ +```ts +// @noErrors +function stopImmediatePropagation( + fn: (event: Event, ...args: Array) => void +): (event: Event, ...args: unknown[]) => void; +``` + +
+ +## stopPropagation + +Substitute for the `stopPropagation` event modifier + +
+ +```ts +// @noErrors +function stopPropagation( + fn: (event: Event, ...args: Array) => void +): (event: Event, ...args: unknown[]) => void; +``` + +
+ +## trusted + +Substitute for the `trusted` event modifier + +
+ +```ts +// @noErrors +function trusted( + fn: (event: Event, ...args: Array) => void +): (event: Event, ...args: unknown[]) => void; +``` + +
+ From 2959da51d0da4ad064b69b066c3b30acdaf34688 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 25 Sep 2024 16:31:08 -0400 Subject: [PATCH 2/4] preserve local changes showing legacy blocks --- .../03-reactivity-fundamentals.md | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md b/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md index 0f1c8e0799..1d165d46ac 100644 --- a/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md +++ b/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md @@ -40,6 +40,23 @@ class Todo { } ``` +
+Legacy mode + +In Svelte 4, state was implicitly reactive if the variable was declared at the top level + +```svelte + + + +``` + +
+ ## `$derived` Derived state is declared with the `$derived` rune: @@ -61,6 +78,27 @@ The expression inside `$derived(...)` should be free of side-effects. Svelte wil As with `$state`, you can mark class fields as `$derived`. +
+Legacy mode +In Svelte 4, you could use reactive statements for this. + +```svelte + + + + +

{count} doubled is {doubled}

+``` + +This only worked at the top level of a component. + +
+ ## `$effect` To run _side-effects_ when the component is mounted to the DOM, and when values change, we can use the `$effect` rune ([demo](/#H4sIAAAAAAAAE31T24rbMBD9lUG7kAQ2sbdlX7xOYNk_aB_rQhRpbAsU2UiTW0P-vbrYubSlYGzmzMzROTPymdVKo2PFjzMzfIusYB99z14YnfoQuD1qQh-7bmdFQEonrOppVZmKNBI49QthCc-OOOH0LZ-9jxnR6c7eUpOnuv6KeT5JFdcqbvbcBcgDz1jXKGg6ncFyBedYR6IzLrAZwiN5vtSxaJA-EzadfJEjKw11C6GR22-BLH8B_wxdByWpvUYtqqal2XB6RVkG1CoHB6U1WJzbnYFDiwb3aGEdDa3Bm1oH12sQLTcNPp7r56m_00mHocSG97_zd7ICUXonA5fwKbPbkE2ZtMJGGVkEdctzQi4QzSwr9prnFYNk5hpmqVuqPQjNnfOJoMF22lUsrq_UfIN6lfSVyvQ7grB3X2mjMZYO3XO9w-U5iLx42qg29md3BP_ni5P4gy9ikTBlHxjLzAtPDlyYZmRdjAbGq7HprEQ7p64v4LU_guu0kvAkhBim3nMplWl8FreQD-CW20aZR0wq12t-KqDWeBywhvexKC3memmDwlHAv9q4Vo2ZK8KtK0CgX7u9J8wXbzdKv-nRnfF_2baTqlYoWUF2h5efl9-n0O6koAMAAA==)): @@ -86,3 +124,31 @@ To run _side-effects_ when the component is mounted to the DOM, and when values ``` The function passed to `$effect` will run when the component mounts, and will re-run after any changes to the values it reads that were declared with `$state` or `$derived` (including those passed in with `$props`). Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied. + +
+Legacy mode +In Svelte 4, you could use reactive statements for this. + +```svelte + + + +``` + +This only worked at the top level of a component. + +
From fd49f9a30d395502b672193f5317d895b261e5c3 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 25 Sep 2024 18:32:43 -0400 Subject: [PATCH 3/4] remove --- .../docs/kit/50-reference/10-configuration.md | 1154 ------ .../content/docs/kit/50-reference/20-cli.md | 15 - .../docs/kit/50-reference/30-modules.md | 1186 ------ .../content/docs/kit/50-reference/40-types.md | 3468 ----------------- .../content/docs/kit/50-reference/index.md | 3 - 5 files changed, 5826 deletions(-) delete mode 100644 apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md delete mode 100644 apps/svelte.dev/content/docs/kit/50-reference/20-cli.md delete mode 100644 apps/svelte.dev/content/docs/kit/50-reference/30-modules.md delete mode 100644 apps/svelte.dev/content/docs/kit/50-reference/40-types.md delete mode 100644 apps/svelte.dev/content/docs/kit/50-reference/index.md diff --git a/apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md b/apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md deleted file mode 100644 index dde2f235d4..0000000000 --- a/apps/svelte.dev/content/docs/kit/50-reference/10-configuration.md +++ /dev/null @@ -1,1154 +0,0 @@ ---- -title: Configuration ---- - -Your project's configuration lives in a `svelte.config.js` file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions. - -```js -/// file: svelte.config.js -// @filename: ambient.d.ts -declare module '@sveltejs/adapter-auto' { - const plugin: () => import('@sveltejs/kit').Adapter; - export default plugin; -} - -// @filename: index.js -// ---cut--- -import adapter from '@sveltejs/adapter-auto'; - -/** @type {import('@sveltejs/kit').Config} */ -const config = { - kit: { - adapter: adapter() - } -}; - -export default config; -``` - -
- -```dts -interface Config {/*…*/} -``` - -
- -```dts -compilerOptions?: CompileOptions; -``` - -
- -
- -- default `{}` - -
- -Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). - -
-
- -
- -```dts -extensions?: string[]; -``` - -
- -
- -- default `[".svelte"]` - -
- -List of file extensions that should be treated as Svelte files. - -
-
- -
- -```dts -kit?: KitConfig; -``` - -
- -SvelteKit options - -
-
- -
- -```dts -preprocess?: any; -``` - -
- -Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. - -
-
- -
- -```dts -vitePlugin?: PluginOptions; -``` - -
- -`vite-plugin-svelte` plugin options. - -
-
- -
- -```dts -[key: string]: any; -``` - -
- -Any additional options required by tooling that integrates with Svelte. - -
-
-
- - - -The `kit` property configures SvelteKit, and can have the following properties: - -## adapter - -
- -- default `undefined` - -
- -Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. - -
- - - -
- -## alias - -
- -- default `{}` - -
- -An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. - -```js -// @errors: 7031 -/// file: svelte.config.js -/** @type {import('@sveltejs/kit').Config} */ -const config = { - kit: { - alias: { - // this will match a file - 'my-file': 'path/to/my-file.js', - - // this will match a directory and its contents - // (`my-directory/x` resolves to `path/to/my-directory/x`) - 'my-directory': 'path/to/my-directory', - - // an alias ending /* will only match - // the contents of a directory, not the directory itself - 'my-directory/*': 'path/to/my-directory/*' - } - } -}; -``` - -> The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. - -> You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. - -
- - - -
- -## appDir - -
- -- default `"_app"` - -
- -The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes. - -If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`. - -
- - - -
- -## 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... - -```js -// @errors: 7031 -/// file: svelte.config.js -/** @type {import('@sveltejs/kit').Config} */ -const config = { - kit: { - csp: { - directives: { - 'script-src': ['self'] - }, - reportOnly: { - 'script-src': ['self'] - } - } - } -}; - -export default config; -``` - -...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. - -To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` -``` - -If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](/docs/kit/reference/$app-stores#updated) store to `true` when it detects one. - -
- -
- -```ts -// @noErrors -name?: string; -``` - -
- -The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. - -For example, to use the current commit hash, you could do use `git rev-parse HEAD`: - -```js -// @errors: 7031 -/// file: svelte.config.js -import * as child_process from 'node:child_process'; - -export default { - kit: { - version: { - name: child_process.execSync('git rev-parse HEAD').toString().trim() - } - } -}; -``` - -
-
-
- -```ts -// @noErrors -pollInterval?: number; -``` - -
- -
- -- default `0` - -
- -The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. - -
-
- -
\ No newline at end of file diff --git a/apps/svelte.dev/content/docs/kit/50-reference/20-cli.md b/apps/svelte.dev/content/docs/kit/50-reference/20-cli.md deleted file mode 100644 index d365c446f1..0000000000 --- a/apps/svelte.dev/content/docs/kit/50-reference/20-cli.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Command Line Interface ---- - -SvelteKit projects use [Vite](https://vitejs.dev), meaning you'll mostly use its CLI (albeit via `npm run dev/build/preview` scripts): - -- `vite dev` — start a development server -- `vite build` — build a production version of your app -- `vite preview` — run the production version locally - -However SvelteKit includes its own CLI for initialising your project: - -## svelte-kit sync - -`svelte-kit sync` creates the `tsconfig.json` and all generated types (which you can import as `./$types` inside routing files) for your project. When you create a new project, it is listed as the `prepare` script and will be run automatically as part of the npm lifecycle, so you should not ordinarily have to run this command. diff --git a/apps/svelte.dev/content/docs/kit/50-reference/30-modules.md b/apps/svelte.dev/content/docs/kit/50-reference/30-modules.md deleted file mode 100644 index 12bd86defe..0000000000 --- a/apps/svelte.dev/content/docs/kit/50-reference/30-modules.md +++ /dev/null @@ -1,1186 +0,0 @@ ---- -title: Modules ---- - -SvelteKit makes a number of modules available to your application. - -## $app/environment - - - -```js -// @noErrors -import { browser, building, dev, version } from '$app/environment'; -``` - - - - - -### browser - -`true` if the app is running in the browser. - -
- -```ts -// @noErrors -const browser: boolean; -``` - -
- -### building - -SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. - -
- -```ts -// @noErrors -const building: boolean; -``` - -
- -### dev - -Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. - -
- -```ts -// @noErrors -const dev: boolean; -``` - -
- -### version - -The value of `config.kit.version.name`. - -
- -```ts -// @noErrors -const version: string; -``` - -
- -## $app/forms - - - -```js -// @noErrors -import { applyAction, deserialize, enhance } from '$app/forms'; -``` - - - - - -### applyAction - -This action updates the `form` property of the current page with the given data and updates `$page.status`. -In case of an error, it redirects to the nearest error page. - -
- -```ts -// @noErrors -function applyAction< - Success extends Record | undefined, - Failure extends Record | undefined ->( - result: import('@sveltejs/kit').ActionResult< - Success, - Failure - > -): Promise; -``` - -
- -### deserialize - -Use this function to deserialize the response from a form submission. -Usage: - -```js -// @errors: 7031 -import { deserialize } from '$app/forms'; - -async function handleSubmit(event) { - const response = await fetch('/form?/action', { - method: 'POST', - body: new FormData(event.target) - }); - - const result = deserialize(await response.text()); - // ... -} -``` - -
- -```ts -// @noErrors -function deserialize< - Success extends Record | undefined, - Failure extends Record | undefined ->( - result: string -): import('@sveltejs/kit').ActionResult; -``` - -
- -### enhance - -This action enhances a `` element that otherwise would work without JavaScript. - -The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. -If `cancel` is called, the form will not be submitted. -You can use the abort `controller` to cancel the submission in case another one starts. -If a function is returned, that function is called with the response from the server. -If nothing is returned, the fallback will be used. - -If this function or its return value isn't set, it -- falls back to updating the `form` prop with the returned data if the action is on the same page as the form -- updates `$page.status` -- resets the `` element and invalidates all data in case of successful submission with no redirect response -- redirects in case of a redirect response -- redirects to the nearest error page in case of an unexpected error - -If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. - -
- -```ts -// @noErrors -function enhance< - Success extends Record | undefined, - Failure extends Record | undefined ->( - form_element: HTMLFormElement, - submit?: import('@sveltejs/kit').SubmitFunction< - Success, - Failure - > -): { - destroy(): void; -}; -``` - -
- -## $app/navigation - - - -```js -// @noErrors -import { - afterNavigate, - beforeNavigate, - disableScrollHandling, - goto, - invalidate, - invalidateAll, - onNavigate, - preloadCode, - preloadData, - pushState, - replaceState -} from '$app/navigation'; -``` - - - - - -### afterNavigate - -A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. - -`afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. - -
- -```ts -// @noErrors -function afterNavigate( - callback: ( - navigation: import('@sveltejs/kit').AfterNavigate - ) => void -): void; -``` - -
- -### beforeNavigate - -A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. - -Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. - -When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`. - -If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`. - -`beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. - -
- -```ts -// @noErrors -function beforeNavigate( - callback: ( - navigation: import('@sveltejs/kit').BeforeNavigate - ) => void -): void; -``` - -
- -### disableScrollHandling - -If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. -This is generally discouraged, since it breaks user expectations. - -
- -```ts -// @noErrors -function disableScrollHandling(): void; -``` - -
- -### goto - -Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. -For external URLs, use `window.location = url` instead of calling `goto(url)`. - -
- -```ts -// @noErrors -function goto( - url: string | URL, - opts?: - | { - replaceState?: boolean | undefined; - noScroll?: boolean | undefined; - keepFocus?: boolean | undefined; - invalidateAll?: boolean | undefined; - state?: App.PageState | undefined; - } - | undefined -): Promise; -``` - -
- -### invalidate - -Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. - -If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). -To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. - -The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. -This can be useful if you want to invalidate based on a pattern instead of a exact match. - -```ts -// Example: Match '/path' regardless of the query parameters -import { invalidate } from '$app/navigation'; - -invalidate((url) => url.pathname === '/path'); -``` - -
- -```ts -// @noErrors -function invalidate( - resource: string | URL | ((url: URL) => boolean) -): Promise; -``` - -
- -### invalidateAll - -Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. - -
- -```ts -// @noErrors -function invalidateAll(): Promise; -``` - -
- -### onNavigate - -A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations. - -If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. - -If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated. - -`onNavigate` must be called during a component initialization. It remains active as long as the component is mounted. - -
- -```ts -// @noErrors -function onNavigate( - callback: ( - navigation: import('@sveltejs/kit').OnNavigate - ) => MaybePromise<(() => void) | void> -): void; -``` - -
- -### preloadCode - -Programmatically imports the code for routes that haven't yet been fetched. -Typically, you might call this to speed up subsequent navigation. - -You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). - -Unlike `preloadData`, this won't call `load` functions. -Returns a Promise that resolves when the modules have been imported. - -
- -```ts -// @noErrors -function preloadCode(pathname: string): Promise; -``` - -
- -### preloadData - -Programmatically preloads the given page, which means - 1. ensuring that the code for the page is loaded, and - 2. calling the page's load function with the appropriate options. - -This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. -If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. -Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete. - -
- -```ts -// @noErrors -function preloadData(href: string): Promise< - | { - type: 'loaded'; - status: number; - data: Record; - } - | { - type: 'redirect'; - location: string; - } ->; -``` - -
- -### pushState - -Programmatically create a new history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). - -
- -```ts -// @noErrors -function pushState( - url: string | URL, - state: App.PageState -): void; -``` - -
- -### replaceState - -Programmatically replace the current history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing). - -
- -```ts -// @noErrors -function replaceState( - url: string | URL, - state: App.PageState -): void; -``` - -
- -## $app/paths - - - -```js -// @noErrors -import { assets, base, resolveRoute } from '$app/paths'; -``` - - - - - -### assets - -An absolute path that matches [`config.kit.paths.assets`](/docs/kit/reference/configuration#paths). - -> If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. - -
- -```ts -// @noErrors -let assets: - | '' - | `https://${string}` - | `http://${string}` - | '/_svelte_kit_assets'; -``` - -
- -### base - -A string that matches [`config.kit.paths.base`](/docs/kit/reference/configuration#paths). - -Example usage: `
Link` - -
- -```ts -// @noErrors -let base: '' | `/${string}`; -``` - -
- -### resolveRoute - -Populate a route ID with params to resolve a pathname. - -
- -```ts -// @noErrors -function resolveRoute( - id: string, - params: Record -): string; -``` - -
- -## $app/server - - - -```js -// @noErrors -import { read } from '$app/server'; -``` - - - - - -### read - -Read the contents of an imported asset from the filesystem - -
- -```ts -// @noErrors -function read(asset: string): Response; -``` - -
- -## $app/stores - - - -```js -// @noErrors -import { getStores, navigating, page, updated } from '$app/stores'; -``` - - - - - -### getStores - - - -
- -```ts -// @noErrors -function getStores(): { - page: typeof page; - - navigating: typeof navigating; - - updated: typeof updated; -}; -``` - -
- -### navigating - -A readable store. -When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. -When navigating finishes, its value reverts to `null`. - -On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. - -
- -```ts -// @noErrors -const navigating: import('svelte/store').Readable< - import('@sveltejs/kit').Navigation | null ->; -``` - -
- -### page - -A readable store whose value contains page data. - -On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. - -
- -```ts -// @noErrors -const page: import('svelte/store').Readable< - import('@sveltejs/kit').Page ->; -``` - -
- -### updated - -A readable store whose initial value is `false`. If [`version.pollInterval`](/docs/kit/reference/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. - -On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. - -
- -```ts -// @noErrors -const updated: import('svelte/store').Readable & { - check(): Promise; -}; -``` - -
- -## $env/dynamic/private - - - -This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](/docs/kit/reference/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/reference/configuration#env) (if configured). - -This module cannot be imported into client-side code. - -Dynamic environment variables cannot be used during prerendering. - -```ts -import { env } from '$env/dynamic/private'; -console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); -``` - -> In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. - - - - -## $env/dynamic/public - - - -Similar to [`$env/dynamic/private`](/docs/kit/reference/$env-all#$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. - -Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead. - -Dynamic environment variables cannot be used during prerendering. - -```ts -import { env } from '$env/dynamic/public'; -console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); -``` - - - - -## $env/static/private - - - -Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](/docs/kit/reference/$env-all#$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/reference/configuration#env) (if configured). - -_Unlike_ [`$env/dynamic/private`](/docs/kit/reference/$env-all#$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination. - -```ts -import { API_KEY } from '$env/static/private'; -``` - -Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: - -``` -MY_FEATURE_FLAG="" -``` - -You can override `.env` values from the command line like so: - -```bash -MY_FEATURE_FLAG="enabled" npm run dev -``` - - - - -## $env/static/public - - - -Similar to [`$env/static/private`](/docs/kit/reference/$env-all#$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/reference/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. - -Values are replaced statically at build time. - -```ts -import { PUBLIC_BASE_URL } from '$env/static/public'; -``` - - - - -## $lib - - - -This is a simple alias to `src/lib`, or whatever directory is specified as [`config.kit.files.lib`](/docs/kit/reference/configuration#files). It allows you to access common components and utility modules without `../../../../` nonsense. - -### `$lib/server` - -A subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](/docs/server-only-modules). - - - - -## $service-worker - - - -```js -// @noErrors -import { base, build, files, prerendered, version } from '$service-worker'; -``` - - - -This module is only available to [service workers](/docs/service-workers). - -### base - -The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. -Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. - -
- -```ts -// @noErrors -const base: string; -``` - -
- -### build - -An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. -During development, this is an empty array. - -
- -```ts -// @noErrors -const build: string[]; -``` - -
- -### files - -An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](/docs/kit/reference/configuration) - -
- -```ts -// @noErrors -const files: string[]; -``` - -
- -### prerendered - -An array of pathnames corresponding to prerendered pages and endpoints. -During development, this is an empty array. - -
- -```ts -// @noErrors -const prerendered: string[]; -``` - -
- -### version - -See [`config.kit.version`](/docs/kit/reference/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. - -
- -```ts -// @noErrors -const version: string; -``` - -
- -## @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; -``` - -
- -## @sveltejs/kit/hooks - - - -```js -// @noErrors -import { sequence } from '@sveltejs/kit/hooks'; -``` - - - - - -### sequence - -A helper function for sequencing multiple `handle` calls in a middleware-like manner. -The behavior for the `handle` options is as follows: -- `transformPageChunk` is applied in reverse order and merged -- `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called -- `filterSerializedResponseHeaders` behaves the same as `preload` - -```js -// @errors: 7031 -/// file: src/hooks.server.js -import { sequence } from '@sveltejs/kit/hooks'; - -/** @type {import('@sveltejs/kit').Handle} */ -async function first({ event, resolve }) { - console.log('first pre-processing'); - const result = await resolve(event, { - transformPageChunk: ({ html }) => { - // transforms are applied in reverse order - console.log('first transform'); - return html; - }, - preload: () => { - // this one wins as it's the first defined in the chain - console.log('first preload'); - } - }); - console.log('first post-processing'); - return result; -} - -/** @type {import('@sveltejs/kit').Handle} */ -async function second({ event, resolve }) { - console.log('second pre-processing'); - const result = await resolve(event, { - transformPageChunk: ({ html }) => { - console.log('second transform'); - return html; - }, - preload: () => { - console.log('second preload'); - }, - filterSerializedResponseHeaders: () => { - // this one wins as it's the first defined in the chain - console.log('second filterSerializedResponseHeaders'); - } - }); - console.log('second post-processing'); - return result; -} - -export const handle = sequence(first, second); -``` - -The example above would print: - -``` -first pre-processing -first preload -second pre-processing -second filterSerializedResponseHeaders -second transform -first transform -second post-processing -first post-processing -``` - -
- -```ts -// @noErrors -function sequence( - ...handlers: import('@sveltejs/kit').Handle[] -): import('@sveltejs/kit').Handle; -``` - -
- -## @sveltejs/kit/node - - - -```js -// @noErrors -import { - createReadableStream, - getRequest, - setResponse -} from '@sveltejs/kit/node'; -``` - - - - - -### createReadableStream - -Converts a file on disk to a readable stream - -
- -```ts -// @noErrors -function createReadableStream(file: string): ReadableStream; -``` - -
- -### getRequest - - - -
- -```ts -// @noErrors -function getRequest({ - request, - base, - bodySizeLimit -}: { - request: import('http').IncomingMessage; - base: string; - bodySizeLimit?: number; -}): Promise; -``` - -
- -### setResponse - - - -
- -```ts -// @noErrors -function setResponse( - res: import('http').ServerResponse, - response: Response -): Promise; -``` - -
- -## @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; -``` - -
- -## @sveltejs/kit/vite - - - -```js -// @noErrors -import { sveltekit } from '@sveltejs/kit/vite'; -``` - - - - - -### sveltekit - -Returns the SvelteKit Vite plugins. - -
- -```ts -// @noErrors -function sveltekit(): Promise; -``` - -
- - - - diff --git a/apps/svelte.dev/content/docs/kit/50-reference/40-types.md b/apps/svelte.dev/content/docs/kit/50-reference/40-types.md deleted file mode 100644 index 65f37d2521..0000000000 --- a/apps/svelte.dev/content/docs/kit/50-reference/40-types.md +++ /dev/null @@ -1,3468 +0,0 @@ ---- -title: Types ---- - -## Public types - -The following types can be imported from `@sveltejs/kit`: - -## 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'; -``` - - -
- - - -## Generated types - -The `RequestHandler` and `Load` types both accept a `Params` argument allowing you to type the `params` object. For example this endpoint expects `foo`, `bar` and `baz` params: - -```js -/// file: src/routes/[foo]/[bar]/[baz]/+page.server.js -// @errors: 2355 2322 1360 -/** @type {import('@sveltejs/kit').RequestHandler<{ - foo: string; - bar: string; - baz: string - }>} */ -export async function GET({ params }) { - // ... -} -``` - -Needless to say, this is cumbersome to write out, and less portable (if you were to rename the `[foo]` directory to `[qux]`, the type would no longer reflect reality). - -To solve this problem, SvelteKit generates `.d.ts` files for each of your endpoints and pages: - -```ts -/// file: .svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts -/// link: false -import type * as Kit from '@sveltejs/kit'; - -type RouteParams = { - foo: string; - bar: string; - baz: string; -} - -export type PageServerLoad = Kit.ServerLoad; -export type PageLoad = Kit.Load; -``` - -These files can be imported into your endpoints and pages as siblings, thanks to the [`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs) option in your TypeScript configuration: - -```js -/// file: src/routes/[foo]/[bar]/[baz]/+page.server.js -// @filename: $types.d.ts -import type * as Kit from '@sveltejs/kit'; - -type RouteParams = { - foo: string; - bar: string; - baz: string; -} - -export type PageServerLoad = Kit.ServerLoad; - -// @filename: index.js -// @errors: 2355 -// ---cut--- -/** @type {import('./$types').PageServerLoad} */ -export async function GET({ params }) { - // ... -} -``` - -```js -/// file: src/routes/[foo]/[bar]/[baz]/+page.js -// @filename: $types.d.ts -import type * as Kit from '@sveltejs/kit'; - -type RouteParams = { - foo: string; - bar: string; - baz: string; -} - -export type PageLoad = Kit.Load; - -// @filename: index.js -// @errors: 2355 -// ---cut--- -/** @type {import('./$types').PageLoad} */ -export async function load({ params, fetch }) { - // ... -} -``` - -> For this to work, your own `tsconfig.json` or `jsconfig.json` should extend from the generated `.svelte-kit/tsconfig.json` (where `.svelte-kit` is your [`outDir`](configuration#outdir)) and TypeScript should be installed as a dependency: -> -> `{ "extends": "./.svelte-kit/tsconfig.json" }` - -### Default tsconfig.json - -The generated `.svelte-kit/tsconfig.json` file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason: - -```json -/// file: .svelte-kit/tsconfig.json -{ - "compilerOptions": { - "baseUrl": "..", - "paths": { - "$lib": "src/lib", - "$lib/*": "src/lib/*" - }, - "rootDirs": ["..", "./types"] - }, - "include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"], - "exclude": ["../node_modules/**", "./**"] -} -``` - -Others are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing: - -```json -/// file: .svelte-kit/tsconfig.json -{ - "compilerOptions": { - // this ensures that types are explicitly - // imported with `import type`, which is - // necessary as svelte-preprocess cannot - // otherwise compile components correctly - "importsNotUsedAsValues": "error", - - // Vite compiles one TypeScript module - // at a time, rather than compiling - // the entire module graph - "isolatedModules": true, - - // TypeScript cannot 'see' when you - // use an imported value in your - // markup, so we need this - "preserveValueImports": true, - - // This ensures both `vite build` - // and `svelte-package` work correctly - "lib": ["esnext", "DOM", "DOM.Iterable"], - "moduleResolution": "node", - "module": "esnext", - "target": "esnext" - } -} -``` - -## App - -## Error - -Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. - -
- -```dts -interface Error {/*…*/} -``` - -
- -```dts -message: string; -``` - -
-
-
- -## Locals - -The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. - -
- -```dts -interface Locals {} -``` - - -
- -## PageData - -Defines the common shape of the [$page.data store](/docs/kit/reference/$app-stores#page) - that is, the data that is shared between all pages. -The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. -Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). - -
- -```dts -interface PageData {} -``` - - -
- -## PageState - -The shape of the `$page.state` object, 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 -interface PageState {} -``` - - -
- -## Platform - -If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. - -
- -```dts -interface Platform {} -``` - - -
- - diff --git a/apps/svelte.dev/content/docs/kit/50-reference/index.md b/apps/svelte.dev/content/docs/kit/50-reference/index.md deleted file mode 100644 index b98302768e..0000000000 --- a/apps/svelte.dev/content/docs/kit/50-reference/index.md +++ /dev/null @@ -1,3 +0,0 @@ ---- -title: Reference ---- From b075e5d58dced1be3388f35ef2ab28957b3c5a36 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 25 Sep 2024 18:33:32 -0400 Subject: [PATCH 4/4] gitignore --- apps/svelte.dev/.gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/svelte.dev/.gitignore b/apps/svelte.dev/.gitignore index 4763018f77..d5d05236ed 100644 --- a/apps/svelte.dev/.gitignore +++ b/apps/svelte.dev/.gitignore @@ -9,4 +9,7 @@ /static/svelte-app.json # git-repositories of synced docs go here -/repos/ \ No newline at end of file +/repos/ + +# TODO remove this after https://github.com/sveltejs/kit/pull/12718 is merged +/content/docs/kit/50-reference