From 2fdff69331b34e3ea3cd648acfbbbe3dd27bd3dd Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 19 May 2023 13:19:53 -0400 Subject: [PATCH 01/42] use dts-buddy --- packages/kit/package.json | 3 +- packages/kit/scripts/generate-dts.js | 18 + packages/kit/src/exports/hooks/sequence.js | 78 +- packages/kit/src/exports/index.js | 48 +- packages/kit/src/exports/node/polyfills.js | 8 + .../index.d.ts => src/exports/public.d.ts} | 94 +- packages/kit/src/exports/vite/index.js | 5 +- packages/kit/src/runtime/app/environment.js | 15 +- packages/kit/src/runtime/app/forms.js | 57 +- packages/kit/src/runtime/app/navigation.js | 81 + packages/kit/src/runtime/app/paths.js | 18 +- packages/kit/src/runtime/app/stores.js | 31 +- packages/kit/src/runtime/server/ambient.d.ts | 6 +- packages/kit/src/runtime/server/cookie.js | 4 +- packages/kit/test-types/index.d.ts | 2215 +++++++++++++++++ packages/kit/tsconfig.json | 2 +- packages/kit/types/ambient-private.d.ts | 11 + packages/kit/types/ambient.d.ts | 411 --- packages/kit/types/internal.d.ts | 14 +- packages/kit/types/private.d.ts | 4 +- pnpm-lock.yaml | 3 + 21 files changed, 2596 insertions(+), 530 deletions(-) create mode 100644 packages/kit/scripts/generate-dts.js rename packages/kit/{types/index.d.ts => src/exports/public.d.ts} (94%) create mode 100644 packages/kit/test-types/index.d.ts create mode 100644 packages/kit/types/ambient-private.d.ts diff --git a/packages/kit/package.json b/packages/kit/package.json index a3ff7b4d19d3..3f685b653afd 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -15,6 +15,7 @@ "@types/cookie": "^0.5.1", "cookie": "^0.5.0", "devalue": "^4.3.1", + "dts-buddy": "*", "esm-env": "^1.0.0", "kleur": "^4.1.5", "magic-string": "^0.30.0", @@ -92,4 +93,4 @@ "engines": { "node": "^16.14 || >=18" } -} +} \ No newline at end of file diff --git a/packages/kit/scripts/generate-dts.js b/packages/kit/scripts/generate-dts.js new file mode 100644 index 000000000000..4834623f8a90 --- /dev/null +++ b/packages/kit/scripts/generate-dts.js @@ -0,0 +1,18 @@ +import { createModuleDeclarations } from 'dts-buddy'; + +createModuleDeclarations({ + output: 'test-types/index.d.ts', + modules: { + '@sveltejs/kit': 'src/exports/public.d.ts', + '@sveltejs/kit/hooks': 'src/exports/hooks/index.js', + '@sveltejs/kit/node': 'src/exports/node/index.js', + '@sveltejs/kit/node/polyfills': 'src/exports/node/polyfills.js', + '@sveltejs/kit/vite': 'src/exports/vite/index.js', + '$app/environment': 'src/runtime/app/environment.js', + '$app/forms': 'src/runtime/app/forms.js', + '$app/navigation': 'src/runtime/app/navigation.js', + '$app/paths': 'src/runtime/app/paths.js', + '$app/stores': 'src/runtime/app/stores.js' + }, + include: ['src'] +}); diff --git a/packages/kit/src/exports/hooks/sequence.js b/packages/kit/src/exports/hooks/sequence.js index 267224c11a2d..3a6995f14b8e 100644 --- a/packages/kit/src/exports/hooks/sequence.js +++ b/packages/kit/src/exports/hooks/sequence.js @@ -1,6 +1,70 @@ /** - * @param {...import('types').Handle} handlers - * @returns {import('types').Handle} + * 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 + * /// 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 + * ``` + * + * @param {...import('@sveltejs/kit').Handle} handlers The chain of `handle` functions + * @returns {import('@sveltejs/kit').Handle} */ export function sequence(...handlers) { const length = handlers.length; @@ -11,8 +75,8 @@ export function sequence(...handlers) { /** * @param {number} i - * @param {import('types').RequestEvent} event - * @param {import('types').ResolveOptions | undefined} parent_options + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions | undefined} parent_options * @returns {import('types').MaybePromise} */ function apply_handle(i, event, parent_options) { @@ -21,7 +85,7 @@ export function sequence(...handlers) { return handle({ event, resolve: (event, options) => { - /** @type {import('types').ResolveOptions['transformPageChunk']} */ + /** @type {import('@sveltejs/kit').ResolveOptions['transformPageChunk']} */ const transformPageChunk = async ({ html, done }) => { if (options?.transformPageChunk) { html = (await options.transformPageChunk({ html, done })) ?? ''; @@ -34,12 +98,12 @@ export function sequence(...handlers) { return html; }; - /** @type {import('types').ResolveOptions['filterSerializedResponseHeaders']} */ + /** @type {import('@sveltejs/kit').ResolveOptions['filterSerializedResponseHeaders']} */ const filterSerializedResponseHeaders = parent_options?.filterSerializedResponseHeaders ?? options?.filterSerializedResponseHeaders; - /** @type {import('types').ResolveOptions['preload']} */ + /** @type {import('@sveltejs/kit').ResolveOptions['preload']} */ const preload = parent_options?.preload ?? options?.preload; return i < length - 1 diff --git a/packages/kit/src/exports/index.js b/packages/kit/src/exports/index.js index 3050bdb91d30..36e4102aad23 100644 --- a/packages/kit/src/exports/index.js +++ b/packages/kit/src/exports/index.js @@ -2,12 +2,27 @@ import { HttpError, Redirect, ActionFailure } from '../runtime/control.js'; import { BROWSER, DEV } from 'esm-env'; import { get_route_segments } from '../utils/routing.js'; -// For some reason we need to type the params as well here, -// JSdoc doesn't seem to like @type with function overloads /** - * @type {import('@sveltejs/kit').error} + * @overload * @param {number} status - * @param {any} message + * @param {App.Error} body + * @return {HttpError} + */ + +/** + * @overload + * @param {number} status + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} [body] + * @return {HttpError} + */ + +/** + * Creates an `HttpError` object with an HTTP status code and an optional message. + * This object, if thrown during request handling, 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. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} message An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. */ export function error(status, message) { if ((!BROWSER || DEV) && (isNaN(status) || status < 400 || status > 599)) { @@ -17,7 +32,12 @@ export function error(status, message) { return new HttpError(status, message); } -/** @type {import('@sveltejs/kit').redirect} */ +/** + * Create a `Redirect` object. If thrown 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. + * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. + * @param {string} location The location to redirect to. + */ export function redirect(status, location) { if ((!BROWSER || DEV) && (isNaN(status) || status < 300 || status > 308)) { throw new Error('Invalid status code'); @@ -26,7 +46,11 @@ export function redirect(status, location) { return new Redirect(status, location); } -/** @type {import('@sveltejs/kit').json} */ +/** + * Create a JSON `Response` object from the supplied data. + * @param {any} data The value that will be serialized as JSON. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. + */ export function json(data, init) { // TODO deprecate this in favour of `Response.json` when it's // more widely supported @@ -52,7 +76,11 @@ export function json(data, init) { const encoder = new TextEncoder(); -/** @type {import('@sveltejs/kit').text} */ +/** + * Create a `Response` object from the supplied body. + * @param {string} body The value that will be used as-is. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. + */ export function text(body, init) { const headers = new Headers(init?.headers); if (!headers.has('content-length')) { @@ -66,9 +94,9 @@ export function text(body, init) { } /** - * Generates an `ActionFailure` object. - * @param {number} status - * @param {Record | undefined} [data] + * Create an `ActionFailure` object. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {Record | undefined} [data] Data associated with the failure (e.g. validation errors) */ export function fail(status, data) { return new ActionFailure(status, data); diff --git a/packages/kit/src/exports/node/polyfills.js b/packages/kit/src/exports/node/polyfills.js index 950c645258bc..d1bb58d72b74 100644 --- a/packages/kit/src/exports/node/polyfills.js +++ b/packages/kit/src/exports/node/polyfills.js @@ -22,6 +22,14 @@ const globals = { // exported for dev/preview and node environments // TODO: remove this once we only support Node 18.11+ (the version multipart/form-data was added) +/** + * Make various web APIs available as globals: + * - `crypto` + * - `fetch` + * - `Headers` + * - `Request` + * - `Response` + */ export function installPolyfills() { for (const name in globals) { Object.defineProperty(globalThis, name, { diff --git a/packages/kit/types/index.d.ts b/packages/kit/src/exports/public.d.ts similarity index 94% rename from packages/kit/types/index.d.ts rename to packages/kit/src/exports/public.d.ts index 7ef60082de58..084399f76d60 100644 --- a/packages/kit/types/index.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -1,7 +1,7 @@ /// /// -import './ambient.js'; +import '../../types/ambient.js'; import { CompileOptions } from 'svelte/types/compiler/interfaces'; import { @@ -18,11 +18,11 @@ import { RequestOptions, RouteSegment, UniqueInterface -} from './private.js'; -import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from './internal.js'; +} from '../../types/private.js'; +import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from '../../types/internal.js'; import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; -export { PrerenderOption } from './private.js'; +export { PrerenderOption } from '../../types/private.js'; /** * [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. @@ -1196,21 +1196,6 @@ export type ActionResult< | { type: 'redirect'; status: number; location: string } | { type: 'error'; status?: number; error: any }; -/** - * Creates an `HttpError` object with an HTTP status code and an optional message. - * This object, if thrown during request handling, 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. - * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. - * @param body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. - */ -export function error(status: number, body: App.Error): HttpError; -export function error( - status: number, - // this overload ensures you can omit the argument or pass in a string if App.Error is of type { message: string } - body?: { message: string } extends App.Error ? App.Error | string | undefined : never -): HttpError; - /** * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. */ @@ -1221,17 +1206,6 @@ export interface HttpError { body: App.Error; } -/** - * Create a `Redirect` object. If thrown 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. - * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. - * @param location The location to redirect to. - */ -export function redirect( - status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, - location: string -): Redirect; - /** * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function */ @@ -1242,30 +1216,6 @@ export interface Redirect { location: string; } -/** - * Create a JSON `Response` object from the supplied data. - * @param data The value that will be serialized as JSON. - * @param init Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. - */ -export function json(data: any, init?: ResponseInit): Response; - -/** - * Create a `Response` object from the supplied body. - * @param body The value that will be used as-is. - * @param init Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. - */ -export function text(body: string, init?: ResponseInit): Response; - -/** - * Create an `ActionFailure` object. - * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. - * @param data Data associated with the failure (e.g. validation errors) - */ -export function fail | undefined = undefined>( - status: number, - data?: T -): ActionFailure; - /** * The object returned by the [`fail`](https://kit.svelte.dev/docs/modules#sveltejs-kit-fail) function */ @@ -1283,15 +1233,36 @@ export interface SubmitFunction< > { (input: { action: URL; + /** + * use `formData` instead of `data` + * @deprecated + */ data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ form: HTMLFormElement; + formElement: HTMLFormElement; controller: AbortController; submitter: HTMLElement | null; cancel(): void; }): MaybePromise< | void | ((opts: { + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ form: HTMLFormElement; + formElement: HTMLFormElement; action: URL; result: ActionResult; /** @@ -1311,17 +1282,4 @@ export interface Snapshot { restore: (snapshot: T) => void; } -/** - * Populate a route ID with params to resolve a pathname. - * @example - * ```js - * resolvePath( - * `/blog/[slug]/[...somethingElse]`, - * { - * slug: 'hello-world', - * somethingElse: 'something/else' - * } - * ); // `/blog/hello-world/something/else` - * ``` - */ -export function resolvePath(id: string, params: Record): string; +export * from './index.js'; diff --git a/packages/kit/src/exports/vite/index.js b/packages/kit/src/exports/vite/index.js index 12cf0601fe1e..0140a738239f 100644 --- a/packages/kit/src/exports/vite/index.js +++ b/packages/kit/src/exports/vite/index.js @@ -111,7 +111,10 @@ const warning_preprocessor = { } }; -/** @return {Promise} */ +/** + * Returns the SvelteKit Vite plugins. + * @returns {Promise} + */ export async function sveltekit() { const svelte_config = await load_config(); diff --git a/packages/kit/src/runtime/app/environment.js b/packages/kit/src/runtime/app/environment.js index 0d11daf31b1b..ca378d3553b2 100644 --- a/packages/kit/src/runtime/app/environment.js +++ b/packages/kit/src/runtime/app/environment.js @@ -1,13 +1,24 @@ import { BROWSER, DEV } from 'esm-env'; /** - * @type {import('$app/environment').browser} + * `true` if the app is running in the browser. */ export const browser = BROWSER; /** - * @type {import('$app/environment').dev} + * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. */ export const dev = DEV; export { building, version } from '__sveltekit/environment'; + +// TODO this will need to be declared ambiently somewhere +// /** +// * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. +// */ +// export const building: boolean; + +// /** +// * The value of `config.kit.version.name`. +// */ +// export const version: string; diff --git a/packages/kit/src/runtime/app/forms.js b/packages/kit/src/runtime/app/forms.js index 30858235032f..5be0e7b30cc3 100644 --- a/packages/kit/src/runtime/app/forms.js +++ b/packages/kit/src/runtime/app/forms.js @@ -3,9 +3,37 @@ import { DEV } from 'esm-env'; import { client_method } from '../client/singletons.js'; import { invalidateAll } from './navigation.js'; +/** + * 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. + * @template {Record | undefined} Success + * @template {Record | undefined} Invalid + * @param {import('@sveltejs/kit').ActionResult} result + */ export const applyAction = client_method('apply_action'); -/** @type {import('$app/forms').deserialize} */ +/** + * Use this function to deserialize the response from a form submission. + * Usage: + * + * ```js + * 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()); + * // ... + * } + * ``` + * @template {Record | undefined} Success + * @template {Record | undefined} Invalid + * @param {string} result + * @returns {import('@sveltejs/kit').ActionResult} + */ export function deserialize(result) { const parsed = JSON.parse(result); if (parsed.data) { @@ -39,7 +67,28 @@ function clone(element) { return /** @type {T} */ (HTMLElement.prototype.cloneNode.call(element)); } -/** @type {import('$app/forms').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 one 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. + * @template {Record | undefined} Success + * @template {Record | undefined} Invalid + * @param {HTMLFormElement} form_element The form element + * @param {import('@sveltejs/kit').SubmitFunction} submit Submit callback + */ export function enhance(form_element, submit = () => {}) { if (DEV && clone(form_element).method !== 'post') { throw new Error('use:enhance can only be used on fields with method="POST"'); @@ -48,7 +97,7 @@ export function enhance(form_element, submit = () => {}) { /** * @param {{ * action: URL; - * result: import('types').ActionResult; + * result: import('@sveltejs/kit').ActionResult; * reset?: boolean * }} opts */ @@ -127,7 +176,7 @@ export function enhance(form_element, submit = () => {}) { })) ?? fallback_callback; if (cancelled) return; - /** @type {import('types').ActionResult} */ + /** @type {import('@sveltejs/kit').ActionResult} */ let result; try { diff --git a/packages/kit/src/runtime/app/navigation.js b/packages/kit/src/runtime/app/navigation.js index 30fa41375531..9daf17412650 100644 --- a/packages/kit/src/runtime/app/navigation.js +++ b/packages/kit/src/runtime/app/navigation.js @@ -1,17 +1,98 @@ import { client_method } from '../client/singletons.js'; +/** + * 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. + * @returns {void} + */ export const disableScrollHandling = /* @__PURE__ */ client_method('disable_scroll_handling'); +/** + * 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)`. + * + * @param {string | URL} url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. + * @param {Object} [opts] Options related to the navigation + * @param {boolean} [opts.replaceState] If `true`, will replace the current `history` entry rather than creating a new one with `pushState` + * @param {boolean} [opts.noScroll] If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation + * @param {boolean} [opts.keepFocus] If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body + * @param {boolean} [invalidateAll] If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation. + * @param {any} [opts.state] The state of the new/updated history entry + * @returns {Promise} + */ export const goto = /* @__PURE__ */ client_method('goto'); +/** + * 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'); + * ``` + * @param {string | URL | ((url: URL) => boolean)} url The invalidated URL + * @returns {Promise} + */ export const invalidate = /* @__PURE__ */ client_method('invalidate'); +/** + * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * @returns {Promise} + */ export const invalidateAll = /* @__PURE__ */ client_method('invalidate_all'); +/** + * 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 when the preload is complete. + * + * @param {string} href Page to preload + * @returns {Promise} + */ export const preloadData = /* @__PURE__ */ client_method('preload_data'); +/** + * 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. + * @param {...string[]} urls + * @returns {Promise} + */ export const preloadCode = /* @__PURE__ */ client_method('preload_code'); +/** + * 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 the navigation would have directly unloaded the current page, calling `cancel` will trigger the native + * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. + * + * When a navigation isn't client side, `navigation.to.route.id` will be `null`. + * + * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @param {(navigation: import('@sveltejs/kit').BeforeNavigate) => void} callback + * @returns {void} + */ export const beforeNavigate = /* @__PURE__ */ client_method('before_navigate'); +/** + * 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. + * @param {(navigation: import('@sveltejs/kit').AfterNavigate) => void} callback + * @returns {void} + */ export const afterNavigate = /* @__PURE__ */ client_method('after_navigate'); diff --git a/packages/kit/src/runtime/app/paths.js b/packages/kit/src/runtime/app/paths.js index 20c6b1c4d716..c0cbe2379508 100644 --- a/packages/kit/src/runtime/app/paths.js +++ b/packages/kit/src/runtime/app/paths.js @@ -1 +1,17 @@ -export { base, assets } from '__sveltekit/paths'; +import * as paths from '__sveltekit/paths'; + +// TODO ensure that the underlying types are `/${string}` (for base) and `https://${string}` | `http://${string}` (for assets) + +/** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ +export const base = paths.base; + +/** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. + */ +export const assets = paths.assets; diff --git a/packages/kit/src/runtime/app/stores.js b/packages/kit/src/runtime/app/stores.js index f93d8e6349de..9cbd9e5bf907 100644 --- a/packages/kit/src/runtime/app/stores.js +++ b/packages/kit/src/runtime/app/stores.js @@ -3,32 +3,48 @@ import { browser } from './environment.js'; import { stores as browser_stores } from '../client/singletons.js'; /** - * @type {import('$app/stores').getStores} + * A function that returns all of the contextual stores. On the server, this must be called during component initialization. + * Only use this if you need to defer store subscription until after the component has mounted, for some reason. */ export const getStores = () => { const stores = browser ? browser_stores : getContext('__svelte__'); return { + /** @type {typeof page} */ page: { subscribe: stores.page.subscribe }, + /** @type {typeof navigating} */ navigating: { subscribe: stores.navigating.subscribe }, + /** @type {typeof updated} */ updated: stores.updated }; }; -/** @type {typeof import('$app/stores').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. + * + * @type {import('svelte/store').Readable} + */ export const page = { - /** @param {(value: any) => void} fn */ subscribe(fn) { const store = __SVELTEKIT_DEV__ ? get_store('page') : getStores().page; return store.subscribe(fn); } }; -/** @type {typeof import('$app/stores').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. + * @type {import('svelte/store').Readable} + */ export const navigating = { subscribe(fn) { const store = __SVELTEKIT_DEV__ ? get_store('navigating') : getStores().navigating; @@ -36,7 +52,12 @@ export const navigating = { } }; -/** @type {typeof import('$app/stores').updated} */ +/** + * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/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. + * @type {import('svelte/store').Readable & { check(): Promise }} + */ export const updated = { subscribe(fn) { const store = __SVELTEKIT_DEV__ ? get_store('updated') : getStores().updated; diff --git a/packages/kit/src/runtime/server/ambient.d.ts b/packages/kit/src/runtime/server/ambient.d.ts index cc7b0f428d47..c893c94ff32b 100644 --- a/packages/kit/src/runtime/server/ambient.d.ts +++ b/packages/kit/src/runtime/server/ambient.d.ts @@ -1,8 +1,8 @@ declare module '__SERVER__/internal.js' { export const options: import('types').SSROptions; export const get_hooks: () => Promise<{ - handle?: import('types').Handle; - handleError?: import('types').HandleServerError; - handleFetch?: import('types').HandleFetch; + handle?: import('@sveltejs/kit').Handle; + handleError?: import('@sveltejs/kit').HandleServerError; + handleFetch?: import('@sveltejs/kit').HandleFetch; }>; } diff --git a/packages/kit/src/runtime/server/cookie.js b/packages/kit/src/runtime/server/cookie.js index 1ca4b5b15b5c..3936c1c47ec7 100644 --- a/packages/kit/src/runtime/server/cookie.js +++ b/packages/kit/src/runtime/server/cookie.js @@ -37,11 +37,11 @@ export function get_cookies(request, url, trailing_slash) { secure: url.hostname === 'localhost' && url.protocol === 'http:' ? false : true }; - /** @type {import('types').Cookies} */ + /** @type {import('@sveltejs/kit').Cookies} */ const cookies = { // The JSDoc param annotations appearing below for get, set and delete // are necessary to expose the `cookie` library types to - // typescript users. `@type {import('types').Cookies}` above is not + // typescript users. `@type {import('@sveltejs/kit').Cookies}` above is not // sufficient to do so. /** diff --git a/packages/kit/test-types/index.d.ts b/packages/kit/test-types/index.d.ts new file mode 100644 index 000000000000..74869fb1997d --- /dev/null +++ b/packages/kit/test-types/index.d.ts @@ -0,0 +1,2215 @@ +declare module '@sveltejs/kit' { + import { CompileOptions } from 'svelte/types/compiler/interfaces'; + import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; + + /** + * [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. + */ + export interface Adapter { + /** + * The name of the adapter, using for logging. Will typically correspond to the package name. + */ + name: string; + /** + * This function is called after SvelteKit has built your app. + * */ + adapt(builder: Builder): MaybePromise; + } + + type AwaitedPropertiesUnion | void> = input extends void + ? undefined // needs to be undefined, because void will break intellisense + : input extends Record + ? { + [key in keyof input]: Awaited; + } + : {} extends input // handles the any case + ? input + : unknown; + + export type AwaitedProperties | void> = + AwaitedPropertiesUnion extends Record + ? OptionalUnion> + : AwaitedPropertiesUnion; + + export type AwaitedActions any>> = OptionalUnion< + { + [Key in keyof T]: UnpackValidationError>>; + }[keyof T] + >; + + // Takes a union type and returns a union type where each type also has all properties + // of all possible types (typed as undefined), making accessing them more ergonomic + type OptionalUnion< + U extends Record, // not unknown, else interfaces don't satisfy this constraint + A extends keyof U = U extends U ? keyof U : never + > = U extends unknown ? { [P in Exclude]?: never } & U : never; + + type UnpackValidationError = T extends ActionFailure + ? X + : T extends void + ? undefined // needs to be undefined, because void will corrupt union type + : T; + + /** + * This object is passed to the `adapt` function of adapters. + * It contains various methods and properties that are useful for adapting the app. + */ + export interface Builder { + /** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */ + log: Logger; + /** Remove `dir` and all its contents. */ + rimraf(dir: string): void; + /** Create `dir` and any required parent directories. */ + mkdirp(dir: string): void; + + /** The fully resolved `svelte.config.js`. */ + config: ValidatedConfig; + /** Information about prerendered pages and assets, if any. */ + prerendered: Prerendered; + /** An array of all routes (including prerendered) */ + routes: RouteDefinition[]; + + /** + * Create separate functions that map to one or more routes of your app. + * */ + createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; + + /** + * Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. + */ + generateFallback(dest: string): Promise; + + /** + * Generate a server-side manifest to initialise the SvelteKit [server](https://kit.svelte.dev/docs/types#public-types-server) with. + * */ + generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; + + /** + * Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. + * */ + getBuildDirectory(name: string): string; + /** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */ + getClientDirectory(): string; + /** Get the fully resolved path to the directory containing server-side code. */ + getServerDirectory(): string; + /** Get the application path including any configured `base` path, e.g. `/my-base-path/_app`. */ + getAppPath(): string; + + /** + * Write client assets to `dest`. + * */ + writeClient(dest: string): string[]; + /** + * Write prerendered files to `dest`. + * */ + writePrerendered(dest: string): string[]; + /** + * Write server-side code to `dest`. + * */ + writeServer(dest: string): string[]; + /** + * Copy a file or directory. + * */ + copy( + from: string, + to: string, + opts?: { + filter?(basename: string): boolean; + replace?: Record; + } + ): string[]; + + /** + * Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. + * */ + compress(directory: string): Promise; + } + + export interface Config { + /** + * Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). + * */ + compilerOptions?: CompileOptions; + /** + * List of file extensions that should be treated as Svelte files. + * */ + extensions?: string[]; + /** SvelteKit options */ + kit?: KitConfig; + /** [`@sveltejs/package`](/docs/packaging) options. */ + package?: { + source?: string; + dir?: string; + emitTypes?: boolean; + exports?(filepath: string): boolean; + files?(filepath: string): boolean; + }; + /** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */ + preprocess?: any; + /** `vite-plugin-svelte` plugin options. */ + vitePlugin?: PluginOptions; + /** Any additional options required by tooling that integrates with Svelte. */ + [key: string]: any; + } + + export interface Cookies { + /** + * Gets a cookie that was previously set with `cookies.set`, or from the request headers. + * */ + get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; + + /** + * Gets all cookies that were previously set with `cookies.set`, or from the request headers. + * */ + getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; + + /** + * 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`. + * + * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * */ + set(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): void; + + /** + * Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. + * + * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * */ + delete(name: string, opts?: import('cookie').CookieSerializeOptions): void; + + /** + * 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`. + * + * By default, the `path` of a cookie is the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * + * */ + serialize(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): string; + } + + export interface KitConfig { + /** + * Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. + * */ + adapter?: Adapter; + /** + * An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. + * + * ```js + * /// 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`. + * */ + alias?: Record; + /** + * The directory relative to `paths.assets` where the built JS and CSS (and imported assets) are served from. (The filenames therein contain content-based hashes, meaning they can be cached indefinitely). Must not start or end with `/`. + * */ + appDir?: string; + /** + * [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 + * /// 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/modules#$app-stores-updated) store to `true` when it detects one. + */ + version?: { + /** + * 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 + * /// 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() + * } + * } + * }; + * ``` + */ + name?: string; + /** + * The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. + * */ + pollInterval?: number; + }; + } + + /** + * 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). + */ + export interface Handle { + (input: { + event: RequestEvent; + resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; + }): MaybePromise; + } + + /** + * 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. + */ + export interface HandleServerError { + (input: { error: unknown; event: RequestEvent }): MaybePromise; + } + + /** + * 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. + */ + export interface HandleClientError { + (input: { error: unknown; event: NavigationEvent }): MaybePromise; + } + + /** + * 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) + */ + export interface HandleFetch { + (input: { event: RequestEvent; request: Request; fetch: typeof fetch }): MaybePromise; + } + + /** + * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `Load` directly. + */ + export interface Load< + Params extends Partial> = Partial>, + InputData extends Record | null = Record | null, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > { + (event: LoadEvent): MaybePromise; + } + + /** + * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `LoadEvent` directly. + */ + export interface LoadEvent< + Params extends Partial> = Partial>, + Data extends Record | null = Record | null, + ParentData extends Record = Record, + RouteId extends string | null = string | null + > extends NavigationEvent { + /** + * `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. 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 + * + * > Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it. + */ + fetch: typeof fetch; + /** + * Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. + */ + data: Data; + /** + * 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 + * /// 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`](https://kit.svelte.dev/docs/types#public-types-cookies) API in a server-only `load` function instead. + * + * `setHeaders` has no effect when a `load` function runs in the browser. + */ + setHeaders(headers: Record): void; + /** + * `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. + */ + parent(): Promise; + /** + * 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/modules#$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 + * /// 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}

+ * + * ``` + */ + depends(...deps: string[]): void; + } + + export interface NavigationEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > { + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * The URL of the current page + */ + url: URL; + } + + /** + * Information about the target of a specific navigation. + */ + export interface NavigationTarget { + /** + * 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). + */ + params: Record | null; + /** + * Info about the target route + */ + route: { id: string | null }; + /** + * The URL that is navigated to + */ + url: URL; + } + + /** + * - `enter`: The app has hydrated + * - `form`: The user submitted a `` + * - `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 + */ + export type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; + + export interface Navigation { + /** + * Where navigation was triggered from + */ + from: NavigationTarget | null; + /** + * Where navigation is going to/has gone to + */ + to: NavigationTarget | null; + /** + * The type of navigation: + * - `form`: The user submitted a `` + * - `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 + */ + type: Omit; + /** + * Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) + */ + willUnload: boolean; + /** + * In case of a history back/forward navigation, the number of steps to go back/forward + */ + delta?: number; + } + + /** + * The argument passed to [`beforeNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate) callbacks. + */ + export interface BeforeNavigate extends Navigation { + /** + * Call this to prevent the navigation from starting. + */ + cancel(): void; + } + + /** + * The argument passed to [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks. + */ + export interface AfterNavigate extends Navigation { + /** + * 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 + */ + type: Omit; + /** + * Since `afterNavigate` is called after a navigation completes, it will never be called with a navigation that unloads the page. + */ + willUnload: false; + } + + /** + * The shape of the `$page` store + */ + export interface Page< + Params extends Record = Record, + RouteId extends string | null = string | null + > { + /** + * The URL of the current page + */ + url: URL; + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * Http status code of the current page + */ + status: number; + /** + * The error object of the current page, if any. Filled from the `handleError` hooks. + */ + error: App.Error | null; + /** + * The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. + */ + data: App.PageData & Record; + /** + * Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. + */ + form: any; + } + + /** + * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. + */ + export interface ParamMatcher { + (param: string): boolean; + } + + export interface RequestEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > { + /** + * Get or set cookies related to the current request + */ + cookies: Cookies; + /** + * `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 + * + * > Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it. + */ + fetch: typeof fetch; + /** + * The client's IP address, set by the adapter. + */ + getClientAddress(): string; + /** + * Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). + */ + locals: App.Locals; + /** + * The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Additional data made available through the adapter. + */ + platform: Readonly | undefined; + /** + * The original request object + */ + request: Request; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * 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 + * /// 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`](https://kit.svelte.dev/docs/types#public-types-cookies) API instead. + */ + setHeaders(headers: Record): void; + /** + * The requested URL. + */ + url: URL; + /** + * `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. + */ + isDataRequest: boolean; + } + + /** + * 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](https://kit.svelte.dev/docs/types#generated-types) instead. + */ + export interface RequestHandler< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > { + (event: RequestEvent): MaybePromise; + } + + export interface ResolveOptions { + /** + * 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. + * */ + transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; + /** + * Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. + * By default, none will be included. + * */ + filterSerializedResponseHeaders?(name: string, value: string): boolean; + /** + * Determines what should be added to the `` tag to preload it. + * By default, `js`, `css` and `font` files will be preloaded. + * */ + preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; + } + + export interface RouteDefinition { + id: string; + api: { + methods: HttpMethod[]; + }; + page: { + methods: Extract[]; + }; + pattern: RegExp; + prerender: PrerenderOption; + segments: RouteSegment[]; + methods: HttpMethod[]; + config: Config; + } + + export class Server { + constructor(manifest: SSRManifest); + init(options: ServerInitOptions): Promise; + respond(request: Request, options: RequestOptions): Promise; + } + + export interface ServerInitOptions { + env: Record; + } + + export interface SSRManifest { + appDir: string; + appPath: string; + assets: Set; + mimeTypes: Record; + + /** private fields */ + _: { + client: NonNullable; + nodes: SSRNodeLoader[]; + routes: SSRRoute[]; + matchers(): Promise>; + }; + } + + /** + * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `ServerLoad` directly. + */ + export interface ServerLoad< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > { + (event: ServerLoadEvent): MaybePromise; + } + + export interface ServerLoadEvent< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + RouteId extends string | null = string | null + > extends RequestEvent { + /** + * `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. + */ + parent(): Promise; + /** + * 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/modules#$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 + * /// 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}

+ * + * ``` + */ + depends(...deps: string[]): void; + } + + /** + * 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. + */ + export interface Action< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > { + (event: RequestEvent): MaybePromise; + } + + /** + * Shape of the `export const actions = {..}` object in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ + export type Actions< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = Record>; + + /** + * When calling a form action via fetch, the response will be one of these shapes. + * ```svelte + * { + * return ({ result }) => { + * // result is of type ActionResult + * }; + * }} + * ``` + */ + export 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 }; + + /** + * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. + */ + export interface HttpError { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ + status: number; + /** The content of the error. */ + body: App.Error; + } + + /** + * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function + */ + export interface Redirect { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */ + status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; + /** The location to redirect to. */ + location: string; + } + + /** + * The object returned by the [`fail`](https://kit.svelte.dev/docs/modules#sveltejs-kit-fail) function + */ + export interface ActionFailure | undefined = undefined> + extends UniqueInterface { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ + status: number; + /** Data associated with the failure (e.g. validation errors) */ + data: T; + } + + export interface SubmitFunction< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record + > { + (input: { + action: URL; + /** + * use `formData` instead of `data` + * */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * */ + form: HTMLFormElement; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; + }): MaybePromise< + | void + | ((opts: { + /** + * use `formData` instead of `data` + * */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * */ + form: HTMLFormElement; + formElement: HTMLFormElement; + action: URL; + result: ActionResult; + /** + * Call this to get the default behavior of a form submission response. + * */ + update(options?: { reset: boolean }): Promise; + }) => void) + >; + } + + /** + * The type of `export const snapshot` exported from a page or layout component. + */ + export interface Snapshot { + capture: () => T; + restore: (snapshot: T) => void; + } + export interface AdapterEntry { + /** + * 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 + */ + id: string; + + /** + * 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 + */ + filter(route: RouteDefinition): boolean; + + /** + * 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. + */ + complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise; + } + + // Based on https://github.com/josh-hemphill/csp-typed-directives/blob/latest/src/csp.types.ts + // + // MIT License + // + // Copyright (c) 2021-present, Joshua Hemphill + // Copyright (c) 2021, Tecnico Corporation + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to deal + // in the Software without restriction, including without limitation the rights + // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + // copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. + + export 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[]; + type UriPath = `${HttpDelineator}${string}`; + } + + export interface CspDirectives { + 'child-src'?: Csp.Sources; + 'default-src'?: Array; + 'frame-src'?: Csp.Sources; + 'worker-src'?: Csp.Sources; + 'connect-src'?: Csp.Sources; + 'font-src'?: Csp.Sources; + 'img-src'?: Csp.Sources; + 'manifest-src'?: Csp.Sources; + 'media-src'?: Csp.Sources; + 'object-src'?: Csp.Sources; + 'prefetch-src'?: Csp.Sources; + 'script-src'?: Array; + 'script-src-elem'?: Csp.Sources; + 'script-src-attr'?: Csp.Sources; + 'style-src'?: Array; + 'style-src-elem'?: Csp.Sources; + 'style-src-attr'?: Csp.Sources; + 'base-uri'?: Array; + 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' + >; + 'form-action'?: Array; + 'frame-ancestors'?: Array; + 'navigate-to'?: Array; + 'report-uri'?: Csp.UriPath[]; + 'report-to'?: string[]; + + 'require-trusted-types-for'?: Array<'script'>; + 'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; + 'upgrade-insecure-requests'?: boolean; + + + 'require-sri-for'?: Array<'script' | 'style' | 'script style'>; + + + 'block-all-mixed-content'?: boolean; + + + 'plugin-types'?: Array<`${string}/${string}` | 'none'>; + + + 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' + >; + } + + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; + + export interface Logger { + (msg: string): void; + success(msg: string): void; + error(msg: string): void; + warn(msg: string): void; + minor(msg: string): void; + info(msg: string): void; + } + + export type MaybePromise = T | Promise; + + export interface Prerendered { + /** + * 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`. + */ + pages: Map< + string, + { + /** The location of the .html file relative to the output directory */ + file: string; + } + >; + /** + * A map of `path` to `{ type }` objects. + */ + assets: Map< + string, + { + /** The MIME type of the asset */ + type: string; + } + >; + /** + * A map of redirects encountered during prerendering. + */ + redirects: Map< + string, + { + status: number; + location: string; + } + >; + /** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */ + paths: string[]; + } + + export interface PrerenderHttpErrorHandler { + (details: { + status: number; + path: string; + referrer: string | null; + referenceType: 'linked' | 'fetched'; + message: string; + }): void; + } + + export interface PrerenderMissingIdHandler { + (details: { path: string; id: string; referrers: string[]; message: string }): void; + } + + export interface PrerenderEntryGeneratorMismatchHandler { + (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; + } + + export type PrerenderHttpErrorHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; + export type PrerenderMissingIdHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; + export type PrerenderEntryGeneratorMismatchHandlerValue = + | 'fail' + | 'warn' + | 'ignore' + | PrerenderEntryGeneratorMismatchHandler; + + export type PrerenderOption = boolean | 'auto'; + + export type PrerenderMap = Map; + + export interface RequestOptions { + getClientAddress(): string; + platform?: App.Platform; + } + + export interface RouteSegment { + content: string; + dynamic: boolean; + rest: boolean; + } + + export type TrailingSlash = 'never' | 'always' | 'ignore'; + + /** + * This doesn't actually exist, it's a way to better distinguish the type + */ + export const uniqueSymbol: unique symbol; + + export interface UniqueInterface { + readonly [uniqueSymbol]: unknown; + } + import { SvelteComponent } from 'svelte/internal'; + + export interface ServerModule { + Server: typeof InternalServer; + } + + export interface ServerInternalModule { + set_building(building: boolean): void; + set_assets(path: string): void; + set_private_env(environment: Record): void; + set_public_env(environment: Record): void; + set_version(version: string): void; + set_fix_stack_trace(fix_stack_trace: (stack: string) => string): void; + } + + export interface Asset { + file: string; + size: number; + type: string | null; + } + + export interface AssetDependencies { + file: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; + } + + export interface BuildData { + app_dir: string; + app_path: string; + manifest_data: ManifestData; + service_worker: string | null; + client: { + start: string; + app: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; + } | null; + server_manifest: import('vite').Manifest; + } + + export interface CSRPageNode { + component: typeof SvelteComponent; + universal: { + load?: Load; + trailingSlash?: TrailingSlash; + }; + } + + export type CSRPageNodeLoader = () => Promise; + + /** + * Definition of a client side route. + * The boolean in the tuples indicates whether the route has a server load. + */ + export type CSRRoute = { + id: string; + exec(path: string): undefined | Record; + errors: Array; + layouts: Array<[has_server_load: boolean, node_loader: CSRPageNodeLoader] | undefined>; + leaf: [has_server_load: boolean, node_loader: CSRPageNodeLoader]; + }; + + export interface Deferred { + fulfil: (value: any) => void; + reject: (error: Error) => void; + } + + export type GetParams = (match: RegExpExecArray) => Record; + + export interface ServerHooks { + handleFetch: HandleFetch; + handle: Handle; + handleError: HandleServerError; + } + + export interface ClientHooks { + handleError: HandleClientError; + } + + export interface Env { + private: Record; + public: Record; + } + + export class InternalServer extends Server { + init(options: ServerInitOptions): Promise; + respond( + request: Request, + options: RequestOptions & { + prerendering?: PrerenderOptions; + read: (file: string) => Buffer; + } + ): Promise; + } + + export interface ManifestData { + assets: Asset[]; + nodes: PageNode[]; + routes: RouteData[]; + matchers: Record; + } + + export interface PageNode { + depth: number; + component?: string; // TODO supply default component if it's missing (bit of an edge case) + universal?: string; + server?: string; + parent_id?: string; + parent?: PageNode; + /** + * Filled with the pages that reference this layout (if this is a layout) + */ + child_pages?: PageNode[]; + } + + export interface PrerenderDependency { + response: Response; + body: null | string | Uint8Array; + } + + export interface PrerenderOptions { + cache?: string; // including this here is a bit of a hack, but it makes it easy to add + fallback?: boolean; + dependencies: Map; + } + + export type RecursiveRequired = { + // Recursive implementation of TypeScript's Required utility type. + // Will recursively continue until it reaches a primitive or Function + [K in keyof T]-?: Extract extends never // If it does not have a Function type + ? RecursiveRequired // recursively continue through. + : T[K]; // Use the exact type for everything else + }; + + export type RequiredResolveOptions = Required; + + export interface RouteParam { + name: string; + matcher: string; + optional: boolean; + rest: boolean; + chained: boolean; + } + + /** + * Represents a route segment in the app. It can either be an intermediate node + * with only layout/error pages, or a leaf, at which point either `page` and `leaf` + * or `endpoint` is set. + */ + export interface RouteData { + id: string; + parent: RouteData | null; + + segment: string; + pattern: RegExp; + params: RouteParam[]; + + layout: PageNode | null; + error: PageNode | null; + leaf: PageNode | null; + + page: { + layouts: Array; + errors: Array; + leaf: number; + } | null; + + endpoint: { + file: string; + } | null; + } + + export type ServerRedirectNode = { + type: 'redirect'; + location: string; + }; + + export type ServerNodesResponse = { + type: 'data'; + /** + * If `null`, then there was no load function <- TODO is this outdated now with the recent changes? + */ + nodes: Array; + }; + + export type ServerDataResponse = ServerRedirectNode | ServerNodesResponse; + + /** + * Signals a successful response of the server `load` function. + * The `uses` property tells the client when it's possible to reuse this data + * in a subsequent request. + */ + export interface ServerDataNode { + type: 'data'; + /** + * The serialized version of this contains a serialized representation of any deferred promises, + * which will be resolved later through chunk nodes. + */ + data: Record | null; + uses: Uses; + slash?: TrailingSlash; + } + + /** + * Resolved data/error of a deferred promise. + */ + export interface ServerDataChunkNode { + type: 'chunk'; + id: number; + data?: Record; + error?: any; + } + + /** + * Signals that the server `load` function was not run, and the + * client should use what it has in memory + */ + export interface ServerDataSkippedNode { + type: 'skip'; + } + + /** + * Signals that the server `load` function failed + */ + export interface ServerErrorNode { + type: 'error'; + error: App.Error; + /** + * Only set for HttpErrors + */ + status?: number; + } + + export interface ServerMetadataRoute { + config: any; + api: { + methods: HttpMethod[]; + }; + page: { + methods: Array<'GET' | 'POST'>; + }; + methods: HttpMethod[]; + prerender: PrerenderOption | undefined; + entries: Array | undefined; + } + + export interface ServerMetadata { + nodes: Array<{ has_server_load: boolean }>; + routes: Map; + } + + export interface SSRComponent { + default: { + render(props: Record): { + html: string; + head: string; + css: { + code: string; + map: any; // TODO + }; + }; + }; + } + + export type SSRComponentLoader = () => Promise; + + export interface SSRNode { + component: SSRComponentLoader; + /** index into the `components` array in client/manifest.js */ + index: number; + /** external JS files */ + imports: string[]; + /** external CSS files */ + stylesheets: string[]; + /** external font files */ + fonts: string[]; + /** inlined styles */ + inline_styles?(): MaybePromise>; + + universal: { + load?: Load; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + server: { + load?: ServerLoad; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + actions?: Actions; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + universal_id: string; + server_id: string; + } + + export type SSRNodeLoader = () => Promise; + + export interface SSROptions { + app_template_contains_nonce: boolean; + csp: ValidatedConfig['kit']['csp']; + csrf_check_origin: boolean; + track_server_fetches: boolean; + embedded: boolean; + env_public_prefix: string; + hooks: ServerHooks; + preload_strategy: ValidatedConfig['kit']['output']['preloadStrategy']; + root: SSRComponent['default']; + service_worker: boolean; + templates: { + app(values: { + head: string; + body: string; + assets: string; + nonce: string; + env: Record; + }): string; + error(values: { message: string; status: number }): string; + }; + version_hash: string; + } + + export interface PageNodeIndexes { + errors: Array; + layouts: Array; + leaf: number; + } + + export type PrerenderEntryGenerator = () => MaybePromise>>; + + export type SSREndpoint = Partial> & { + prerender?: PrerenderOption; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + export interface SSRRoute { + id: string; + pattern: RegExp; + params: RouteParam[]; + page: PageNodeIndexes | null; + endpoint: (() => Promise) | null; + endpoint_id?: string; + } + + export interface SSRState { + fallback?: string; + getClientAddress(): string; + /** + * True if we're currently attempting to render an error page + */ + error: boolean; + /** + * Allows us to prevent `event.fetch` from making infinitely looping internal requests + */ + depth: number; + platform?: any; + prerendering?: PrerenderOptions; + /** + * When fetching data from a +server.js endpoint in `load`, the page's + * prerender option is inherited by the endpoint, unless overridden + */ + prerender_default?: PrerenderOption; + read?: (file: string) => Buffer; + } + + export type StrictBody = string | ArrayBufferView; + + export interface Uses { + dependencies: Set; + params: Set; + parent: boolean; + route: boolean; + url: boolean; + } + + export type ValidatedConfig = RecursiveRequired; + + export type ValidatedKitConfig = RecursiveRequired; + export function error(status: number, body: App.Error): { + status: number; + body: App.Error; + toString(): string; + }; + export function error(status: number, body?: { + message: string; + } extends App.Error ? App.Error | string | undefined : never): { + status: number; + body: App.Error; + toString(): string; + }; + /** + * Create a `Redirect` object. If thrown 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. + * */ + export function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, location: string): { + status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; + location: string; + }; + /** + * Create a JSON `Response` object from the supplied data. + * */ + export function json(data: any, init?: ResponseInit | undefined): Response; + /** + * Create a `Response` object from the supplied body. + * */ + export function text(body: string, init?: ResponseInit | undefined): Response; + /** + * Create an `ActionFailure` object. + * */ + export function fail(status: number, data?: Record | undefined): { + status: number; + data: Record | undefined; + }; + /** + * Populate a route ID with params to resolve a pathname. + * */ + export function resolvePath(id: string, params: Record): string; +} + +declare module '@sveltejs/kit/hooks' { + + /** + * 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 + * /// 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 + * ``` + * + * */ + export function sequence(...handlers: import('@sveltejs/kit').Handle[]): import('@sveltejs/kit').Handle; +} + +declare module '@sveltejs/kit/node' { + export function getRequest({ request, base, bodySizeLimit }: { + request: any; + base: any; + bodySizeLimit: any; + }): Promise; + + export function setResponse(res: any, response: any): Promise; +} + +declare module '@sveltejs/kit/node/polyfills' { + /** + * Make various web APIs available as globals: + * - `crypto` + * - `fetch` + * - `Headers` + * - `Request` + * - `Response` + */ + export function installPolyfills(): void; +} + +declare module '@sveltejs/kit/vite' { + /** + * Returns the SvelteKit Vite plugins. + * */ + export function sveltekit(): Promise; + export { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; +} + +declare module '$app/environment' { + /** + * `true` if the app is running in the browser. + */ + export const browser: boolean; + /** + * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. + */ + export const dev: boolean; + export { building, version } from "__sveltekit/environment"; +} + +declare module '$app/forms' { + /** + * Use this function to deserialize the response from a form submission. + * Usage: + * + * ```js + * 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()); + * // ... + * } + * ``` + * */ + export function deserialize | undefined, Invalid_1 extends Record | undefined>(result: string): import("@sveltejs/kit").ActionResult; + /** + * 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 one 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. + * */ + export function enhance | undefined, Invalid_1 extends Record | undefined>(form_element: HTMLFormElement, submit?: import("@sveltejs/kit").SubmitFunction): { + destroy(): void; + }; + /** + * 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. + * */ + export const applyAction: any; +} + +declare module '$app/navigation' { + /** + * 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. + * */ + export const disableScrollHandling: () => void; + /** + * 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)`. + * + * */ + export const goto: any; + /** + * 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'); + * ``` + * */ + export const invalidate: any; + /** + * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * */ + export const invalidateAll: any; + /** + * 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 when the preload is complete. + * + * */ + export const preloadData: any; + /** + * 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. + * */ + export const preloadCode: any; + /** + * 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 the navigation would have directly unloaded the current page, calling `cancel` will trigger the native + * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. + * + * When a navigation isn't client side, `navigation.to.route.id` will be `null`. + * + * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * */ + export const beforeNavigate: any; + /** + * 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. + * */ + export const afterNavigate: any; +} + +declare module '$app/paths' { + /** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ + export const base: "" | `/${string}`; + /** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. + */ + export const assets: "" | `http://${string}` | `https://${string}` | "/_svelte_kit_assets"; +} + +declare module '$app/stores' { + export function getStores(): { + + page: typeof page; + + navigating: typeof navigating; + + updated: typeof updated; + }; + /** + * 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. + * + * */ + export const page: import('svelte/store').Readable; + /** + * 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. + * */ + export const navigating: import('svelte/store').Readable; + /** + * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/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. + * */ + export const updated: import('svelte/store').Readable & { + check(): Promise; + }; +} + +/** + * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: + * + * ```ts + * declare global { + * namespace App { + * // interface Error {} + * // interface Locals {} + * // interface PageData {} + * // interface Platform {} + * } + * } + * + * export {}; + * ``` + * + * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. + * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. + * + * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. + */ +declare namespace App { + /** + * 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. + */ + export interface Error { + message: string; + } + + /** + * 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. + */ + export interface Locals {} + + /** + * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$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`). + */ + export interface PageData {} + + /** + * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. + */ + export interface Platform {} +} + +/** + * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). + */ +declare module '$service-worker' { + /** + * 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. + */ + export const base: string; + /** + * 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. + */ + export const build: string[]; + /** + * 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`](https://kit.svelte.dev/docs/configuration) + */ + export const files: string[]; + /** + * An array of pathnames corresponding to prerendered pages and endpoints. + * During development, this is an empty array. + */ + export const prerendered: string[]; + /** + * See [`config.kit.version`](https://kit.svelte.dev/docs/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. + */ + export const version: string; +} \ No newline at end of file diff --git a/packages/kit/tsconfig.json b/packages/kit/tsconfig.json index b7eca62d1a3d..df193be401c6 100644 --- a/packages/kit/tsconfig.json +++ b/packages/kit/tsconfig.json @@ -9,7 +9,7 @@ "moduleResolution": "node", "allowSyntheticDefaultImports": true, "paths": { - "@sveltejs/kit": ["./types/index"], + "@sveltejs/kit": ["./src/exports/public.d.ts"], // internal use only "types": ["./types/internal"] }, diff --git a/packages/kit/types/ambient-private.d.ts b/packages/kit/types/ambient-private.d.ts new file mode 100644 index 000000000000..843cc94d342b --- /dev/null +++ b/packages/kit/types/ambient-private.d.ts @@ -0,0 +1,11 @@ +declare global { + const __SVELTEKIT_ADAPTER_NAME__: string; + const __SVELTEKIT_APP_VERSION_FILE__: string; + const __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: number; + const __SVELTEKIT_DEV__: boolean; + const __SVELTEKIT_EMBEDDED__: boolean; + var Bun: object; + var Deno: object; +} + +export {}; diff --git a/packages/kit/types/ambient.d.ts b/packages/kit/types/ambient.d.ts index 10e3529d238b..c6a40f78de40 100644 --- a/packages/kit/types/ambient.d.ts +++ b/packages/kit/types/ambient.d.ts @@ -45,307 +45,6 @@ declare namespace App { export interface Platform {} } -declare module '$app/environment' { - /** - * `true` if the app is running in the browser. - */ - export const browser: boolean; - - /** - * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. - */ - export const building: boolean; - - /** - * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. - */ - export const dev: boolean; - - /** - * The value of `config.kit.version.name`. - */ - export const version: string; -} - -declare module '$app/forms' { - import type { ActionResult } from '@sveltejs/kit'; - - type MaybePromise = T | Promise; - - // this is duplicated in @sveltejs/kit because create-svelte tests fail - // if we use the imported version. See https://github.com/sveltejs/kit/pull/7003#issuecomment-1330921789 - // for why this happens (it's likely a bug in TypeScript, but one that is so rare that it's unlikely to be fixed) - type SubmitFunction< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - > = (input: { - action: URL; - /** - * use `formData` instead of `data` - * @deprecated - */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * @deprecated - */ - form: HTMLFormElement; - formElement: HTMLFormElement; - controller: AbortController; - cancel(): void; - submitter: HTMLElement | null; - }) => MaybePromise< - | void - | ((opts: { - /** - * use `formData` instead of `data` - * @deprecated - */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * @deprecated - */ - form: HTMLFormElement; - 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. - */ - update(options?: { reset: boolean }): Promise; - }) => void) - >; - - /** - * This action enhances a `` element that otherwise would work without JavaScript. - * @param form The form element - * @param options Callbacks for different states of the form lifecycle - */ - export function enhance< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - >( - formElement: HTMLFormElement, - /** - * 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 one 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. - */ - submit?: SubmitFunction - ): { destroy(): void }; - - /** - * 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. - */ - export function applyAction< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - >(result: ActionResult): Promise; - - /** - * Use this function to deserialize the response from a form submission. - * Usage: - * - * ```js - * 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()); - * // ... - * } - * ``` - */ - export function deserialize< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - >(serialized: string): ActionResult; -} - -declare module '$app/navigation' { - import { BeforeNavigate, AfterNavigate } from '@sveltejs/kit'; - - /** - * 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. - */ - export function disableScrollHandling(): void; - /** - * 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)`. - * - * @param url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. - * @param opts Options related to the navigation - */ - export function goto( - url: string | URL, - opts?: { - /** - * If `true`, will replace the current `history` entry rather than creating a new one with `pushState` - */ - replaceState?: boolean; - /** - * If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation - */ - noScroll?: boolean; - /** - * If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body - */ - keepFocus?: boolean; - /** - * The state of the new/updated history entry - */ - state?: any; - /** - * If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation. - */ - invalidateAll?: boolean; - } - ): Promise; - /** - * 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'); - * ``` - * @param url The invalidated URL - */ - export function invalidate(url: string | URL | ((url: URL) => boolean)): Promise; - /** - * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. - */ - export function invalidateAll(): Promise; - /** - * 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 when the preload is complete. - * - * @param href Page to preload - */ - export function preloadData(href: string): Promise; - /** - * 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. - */ - export function preloadCode(...urls: string[]): Promise; - - /** - * 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 the navigation would have directly unloaded the current page, calling `cancel` will trigger the native - * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. - * - * When a navigation isn't client side, `navigation.to.route.id` will be `null`. - * - * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. - */ - export function beforeNavigate(callback: (navigation: BeforeNavigate) => void): void; - - /** - * 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. - */ - export function afterNavigate(callback: (navigation: AfterNavigate) => void): void; -} - -declare module '$app/paths' { - /** - * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). - * - * Example usage: `Link` - */ - export const base: `/${string}`; - /** - * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. - */ - export const assets: `https://${string}` | `http://${string}`; -} - -/** - * These stores are _contextual_ on the server — they are added to the [context](https://svelte.dev/tutorial/context-api) of your root component. This means that `page` is unique to each request, rather than shared between multiple requests handled by the same server simultaneously. - * - * Because of that, you must subscribe to the stores during component initialization (which happens automatically if you reference the store value, e.g. as `$page`, in a component) before you can use them. - * - * In the browser, we don't need to worry about this, and stores can be accessed from anywhere. Code that will only ever run on the browser can refer to (or subscribe to) any of these stores at any time. - * - * You can read more about client/server differences in the [state management](https://kit.svelte.dev/docs/state-management#using-stores-with-context) documentation. - */ -declare module '$app/stores' { - import { Readable } from 'svelte/store'; - import { Navigation, Page } from '@sveltejs/kit'; - - /** - * 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. - */ - export const page: Readable; - /** - * 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. - */ - export const navigating: Readable; - /** - * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/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. - */ - export const updated: Readable & { check(): Promise }; - - /** - * A function that returns all of the contextual stores. On the server, this must be called during component initialization. - * Only use this if you need to defer store subscription until after the component has mounted, for some reason. - */ - export function getStores(): { - navigating: typeof navigating; - page: typeof page; - updated: typeof updated; - }; -} - /** * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). */ @@ -374,113 +73,3 @@ declare module '$service-worker' { */ export const version: string; } - -declare module '@sveltejs/kit/hooks' { - import { Handle } from '@sveltejs/kit'; - - /** - * 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 - * /// 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 - * ``` - * - * @param handlers The chain of `handle` functions - */ - export function sequence(...handlers: Handle[]): Handle; -} - -/** - * A polyfill for `fetch` and its related interfaces, used by adapters for environments that don't provide a native implementation. - */ -declare module '@sveltejs/kit/node/polyfills' { - /** - * Make various web APIs available as globals: - * - `crypto` - * - `fetch` - * - `Headers` - * - `Request` - * - `Response` - */ - export function installPolyfills(): void; -} - -/** - * Utilities used by adapters for Node-like environments. - */ -declare module '@sveltejs/kit/node' { - export function getRequest(opts: { - base: string; - request: import('http').IncomingMessage; - bodySizeLimit?: number; - }): Promise; - export function setResponse(res: import('http').ServerResponse, response: Response): void; -} - -declare module '@sveltejs/kit/vite' { - import { Plugin } from 'vite'; - - /** - * Returns the SvelteKit Vite plugins. - */ - export function sveltekit(): Promise; - export { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; -} diff --git a/packages/kit/types/internal.d.ts b/packages/kit/types/internal.d.ts index 379328678073..e9865778c903 100644 --- a/packages/kit/types/internal.d.ts +++ b/packages/kit/types/internal.d.ts @@ -13,7 +13,7 @@ import { HandleFetch, Actions, HandleClientError -} from './index.js'; +} from '@sveltejs/kit'; import { HttpMethod, MaybePromise, @@ -412,15 +412,5 @@ export type ValidatedConfig = RecursiveRequired; export type ValidatedKitConfig = RecursiveRequired; -export * from './index'; +export * from '../src/exports/index'; export * from './private'; - -declare global { - const __SVELTEKIT_ADAPTER_NAME__: string; - const __SVELTEKIT_APP_VERSION_FILE__: string; - const __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: number; - const __SVELTEKIT_DEV__: boolean; - const __SVELTEKIT_EMBEDDED__: boolean; - var Bun: object; - var Deno: object; -} diff --git a/packages/kit/types/private.d.ts b/packages/kit/types/private.d.ts index ad02da171242..23b5f554193c 100644 --- a/packages/kit/types/private.d.ts +++ b/packages/kit/types/private.d.ts @@ -2,7 +2,7 @@ // but which cannot be imported from `@sveltejs/kit`. Care should // be taken to avoid breaking changes when editing this file -import { RouteDefinition } from './index.js'; +import { RouteDefinition } from '../src/exports/index.js'; export interface AdapterEntry { /** @@ -237,7 +237,7 @@ export type TrailingSlash = 'never' | 'always' | 'ignore'; /** * This doesn't actually exist, it's a way to better distinguish the type */ -declare const uniqueSymbol: unique symbol; +export const uniqueSymbol: unique symbol; export interface UniqueInterface { readonly [uniqueSymbol]: unknown; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ef47557b7c0d..bbb95d2a9557 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -375,6 +375,9 @@ importers: devalue: specifier: ^4.3.1 version: 4.3.1 + dts-buddy: + specifier: '*' + version: link:../../../../../dts-buddy esm-env: specifier: ^1.0.0 version: 1.0.0 From a7ecb57484c35dc739cb284aae158f611669469a Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 19 May 2023 14:28:02 -0400 Subject: [PATCH 02/42] updates --- packages/kit/scripts/generate-dts.js | 2 +- packages/kit/src/core/adapt/builder.js | 6 ++--- packages/kit/src/core/adapt/builder.spec.js | 2 +- packages/kit/src/core/config/index.js | 4 ++-- packages/kit/src/core/config/index.spec.js | 4 ++-- .../kit/src/core/generate_manifest/index.js | 2 +- packages/kit/src/core/postbuild/analyse.js | 2 +- packages/kit/src/core/postbuild/fallback.js | 2 +- packages/kit/src/core/postbuild/prerender.js | 2 +- .../sync/create_manifest_data/index.spec.js | 2 +- .../write_types/test/actions/+page.server.js | 2 +- .../kit/src/exports/hooks/sequence.spec.js | 10 ++++---- packages/kit/src/exports/public.d.ts | 8 +++---- packages/kit/src/exports/vite/dev/index.js | 2 +- packages/kit/src/runtime/client/client.js | 24 +++++++++---------- packages/kit/src/runtime/client/singletons.js | 2 +- packages/kit/src/runtime/server/data/index.js | 6 ++--- packages/kit/src/runtime/server/endpoint.js | 6 ++--- packages/kit/src/runtime/server/fetch.js | 4 ++-- packages/kit/src/runtime/server/index.js | 4 ++-- .../kit/src/runtime/server/page/actions.js | 18 +++++++------- packages/kit/src/runtime/server/page/index.js | 6 ++--- .../kit/src/runtime/server/page/load_data.js | 12 +++++----- .../src/runtime/server/page/load_data.spec.js | 4 ++-- .../kit/src/runtime/server/page/render.js | 8 +++---- .../runtime/server/page/respond_with_error.js | 4 ++-- packages/kit/src/runtime/server/respond.js | 8 +++---- packages/kit/src/runtime/server/utils.js | 6 ++--- .../kit/{ => src}/types/ambient-private.d.ts | 0 packages/kit/{ => src}/types/ambient.d.ts | 0 packages/kit/{ => src}/types/internal.d.ts | 4 ++-- packages/kit/{ => src}/types/private.d.ts | 2 +- .../types/synthetic/$env+dynamic+private.md | 0 .../types/synthetic/$env+dynamic+public.md | 0 .../types/synthetic/$env+static+private.md | 0 .../types/synthetic/$env+static+public.md | 0 .../kit/{ => src}/types/synthetic/$lib.md | 0 packages/kit/src/utils/streaming.js | 2 +- packages/kit/tsconfig.json | 4 ++-- 39 files changed, 87 insertions(+), 87 deletions(-) rename packages/kit/{ => src}/types/ambient-private.d.ts (100%) rename packages/kit/{ => src}/types/ambient.d.ts (100%) rename packages/kit/{ => src}/types/internal.d.ts (99%) rename packages/kit/{ => src}/types/private.d.ts (99%) rename packages/kit/{ => src}/types/synthetic/$env+dynamic+private.md (100%) rename packages/kit/{ => src}/types/synthetic/$env+dynamic+public.md (100%) rename packages/kit/{ => src}/types/synthetic/$env+static+private.md (100%) rename packages/kit/{ => src}/types/synthetic/$env+static+public.md (100%) rename packages/kit/{ => src}/types/synthetic/$lib.md (100%) diff --git a/packages/kit/scripts/generate-dts.js b/packages/kit/scripts/generate-dts.js index 4834623f8a90..759780337287 100644 --- a/packages/kit/scripts/generate-dts.js +++ b/packages/kit/scripts/generate-dts.js @@ -1,7 +1,7 @@ import { createModuleDeclarations } from 'dts-buddy'; createModuleDeclarations({ - output: 'test-types/index.d.ts', + output: 'types/index.d.ts', modules: { '@sveltejs/kit': 'src/exports/public.d.ts', '@sveltejs/kit/hooks': 'src/exports/hooks/index.js', diff --git a/packages/kit/src/core/adapt/builder.js b/packages/kit/src/core/adapt/builder.js index 91ecf525f447..8493fca45152 100644 --- a/packages/kit/src/core/adapt/builder.js +++ b/packages/kit/src/core/adapt/builder.js @@ -24,7 +24,7 @@ const pipe = promisify(pipeline); * prerender_map: import('types').PrerenderMap; * log: import('types').Logger; * }} opts - * @returns {import('types').Builder} + * @returns {import('@sveltejs/kit').Builder} */ export function create_builder({ config, @@ -35,7 +35,7 @@ export function create_builder({ prerender_map, log }) { - /** @type {Map} */ + /** @type {Map} */ const lookup = new Map(); /** @@ -47,7 +47,7 @@ export function create_builder({ server_metadata.routes.get(route.id) ); - /** @type {import('types').RouteDefinition} */ + /** @type {import('@sveltejs/kit').RouteDefinition} */ const facade = { id: route.id, api, diff --git a/packages/kit/src/core/adapt/builder.spec.js b/packages/kit/src/core/adapt/builder.spec.js index 16832bef7d41..483e9fffce2a 100644 --- a/packages/kit/src/core/adapt/builder.spec.js +++ b/packages/kit/src/core/adapt/builder.spec.js @@ -13,7 +13,7 @@ test('copy files', () => { const cwd = join(__dirname, 'fixtures/basic'); const outDir = join(cwd, '.svelte-kit'); - /** @type {import('types').Config} */ + /** @type {import('@sveltejs/kit').Config} */ const mocked = { extensions: ['.svelte'], kit: { diff --git a/packages/kit/src/core/config/index.js b/packages/kit/src/core/config/index.js index aab5520c7087..a6e37d794277 100644 --- a/packages/kit/src/core/config/index.js +++ b/packages/kit/src/core/config/index.js @@ -73,7 +73,7 @@ export async function load_config({ cwd = process.cwd() } = {}) { } /** - * @param {import('types').Config} config + * @param {import('@sveltejs/kit').Config} config * @returns {import('types').ValidatedConfig} */ function process_config(config, { cwd = process.cwd() } = {}) { @@ -95,7 +95,7 @@ function process_config(config, { cwd = process.cwd() } = {}) { } /** - * @param {import('types').Config} config + * @param {import('@sveltejs/kit').Config} config * @returns {import('types').ValidatedConfig} */ export function validate_config(config) { diff --git a/packages/kit/src/core/config/index.spec.js b/packages/kit/src/core/config/index.spec.js index 3388f149b7df..a7fb7a678874 100644 --- a/packages/kit/src/core/config/index.spec.js +++ b/packages/kit/src/core/config/index.spec.js @@ -297,8 +297,8 @@ test('fails if prerender.entries are invalid', () => { /** * @param {string} name - * @param {import('types').KitConfig['paths']} input - * @param {import('types').KitConfig['paths']} output + * @param {import('@sveltejs/kit').KitConfig['paths']} input + * @param {import('@sveltejs/kit').KitConfig['paths']} output */ function validate_paths(name, input, output) { test(name, () => { diff --git a/packages/kit/src/core/generate_manifest/index.js b/packages/kit/src/core/generate_manifest/index.js index e8074ceb7f87..110930db519d 100644 --- a/packages/kit/src/core/generate_manifest/index.js +++ b/packages/kit/src/core/generate_manifest/index.js @@ -65,7 +65,7 @@ export function generate_manifest({ build_data, relative_path, routes }) { // prettier-ignore // String representation of - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ return dedent` { appDir: ${s(build_data.app_dir)}, diff --git a/packages/kit/src/core/postbuild/analyse.js b/packages/kit/src/core/postbuild/analyse.js index 1b82177fba66..64a93478af0e 100644 --- a/packages/kit/src/core/postbuild/analyse.js +++ b/packages/kit/src/core/postbuild/analyse.js @@ -23,7 +23,7 @@ export default forked(import.meta.url, analyse); * }} opts */ async function analyse({ manifest_path, env }) { - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; /** @type {import('types').ValidatedKitConfig} */ diff --git a/packages/kit/src/core/postbuild/fallback.js b/packages/kit/src/core/postbuild/fallback.js index dbce677d7094..40d6a9a78289 100644 --- a/packages/kit/src/core/postbuild/fallback.js +++ b/packages/kit/src/core/postbuild/fallback.js @@ -27,7 +27,7 @@ async function generate_fallback({ manifest_path, env }) { /** @type {import('types').ServerModule} */ const { Server } = await import(pathToFileURL(`${server_root}/server/index.js`).href); - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; set_building(true); diff --git a/packages/kit/src/core/postbuild/prerender.js b/packages/kit/src/core/postbuild/prerender.js index fa112ca152bc..e64b7f852364 100644 --- a/packages/kit/src/core/postbuild/prerender.js +++ b/packages/kit/src/core/postbuild/prerender.js @@ -26,7 +26,7 @@ export default forked(import.meta.url, prerender); * }} opts */ async function prerender({ out, manifest_path, metadata, verbose, env }) { - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; /** @type {import('types').ServerInternalModule} */ diff --git a/packages/kit/src/core/sync/create_manifest_data/index.spec.js b/packages/kit/src/core/sync/create_manifest_data/index.spec.js index cde94b1c1489..758206be45d5 100644 --- a/packages/kit/src/core/sync/create_manifest_data/index.spec.js +++ b/packages/kit/src/core/sync/create_manifest_data/index.spec.js @@ -10,7 +10,7 @@ const cwd = fileURLToPath(new URL('./test', import.meta.url)); /** * @param {string} dir - * @param {import('types').Config} config + * @param {import('@sveltejs/kit').Config} config */ const create = (dir, config = {}) => { const initial = options(config, 'config'); diff --git a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js index 46dd8f8f4823..6613e7fe3467 100644 --- a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js +++ b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js @@ -1,4 +1,4 @@ -import { fail } from '../../../../../../types/internal.js'; +import { fail } from '../../../../../../src/exports/index.js'; let condition = false; diff --git a/packages/kit/src/exports/hooks/sequence.spec.js b/packages/kit/src/exports/hooks/sequence.spec.js index da5e4e8d1b2f..a4912bdd5790 100644 --- a/packages/kit/src/exports/hooks/sequence.spec.js +++ b/packages/kit/src/exports/hooks/sequence.spec.js @@ -29,7 +29,7 @@ test('applies handlers in sequence', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = new Response(); assert.equal(await handler({ event, resolve: () => response }), response); @@ -47,7 +47,7 @@ test('uses transformPageChunk option passed to non-terminal handle function', as async ({ event, resolve }) => resolve(event) ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { @@ -84,7 +84,7 @@ test('merges transformPageChunk option', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { @@ -117,7 +117,7 @@ test('uses first defined preload option', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { @@ -150,7 +150,7 @@ test('uses first defined filterSerializedResponseHeaders option', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index 084399f76d60..ed2f94ccad61 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -1,7 +1,7 @@ /// /// -import '../../types/ambient.js'; +import '../types/ambient.js'; import { CompileOptions } from 'svelte/types/compiler/interfaces'; import { @@ -18,11 +18,11 @@ import { RequestOptions, RouteSegment, UniqueInterface -} from '../../types/private.js'; -import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from '../../types/internal.js'; +} from '../types/private.js'; +import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from 'types'; import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; -export { PrerenderOption } from '../../types/private.js'; +export { PrerenderOption } from '../types/private.js'; /** * [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. diff --git a/packages/kit/src/exports/vite/dev/index.js b/packages/kit/src/exports/vite/dev/index.js index 1f2a5b4881b5..a076dcf12daf 100644 --- a/packages/kit/src/exports/vite/dev/index.js +++ b/packages/kit/src/exports/vite/dev/index.js @@ -44,7 +44,7 @@ export async function dev(vite, vite_config, svelte_config) { /** @type {import('types').ManifestData} */ let manifest_data; - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ let manifest; /** @type {Error | null} */ diff --git a/packages/kit/src/runtime/client/client.js b/packages/kit/src/runtime/client/client.js index 1f76651d2a82..b9d9535bddd9 100644 --- a/packages/kit/src/runtime/client/client.js +++ b/packages/kit/src/runtime/client/client.js @@ -86,10 +86,10 @@ export function create_client(app, target) { let load_cache = null; const callbacks = { - /** @type {Array<(navigation: import('types').BeforeNavigate) => void>} */ + /** @type {Array<(navigation: import('@sveltejs/kit').BeforeNavigate) => void>} */ before_navigate: [], - /** @type {Array<(navigation: import('types').AfterNavigate) => void>} */ + /** @type {Array<(navigation: import('@sveltejs/kit').AfterNavigate) => void>} */ after_navigate: [] }; @@ -138,7 +138,7 @@ export function create_client(app, target) { scrollTo(scroll.x, scroll.y); } - /** @type {import('types').Page} */ + /** @type {import('@sveltejs/kit').Page} */ let page; /** @type {{}} */ @@ -279,7 +279,7 @@ export function create_client(app, target) { const style = document.querySelector('style[data-sveltekit]'); if (style) style.remove(); - page = /** @type {import('types').Page} */ (result.props.page); + page = /** @type {import('@sveltejs/kit').Page} */ (result.props.page); root = new app.root({ target, @@ -289,7 +289,7 @@ export function create_client(app, target) { restore_snapshot(current_history_index); - /** @type {import('types').AfterNavigate} */ + /** @type {import('@sveltejs/kit').AfterNavigate} */ const navigation = { from: null, to: { @@ -445,7 +445,7 @@ export function create_client(app, target) { } } - /** @type {import('types').LoadEvent} */ + /** @type {import('@sveltejs/kit').LoadEvent} */ const load_input = { route: { get id() { @@ -900,7 +900,7 @@ export function create_client(app, target) { /** * @param {{ * url: URL; - * type: import('types').NavigationType; + * type: import('@sveltejs/kit').NavigationType; * intent?: import('./types').NavigationIntent; * delta?: number; * }} opts @@ -908,7 +908,7 @@ export function create_client(app, target) { function before_navigate({ url, type, intent, delta }) { let should_block = false; - /** @type {import('types').Navigation} */ + /** @type {import('@sveltejs/kit').Navigation} */ const navigation = { from: { params: current.params, @@ -953,7 +953,7 @@ export function create_client(app, target) { * replaceState: boolean; * state: any; * } | null; - * type: import('types').NavigationType; + * type: import('@sveltejs/kit').NavigationType; * delta?: number; * nav_token?: {}; * accepted: () => void; @@ -1141,7 +1141,7 @@ export function create_client(app, target) { } callbacks.after_navigate.forEach((fn) => - fn(/** @type {import('types').AfterNavigate} */ (navigation)) + fn(/** @type {import('@sveltejs/kit').AfterNavigate} */ (navigation)) ); stores.navigating.set(null); @@ -1295,7 +1295,7 @@ export function create_client(app, target) { /** * @param {unknown} error - * @param {import('types').NavigationEvent} event + * @param {import('@sveltejs/kit').NavigationEvent} event * @returns {import('types').MaybePromise} */ function handle_error(error, event) { @@ -1444,7 +1444,7 @@ export function create_client(app, target) { if (!navigating) { // If we're navigating, beforeNavigate was already called. If we end up in here during navigation, // it's due to an external or full-page-reload link, for which we don't want to call the hook again. - /** @type {import('types').BeforeNavigate} */ + /** @type {import('@sveltejs/kit').BeforeNavigate} */ const navigation = { from: { params: current.params, diff --git a/packages/kit/src/runtime/client/singletons.js b/packages/kit/src/runtime/client/singletons.js index 6316373753dd..ec50c7295900 100644 --- a/packages/kit/src/runtime/client/singletons.js +++ b/packages/kit/src/runtime/client/singletons.js @@ -46,6 +46,6 @@ export function client_method(key) { export const stores = { url: notifiable_store({}), page: notifiable_store({}), - navigating: writable(/** @type {import('types').Navigation | null} */ (null)), + navigating: writable(/** @type {import('@sveltejs/kit').Navigation | null} */ (null)), updated: create_updated_store() }; diff --git a/packages/kit/src/runtime/server/data/index.js b/packages/kit/src/runtime/server/data/index.js index 8d38b1e10720..472c2c10c479 100644 --- a/packages/kit/src/runtime/server/data/index.js +++ b/packages/kit/src/runtime/server/data/index.js @@ -11,10 +11,10 @@ import { create_async_iterator } from '../../../utils/streaming.js'; const encoder = new TextEncoder(); /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSRRoute} route * @param {import('types').SSROptions} options - * @param {import('types').SSRManifest} manifest + * @param {import('@sveltejs/kit').SSRManifest} manifest * @param {import('types').SSRState} state * @param {boolean[] | undefined} invalidated_data_nodes * @param {import('types').TrailingSlash} trailing_slash @@ -183,7 +183,7 @@ export function redirect_json_response(redirect) { /** * If the serialized data contains promises, `chunks` will be an * async iterable containing their resolutions - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {Array} nodes * @returns {{ data: string, chunks: AsyncIterable | null }} diff --git a/packages/kit/src/runtime/server/endpoint.js b/packages/kit/src/runtime/server/endpoint.js index a98982536ac5..28e57eb047d5 100644 --- a/packages/kit/src/runtime/server/endpoint.js +++ b/packages/kit/src/runtime/server/endpoint.js @@ -3,7 +3,7 @@ import { Redirect } from '../control.js'; import { method_not_allowed } from './utils.js'; /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSREndpoint} mod * @param {import('types').SSRState} state * @returns {Promise} @@ -40,7 +40,7 @@ export async function render_endpoint(event, mod, state) { try { const response = await handler( - /** @type {import('types').RequestEvent>} */ (event) + /** @type {import('@sveltejs/kit').RequestEvent>} */ (event) ); if (!(response instanceof Response)) { @@ -67,7 +67,7 @@ export async function render_endpoint(event, mod, state) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event */ export function is_endpoint_request(event) { const { method, headers } = event.request; diff --git a/packages/kit/src/runtime/server/fetch.js b/packages/kit/src/runtime/server/fetch.js index 234da0eb82a4..cb47a89873cf 100644 --- a/packages/kit/src/runtime/server/fetch.js +++ b/packages/kit/src/runtime/server/fetch.js @@ -4,9 +4,9 @@ import * as paths from '__sveltekit/paths'; /** * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * options: import('types').SSROptions; - * manifest: import('types').SSRManifest; + * manifest: import('@sveltejs/kit').SSRManifest; * state: import('types').SSRState; * get_cookie_header: (url: URL, header: string | null) => string; * set_internal: (name: string, value: string, opts: import('cookie').CookieSerializeOptions) => void; diff --git a/packages/kit/src/runtime/server/index.js b/packages/kit/src/runtime/server/index.js index a20a76cc6f13..9f3a6eb56915 100644 --- a/packages/kit/src/runtime/server/index.js +++ b/packages/kit/src/runtime/server/index.js @@ -7,10 +7,10 @@ export class Server { /** @type {import('types').SSROptions} */ #options; - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ #manifest; - /** @param {import('types').SSRManifest} manifest */ + /** @param {import('@sveltejs/kit').SSRManifest} manifest */ constructor(manifest) { /** @type {import('types').SSROptions} */ this.#options = options; diff --git a/packages/kit/src/runtime/server/page/actions.js b/packages/kit/src/runtime/server/page/actions.js index 75d9bf039724..6e9119b0b8b1 100644 --- a/packages/kit/src/runtime/server/page/actions.js +++ b/packages/kit/src/runtime/server/page/actions.js @@ -5,7 +5,7 @@ import { is_form_content_type, negotiate } from '../../../utils/http.js'; import { HttpError, Redirect, ActionFailure } from '../../control.js'; import { handle_error_and_jsonify } from '../utils.js'; -/** @param {import('types').RequestEvent} event */ +/** @param {import('@sveltejs/kit').RequestEvent} event */ export function is_action_json_request(event) { const accept = negotiate(event.request.headers.get('accept') ?? '*/*', [ 'application/json', @@ -16,7 +16,7 @@ export function is_action_json_request(event) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {import('types').SSRNode['server'] | undefined} server */ @@ -97,7 +97,7 @@ function check_incorrect_fail_use(error) { } /** - * @param {import('types').Redirect} redirect + * @param {import('@sveltejs/kit').Redirect} redirect */ export function action_json_redirect(redirect) { return action_json({ @@ -108,7 +108,7 @@ export function action_json_redirect(redirect) { } /** - * @param {import('types').ActionResult} data + * @param {import('@sveltejs/kit').ActionResult} data * @param {ResponseInit} [init] */ function action_json(data, init) { @@ -116,16 +116,16 @@ function action_json(data, init) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event */ export function is_action_request(event) { return event.request.method === 'POST'; } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSRNode['server'] | undefined} server - * @returns {Promise} + * @returns {Promise} */ export async function handle_action_request(event, server) { const actions = server?.actions; @@ -185,7 +185,7 @@ export async function handle_action_request(event, server) { } /** - * @param {import('types').Actions} actions + * @param {import('@sveltejs/kit').Actions} actions */ function check_named_default_separate(actions) { if (actions.default && Object.keys(actions).length > 1) { @@ -196,7 +196,7 @@ function check_named_default_separate(actions) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {NonNullable} actions * @throws {Redirect | ActionFailure | HttpError | Error} */ diff --git a/packages/kit/src/runtime/server/page/index.js b/packages/kit/src/runtime/server/page/index.js index b7009a27b9fe..e07081a0551e 100644 --- a/packages/kit/src/runtime/server/page/index.js +++ b/packages/kit/src/runtime/server/page/index.js @@ -22,10 +22,10 @@ import { get_data_json } from '../data/index.js'; const MAX_DEPTH = 10; /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').PageNodeIndexes} page * @param {import('types').SSROptions} options - * @param {import('types').SSRManifest} manifest + * @param {import('@sveltejs/kit').SSRManifest} manifest * @param {import('types').SSRState} state * @param {import('types').RequiredResolveOptions} resolve_opts * @returns {Promise} @@ -54,7 +54,7 @@ export async function render_page(event, page, options, manifest, state, resolve let status = 200; - /** @type {import('types').ActionResult | undefined} */ + /** @type {import('@sveltejs/kit').ActionResult | undefined} */ let action_result = undefined; if (is_action_request(event)) { diff --git a/packages/kit/src/runtime/server/page/load_data.js b/packages/kit/src/runtime/server/page/load_data.js index ced84ab9918c..e7bac923e2d0 100644 --- a/packages/kit/src/runtime/server/page/load_data.js +++ b/packages/kit/src/runtime/server/page/load_data.js @@ -6,7 +6,7 @@ import { validate_depends } from '../../shared.js'; /** * Calls the user's server `load` function. * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * state: import('types').SSRState; * node: import('types').SSRNode | undefined; * parent: () => Promise>; @@ -143,7 +143,7 @@ export async function load_server_data({ /** * Calls the user's `load` function. * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * fetched: import('./types').Fetched[]; * node: import('types').SSRNode | undefined; * parent: () => Promise>; @@ -190,11 +190,11 @@ export async function load_data({ } /** - * @param {Pick} event - * @param {import("types").SSRState} state - * @param {import("./types").Fetched[]} fetched + * @param {Pick} event + * @param {import('types').SSRState} state + * @param {import('./types').Fetched[]} fetched * @param {boolean} csr - * @param {Pick, 'filterSerializedResponseHeaders'>} resolve_opts + * @param {Pick, 'filterSerializedResponseHeaders'>} resolve_opts */ export function create_universal_fetch(event, state, fetched, csr, resolve_opts) { /** diff --git a/packages/kit/src/runtime/server/page/load_data.spec.js b/packages/kit/src/runtime/server/page/load_data.spec.js index 88785b4a7b98..ec3167c08822 100644 --- a/packages/kit/src/runtime/server/page/load_data.spec.js +++ b/packages/kit/src/runtime/server/page/load_data.spec.js @@ -2,7 +2,7 @@ import { assert, expect, test } from 'vitest'; import { create_universal_fetch } from './load_data.js'; /** - * @param {Partial>} event + * @param {Partial>} event */ function create_fetch(event) { event.fetch = event.fetch || (async () => new Response('foo')); @@ -10,7 +10,7 @@ function create_fetch(event) { event.route = event.route || { id: 'foo' }; event.url = event.url || new URL('https://domain-a.com'); return create_universal_fetch( - /** @type {Pick} */ ( + /** @type {Pick} */ ( event ), { getClientAddress: () => '', error: false, depth: 0 }, diff --git a/packages/kit/src/runtime/server/page/render.js b/packages/kit/src/runtime/server/page/render.js index 33fc2f8f268a..265bcf7a8f2b 100644 --- a/packages/kit/src/runtime/server/page/render.js +++ b/packages/kit/src/runtime/server/page/render.js @@ -28,14 +28,14 @@ const encoder = new TextEncoder(); * branch: Array; * fetched: Array; * options: import('types').SSROptions; - * manifest: import('types').SSRManifest; + * manifest: import('@sveltejs/kit').SSRManifest; * state: import('types').SSRState; * page_config: { ssr: boolean; csr: boolean }; * status: number; * error: App.Error | null; - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * resolve_opts: import('types').RequiredResolveOptions; - * action_result?: import('types').ActionResult; + * action_result?: import('@sveltejs/kit').ActionResult; * }} opts */ export async function render_response({ @@ -490,7 +490,7 @@ export async function render_response({ /** * If the serialized data contains promises, `chunks` will be an * async iterable containing their resolutions - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {Array} nodes * @param {string} global diff --git a/packages/kit/src/runtime/server/page/respond_with_error.js b/packages/kit/src/runtime/server/page/respond_with_error.js index 2567b7e768e8..15148b379bf9 100644 --- a/packages/kit/src/runtime/server/page/respond_with_error.js +++ b/packages/kit/src/runtime/server/page/respond_with_error.js @@ -10,9 +10,9 @@ import { HttpError, Redirect } from '../../control.js'; /** * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * options: import('types').SSROptions; - * manifest: import('types').SSRManifest; + * manifest: import('@sveltejs/kit').SSRManifest; * state: import('types').SSRState; * status: number; * error: unknown; diff --git a/packages/kit/src/runtime/server/respond.js b/packages/kit/src/runtime/server/respond.js index a82f48ce1111..b53693af3e8d 100644 --- a/packages/kit/src/runtime/server/respond.js +++ b/packages/kit/src/runtime/server/respond.js @@ -45,7 +45,7 @@ const default_preload = ({ type }) => type === 'js' || type === 'css'; /** * @param {Request} request * @param {import('types').SSROptions} options - * @param {import('types').SSRManifest} manifest + * @param {import('@sveltejs/kit').SSRManifest} manifest * @param {import('types').SSRState} state * @returns {Promise} */ @@ -130,7 +130,7 @@ export async function respond(request, options, manifest, state) { /** @type {Record} */ let cookies_to_add = {}; - /** @type {import('types').RequestEvent} */ + /** @type {import('@sveltejs/kit').RequestEvent} */ const event = { // @ts-expect-error `cookies` and `fetch` need to be created after the `event` itself cookies: null, @@ -343,8 +343,8 @@ export async function respond(request, options, manifest, state) { /** * - * @param {import('types').RequestEvent} event - * @param {import('types').ResolveOptions} [opts] + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions} [opts] */ async function resolve(event, opts) { try { diff --git a/packages/kit/src/runtime/server/utils.js b/packages/kit/src/runtime/server/utils.js index e9c9e3354e1d..211c8017757c 100644 --- a/packages/kit/src/runtime/server/utils.js +++ b/packages/kit/src/runtime/server/utils.js @@ -65,7 +65,7 @@ export function static_error_page(options, status, message) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {unknown} error */ @@ -90,7 +90,7 @@ export async function handle_fatal_error(event, options, error) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {any} error * @returns {Promise} @@ -132,7 +132,7 @@ export function redirect_response(status, location) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {Error & { path: string }} error */ export function clarify_devalue_error(event, error) { diff --git a/packages/kit/types/ambient-private.d.ts b/packages/kit/src/types/ambient-private.d.ts similarity index 100% rename from packages/kit/types/ambient-private.d.ts rename to packages/kit/src/types/ambient-private.d.ts diff --git a/packages/kit/types/ambient.d.ts b/packages/kit/src/types/ambient.d.ts similarity index 100% rename from packages/kit/types/ambient.d.ts rename to packages/kit/src/types/ambient.d.ts diff --git a/packages/kit/types/internal.d.ts b/packages/kit/src/types/internal.d.ts similarity index 99% rename from packages/kit/types/internal.d.ts rename to packages/kit/src/types/internal.d.ts index e9865778c903..76c4c89c5d85 100644 --- a/packages/kit/types/internal.d.ts +++ b/packages/kit/src/types/internal.d.ts @@ -412,5 +412,5 @@ export type ValidatedConfig = RecursiveRequired; export type ValidatedKitConfig = RecursiveRequired; -export * from '../src/exports/index'; -export * from './private'; +export * from '../exports/index'; +export * from './private.js'; diff --git a/packages/kit/types/private.d.ts b/packages/kit/src/types/private.d.ts similarity index 99% rename from packages/kit/types/private.d.ts rename to packages/kit/src/types/private.d.ts index 23b5f554193c..35c60ffd2ed0 100644 --- a/packages/kit/types/private.d.ts +++ b/packages/kit/src/types/private.d.ts @@ -2,7 +2,7 @@ // but which cannot be imported from `@sveltejs/kit`. Care should // be taken to avoid breaking changes when editing this file -import { RouteDefinition } from '../src/exports/index.js'; +import { RouteDefinition } from '../exports/index.js'; export interface AdapterEntry { /** diff --git a/packages/kit/types/synthetic/$env+dynamic+private.md b/packages/kit/src/types/synthetic/$env+dynamic+private.md similarity index 100% rename from packages/kit/types/synthetic/$env+dynamic+private.md rename to packages/kit/src/types/synthetic/$env+dynamic+private.md diff --git a/packages/kit/types/synthetic/$env+dynamic+public.md b/packages/kit/src/types/synthetic/$env+dynamic+public.md similarity index 100% rename from packages/kit/types/synthetic/$env+dynamic+public.md rename to packages/kit/src/types/synthetic/$env+dynamic+public.md diff --git a/packages/kit/types/synthetic/$env+static+private.md b/packages/kit/src/types/synthetic/$env+static+private.md similarity index 100% rename from packages/kit/types/synthetic/$env+static+private.md rename to packages/kit/src/types/synthetic/$env+static+private.md diff --git a/packages/kit/types/synthetic/$env+static+public.md b/packages/kit/src/types/synthetic/$env+static+public.md similarity index 100% rename from packages/kit/types/synthetic/$env+static+public.md rename to packages/kit/src/types/synthetic/$env+static+public.md diff --git a/packages/kit/types/synthetic/$lib.md b/packages/kit/src/types/synthetic/$lib.md similarity index 100% rename from packages/kit/types/synthetic/$lib.md rename to packages/kit/src/types/synthetic/$lib.md diff --git a/packages/kit/src/utils/streaming.js b/packages/kit/src/utils/streaming.js index 1015231f46b8..8e0bc9314fae 100644 --- a/packages/kit/src/utils/streaming.js +++ b/packages/kit/src/utils/streaming.js @@ -1,5 +1,5 @@ /** - * @returns {import("types").Deferred & { promise: Promise }}} + * @returns {import('types').Deferred & { promise: Promise }}} */ function defer() { let fulfil; diff --git a/packages/kit/tsconfig.json b/packages/kit/tsconfig.json index df193be401c6..23e1a7c0fa31 100644 --- a/packages/kit/tsconfig.json +++ b/packages/kit/tsconfig.json @@ -11,7 +11,7 @@ "paths": { "@sveltejs/kit": ["./src/exports/public.d.ts"], // internal use only - "types": ["./types/internal"] + "types": ["src/types/internal"] }, "noUnusedLocals": true, "noUnusedParameters": true @@ -19,7 +19,7 @@ "include": [ "scripts/**/*", "src/**/*", - "types/**/*", + "src/types/**/*", "../../sites/kit.svelte.dev/scripts/extract-types.js" ], "exclude": ["./**/write_types/test/**"] From 9c0712e3c0c3e0f72e8bbe3abe87f096213d6052 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 19 May 2023 14:48:34 -0400 Subject: [PATCH 03/42] fixes --- packages/kit/src/exports/node/index.js | 15 +++++++++++++-- packages/kit/src/exports/vite/dev/index.js | 2 +- packages/kit/src/runtime/app/forms.js | 1 + packages/kit/src/runtime/app/navigation.js | 14 ++++++++++++++ packages/kit/src/runtime/client/types.d.ts | 16 ++++------------ packages/kit/src/types/private.d.ts | 2 +- packages/kit/src/utils/routing.js | 2 +- packages/kit/tsconfig.json | 3 ++- 8 files changed, 37 insertions(+), 18 deletions(-) diff --git a/packages/kit/src/exports/node/index.js b/packages/kit/src/exports/node/index.js index 76233e074a58..a8b835b41d6b 100644 --- a/packages/kit/src/exports/node/index.js +++ b/packages/kit/src/exports/node/index.js @@ -92,7 +92,14 @@ function get_raw_body(req, body_size_limit) { }); } -/** @type {import('@sveltejs/kit/node').getRequest} */ +/** + * @param {{ + * request: import('http').IncomingMessage; + * base: string; + * bodySizeLimit?: number; + * }} options + * @returns {Promise} + */ export async function getRequest({ request, base, bodySizeLimit }) { return new Request(base + request.url, { // @ts-expect-error @@ -103,7 +110,11 @@ export async function getRequest({ request, base, bodySizeLimit }) { }); } -/** @type {import('@sveltejs/kit/node').setResponse} */ +/** + * @param {import('http').ServerResponse} res + * @param {Response} response + * @returns {Promise} + */ export async function setResponse(res, response) { for (const [key, value] of response.headers) { try { diff --git a/packages/kit/src/exports/vite/dev/index.js b/packages/kit/src/exports/vite/dev/index.js index a076dcf12daf..afc27a4f0d12 100644 --- a/packages/kit/src/exports/vite/dev/index.js +++ b/packages/kit/src/exports/vite/dev/index.js @@ -226,7 +226,7 @@ export async function dev(vite, vite_config, svelte_config) { }) ), matchers: async () => { - /** @type {Record} */ + /** @type {Record} */ const matchers = {}; for (const key in manifest_data.matchers) { diff --git a/packages/kit/src/runtime/app/forms.js b/packages/kit/src/runtime/app/forms.js index 5be0e7b30cc3..d711bff758f2 100644 --- a/packages/kit/src/runtime/app/forms.js +++ b/packages/kit/src/runtime/app/forms.js @@ -8,6 +8,7 @@ import { invalidateAll } from './navigation.js'; * In case of an error, it redirects to the nearest error page. * @template {Record | undefined} Success * @template {Record | undefined} Invalid + * @type {(result: import('@sveltejs/kit').ActionResult) => void} * @param {import('@sveltejs/kit').ActionResult} result */ export const applyAction = client_method('apply_action'); diff --git a/packages/kit/src/runtime/app/navigation.js b/packages/kit/src/runtime/app/navigation.js index 9daf17412650..bea51d1b12c1 100644 --- a/packages/kit/src/runtime/app/navigation.js +++ b/packages/kit/src/runtime/app/navigation.js @@ -11,6 +11,13 @@ export const disableScrollHandling = /* @__PURE__ */ client_method('disable_scro * 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)`. * + * @type {(url: string | URL, opts?: { + * replaceState?: boolean; + * noScroll?: boolean; + * keepFocus?: boolean; + * invalidateAll?: boolean; + * state?: any + * }) => Promise} * @param {string | URL} url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. * @param {Object} [opts] Options related to the navigation * @param {boolean} [opts.replaceState] If `true`, will replace the current `history` entry rather than creating a new one with `pushState` @@ -37,6 +44,7 @@ export const goto = /* @__PURE__ */ client_method('goto'); * * invalidate((url) => url.pathname === '/path'); * ``` + * @type {(url: string | URL | ((url: URL) => boolean)) => Promise} * @param {string | URL | ((url: URL) => boolean)} url The invalidated URL * @returns {Promise} */ @@ -44,6 +52,7 @@ export const invalidate = /* @__PURE__ */ client_method('invalidate'); /** * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * @type {() => Promise} * @returns {Promise} */ export const invalidateAll = /* @__PURE__ */ client_method('invalidate_all'); @@ -57,6 +66,7 @@ export const invalidateAll = /* @__PURE__ */ client_method('invalidate_all'); * If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. * Returns a Promise that resolves when the preload is complete. * + * @type {(href: string) => Promise} * @param {string} href Page to preload * @returns {Promise} */ @@ -70,6 +80,8 @@ export const preloadData = /* @__PURE__ */ client_method('preload_data'); * * Unlike `preloadData`, this won't call `load` functions. * Returns a Promise that resolves when the modules have been imported. + * + * @type {(...urls: string[]) => Promise} * @param {...string[]} urls * @returns {Promise} */ @@ -83,6 +95,7 @@ export const preloadCode = /* @__PURE__ */ client_method('preload_code'); * When a navigation isn't client side, `navigation.to.route.id` will be `null`. * * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @type {(callback: (navigation: import('@sveltejs/kit').BeforeNavigate) => void) => void} * @param {(navigation: import('@sveltejs/kit').BeforeNavigate) => void} callback * @returns {void} */ @@ -92,6 +105,7 @@ export const beforeNavigate = /* @__PURE__ */ client_method('before_navigate'); * 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. + * @type {(callback: (navigation: import('@sveltejs/kit').AfterNavigate) => void) => void} * @param {(navigation: import('@sveltejs/kit').AfterNavigate) => void} callback * @returns {void} */ diff --git a/packages/kit/src/runtime/client/types.d.ts b/packages/kit/src/runtime/client/types.d.ts index c3e2a916e9b6..8fba78e51e0b 100644 --- a/packages/kit/src/runtime/client/types.d.ts +++ b/packages/kit/src/runtime/client/types.d.ts @@ -1,4 +1,4 @@ -import { applyAction } from '$app/forms'; +import { applyAction } from '../app/forms'; import { afterNavigate, beforeNavigate, @@ -7,18 +7,10 @@ import { invalidateAll, preloadCode, preloadData -} from '$app/navigation'; +} from '../app/navigation'; import { SvelteComponent } from 'svelte'; -import { - ClientHooks, - CSRPageNode, - CSRPageNodeLoader, - CSRRoute, - Page, - ParamMatcher, - TrailingSlash, - Uses -} from 'types'; +import { ClientHooks, CSRPageNode, CSRPageNodeLoader, CSRRoute, TrailingSlash, Uses } from 'types'; +import { Page, ParamMatcher } from '@sveltejs/kit'; export interface SvelteKitApp { /** diff --git a/packages/kit/src/types/private.d.ts b/packages/kit/src/types/private.d.ts index 35c60ffd2ed0..4ead17bc3bff 100644 --- a/packages/kit/src/types/private.d.ts +++ b/packages/kit/src/types/private.d.ts @@ -2,7 +2,7 @@ // but which cannot be imported from `@sveltejs/kit`. Care should // be taken to avoid breaking changes when editing this file -import { RouteDefinition } from '../exports/index.js'; +import { RouteDefinition } from '@sveltejs/kit'; export interface AdapterEntry { /** diff --git a/packages/kit/src/utils/routing.js b/packages/kit/src/utils/routing.js index 9803ac7b6acd..17dec1f53f23 100644 --- a/packages/kit/src/utils/routing.js +++ b/packages/kit/src/utils/routing.js @@ -129,7 +129,7 @@ export function get_route_segments(route) { /** * @param {RegExpMatchArray} match * @param {import('types').RouteParam[]} params - * @param {Record} matchers + * @param {Record} matchers */ export function exec(match, params, matchers) { /** @type {Record} */ diff --git a/packages/kit/tsconfig.json b/packages/kit/tsconfig.json index 23e1a7c0fa31..461ebb2d8c6c 100644 --- a/packages/kit/tsconfig.json +++ b/packages/kit/tsconfig.json @@ -10,8 +10,9 @@ "allowSyntheticDefaultImports": true, "paths": { "@sveltejs/kit": ["./src/exports/public.d.ts"], + "@sveltejs/kit/node": ["./src/exports/node/index.js"], // internal use only - "types": ["src/types/internal"] + "types": ["./src/types/internal"] }, "noUnusedLocals": true, "noUnusedParameters": true From ae74981ef96870621aaabc3e5e11f41b4ece8030 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 19 May 2023 15:54:14 -0400 Subject: [PATCH 04/42] tidy up --- packages/kit/.gitignore | 1 + packages/kit/package.json | 6 +- packages/kit/src/exports/public.d.ts | 10 +- packages/kit/test-types/index.d.ts | 2215 -------------------------- pnpm-lock.yaml | 43 +- 5 files changed, 50 insertions(+), 2225 deletions(-) delete mode 100644 packages/kit/test-types/index.d.ts diff --git a/packages/kit/.gitignore b/packages/kit/.gitignore index b8a64baa8b3f..913a7f9a6583 100644 --- a/packages/kit/.gitignore +++ b/packages/kit/.gitignore @@ -7,6 +7,7 @@ !/src/core/adapt/fixtures/*/.svelte-kit !/test/node_modules /test/apps/basics/test/errors.json +/types .custom-out-dir # these are already ignored by the top level .gitignore diff --git a/packages/kit/package.json b/packages/kit/package.json index 3f685b653afd..c1b92f91afd0 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -15,7 +15,6 @@ "@types/cookie": "^0.5.1", "cookie": "^0.5.0", "devalue": "^4.3.1", - "dts-buddy": "*", "esm-env": "^1.0.0", "kleur": "^4.1.5", "magic-string": "^0.30.0", @@ -34,6 +33,7 @@ "@types/node": "^16.18.6", "@types/sade": "^1.7.4", "@types/set-cookie-parser": "^2.4.2", + "dts-buddy": "^0.0.1", "marked": "^4.2.3", "rollup": "^3.7.0", "svelte": "^3.56.0", @@ -77,15 +77,19 @@ "import": "./src/exports/index.js" }, "./node": { + "types": "./types/index.d.ts", "import": "./src/exports/node/index.js" }, "./node/polyfills": { + "types": "./types/index.d.ts", "import": "./src/exports/node/polyfills.js" }, "./hooks": { + "types": "./types/index.d.ts", "import": "./src/exports/hooks/index.js" }, "./vite": { + "types": "./types/index.d.ts", "import": "./src/exports/vite/index.js" } }, diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index ed2f94ccad61..e817f8ef2eba 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -631,12 +631,10 @@ export interface KitConfig { * 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). */ -export interface Handle { - (input: { - event: RequestEvent; - resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; - }): MaybePromise; -} +export type Handle = (input: { + event: RequestEvent; + resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; +}) => MaybePromise; /** * 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. diff --git a/packages/kit/test-types/index.d.ts b/packages/kit/test-types/index.d.ts deleted file mode 100644 index 74869fb1997d..000000000000 --- a/packages/kit/test-types/index.d.ts +++ /dev/null @@ -1,2215 +0,0 @@ -declare module '@sveltejs/kit' { - import { CompileOptions } from 'svelte/types/compiler/interfaces'; - import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; - - /** - * [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. - */ - export interface Adapter { - /** - * The name of the adapter, using for logging. Will typically correspond to the package name. - */ - name: string; - /** - * This function is called after SvelteKit has built your app. - * */ - adapt(builder: Builder): MaybePromise; - } - - type AwaitedPropertiesUnion | void> = input extends void - ? undefined // needs to be undefined, because void will break intellisense - : input extends Record - ? { - [key in keyof input]: Awaited; - } - : {} extends input // handles the any case - ? input - : unknown; - - export type AwaitedProperties | void> = - AwaitedPropertiesUnion extends Record - ? OptionalUnion> - : AwaitedPropertiesUnion; - - export type AwaitedActions any>> = OptionalUnion< - { - [Key in keyof T]: UnpackValidationError>>; - }[keyof T] - >; - - // Takes a union type and returns a union type where each type also has all properties - // of all possible types (typed as undefined), making accessing them more ergonomic - type OptionalUnion< - U extends Record, // not unknown, else interfaces don't satisfy this constraint - A extends keyof U = U extends U ? keyof U : never - > = U extends unknown ? { [P in Exclude]?: never } & U : never; - - type UnpackValidationError = T extends ActionFailure - ? X - : T extends void - ? undefined // needs to be undefined, because void will corrupt union type - : T; - - /** - * This object is passed to the `adapt` function of adapters. - * It contains various methods and properties that are useful for adapting the app. - */ - export interface Builder { - /** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */ - log: Logger; - /** Remove `dir` and all its contents. */ - rimraf(dir: string): void; - /** Create `dir` and any required parent directories. */ - mkdirp(dir: string): void; - - /** The fully resolved `svelte.config.js`. */ - config: ValidatedConfig; - /** Information about prerendered pages and assets, if any. */ - prerendered: Prerendered; - /** An array of all routes (including prerendered) */ - routes: RouteDefinition[]; - - /** - * Create separate functions that map to one or more routes of your app. - * */ - createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; - - /** - * Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. - */ - generateFallback(dest: string): Promise; - - /** - * Generate a server-side manifest to initialise the SvelteKit [server](https://kit.svelte.dev/docs/types#public-types-server) with. - * */ - generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; - - /** - * Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. - * */ - getBuildDirectory(name: string): string; - /** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */ - getClientDirectory(): string; - /** Get the fully resolved path to the directory containing server-side code. */ - getServerDirectory(): string; - /** Get the application path including any configured `base` path, e.g. `/my-base-path/_app`. */ - getAppPath(): string; - - /** - * Write client assets to `dest`. - * */ - writeClient(dest: string): string[]; - /** - * Write prerendered files to `dest`. - * */ - writePrerendered(dest: string): string[]; - /** - * Write server-side code to `dest`. - * */ - writeServer(dest: string): string[]; - /** - * Copy a file or directory. - * */ - copy( - from: string, - to: string, - opts?: { - filter?(basename: string): boolean; - replace?: Record; - } - ): string[]; - - /** - * Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. - * */ - compress(directory: string): Promise; - } - - export interface Config { - /** - * Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). - * */ - compilerOptions?: CompileOptions; - /** - * List of file extensions that should be treated as Svelte files. - * */ - extensions?: string[]; - /** SvelteKit options */ - kit?: KitConfig; - /** [`@sveltejs/package`](/docs/packaging) options. */ - package?: { - source?: string; - dir?: string; - emitTypes?: boolean; - exports?(filepath: string): boolean; - files?(filepath: string): boolean; - }; - /** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */ - preprocess?: any; - /** `vite-plugin-svelte` plugin options. */ - vitePlugin?: PluginOptions; - /** Any additional options required by tooling that integrates with Svelte. */ - [key: string]: any; - } - - export interface Cookies { - /** - * Gets a cookie that was previously set with `cookies.set`, or from the request headers. - * */ - get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; - - /** - * Gets all cookies that were previously set with `cookies.set`, or from the request headers. - * */ - getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; - - /** - * 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`. - * - * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. - * */ - set(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): void; - - /** - * Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. - * - * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. - * */ - delete(name: string, opts?: import('cookie').CookieSerializeOptions): void; - - /** - * 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`. - * - * By default, the `path` of a cookie is the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. - * - * */ - serialize(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): string; - } - - export interface KitConfig { - /** - * Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. - * */ - adapter?: Adapter; - /** - * An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. - * - * ```js - * /// 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`. - * */ - alias?: Record; - /** - * The directory relative to `paths.assets` where the built JS and CSS (and imported assets) are served from. (The filenames therein contain content-based hashes, meaning they can be cached indefinitely). Must not start or end with `/`. - * */ - appDir?: string; - /** - * [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 - * /// 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/modules#$app-stores-updated) store to `true` when it detects one. - */ - version?: { - /** - * 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 - * /// 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() - * } - * } - * }; - * ``` - */ - name?: string; - /** - * The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. - * */ - pollInterval?: number; - }; - } - - /** - * 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). - */ - export interface Handle { - (input: { - event: RequestEvent; - resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; - }): MaybePromise; - } - - /** - * 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. - */ - export interface HandleServerError { - (input: { error: unknown; event: RequestEvent }): MaybePromise; - } - - /** - * 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. - */ - export interface HandleClientError { - (input: { error: unknown; event: NavigationEvent }): MaybePromise; - } - - /** - * 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) - */ - export interface HandleFetch { - (input: { event: RequestEvent; request: Request; fetch: typeof fetch }): MaybePromise; - } - - /** - * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) - * rather than using `Load` directly. - */ - export interface Load< - Params extends Partial> = Partial>, - InputData extends Record | null = Record | null, - ParentData extends Record = Record, - OutputData extends Record | void = Record | void, - RouteId extends string | null = string | null - > { - (event: LoadEvent): MaybePromise; - } - - /** - * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) - * rather than using `LoadEvent` directly. - */ - export interface LoadEvent< - Params extends Partial> = Partial>, - Data extends Record | null = Record | null, - ParentData extends Record = Record, - RouteId extends string | null = string | null - > extends NavigationEvent { - /** - * `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. 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 - * - * > Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it. - */ - fetch: typeof fetch; - /** - * Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. - */ - data: Data; - /** - * 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 - * /// 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`](https://kit.svelte.dev/docs/types#public-types-cookies) API in a server-only `load` function instead. - * - * `setHeaders` has no effect when a `load` function runs in the browser. - */ - setHeaders(headers: Record): void; - /** - * `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. - */ - parent(): Promise; - /** - * 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/modules#$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 - * /// 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}

- * - * ``` - */ - depends(...deps: string[]): void; - } - - export interface NavigationEvent< - Params extends Partial> = Partial>, - RouteId extends string | null = string | null - > { - /** - * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object - */ - params: Params; - /** - * Info about the current route - */ - route: { - /** - * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` - */ - id: RouteId; - }; - /** - * The URL of the current page - */ - url: URL; - } - - /** - * Information about the target of a specific navigation. - */ - export interface NavigationTarget { - /** - * 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). - */ - params: Record | null; - /** - * Info about the target route - */ - route: { id: string | null }; - /** - * The URL that is navigated to - */ - url: URL; - } - - /** - * - `enter`: The app has hydrated - * - `form`: The user submitted a `` - * - `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 - */ - export type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; - - export interface Navigation { - /** - * Where navigation was triggered from - */ - from: NavigationTarget | null; - /** - * Where navigation is going to/has gone to - */ - to: NavigationTarget | null; - /** - * The type of navigation: - * - `form`: The user submitted a `` - * - `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 - */ - type: Omit; - /** - * Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) - */ - willUnload: boolean; - /** - * In case of a history back/forward navigation, the number of steps to go back/forward - */ - delta?: number; - } - - /** - * The argument passed to [`beforeNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate) callbacks. - */ - export interface BeforeNavigate extends Navigation { - /** - * Call this to prevent the navigation from starting. - */ - cancel(): void; - } - - /** - * The argument passed to [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks. - */ - export interface AfterNavigate extends Navigation { - /** - * 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 - */ - type: Omit; - /** - * Since `afterNavigate` is called after a navigation completes, it will never be called with a navigation that unloads the page. - */ - willUnload: false; - } - - /** - * The shape of the `$page` store - */ - export interface Page< - Params extends Record = Record, - RouteId extends string | null = string | null - > { - /** - * The URL of the current page - */ - url: URL; - /** - * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object - */ - params: Params; - /** - * Info about the current route - */ - route: { - /** - * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` - */ - id: RouteId; - }; - /** - * Http status code of the current page - */ - status: number; - /** - * The error object of the current page, if any. Filled from the `handleError` hooks. - */ - error: App.Error | null; - /** - * The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. - */ - data: App.PageData & Record; - /** - * Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. - */ - form: any; - } - - /** - * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. - */ - export interface ParamMatcher { - (param: string): boolean; - } - - export interface RequestEvent< - Params extends Partial> = Partial>, - RouteId extends string | null = string | null - > { - /** - * Get or set cookies related to the current request - */ - cookies: Cookies; - /** - * `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 - * - * > Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it. - */ - fetch: typeof fetch; - /** - * The client's IP address, set by the adapter. - */ - getClientAddress(): string; - /** - * Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). - */ - locals: App.Locals; - /** - * The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object - */ - params: Params; - /** - * Additional data made available through the adapter. - */ - platform: Readonly | undefined; - /** - * The original request object - */ - request: Request; - /** - * Info about the current route - */ - route: { - /** - * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` - */ - id: RouteId; - }; - /** - * 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 - * /// 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`](https://kit.svelte.dev/docs/types#public-types-cookies) API instead. - */ - setHeaders(headers: Record): void; - /** - * The requested URL. - */ - url: URL; - /** - * `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. - */ - isDataRequest: boolean; - } - - /** - * 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](https://kit.svelte.dev/docs/types#generated-types) instead. - */ - export interface RequestHandler< - Params extends Partial> = Partial>, - RouteId extends string | null = string | null - > { - (event: RequestEvent): MaybePromise; - } - - export interface ResolveOptions { - /** - * 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. - * */ - transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; - /** - * Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. - * By default, none will be included. - * */ - filterSerializedResponseHeaders?(name: string, value: string): boolean; - /** - * Determines what should be added to the `` tag to preload it. - * By default, `js`, `css` and `font` files will be preloaded. - * */ - preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; - } - - export interface RouteDefinition { - id: string; - api: { - methods: HttpMethod[]; - }; - page: { - methods: Extract[]; - }; - pattern: RegExp; - prerender: PrerenderOption; - segments: RouteSegment[]; - methods: HttpMethod[]; - config: Config; - } - - export class Server { - constructor(manifest: SSRManifest); - init(options: ServerInitOptions): Promise; - respond(request: Request, options: RequestOptions): Promise; - } - - export interface ServerInitOptions { - env: Record; - } - - export interface SSRManifest { - appDir: string; - appPath: string; - assets: Set; - mimeTypes: Record; - - /** private fields */ - _: { - client: NonNullable; - nodes: SSRNodeLoader[]; - routes: SSRRoute[]; - matchers(): Promise>; - }; - } - - /** - * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) - * rather than using `ServerLoad` directly. - */ - export interface ServerLoad< - Params extends Partial> = Partial>, - ParentData extends Record = Record, - OutputData extends Record | void = Record | void, - RouteId extends string | null = string | null - > { - (event: ServerLoadEvent): MaybePromise; - } - - export interface ServerLoadEvent< - Params extends Partial> = Partial>, - ParentData extends Record = Record, - RouteId extends string | null = string | null - > extends RequestEvent { - /** - * `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. - */ - parent(): Promise; - /** - * 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/modules#$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 - * /// 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}

- * - * ``` - */ - depends(...deps: string[]): void; - } - - /** - * 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. - */ - export interface Action< - Params extends Partial> = Partial>, - OutputData extends Record | void = Record | void, - RouteId extends string | null = string | null - > { - (event: RequestEvent): MaybePromise; - } - - /** - * Shape of the `export const actions = {..}` object in `+page.server.js`. - * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. - */ - export type Actions< - Params extends Partial> = Partial>, - OutputData extends Record | void = Record | void, - RouteId extends string | null = string | null - > = Record>; - - /** - * When calling a form action via fetch, the response will be one of these shapes. - * ```svelte - * { - * return ({ result }) => { - * // result is of type ActionResult - * }; - * }} - * ``` - */ - export 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 }; - - /** - * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. - */ - export interface HttpError { - /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ - status: number; - /** The content of the error. */ - body: App.Error; - } - - /** - * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function - */ - export interface Redirect { - /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */ - status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; - /** The location to redirect to. */ - location: string; - } - - /** - * The object returned by the [`fail`](https://kit.svelte.dev/docs/modules#sveltejs-kit-fail) function - */ - export interface ActionFailure | undefined = undefined> - extends UniqueInterface { - /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ - status: number; - /** Data associated with the failure (e.g. validation errors) */ - data: T; - } - - export interface SubmitFunction< - Success extends Record | undefined = Record, - Failure extends Record | undefined = Record - > { - (input: { - action: URL; - /** - * use `formData` instead of `data` - * */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * */ - form: HTMLFormElement; - formElement: HTMLFormElement; - controller: AbortController; - submitter: HTMLElement | null; - cancel(): void; - }): MaybePromise< - | void - | ((opts: { - /** - * use `formData` instead of `data` - * */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * */ - form: HTMLFormElement; - formElement: HTMLFormElement; - action: URL; - result: ActionResult; - /** - * Call this to get the default behavior of a form submission response. - * */ - update(options?: { reset: boolean }): Promise; - }) => void) - >; - } - - /** - * The type of `export const snapshot` exported from a page or layout component. - */ - export interface Snapshot { - capture: () => T; - restore: (snapshot: T) => void; - } - export interface AdapterEntry { - /** - * 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 - */ - id: string; - - /** - * 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 - */ - filter(route: RouteDefinition): boolean; - - /** - * 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. - */ - complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise; - } - - // Based on https://github.com/josh-hemphill/csp-typed-directives/blob/latest/src/csp.types.ts - // - // MIT License - // - // Copyright (c) 2021-present, Joshua Hemphill - // Copyright (c) 2021, Tecnico Corporation - // - // Permission is hereby granted, free of charge, to any person obtaining a copy - // of this software and associated documentation files (the "Software"), to deal - // in the Software without restriction, including without limitation the rights - // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - // copies of the Software, and to permit persons to whom the Software is - // furnished to do so, subject to the following conditions: - // - // The above copyright notice and this permission notice shall be included in all - // copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - // SOFTWARE. - - export 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[]; - type UriPath = `${HttpDelineator}${string}`; - } - - export interface CspDirectives { - 'child-src'?: Csp.Sources; - 'default-src'?: Array; - 'frame-src'?: Csp.Sources; - 'worker-src'?: Csp.Sources; - 'connect-src'?: Csp.Sources; - 'font-src'?: Csp.Sources; - 'img-src'?: Csp.Sources; - 'manifest-src'?: Csp.Sources; - 'media-src'?: Csp.Sources; - 'object-src'?: Csp.Sources; - 'prefetch-src'?: Csp.Sources; - 'script-src'?: Array; - 'script-src-elem'?: Csp.Sources; - 'script-src-attr'?: Csp.Sources; - 'style-src'?: Array; - 'style-src-elem'?: Csp.Sources; - 'style-src-attr'?: Csp.Sources; - 'base-uri'?: Array; - 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' - >; - 'form-action'?: Array; - 'frame-ancestors'?: Array; - 'navigate-to'?: Array; - 'report-uri'?: Csp.UriPath[]; - 'report-to'?: string[]; - - 'require-trusted-types-for'?: Array<'script'>; - 'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; - 'upgrade-insecure-requests'?: boolean; - - - 'require-sri-for'?: Array<'script' | 'style' | 'script style'>; - - - 'block-all-mixed-content'?: boolean; - - - 'plugin-types'?: Array<`${string}/${string}` | 'none'>; - - - 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' - >; - } - - export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; - - export interface Logger { - (msg: string): void; - success(msg: string): void; - error(msg: string): void; - warn(msg: string): void; - minor(msg: string): void; - info(msg: string): void; - } - - export type MaybePromise = T | Promise; - - export interface Prerendered { - /** - * 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`. - */ - pages: Map< - string, - { - /** The location of the .html file relative to the output directory */ - file: string; - } - >; - /** - * A map of `path` to `{ type }` objects. - */ - assets: Map< - string, - { - /** The MIME type of the asset */ - type: string; - } - >; - /** - * A map of redirects encountered during prerendering. - */ - redirects: Map< - string, - { - status: number; - location: string; - } - >; - /** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */ - paths: string[]; - } - - export interface PrerenderHttpErrorHandler { - (details: { - status: number; - path: string; - referrer: string | null; - referenceType: 'linked' | 'fetched'; - message: string; - }): void; - } - - export interface PrerenderMissingIdHandler { - (details: { path: string; id: string; referrers: string[]; message: string }): void; - } - - export interface PrerenderEntryGeneratorMismatchHandler { - (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; - } - - export type PrerenderHttpErrorHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; - export type PrerenderMissingIdHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; - export type PrerenderEntryGeneratorMismatchHandlerValue = - | 'fail' - | 'warn' - | 'ignore' - | PrerenderEntryGeneratorMismatchHandler; - - export type PrerenderOption = boolean | 'auto'; - - export type PrerenderMap = Map; - - export interface RequestOptions { - getClientAddress(): string; - platform?: App.Platform; - } - - export interface RouteSegment { - content: string; - dynamic: boolean; - rest: boolean; - } - - export type TrailingSlash = 'never' | 'always' | 'ignore'; - - /** - * This doesn't actually exist, it's a way to better distinguish the type - */ - export const uniqueSymbol: unique symbol; - - export interface UniqueInterface { - readonly [uniqueSymbol]: unknown; - } - import { SvelteComponent } from 'svelte/internal'; - - export interface ServerModule { - Server: typeof InternalServer; - } - - export interface ServerInternalModule { - set_building(building: boolean): void; - set_assets(path: string): void; - set_private_env(environment: Record): void; - set_public_env(environment: Record): void; - set_version(version: string): void; - set_fix_stack_trace(fix_stack_trace: (stack: string) => string): void; - } - - export interface Asset { - file: string; - size: number; - type: string | null; - } - - export interface AssetDependencies { - file: string; - imports: string[]; - stylesheets: string[]; - fonts: string[]; - } - - export interface BuildData { - app_dir: string; - app_path: string; - manifest_data: ManifestData; - service_worker: string | null; - client: { - start: string; - app: string; - imports: string[]; - stylesheets: string[]; - fonts: string[]; - } | null; - server_manifest: import('vite').Manifest; - } - - export interface CSRPageNode { - component: typeof SvelteComponent; - universal: { - load?: Load; - trailingSlash?: TrailingSlash; - }; - } - - export type CSRPageNodeLoader = () => Promise; - - /** - * Definition of a client side route. - * The boolean in the tuples indicates whether the route has a server load. - */ - export type CSRRoute = { - id: string; - exec(path: string): undefined | Record; - errors: Array; - layouts: Array<[has_server_load: boolean, node_loader: CSRPageNodeLoader] | undefined>; - leaf: [has_server_load: boolean, node_loader: CSRPageNodeLoader]; - }; - - export interface Deferred { - fulfil: (value: any) => void; - reject: (error: Error) => void; - } - - export type GetParams = (match: RegExpExecArray) => Record; - - export interface ServerHooks { - handleFetch: HandleFetch; - handle: Handle; - handleError: HandleServerError; - } - - export interface ClientHooks { - handleError: HandleClientError; - } - - export interface Env { - private: Record; - public: Record; - } - - export class InternalServer extends Server { - init(options: ServerInitOptions): Promise; - respond( - request: Request, - options: RequestOptions & { - prerendering?: PrerenderOptions; - read: (file: string) => Buffer; - } - ): Promise; - } - - export interface ManifestData { - assets: Asset[]; - nodes: PageNode[]; - routes: RouteData[]; - matchers: Record; - } - - export interface PageNode { - depth: number; - component?: string; // TODO supply default component if it's missing (bit of an edge case) - universal?: string; - server?: string; - parent_id?: string; - parent?: PageNode; - /** - * Filled with the pages that reference this layout (if this is a layout) - */ - child_pages?: PageNode[]; - } - - export interface PrerenderDependency { - response: Response; - body: null | string | Uint8Array; - } - - export interface PrerenderOptions { - cache?: string; // including this here is a bit of a hack, but it makes it easy to add - fallback?: boolean; - dependencies: Map; - } - - export type RecursiveRequired = { - // Recursive implementation of TypeScript's Required utility type. - // Will recursively continue until it reaches a primitive or Function - [K in keyof T]-?: Extract extends never // If it does not have a Function type - ? RecursiveRequired // recursively continue through. - : T[K]; // Use the exact type for everything else - }; - - export type RequiredResolveOptions = Required; - - export interface RouteParam { - name: string; - matcher: string; - optional: boolean; - rest: boolean; - chained: boolean; - } - - /** - * Represents a route segment in the app. It can either be an intermediate node - * with only layout/error pages, or a leaf, at which point either `page` and `leaf` - * or `endpoint` is set. - */ - export interface RouteData { - id: string; - parent: RouteData | null; - - segment: string; - pattern: RegExp; - params: RouteParam[]; - - layout: PageNode | null; - error: PageNode | null; - leaf: PageNode | null; - - page: { - layouts: Array; - errors: Array; - leaf: number; - } | null; - - endpoint: { - file: string; - } | null; - } - - export type ServerRedirectNode = { - type: 'redirect'; - location: string; - }; - - export type ServerNodesResponse = { - type: 'data'; - /** - * If `null`, then there was no load function <- TODO is this outdated now with the recent changes? - */ - nodes: Array; - }; - - export type ServerDataResponse = ServerRedirectNode | ServerNodesResponse; - - /** - * Signals a successful response of the server `load` function. - * The `uses` property tells the client when it's possible to reuse this data - * in a subsequent request. - */ - export interface ServerDataNode { - type: 'data'; - /** - * The serialized version of this contains a serialized representation of any deferred promises, - * which will be resolved later through chunk nodes. - */ - data: Record | null; - uses: Uses; - slash?: TrailingSlash; - } - - /** - * Resolved data/error of a deferred promise. - */ - export interface ServerDataChunkNode { - type: 'chunk'; - id: number; - data?: Record; - error?: any; - } - - /** - * Signals that the server `load` function was not run, and the - * client should use what it has in memory - */ - export interface ServerDataSkippedNode { - type: 'skip'; - } - - /** - * Signals that the server `load` function failed - */ - export interface ServerErrorNode { - type: 'error'; - error: App.Error; - /** - * Only set for HttpErrors - */ - status?: number; - } - - export interface ServerMetadataRoute { - config: any; - api: { - methods: HttpMethod[]; - }; - page: { - methods: Array<'GET' | 'POST'>; - }; - methods: HttpMethod[]; - prerender: PrerenderOption | undefined; - entries: Array | undefined; - } - - export interface ServerMetadata { - nodes: Array<{ has_server_load: boolean }>; - routes: Map; - } - - export interface SSRComponent { - default: { - render(props: Record): { - html: string; - head: string; - css: { - code: string; - map: any; // TODO - }; - }; - }; - } - - export type SSRComponentLoader = () => Promise; - - export interface SSRNode { - component: SSRComponentLoader; - /** index into the `components` array in client/manifest.js */ - index: number; - /** external JS files */ - imports: string[]; - /** external CSS files */ - stylesheets: string[]; - /** external font files */ - fonts: string[]; - /** inlined styles */ - inline_styles?(): MaybePromise>; - - universal: { - load?: Load; - prerender?: PrerenderOption; - ssr?: boolean; - csr?: boolean; - trailingSlash?: TrailingSlash; - config?: any; - entries?: PrerenderEntryGenerator; - }; - - server: { - load?: ServerLoad; - prerender?: PrerenderOption; - ssr?: boolean; - csr?: boolean; - trailingSlash?: TrailingSlash; - actions?: Actions; - config?: any; - entries?: PrerenderEntryGenerator; - }; - - universal_id: string; - server_id: string; - } - - export type SSRNodeLoader = () => Promise; - - export interface SSROptions { - app_template_contains_nonce: boolean; - csp: ValidatedConfig['kit']['csp']; - csrf_check_origin: boolean; - track_server_fetches: boolean; - embedded: boolean; - env_public_prefix: string; - hooks: ServerHooks; - preload_strategy: ValidatedConfig['kit']['output']['preloadStrategy']; - root: SSRComponent['default']; - service_worker: boolean; - templates: { - app(values: { - head: string; - body: string; - assets: string; - nonce: string; - env: Record; - }): string; - error(values: { message: string; status: number }): string; - }; - version_hash: string; - } - - export interface PageNodeIndexes { - errors: Array; - layouts: Array; - leaf: number; - } - - export type PrerenderEntryGenerator = () => MaybePromise>>; - - export type SSREndpoint = Partial> & { - prerender?: PrerenderOption; - trailingSlash?: TrailingSlash; - config?: any; - entries?: PrerenderEntryGenerator; - }; - - export interface SSRRoute { - id: string; - pattern: RegExp; - params: RouteParam[]; - page: PageNodeIndexes | null; - endpoint: (() => Promise) | null; - endpoint_id?: string; - } - - export interface SSRState { - fallback?: string; - getClientAddress(): string; - /** - * True if we're currently attempting to render an error page - */ - error: boolean; - /** - * Allows us to prevent `event.fetch` from making infinitely looping internal requests - */ - depth: number; - platform?: any; - prerendering?: PrerenderOptions; - /** - * When fetching data from a +server.js endpoint in `load`, the page's - * prerender option is inherited by the endpoint, unless overridden - */ - prerender_default?: PrerenderOption; - read?: (file: string) => Buffer; - } - - export type StrictBody = string | ArrayBufferView; - - export interface Uses { - dependencies: Set; - params: Set; - parent: boolean; - route: boolean; - url: boolean; - } - - export type ValidatedConfig = RecursiveRequired; - - export type ValidatedKitConfig = RecursiveRequired; - export function error(status: number, body: App.Error): { - status: number; - body: App.Error; - toString(): string; - }; - export function error(status: number, body?: { - message: string; - } extends App.Error ? App.Error | string | undefined : never): { - status: number; - body: App.Error; - toString(): string; - }; - /** - * Create a `Redirect` object. If thrown 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. - * */ - export function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, location: string): { - status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; - location: string; - }; - /** - * Create a JSON `Response` object from the supplied data. - * */ - export function json(data: any, init?: ResponseInit | undefined): Response; - /** - * Create a `Response` object from the supplied body. - * */ - export function text(body: string, init?: ResponseInit | undefined): Response; - /** - * Create an `ActionFailure` object. - * */ - export function fail(status: number, data?: Record | undefined): { - status: number; - data: Record | undefined; - }; - /** - * Populate a route ID with params to resolve a pathname. - * */ - export function resolvePath(id: string, params: Record): string; -} - -declare module '@sveltejs/kit/hooks' { - - /** - * 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 - * /// 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 - * ``` - * - * */ - export function sequence(...handlers: import('@sveltejs/kit').Handle[]): import('@sveltejs/kit').Handle; -} - -declare module '@sveltejs/kit/node' { - export function getRequest({ request, base, bodySizeLimit }: { - request: any; - base: any; - bodySizeLimit: any; - }): Promise; - - export function setResponse(res: any, response: any): Promise; -} - -declare module '@sveltejs/kit/node/polyfills' { - /** - * Make various web APIs available as globals: - * - `crypto` - * - `fetch` - * - `Headers` - * - `Request` - * - `Response` - */ - export function installPolyfills(): void; -} - -declare module '@sveltejs/kit/vite' { - /** - * Returns the SvelteKit Vite plugins. - * */ - export function sveltekit(): Promise; - export { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; -} - -declare module '$app/environment' { - /** - * `true` if the app is running in the browser. - */ - export const browser: boolean; - /** - * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. - */ - export const dev: boolean; - export { building, version } from "__sveltekit/environment"; -} - -declare module '$app/forms' { - /** - * Use this function to deserialize the response from a form submission. - * Usage: - * - * ```js - * 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()); - * // ... - * } - * ``` - * */ - export function deserialize | undefined, Invalid_1 extends Record | undefined>(result: string): import("@sveltejs/kit").ActionResult; - /** - * 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 one 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. - * */ - export function enhance | undefined, Invalid_1 extends Record | undefined>(form_element: HTMLFormElement, submit?: import("@sveltejs/kit").SubmitFunction): { - destroy(): void; - }; - /** - * 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. - * */ - export const applyAction: any; -} - -declare module '$app/navigation' { - /** - * 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. - * */ - export const disableScrollHandling: () => void; - /** - * 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)`. - * - * */ - export const goto: any; - /** - * 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'); - * ``` - * */ - export const invalidate: any; - /** - * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. - * */ - export const invalidateAll: any; - /** - * 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 when the preload is complete. - * - * */ - export const preloadData: any; - /** - * 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. - * */ - export const preloadCode: any; - /** - * 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 the navigation would have directly unloaded the current page, calling `cancel` will trigger the native - * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. - * - * When a navigation isn't client side, `navigation.to.route.id` will be `null`. - * - * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. - * */ - export const beforeNavigate: any; - /** - * 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. - * */ - export const afterNavigate: any; -} - -declare module '$app/paths' { - /** - * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). - * - * Example usage: `Link` - */ - export const base: "" | `/${string}`; - /** - * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. - */ - export const assets: "" | `http://${string}` | `https://${string}` | "/_svelte_kit_assets"; -} - -declare module '$app/stores' { - export function getStores(): { - - page: typeof page; - - navigating: typeof navigating; - - updated: typeof updated; - }; - /** - * 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. - * - * */ - export const page: import('svelte/store').Readable; - /** - * 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. - * */ - export const navigating: import('svelte/store').Readable; - /** - * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/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. - * */ - export const updated: import('svelte/store').Readable & { - check(): Promise; - }; -} - -/** - * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: - * - * ```ts - * declare global { - * namespace App { - * // interface Error {} - * // interface Locals {} - * // interface PageData {} - * // interface Platform {} - * } - * } - * - * export {}; - * ``` - * - * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. - * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. - * - * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. - */ -declare namespace App { - /** - * 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. - */ - export interface Error { - message: string; - } - - /** - * 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. - */ - export interface Locals {} - - /** - * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$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`). - */ - export interface PageData {} - - /** - * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. - */ - export interface Platform {} -} - -/** - * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). - */ -declare module '$service-worker' { - /** - * 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. - */ - export const base: string; - /** - * 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. - */ - export const build: string[]; - /** - * 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`](https://kit.svelte.dev/docs/configuration) - */ - export const files: string[]; - /** - * An array of pathnames corresponding to prerendered pages and endpoints. - * During development, this is an empty array. - */ - export const prerendered: string[]; - /** - * See [`config.kit.version`](https://kit.svelte.dev/docs/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. - */ - export const version: string; -} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bbb95d2a9557..33ff9429d33e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -375,9 +375,6 @@ importers: devalue: specifier: ^4.3.1 version: 4.3.1 - dts-buddy: - specifier: '*' - version: link:../../../../../dts-buddy esm-env: specifier: ^1.0.0 version: 1.0.0 @@ -427,6 +424,9 @@ importers: '@types/set-cookie-parser': specifier: ^2.4.2 version: 2.4.2 + dts-buddy: + specifier: ^0.0.1 + version: 0.0.1 marked: specifier: ^4.2.3 version: 4.2.3 @@ -1527,11 +1527,32 @@ packages: engines: {node: '>=8'} dev: true + /@jridgewell/gen-mapping@0.3.3: + resolution: {integrity: sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==} + engines: {node: '>=6.0.0'} + dependencies: + '@jridgewell/set-array': 1.1.2 + '@jridgewell/sourcemap-codec': 1.4.15 + '@jridgewell/trace-mapping': 0.3.17 + dev: true + /@jridgewell/resolve-uri@3.1.0: resolution: {integrity: sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==} engines: {node: '>=6.0.0'} dev: true + /@jridgewell/set-array@1.1.2: + resolution: {integrity: sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==} + engines: {node: '>=6.0.0'} + dev: true + + /@jridgewell/source-map@0.3.3: + resolution: {integrity: sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg==} + dependencies: + '@jridgewell/gen-mapping': 0.3.3 + '@jridgewell/trace-mapping': 0.3.17 + dev: true + /@jridgewell/sourcemap-codec@1.4.14: resolution: {integrity: sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==} @@ -2844,6 +2865,16 @@ packages: engines: {node: '>=12'} dev: true + /dts-buddy@0.0.1: + resolution: {integrity: sha512-VKiLpfxCLHrvWdu+Cv+tz4cexL/cFMOWPvGaJU2R/vE/j+HV6zTLU83Q1xuwC0A9oMfUXy7h11e7IbLd5WYxeg==} + dependencies: + '@jridgewell/source-map': 0.3.3 + globrex: 0.1.2 + magic-string: 0.30.0 + tiny-glob: 0.2.9 + typescript: 5.0.4 + dev: true + /emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -5694,6 +5725,12 @@ packages: hasBin: true dev: true + /typescript@5.0.4: + resolution: {integrity: sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==} + engines: {node: '>=12.20'} + hasBin: true + dev: true + /ufo@1.1.2: resolution: {integrity: sha512-TrY6DsjTQQgyS3E3dBaOXf0TpPD8u9FVrVYmKVegJuFw51n/YB9XPt+U6ydzFG5ZIN7+DIjPbNmXoBj9esYhgQ==} dev: true From 595d003a3196a44421c443db1b396fbec13b6aa2 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 19 May 2023 15:55:59 -0400 Subject: [PATCH 05/42] rename --- packages/kit/scripts/generate-dts.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/kit/scripts/generate-dts.js b/packages/kit/scripts/generate-dts.js index 759780337287..8eeffb5b2f82 100644 --- a/packages/kit/scripts/generate-dts.js +++ b/packages/kit/scripts/generate-dts.js @@ -1,6 +1,6 @@ -import { createModuleDeclarations } from 'dts-buddy'; +import { createBundle } from 'dts-buddy'; -createModuleDeclarations({ +createBundle({ output: 'types/index.d.ts', modules: { '@sveltejs/kit': 'src/exports/public.d.ts', From ed7ffcd689a2b26347393239ded6e7d4283653f2 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 19 May 2023 16:30:35 -0400 Subject: [PATCH 06/42] format --- packages/kit/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/kit/package.json b/packages/kit/package.json index c1b92f91afd0..c203702f849a 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -97,4 +97,4 @@ "engines": { "node": "^16.14 || >=18" } -} \ No newline at end of file +} From a252c27063188b80a38c7c4bc75f2dd8be6bdc98 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 19 May 2023 18:07:37 -0400 Subject: [PATCH 07/42] bump dts-buddy --- packages/kit/package.json | 2 +- pnpm-lock.yaml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/kit/package.json b/packages/kit/package.json index c203702f849a..c4aa4c978f47 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -33,7 +33,7 @@ "@types/node": "^16.18.6", "@types/sade": "^1.7.4", "@types/set-cookie-parser": "^2.4.2", - "dts-buddy": "^0.0.1", + "dts-buddy": "^0.0.2", "marked": "^4.2.3", "rollup": "^3.7.0", "svelte": "^3.56.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 33ff9429d33e..2b6ed53dc674 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -425,8 +425,8 @@ importers: specifier: ^2.4.2 version: 2.4.2 dts-buddy: - specifier: ^0.0.1 - version: 0.0.1 + specifier: ^0.0.2 + version: 0.0.2 marked: specifier: ^4.2.3 version: 4.2.3 @@ -2865,8 +2865,8 @@ packages: engines: {node: '>=12'} dev: true - /dts-buddy@0.0.1: - resolution: {integrity: sha512-VKiLpfxCLHrvWdu+Cv+tz4cexL/cFMOWPvGaJU2R/vE/j+HV6zTLU83Q1xuwC0A9oMfUXy7h11e7IbLd5WYxeg==} + /dts-buddy@0.0.2: + resolution: {integrity: sha512-A1AA4zWn6+AtnBZGRFtyMMayJ6CXfCTTIxxzTYpeqWy1Qjf/tK9Wp2LFgu0e/mgQuoUUowEjj26yZ64TwB/0gA==} dependencies: '@jridgewell/source-map': 0.3.3 globrex: 0.1.2 From 1f4160d991c826ebbdddff9bdd1b4a358ca87017 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 13:21:00 -0400 Subject: [PATCH 08/42] bump --- packages/kit/package.json | 2 +- pnpm-lock.yaml | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/kit/package.json b/packages/kit/package.json index c4aa4c978f47..5c50b082216f 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -33,7 +33,7 @@ "@types/node": "^16.18.6", "@types/sade": "^1.7.4", "@types/set-cookie-parser": "^2.4.2", - "dts-buddy": "^0.0.2", + "dts-buddy": "^0.0.6", "marked": "^4.2.3", "rollup": "^3.7.0", "svelte": "^3.56.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2b6ed53dc674..bd628ee6361c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -425,8 +425,8 @@ importers: specifier: ^2.4.2 version: 2.4.2 dts-buddy: - specifier: ^0.0.2 - version: 0.0.2 + specifier: ^0.0.6 + version: 0.0.6 marked: specifier: ^4.2.3 version: 4.2.3 @@ -2865,12 +2865,17 @@ packages: engines: {node: '>=12'} dev: true - /dts-buddy@0.0.2: - resolution: {integrity: sha512-A1AA4zWn6+AtnBZGRFtyMMayJ6CXfCTTIxxzTYpeqWy1Qjf/tK9Wp2LFgu0e/mgQuoUUowEjj26yZ64TwB/0gA==} + /dts-buddy@0.0.6: + resolution: {integrity: sha512-WBLk0YOF/vMzv1uqd3uQewEirDHKgfBGbf5LgE43e1rolKDOrbpPlhmhllmUp2aiT0ZAA+TvKoJgpnPqSPGAPQ==} + hasBin: true dependencies: '@jridgewell/source-map': 0.3.3 + '@jridgewell/sourcemap-codec': 1.4.15 globrex: 0.1.2 + kleur: 4.1.5 + locate-character: 2.0.5 magic-string: 0.30.0 + sade: 1.8.1 tiny-glob: 0.2.9 typescript: 5.0.4 dev: true @@ -3982,6 +3987,10 @@ packages: engines: {node: '>=14'} dev: true + /locate-character@2.0.5: + resolution: {integrity: sha512-n2GmejDXtOPBAZdIiEFy5dJ5N38xBCXLNOtw2WpB9kGh6pnrEuKlwYI+Tkpofc4wDtVXHtoAOJaMRlYG/oYaxg==} + dev: true + /locate-path@2.0.0: resolution: {integrity: sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA==} engines: {node: '>=4'} From db03744fc78dc61bdaf03a2de2bcd1f736ce4004 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 13:29:13 -0400 Subject: [PATCH 09/42] add prepublishOnly script --- packages/kit/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/kit/package.json b/packages/kit/package.json index 5c50b082216f..d76bab36c12e 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -68,7 +68,8 @@ "test:cross-platform:dev": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:dev", "test:cross-platform:build": "pnpm test:unit && pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:build", "test:unit": "vitest --config kit.vitest.config.js run", - "postinstall": "node postinstall.js" + "postinstall": "node postinstall.js", + "prepublishOnly": "node scripts/generate-dts.js" }, "exports": { "./package.json": "./package.json", From b802f6ca3834d7c7202666ccea2f132733a216c1 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 13:49:02 -0400 Subject: [PATCH 10/42] build types before running check --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index d77aca05bec6..5c916d430b3a 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "test:cross-platform:build": "pnpm run --dir packages/kit test:cross-platform:build", "test:vite-ecosystem-ci": "pnpm test --dir packages/kit", "test:create-svelte": "pnpm run --dir packages/create-svelte test", - "check": "pnpm -r check", + "check": "pnpm -r prepublishOnly && pnpm -r check", "lint": "pnpm -r lint && eslint 'packages/**/*.js'", "format": "pnpm -r format", "precommit": "pnpm format && pnpm lint", From 6f7a4fedbb02c19070239df99bb53ae8c5d32f33 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 15:16:12 -0400 Subject: [PATCH 11/42] Invalid should be Failure --- packages/kit/src/runtime/app/forms.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/kit/src/runtime/app/forms.js b/packages/kit/src/runtime/app/forms.js index d711bff758f2..a723aac08fc5 100644 --- a/packages/kit/src/runtime/app/forms.js +++ b/packages/kit/src/runtime/app/forms.js @@ -7,9 +7,9 @@ import { invalidateAll } from './navigation.js'; * 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. * @template {Record | undefined} Success - * @template {Record | undefined} Invalid - * @type {(result: import('@sveltejs/kit').ActionResult) => void} - * @param {import('@sveltejs/kit').ActionResult} result + * @template {Record | undefined} Failure + * @type {(result: import('@sveltejs/kit').ActionResult) => void} + * @param {import('@sveltejs/kit').ActionResult} result */ export const applyAction = client_method('apply_action'); @@ -31,9 +31,9 @@ export const applyAction = client_method('apply_action'); * } * ``` * @template {Record | undefined} Success - * @template {Record | undefined} Invalid + * @template {Record | undefined} Failure * @param {string} result - * @returns {import('@sveltejs/kit').ActionResult} + * @returns {import('@sveltejs/kit').ActionResult} */ export function deserialize(result) { const parsed = JSON.parse(result); @@ -86,9 +86,9 @@ function clone(element) { * * If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. * @template {Record | undefined} Success - * @template {Record | undefined} Invalid + * @template {Record | undefined} Failure * @param {HTMLFormElement} form_element The form element - * @param {import('@sveltejs/kit').SubmitFunction} submit Submit callback + * @param {import('@sveltejs/kit').SubmitFunction} submit Submit callback */ export function enhance(form_element, submit = () => {}) { if (DEV && clone(form_element).method !== 'post') { From a664437e65572f5273b9e0a5304215bd7c6c57a4 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 15:39:59 -0400 Subject: [PATCH 12/42] ugh --- packages/kit/src/runtime/app/forms.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/kit/src/runtime/app/forms.js b/packages/kit/src/runtime/app/forms.js index a723aac08fc5..d449b30eb769 100644 --- a/packages/kit/src/runtime/app/forms.js +++ b/packages/kit/src/runtime/app/forms.js @@ -118,6 +118,7 @@ export function enhance(form_element, submit = () => {}) { result.type === 'redirect' || result.type === 'error' ) { + // @ts-expect-error TODO: somebody fix this. it is beyond my powers applyAction(result); } }; From c10a9a3af3f6f797a7d96dd4cd63df16b5e28eca Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 15:53:23 -0400 Subject: [PATCH 13/42] fix --- packages/kit/src/core/sync/write_types/test/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/kit/src/core/sync/write_types/test/tsconfig.json b/packages/kit/src/core/sync/write_types/test/tsconfig.json index 14e7da72eb96..7188f648648c 100644 --- a/packages/kit/src/core/sync/write_types/test/tsconfig.json +++ b/packages/kit/src/core/sync/write_types/test/tsconfig.json @@ -10,7 +10,7 @@ "allowSyntheticDefaultImports": true, "baseUrl": ".", "paths": { - "@sveltejs/kit": ["../../../../../types/index"] + "@sveltejs/kit": ["../../../../exports/public"] } }, "include": ["./**/*.js"], From ccd520fbae410b812ab0bb5df1e2fab7a7a12d9e Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 16:10:52 -0400 Subject: [PATCH 14/42] fix --- packages/kit/src/core/sync/write_types/test/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/kit/src/core/sync/write_types/test/tsconfig.json b/packages/kit/src/core/sync/write_types/test/tsconfig.json index 7188f648648c..fc3cf322453b 100644 --- a/packages/kit/src/core/sync/write_types/test/tsconfig.json +++ b/packages/kit/src/core/sync/write_types/test/tsconfig.json @@ -10,7 +10,8 @@ "allowSyntheticDefaultImports": true, "baseUrl": ".", "paths": { - "@sveltejs/kit": ["../../../../exports/public"] + "@sveltejs/kit": ["../../../../exports/public"], + "types": ["../../../../types/internal"] } }, "include": ["./**/*.js"], From 1b4a0cb8d0b959c631da5bff7a224016260507c1 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 17:29:39 -0400 Subject: [PATCH 15/42] fix --- packages/kit/src/core/sync/write_ambient.js | 2 +- sites/kit.svelte.dev/scripts/types/index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/kit/src/core/sync/write_ambient.js b/packages/kit/src/core/sync/write_ambient.js index 500ffe17c772..b55b92f4246f 100644 --- a/packages/kit/src/core/sync/write_ambient.js +++ b/packages/kit/src/core/sync/write_ambient.js @@ -8,7 +8,7 @@ import { write_if_changed } from './utils.js'; // TODO these types should be described in a neutral place, rather than // inside either `packages/kit` or `kit.svelte.dev` -const descriptions_dir = fileURLToPath(new URL('../../../types/synthetic', import.meta.url)); +const descriptions_dir = fileURLToPath(new URL('../../../src/types/synthetic', import.meta.url)); /** @param {string} filename */ function read_description(filename) { diff --git a/sites/kit.svelte.dev/scripts/types/index.js b/sites/kit.svelte.dev/scripts/types/index.js index 365ad50820bc..feb5e774ab0d 100644 --- a/sites/kit.svelte.dev/scripts/types/index.js +++ b/sites/kit.svelte.dev/scripts/types/index.js @@ -230,7 +230,7 @@ function read_d_ts_file(file) { } const dir = fileURLToPath( - new URL('../../../../packages/kit/types/synthetic', import.meta.url).href + new URL('../../../../packages/kit/src/types/synthetic', import.meta.url).href ); for (const file of fs.readdirSync(dir)) { if (!file.endsWith('.md')) continue; From 0f7a61f0107c63c082b04f0aa60e8bb179860597 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 18:01:53 -0400 Subject: [PATCH 16/42] get site building --- sites/kit.svelte.dev/scripts/types/index.js | 17 +++-------------- .../src/lib/docs/server/render.js | 1 + 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/sites/kit.svelte.dev/scripts/types/index.js b/sites/kit.svelte.dev/scripts/types/index.js index feb5e774ab0d..9a5b2284595f 100644 --- a/sites/kit.svelte.dev/scripts/types/index.js +++ b/sites/kit.svelte.dev/scripts/types/index.js @@ -208,18 +208,7 @@ function read_d_ts_file(file) { } { - const code = read_d_ts_file('types/index.d.ts'); - const node = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, true); - - modules.push({ - name: '@sveltejs/kit', - comment: '', - ...get_types(code, node.statements) - }); -} - -{ - const code = read_d_ts_file('types/private.d.ts'); + const code = read_d_ts_file('src/types/private.d.ts'); const node = ts.createSourceFile('private.d.ts', code, ts.ScriptTarget.Latest, true); modules.push({ @@ -247,8 +236,8 @@ for (const file of fs.readdirSync(dir)) { } { - const code = read_d_ts_file('types/ambient.d.ts'); - const node = ts.createSourceFile('ambient.d.ts', code, ts.ScriptTarget.Latest, true); + const code = read_d_ts_file('types/index.d.ts'); + const node = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, true); for (const statement of node.statements) { if (ts.isModuleDeclaration(statement)) { diff --git a/sites/kit.svelte.dev/src/lib/docs/server/render.js b/sites/kit.svelte.dev/src/lib/docs/server/render.js index 6762c17ce2c3..cfe1c80bbfec 100644 --- a/sites/kit.svelte.dev/src/lib/docs/server/render.js +++ b/sites/kit.svelte.dev/src/lib/docs/server/render.js @@ -66,6 +66,7 @@ export function replace_placeholders(content) { return modules .map((module) => { if (module.exports.length === 0 && !module.exempt) return ''; + if (module.name === 'Private types') return; let import_block = ''; From e5636893ac8cfbdec27cb10f4ab32f7c59145c47 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 22 May 2023 18:11:28 -0400 Subject: [PATCH 17/42] try this --- sites/kit.svelte.dev/vercel.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sites/kit.svelte.dev/vercel.json b/sites/kit.svelte.dev/vercel.json index e17f42e185c2..c3c586fb80d1 100644 --- a/sites/kit.svelte.dev/vercel.json +++ b/sites/kit.svelte.dev/vercel.json @@ -5,5 +5,5 @@ }, "trailingSlash": false, "installCommand": "pnpm install --frozen-lockfile --verbose && pnpm rebuild", - "buildCommand": "pnpm build" + "buildCommand": "cd ../../packages/kit && pnpm prepublishOnly && cd ../../sites/kit.svelte.dev && pnpm build" } From 1017a492cabb775b665f6f1d454ae5ff92027d75 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 11:08:00 -0400 Subject: [PATCH 18/42] fix --- packages/kit/src/runtime/client/singletons.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/kit/src/runtime/client/singletons.js b/packages/kit/src/runtime/client/singletons.js index f92efb259a3b..327e19303165 100644 --- a/packages/kit/src/runtime/client/singletons.js +++ b/packages/kit/src/runtime/client/singletons.js @@ -46,6 +46,6 @@ export function client_method(key) { export const stores = { url: /* @__PURE__ */ notifiable_store({}), page: /* @__PURE__ */ notifiable_store({}), - navigating: /* @__PURE__ */ writable(/** @type {import('types').Navigation | null} */ (null)), + navigating: /* @__PURE__ */ writable(/** @type {import('@sveltejs/kit').Navigation | null} */ (null)), updated: /* @__PURE__ */ create_updated_store() }; From 38c9e4f71d436ef133384b922971a5edd3af0ddb Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 11:14:52 -0400 Subject: [PATCH 19/42] reinstate code --- .../write_types/test/actions/+page.server.js | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js index dc6536f108d0..b068ab76be3f 100644 --- a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js +++ b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js @@ -1,6 +1,6 @@ import { fail } from '../../../../../../src/exports/index.js'; -const condition = false; +let condition = false; export const actions = { default: () => { @@ -35,3 +35,53 @@ export const actions = { return fail(400); } }; + +/** @type {import('./.svelte-kit/types/src/core/sync/write_types/test/actions/$types').SubmitFunction} */ +const submit = () => { + return ({ result }) => { + if (result.type === 'success') { + // @ts-expect-error does only exist on `failure` result + result.data?.fail; + // @ts-expect-error unknown property + result.data?.something; + + if (result.data && 'success' in result.data) { + result.data.success === true; + // @ts-expect-error should be of type `boolean` + result.data.success === 'success'; + // @ts-expect-error does not exist in this branch + result.data.id; + } + + if (result.data && 'id' in result.data) { + result.data.id === 42; + // @ts-expect-error should be of type `number` + result.data.id === 'John'; + // @ts-expect-error does not exist in this branch + result.data.success; + } + } + + if (result.type === 'failure') { + result.data; + // @ts-expect-error does only exist on `success` result + result.data.success; + // @ts-expect-error unknown property + result.data.unknown; + + if (result.data && 'fail' in result.data) { + result.data.fail === ''; + // @ts-expect-error does not exist in this branch + result.data.reason; + } + + if (result.data && 'reason' in result.data) { + result.data.reason.error.code === 'VALIDATION_FAILED'; + // @ts-expect-error should be a const + result.data.reason.error.code === ''; + // @ts-expect-error does not exist in this branch + result.data.fail; + } + } + }; +}; \ No newline at end of file From 05bd2b8aea923b00cfc49f9aec10d7b06a0eb357 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 13:33:20 -0400 Subject: [PATCH 20/42] appease eslint --- .../core/sync/write_types/test/actions/+page.server.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js index b068ab76be3f..8aba77ed7595 100644 --- a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js +++ b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js @@ -1,6 +1,6 @@ import { fail } from '../../../../../../src/exports/index.js'; -let condition = false; +const condition = false; export const actions = { default: () => { @@ -36,8 +36,12 @@ export const actions = { } }; -/** @type {import('./.svelte-kit/types/src/core/sync/write_types/test/actions/$types').SubmitFunction} */ -const submit = () => { +/** + * Ordinarily this would live in a +page.svelte, but to make it easy to run the tests, we put it here. + * The `export` is so that eslint doesn't throw a hissy fit about the unused variable + * @type {import('./.svelte-kit/types/src/core/sync/write_types/test/actions/$types').SubmitFunction} + */ +export const submit = () => { return ({ result }) => { if (result.type === 'success') { // @ts-expect-error does only exist on `failure` result From 7c9ca73a267c0bbad56b5985b6339df40ff7acb8 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 13:36:31 -0400 Subject: [PATCH 21/42] fix some stuff --- packages/kit/src/exports/public.d.ts | 13 ++----------- packages/kit/src/runtime/control.js | 9 ++++++--- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index e817f8ef2eba..5428cb5c7a85 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -19,10 +19,12 @@ import { RouteSegment, UniqueInterface } from '../types/private.js'; +import { ActionFailure } from '../runtime/control.js'; import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from 'types'; import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; export { PrerenderOption } from '../types/private.js'; +export { ActionFailure }; /** * [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. @@ -1214,17 +1216,6 @@ export interface Redirect { location: string; } -/** - * The object returned by the [`fail`](https://kit.svelte.dev/docs/modules#sveltejs-kit-fail) function - */ -export interface ActionFailure | undefined = undefined> - extends UniqueInterface { - /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ - status: number; - /** Data associated with the failure (e.g. validation errors) */ - data: T; -} - export interface SubmitFunction< Success extends Record | undefined = Record, Failure extends Record | undefined = Record diff --git a/packages/kit/src/runtime/control.js b/packages/kit/src/runtime/control.js index 87e0dcc2b2c5..0a9fa244b80f 100644 --- a/packages/kit/src/runtime/control.js +++ b/packages/kit/src/runtime/control.js @@ -1,4 +1,4 @@ -export let HttpError = class HttpError { +export class HttpError { /** * @param {number} status * @param {{message: string} extends App.Error ? (App.Error | string | undefined) : App.Error} body @@ -19,7 +19,7 @@ export let HttpError = class HttpError { } }; -export let Redirect = class Redirect { +export class Redirect { /** * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status * @param {string} location @@ -33,7 +33,7 @@ export let Redirect = class Redirect { /** * @template {Record | undefined} [T=undefined] */ -export let ActionFailure = class ActionFailure { +export class ActionFailure { /** * @param {number} status * @param {T} [data] @@ -57,7 +57,10 @@ export let ActionFailure = class ActionFailure { * }} implementations */ export function replace_implementations(implementations) { + // @ts-expect-error ActionFailure = implementations.ActionFailure; + // @ts-expect-error HttpError = implementations.HttpError; + // @ts-expect-error Redirect = implementations.Redirect; } From 96f0d25d8cdceac59927589808b040f30adb03f2 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 14:05:59 -0400 Subject: [PATCH 22/42] prettier --- .../src/core/sync/write_types/test/actions/+page.server.js | 2 +- packages/kit/src/runtime/client/singletons.js | 4 +++- packages/kit/src/runtime/control.js | 6 +++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js index 8aba77ed7595..3347ea120fac 100644 --- a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js +++ b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js @@ -88,4 +88,4 @@ export const submit = () => { } } }; -}; \ No newline at end of file +}; diff --git a/packages/kit/src/runtime/client/singletons.js b/packages/kit/src/runtime/client/singletons.js index 327e19303165..9e1e7c1779a1 100644 --- a/packages/kit/src/runtime/client/singletons.js +++ b/packages/kit/src/runtime/client/singletons.js @@ -46,6 +46,8 @@ export function client_method(key) { export const stores = { url: /* @__PURE__ */ notifiable_store({}), page: /* @__PURE__ */ notifiable_store({}), - navigating: /* @__PURE__ */ writable(/** @type {import('@sveltejs/kit').Navigation | null} */ (null)), + navigating: /* @__PURE__ */ writable( + /** @type {import('@sveltejs/kit').Navigation | null} */ (null) + ), updated: /* @__PURE__ */ create_updated_store() }; diff --git a/packages/kit/src/runtime/control.js b/packages/kit/src/runtime/control.js index 0a9fa244b80f..9cdbce169050 100644 --- a/packages/kit/src/runtime/control.js +++ b/packages/kit/src/runtime/control.js @@ -17,7 +17,7 @@ export class HttpError { toString() { return JSON.stringify(this.body); } -}; +} export class Redirect { /** @@ -28,7 +28,7 @@ export class Redirect { this.status = status; this.location = location; } -}; +} /** * @template {Record | undefined} [T=undefined] @@ -42,7 +42,7 @@ export class ActionFailure { this.status = status; this.data = data; } -}; +} /** * This is a grotesque hack that, in dev, allows us to replace the implementations From d7e15d170a2bef4f8e83a62347aa3f2a7bf743e6 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 14:09:40 -0400 Subject: [PATCH 23/42] fix --- packages/kit/src/exports/index.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/kit/src/exports/index.js b/packages/kit/src/exports/index.js index 36e4102aad23..e22ae51f2132 100644 --- a/packages/kit/src/exports/index.js +++ b/packages/kit/src/exports/index.js @@ -95,8 +95,10 @@ export function text(body, init) { /** * Create an `ActionFailure` object. + * @template {Record | undefined} [T=undefined] * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. - * @param {Record | undefined} [data] Data associated with the failure (e.g. validation errors) + * @param {T} [data] Data associated with the failure (e.g. validation errors) + * @returns {ActionFailure} */ export function fail(status, data) { return new ActionFailure(status, data); From c428829f83b111e497fe75b5553d939d43d29b5c Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 15:33:22 -0400 Subject: [PATCH 24/42] appease typescript --- packages/kit/src/runtime/app/forms.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/kit/src/runtime/app/forms.js b/packages/kit/src/runtime/app/forms.js index d449b30eb769..0db93f6be48f 100644 --- a/packages/kit/src/runtime/app/forms.js +++ b/packages/kit/src/runtime/app/forms.js @@ -1,6 +1,6 @@ import * as devalue from 'devalue'; -import { DEV } from 'esm-env'; -import { client_method } from '../client/singletons.js'; +import { BROWSER, DEV } from 'esm-env'; +import { client } from '../client/singletons.js'; import { invalidateAll } from './navigation.js'; /** @@ -8,10 +8,16 @@ import { invalidateAll } from './navigation.js'; * In case of an error, it redirects to the nearest error page. * @template {Record | undefined} Success * @template {Record | undefined} Failure - * @type {(result: import('@sveltejs/kit').ActionResult) => void} * @param {import('@sveltejs/kit').ActionResult} result + * @returns {Promise} */ -export const applyAction = client_method('apply_action'); +export function applyAction(result) { + if (BROWSER) { + return client.apply_action(result); + } else { + throw new Error(`Cannot call applyAction(...) on the server`); + } +} /** * Use this function to deserialize the response from a form submission. @@ -118,7 +124,6 @@ export function enhance(form_element, submit = () => {}) { result.type === 'redirect' || result.type === 'error' ) { - // @ts-expect-error TODO: somebody fix this. it is beyond my powers applyAction(result); } }; From 2bab43c3b21620631acc6d0e39215550940c83ed Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 15:42:01 -0400 Subject: [PATCH 25/42] fix --- packages/kit/src/runtime/app/environment.js | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/packages/kit/src/runtime/app/environment.js b/packages/kit/src/runtime/app/environment.js index ca378d3553b2..d95d40cfbaec 100644 --- a/packages/kit/src/runtime/app/environment.js +++ b/packages/kit/src/runtime/app/environment.js @@ -1,4 +1,5 @@ import { BROWSER, DEV } from 'esm-env'; +import * as environment from '__sveltekit/environment'; /** * `true` if the app is running in the browser. @@ -10,15 +11,12 @@ export const browser = BROWSER; */ export const dev = DEV; -export { building, version } from '__sveltekit/environment'; - -// TODO this will need to be declared ambiently somewhere -// /** -// * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. -// */ -// export const building: boolean; +/** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ +export const building = environment.building; -// /** -// * The value of `config.kit.version.name`. -// */ -// export const version: string; +/** + * The value of `config.kit.version.name`. + */ +export const version = environment.version; From 8e7d00e02d8d001aa54424fbb50b7fdc504097d7 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 16:23:21 -0400 Subject: [PATCH 26/42] "eslint: so you can remember why you hate programming" --- .eslintrc.json | 9 ++++++++- packages/kit/src/runtime/app/forms.js | 2 +- packages/kit/src/runtime/control.js | 6 +++--- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 0d7ea6301105..9501511a710b 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -4,7 +4,14 @@ "env": { "es2022": true }, - "ignorePatterns": ["packages/create-svelte/shared/"], + "ignorePatterns": [ + "packages/create-svelte/shared/", + "packages/kit/test/prerendering/*/build", + "packages/adapter-static/test/apps/*/build", + "packages/adapter-cloudflare/files", + "packages/adapter-netlify/files", + "packages/adapter-node/files" + ], "rules": { "no-undef": "off" } diff --git a/packages/kit/src/runtime/app/forms.js b/packages/kit/src/runtime/app/forms.js index 0db93f6be48f..f6a42c745c6f 100644 --- a/packages/kit/src/runtime/app/forms.js +++ b/packages/kit/src/runtime/app/forms.js @@ -15,7 +15,7 @@ export function applyAction(result) { if (BROWSER) { return client.apply_action(result); } else { - throw new Error(`Cannot call applyAction(...) on the server`); + throw new Error('Cannot call applyAction(...) on the server'); } } diff --git a/packages/kit/src/runtime/control.js b/packages/kit/src/runtime/control.js index 9cdbce169050..d27725429038 100644 --- a/packages/kit/src/runtime/control.js +++ b/packages/kit/src/runtime/control.js @@ -58,9 +58,9 @@ export class ActionFailure { */ export function replace_implementations(implementations) { // @ts-expect-error - ActionFailure = implementations.ActionFailure; + ActionFailure = implementations.ActionFailure; // eslint-disable-line no-class-assign // @ts-expect-error - HttpError = implementations.HttpError; + HttpError = implementations.HttpError; // eslint-disable-line no-class-assign // @ts-expect-error - Redirect = implementations.Redirect; + Redirect = implementations.Redirect; // eslint-disable-line no-class-assign } From 998b5a1f67c4d2136a083f6df7441e7cce3bd055 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 16:28:56 -0400 Subject: [PATCH 27/42] remove unused types --- packages/kit/src/exports/public.d.ts | 3 +-- packages/kit/src/types/private.d.ts | 11 +---------- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index 5428cb5c7a85..f993335fdccc 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -16,8 +16,7 @@ import { PrerenderMissingIdHandlerValue, PrerenderOption, RequestOptions, - RouteSegment, - UniqueInterface + RouteSegment } from '../types/private.js'; import { ActionFailure } from '../runtime/control.js'; import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from 'types'; diff --git a/packages/kit/src/types/private.d.ts b/packages/kit/src/types/private.d.ts index 4ead17bc3bff..15e9fa5915f9 100644 --- a/packages/kit/src/types/private.d.ts +++ b/packages/kit/src/types/private.d.ts @@ -232,13 +232,4 @@ export interface RouteSegment { rest: boolean; } -export type TrailingSlash = 'never' | 'always' | 'ignore'; - -/** - * This doesn't actually exist, it's a way to better distinguish the type - */ -export const uniqueSymbol: unique symbol; - -export interface UniqueInterface { - readonly [uniqueSymbol]: unknown; -} +export type TrailingSlash = 'never' | 'always' | 'ignore'; \ No newline at end of file From b9ea65b7f60dceaae2874fec18b65ba7dfd9611e Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 16:31:17 -0400 Subject: [PATCH 28/42] use proper imports for ambient types --- packages/kit/src/exports/public.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index f993335fdccc..55e91720d7f3 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -1,6 +1,5 @@ -/// -/// - +import 'svelte'; +import 'vite/client'; import '../types/ambient.js'; import { CompileOptions } from 'svelte/types/compiler/interfaces'; From 4a041fe6e4ecaa81da9aa16290b62937ab5d1b8a Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 16:43:25 -0400 Subject: [PATCH 29/42] jfc eslint fuck OFF --- packages/kit/src/types/private.d.ts | 2 +- packages/package/test/index.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/kit/src/types/private.d.ts b/packages/kit/src/types/private.d.ts index 15e9fa5915f9..e84cf1644a4f 100644 --- a/packages/kit/src/types/private.d.ts +++ b/packages/kit/src/types/private.d.ts @@ -232,4 +232,4 @@ export interface RouteSegment { rest: boolean; } -export type TrailingSlash = 'never' | 'always' | 'ignore'; \ No newline at end of file +export type TrailingSlash = 'never' | 'always' | 'ignore'; diff --git a/packages/package/test/index.js b/packages/package/test/index.js index 62ca362f630e..03596f6def55 100644 --- a/packages/package/test/index.js +++ b/packages/package/test/index.js @@ -189,13 +189,13 @@ if (!process.env.CI) { compare('index.js'); // processes a .js file - write('src/lib/a.js', 'export const a = "a";'); + write('src/lib/a.js', "export const a = 'a';"); await settled(); compare('a.js'); compare('a.d.ts'); // processes a .ts file - write('src/lib/b.ts', 'export const b = "b";'); + write('src/lib/b.ts', "export const b = 'b';"); await settled(); compare('b.js'); compare('b.d.ts'); From 2a054e18cddd966ef2fe0763dc67e3f81d69b789 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 17:07:06 -0400 Subject: [PATCH 30/42] try this --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cfded7f93eff..03030bdd9f84 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -136,4 +136,5 @@ jobs: node-version: 16 cache: pnpm - run: pnpm install --frozen-lockfile + - run: cd packages/kit && pnpm prepublishOnly - run: pnpm run test:create-svelte From 9368ee2c976c4f067779e7d39dbb538dcefb621a Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 17:20:45 -0400 Subject: [PATCH 31/42] bump dts-buddy --- packages/kit/package.json | 2 +- pnpm-lock.yaml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/kit/package.json b/packages/kit/package.json index d76bab36c12e..dc67f90d3ea5 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -33,7 +33,7 @@ "@types/node": "^16.18.6", "@types/sade": "^1.7.4", "@types/set-cookie-parser": "^2.4.2", - "dts-buddy": "^0.0.6", + "dts-buddy": "^0.0.7", "marked": "^4.2.3", "rollup": "^3.7.0", "svelte": "^3.56.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 61fc4c72189c..b1396eb3cf5e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -437,8 +437,8 @@ importers: specifier: ^2.4.2 version: 2.4.2 dts-buddy: - specifier: ^0.0.6 - version: 0.0.6 + specifier: ^0.0.7 + version: 0.0.7 marked: specifier: ^4.2.3 version: 4.2.3 @@ -2953,8 +2953,8 @@ packages: engines: {node: '>=12'} dev: true - /dts-buddy@0.0.6: - resolution: {integrity: sha512-WBLk0YOF/vMzv1uqd3uQewEirDHKgfBGbf5LgE43e1rolKDOrbpPlhmhllmUp2aiT0ZAA+TvKoJgpnPqSPGAPQ==} + /dts-buddy@0.0.7: + resolution: {integrity: sha512-MFndKiO7FJBS4JrZc1oZuyxMnuJHPOzhQ1uJnn4uubHLfRKHgrqkqOrvUgGpg/Z87UyrP+Fqjxc9ZABl6xvW8A==} hasBin: true dependencies: '@jridgewell/source-map': 0.3.3 From e8c945f7177c1e28f7af190e976779729f282786 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 17:29:24 -0400 Subject: [PATCH 32/42] try this --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 03030bdd9f84..c7a1464302d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,7 @@ jobs: cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm run lint + - run: cd packages/kit && pnpm prepublishOnly - run: pnpm run check Tests: runs-on: ${{ matrix.os }} From 1a4211d5abb1bcbc43b292e10a61c40f54a59072 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 17:40:50 -0400 Subject: [PATCH 33/42] function interfaces need to be types now. who the hell knows why --- packages/kit/src/exports/public.d.ts | 48 +++++++++------------------- 1 file changed, 15 insertions(+), 33 deletions(-) diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index 55e91720d7f3..bc0338aadb26 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -642,9 +642,7 @@ export type Handle = (input: { * 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. */ -export interface HandleServerError { - (input: { error: unknown; event: RequestEvent }): MaybePromise; -} +export type HandleServerError = (input: { error: unknown; event: RequestEvent }) => MaybePromise; /** * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. @@ -652,30 +650,24 @@ export interface HandleServerError { * 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. */ -export interface HandleClientError { - (input: { error: unknown; event: NavigationEvent }): MaybePromise; -} +export type HandleClientError = (input: { error: unknown; event: NavigationEvent }) => MaybePromise; /** * 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) */ -export interface HandleFetch { - (input: { event: RequestEvent; request: Request; fetch: typeof fetch }): MaybePromise; -} +export type HandleFetch = (input: { event: RequestEvent; request: Request; fetch: typeof fetch }) => MaybePromise; /** * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) * rather than using `Load` directly. */ -export interface Load< +export type Load< Params extends Partial> = Partial>, InputData extends Record | null = Record | null, ParentData extends Record = Record, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null -> { - (event: LoadEvent): MaybePromise; -} +> = (event: LoadEvent) => MaybePromise; /** * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) @@ -929,9 +921,7 @@ export interface Page< /** * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. */ -export interface ParamMatcher { - (param: string): boolean; -} +export type ParamMatcher = (param: string) => boolean; export interface RequestEvent< Params extends Partial> = Partial>, @@ -1019,12 +1009,10 @@ export interface RequestEvent< * * It receives `Params` as the first generic argument, which you can skip by using [generated types](https://kit.svelte.dev/docs/types#generated-types) instead. */ -export interface RequestHandler< +export type RequestHandler< Params extends Partial> = Partial>, RouteId extends string | null = string | null -> { - (event: RequestEvent): MaybePromise; -} +> = (event: RequestEvent) => MaybePromise; export interface ResolveOptions { /** @@ -1093,14 +1081,12 @@ export interface SSRManifest { * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) * rather than using `ServerLoad` directly. */ -export interface ServerLoad< +export type ServerLoad< Params extends Partial> = Partial>, ParentData extends Record = Record, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null -> { - (event: ServerLoadEvent): MaybePromise; -} +> = (event: ServerLoadEvent) => MaybePromise; export interface ServerLoadEvent< Params extends Partial> = Partial>, @@ -1157,13 +1143,11 @@ export interface ServerLoadEvent< * 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. */ -export interface Action< +export type Action< Params extends Partial> = Partial>, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null -> { - (event: RequestEvent): MaybePromise; -} +> = (event: RequestEvent) => MaybePromise; /** * Shape of the `export const actions = {..}` object in `+page.server.js`. @@ -1214,11 +1198,10 @@ export interface Redirect { location: string; } -export interface SubmitFunction< +export type SubmitFunction< Success extends Record | undefined = Record, Failure extends Record | undefined = Record -> { - (input: { +> = (input: { action: URL; /** * use `formData` instead of `data` @@ -1235,7 +1218,7 @@ export interface SubmitFunction< controller: AbortController; submitter: HTMLElement | null; cancel(): void; - }): MaybePromise< + }) => MaybePromise< | void | ((opts: { /** @@ -1259,7 +1242,6 @@ export interface SubmitFunction< update(options?: { reset: boolean }): Promise; }) => void) >; -} /** * The type of `export const snapshot` exported from a page or layout component. From 4376994080e73bd32deceee681dbee03d043d5c4 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 17:44:59 -0400 Subject: [PATCH 34/42] hide-the-pain-harold.jpg --- packages/kit/src/exports/public.d.ts | 96 +++++++++++++++------------- 1 file changed, 53 insertions(+), 43 deletions(-) diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index bc0338aadb26..838dae13be1a 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -642,7 +642,10 @@ export type Handle = (input: { * 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. */ -export type HandleServerError = (input: { error: unknown; event: RequestEvent }) => MaybePromise; +export type HandleServerError = (input: { + error: unknown; + event: RequestEvent; +}) => MaybePromise; /** * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. @@ -650,12 +653,19 @@ export type HandleServerError = (input: { error: unknown; event: RequestEvent }) * 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. */ -export type HandleClientError = (input: { error: unknown; event: NavigationEvent }) => MaybePromise; +export type HandleClientError = (input: { + error: unknown; + event: NavigationEvent; +}) => MaybePromise; /** * 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) */ -export type HandleFetch = (input: { event: RequestEvent; request: Request; fetch: typeof fetch }) => MaybePromise; +export type HandleFetch = (input: { + event: RequestEvent; + request: Request; + fetch: typeof fetch; +}) => MaybePromise; /** * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) @@ -1202,46 +1212,46 @@ export type SubmitFunction< Success extends Record | undefined = Record, Failure extends Record | undefined = Record > = (input: { - action: URL; - /** - * use `formData` instead of `data` - * @deprecated - */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * @deprecated - */ - form: HTMLFormElement; - formElement: HTMLFormElement; - controller: AbortController; - submitter: HTMLElement | null; - cancel(): void; - }) => MaybePromise< - | void - | ((opts: { - /** - * use `formData` instead of `data` - * @deprecated - */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * @deprecated - */ - form: HTMLFormElement; - 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. - */ - update(options?: { reset: boolean }): Promise; - }) => void) - >; + action: URL; + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; +}) => MaybePromise< + | void + | ((opts: { + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + 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. + */ + update(options?: { reset: boolean }): Promise; + }) => void) +>; /** * The type of `export const snapshot` exported from a page or layout component. From 2c4b8ab2232cd835f24408c6d760ce99aa680223 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 18:13:50 -0400 Subject: [PATCH 35/42] juggle some stuff --- packages/kit/src/internal.d.ts | 16 ++++++++++++++++ packages/kit/src/runtime/app/environment.js | 12 +----------- packages/kit/src/runtime/app/paths.js | 18 +----------------- 3 files changed, 18 insertions(+), 28 deletions(-) diff --git a/packages/kit/src/internal.d.ts b/packages/kit/src/internal.d.ts index c248d9d528f6..390de09d117f 100644 --- a/packages/kit/src/internal.d.ts +++ b/packages/kit/src/internal.d.ts @@ -1,13 +1,29 @@ /** Internal version of $app/environment */ declare module '__sveltekit/environment' { + /** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ export const building: boolean; + /** + * The value of `config.kit.version.name`. + */ export const version: string; export function set_building(): void; } /** Internal version of $app/paths */ declare module '__sveltekit/paths' { + /** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ export let base: '' | `/${string}`; + /** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. + */ export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; export let relative: boolean | undefined; // TODO in 2.0, make this a `boolean` that defaults to `true` export function reset(): void; diff --git a/packages/kit/src/runtime/app/environment.js b/packages/kit/src/runtime/app/environment.js index d95d40cfbaec..8393ee6dbda6 100644 --- a/packages/kit/src/runtime/app/environment.js +++ b/packages/kit/src/runtime/app/environment.js @@ -1,5 +1,5 @@ import { BROWSER, DEV } from 'esm-env'; -import * as environment from '__sveltekit/environment'; +export { building, version } from '__sveltekit/environment'; /** * `true` if the app is running in the browser. @@ -10,13 +10,3 @@ export const browser = BROWSER; * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. */ export const dev = DEV; - -/** - * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. - */ -export const building = environment.building; - -/** - * The value of `config.kit.version.name`. - */ -export const version = environment.version; diff --git a/packages/kit/src/runtime/app/paths.js b/packages/kit/src/runtime/app/paths.js index c0cbe2379508..7d0054283e91 100644 --- a/packages/kit/src/runtime/app/paths.js +++ b/packages/kit/src/runtime/app/paths.js @@ -1,17 +1 @@ -import * as paths from '__sveltekit/paths'; - -// TODO ensure that the underlying types are `/${string}` (for base) and `https://${string}` | `http://${string}` (for assets) - -/** - * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). - * - * Example usage: `Link` - */ -export const base = paths.base; - -/** - * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. - */ -export const assets = paths.assets; +export { base, assets } from '__sveltekit/paths'; \ No newline at end of file From c36447d4c04b7811ac50cecd3c8eedb7732c9650 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Tue, 23 May 2023 18:20:28 -0400 Subject: [PATCH 36/42] jfc --- packages/kit/src/runtime/app/paths.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/kit/src/runtime/app/paths.js b/packages/kit/src/runtime/app/paths.js index 7d0054283e91..20c6b1c4d716 100644 --- a/packages/kit/src/runtime/app/paths.js +++ b/packages/kit/src/runtime/app/paths.js @@ -1 +1 @@ -export { base, assets } from '__sveltekit/paths'; \ No newline at end of file +export { base, assets } from '__sveltekit/paths'; From 8a92705dc1c58a31663ddd068a2d50d8c6a23102 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 24 May 2023 12:46:53 -0400 Subject: [PATCH 37/42] expose __sveltekit/paths and __sveltekit/environment --- packages/kit/src/internal.d.ts | 32 ---------------------------- packages/kit/src/types/ambient.d.ts | 33 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 32 deletions(-) delete mode 100644 packages/kit/src/internal.d.ts diff --git a/packages/kit/src/internal.d.ts b/packages/kit/src/internal.d.ts deleted file mode 100644 index 390de09d117f..000000000000 --- a/packages/kit/src/internal.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** Internal version of $app/environment */ -declare module '__sveltekit/environment' { - /** - * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. - */ - export const building: boolean; - /** - * The value of `config.kit.version.name`. - */ - export const version: string; - export function set_building(): void; -} - -/** Internal version of $app/paths */ -declare module '__sveltekit/paths' { - /** - * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). - * - * Example usage: `Link` - */ - export let base: '' | `/${string}`; - /** - * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. - */ - export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; - export let relative: boolean | undefined; // TODO in 2.0, make this a `boolean` that defaults to `true` - export function reset(): void; - export function override(paths: { base: string; assets: string }): void; - export function set_assets(path: string): void; -} diff --git a/packages/kit/src/types/ambient.d.ts b/packages/kit/src/types/ambient.d.ts index c6a40f78de40..b7331402a369 100644 --- a/packages/kit/src/types/ambient.d.ts +++ b/packages/kit/src/types/ambient.d.ts @@ -73,3 +73,36 @@ declare module '$service-worker' { */ export const version: string; } + +/** Internal version of $app/environment */ +declare module '__sveltekit/environment' { + /** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ + export const building: boolean; + /** + * The value of `config.kit.version.name`. + */ + export const version: string; + export function set_building(): void; +} + +/** Internal version of $app/paths */ +declare module '__sveltekit/paths' { + /** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ + export let base: '' | `/${string}`; + /** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/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. + */ + export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; + export let relative: boolean | undefined; // TODO in 2.0, make this a `boolean` that defaults to `true` + export function reset(): void; + export function override(paths: { base: string; assets: string }): void; + export function set_assets(path: string): void; +} From d01d60c7e5b56d70ced02031053ea58508d2af41 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 24 May 2023 12:53:14 -0400 Subject: [PATCH 38/42] exclude internal module declarations --- sites/kit.svelte.dev/scripts/types/index.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sites/kit.svelte.dev/scripts/types/index.js b/sites/kit.svelte.dev/scripts/types/index.js index 9a5b2284595f..001d5d473980 100644 --- a/sites/kit.svelte.dev/scripts/types/index.js +++ b/sites/kit.svelte.dev/scripts/types/index.js @@ -244,6 +244,8 @@ for (const file of fs.readdirSync(dir)) { // @ts-ignore const name = statement.name.text || statement.name.escapedText; + if (name.startsWith('_')) continue; + // @ts-ignore const comment = strip_origin(statement.jsDoc?.[0].comment ?? ''); From eee8be0d3c6d1d88dd1e29de294bffee365d0dee Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 24 May 2023 15:51:41 -0400 Subject: [PATCH 39/42] fix docs --- packages/kit/package.json | 2 +- pnpm-lock.yaml | 8 +++---- sites/kit.svelte.dev/scripts/types/index.js | 24 ++++++++++++++++++--- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/packages/kit/package.json b/packages/kit/package.json index dc67f90d3ea5..a09476eee2a8 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -33,7 +33,7 @@ "@types/node": "^16.18.6", "@types/sade": "^1.7.4", "@types/set-cookie-parser": "^2.4.2", - "dts-buddy": "^0.0.7", + "dts-buddy": "^0.0.9", "marked": "^4.2.3", "rollup": "^3.7.0", "svelte": "^3.56.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b1396eb3cf5e..3b5f36a585aa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -437,8 +437,8 @@ importers: specifier: ^2.4.2 version: 2.4.2 dts-buddy: - specifier: ^0.0.7 - version: 0.0.7 + specifier: ^0.0.9 + version: 0.0.9 marked: specifier: ^4.2.3 version: 4.2.3 @@ -2953,8 +2953,8 @@ packages: engines: {node: '>=12'} dev: true - /dts-buddy@0.0.7: - resolution: {integrity: sha512-MFndKiO7FJBS4JrZc1oZuyxMnuJHPOzhQ1uJnn4uubHLfRKHgrqkqOrvUgGpg/Z87UyrP+Fqjxc9ZABl6xvW8A==} + /dts-buddy@0.0.9: + resolution: {integrity: sha512-T44cc55EgD9J0KEhXa/5Up4E7Cjc45RaGrDdHW/3l/sMu4YQMO77ReehPVweQCDfYwA9XnvxqxhbWLSg2XYQLA==} hasBin: true dependencies: '@jridgewell/source-map': 0.3.3 diff --git a/sites/kit.svelte.dev/scripts/types/index.js b/sites/kit.svelte.dev/scripts/types/index.js index 001d5d473980..ae69a8fb4a6c 100644 --- a/sites/kit.svelte.dev/scripts/types/index.js +++ b/sites/kit.svelte.dev/scripts/types/index.js @@ -244,8 +244,6 @@ for (const file of fs.readdirSync(dir)) { // @ts-ignore const name = statement.name.text || statement.name.escapedText; - if (name.startsWith('_')) continue; - // @ts-ignore const comment = strip_origin(statement.jsDoc?.[0].comment ?? ''); @@ -259,6 +257,22 @@ for (const file of fs.readdirSync(dir)) { } } +// need to do some unfortunate finagling here, hopefully we can remove this one day +const app_paths = modules.find((module) => module.name === '$app/paths'); +const app_environment = modules.find((module) => module.name === '$app/environment'); +const __sveltekit_paths = modules.find((module) => module.name === '__sveltekit/paths'); +const __sveltekit_environment = modules.find((module) => module.name === '__sveltekit/environment'); + +app_paths.exports.push( + __sveltekit_paths.exports.find((e) => e.name === 'assets'), + __sveltekit_paths.exports.find((e) => e.name === 'base') +); + +app_environment.exports.push( + __sveltekit_environment.exports.find((e) => e.name === 'building'), + __sveltekit_environment.exports.find((e) => e.name === 'version') +); + modules.sort((a, b) => (a.name < b.name ? -1 : 1)); mkdirp('docs'); @@ -267,6 +281,10 @@ fs.writeFileSync( ` /* This file is generated by running \`node scripts/extract-types.js\` in the packages/kit directory — do not edit it */ -export const modules = ${JSON.stringify(modules, null, ' ')}; +export const modules = ${JSON.stringify( + modules.filter((m) => !m.name.startsWith('_')), + null, + ' ' + )}; `.trim() ); From 721fc90569b9930d9d260bb7bf70d871ad6b13c5 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 24 May 2023 17:20:12 -0400 Subject: [PATCH 40/42] Update packages/kit/src/exports/public.d.ts Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com> --- packages/kit/src/exports/public.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index 838dae13be1a..42bc14c457c9 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -1,5 +1,5 @@ -import 'svelte'; -import 'vite/client'; +import 'svelte'; // pick up `declare module "*.svelte"` +import 'vite/client'; // pick up `declare module "*.jpg"`, etc. import '../types/ambient.js'; import { CompileOptions } from 'svelte/types/compiler/interfaces'; From 09c13ff7a88d21c56d0f5b2bb45e8aa9dc07898b Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 24 May 2023 17:26:13 -0400 Subject: [PATCH 41/42] format --- packages/kit/src/exports/public.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/kit/src/exports/public.d.ts b/packages/kit/src/exports/public.d.ts index 42bc14c457c9..b6108a1d0a54 100644 --- a/packages/kit/src/exports/public.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -1,4 +1,4 @@ -import 'svelte'; // pick up `declare module "*.svelte"` +import 'svelte'; // pick up `declare module "*.svelte"` import 'vite/client'; // pick up `declare module "*.jpg"`, etc. import '../types/ambient.js'; From 536f47408f21026402c12b11672da2d06d2d8d99 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Thu, 25 May 2023 13:10:25 -0400 Subject: [PATCH 42/42] rename message to body --- packages/kit/src/exports/index.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/kit/src/exports/index.js b/packages/kit/src/exports/index.js index e22ae51f2132..b1d50790c444 100644 --- a/packages/kit/src/exports/index.js +++ b/packages/kit/src/exports/index.js @@ -22,14 +22,14 @@ import { get_route_segments } from '../utils/routing.js'; * return an error response without invoking `handleError`. * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. - * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} message An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. */ -export function error(status, message) { +export function error(status, body) { if ((!BROWSER || DEV) && (isNaN(status) || status < 400 || status > 599)) { throw new Error(`HTTP error status codes must be between 400 and 599 — ${status} is invalid`); } - return new HttpError(status, message); + return new HttpError(status, body); } /**