diff --git a/.changeset/stupid-eels-wink.md b/.changeset/stupid-eels-wink.md new file mode 100644 index 0000000..de4cb07 --- /dev/null +++ b/.changeset/stupid-eels-wink.md @@ -0,0 +1,5 @@ +--- +'mcp-svelte-docs': patch +--- + +update defninitions diff --git a/definitions/$app.forms.md b/definitions/$app.forms.md new file mode 100644 index 0000000..6d6c53a --- /dev/null +++ b/definitions/$app.forms.md @@ -0,0 +1,30 @@ +# $app/forms Definition + +**Definition:** Client helpers for progressive form enhancement and +action results. + +**Syntax:** +`import { enhance, applyAction, deserialize } from '$app/forms'` + +**Functions:** + +- `enhance(form, submit?)` — use:enhance or programmatic; optional + callback per submit +- `applyAction(result)` — apply an `ActionResult` to the current page +- `deserialize(text)` — parse ActionResult from a fetch response + +## Example + +```svelte + + +
+ +
+``` + +## Related + +- `enhance`, `actions`, `fail` diff --git a/definitions/$app.navigation.md b/definitions/$app.navigation.md new file mode 100644 index 0000000..c908b6e --- /dev/null +++ b/definitions/$app.navigation.md @@ -0,0 +1,36 @@ +# $app/navigation Definition + +**Definition:** Client utilities for navigation and invalidation. + +**Syntax:** +`import { goto, invalidate, invalidateAll, beforeNavigate, afterNavigate, onNavigate, preloadData, preloadCode, refreshAll, pushState, replaceState, disableScrollHandling } from '$app/navigation'` + +**Functions:** + +- `goto(href, opts?)` — programmatic navigation +- `invalidate(urlOrPredicate)` — re-run `load` for resources +- `invalidateAll()` — re-run all active `load` functions +- `beforeNavigate(cb)` / `afterNavigate(cb)` — navigation lifecycle + (call during component init) +- `onNavigate(cb)` — pre-navigation hook (call during component init); + can await before completing and return cleanup +- `preloadData(href)` — preload route code and run load +- `preloadCode(pathname)` — preload route modules only +- `refreshAll({ includeLoadFunctions? })` — refresh remote functions + and optionally rerun load +- `pushState(url, state)` / `replaceState(url, state)` — shallow + routing state +- `disableScrollHandling()` — disable router scroll handling for the + update + +## Example + +```ts +import { goto, invalidate } from '$app/navigation'; +await goto('/dashboard'); +await invalidate((url) => url.pathname.startsWith('/api')); +``` + +## Related + +- `$app/stores`, `$app/forms` diff --git a/definitions/$app.paths.md b/definitions/$app.paths.md new file mode 100644 index 0000000..6971327 --- /dev/null +++ b/definitions/$app.paths.md @@ -0,0 +1,31 @@ +# $app/paths Definition + +**Definition:** Helpers for base/assets paths and resolving URLs or +route IDs respecting `config.kit.paths`. + +**Syntax:** `import { asset, resolve } from '$app/paths'` + +**API:** + +- `asset(file)` — resolve URL for assets in `static/` honoring + `paths.assets` (2.26+) +- `resolve(pathOrRoute, params?)` — resolve pathname or route ID with + params honoring base path (2.26+) +- Deprecated: `assets`, `base`, `resolveRoute` + +## Example + +```svelte + + +logo +Post +``` + +## Related + +- `configuration#paths`, `$app/navigation` diff --git a/definitions/$app.server.md b/definitions/$app.server.md new file mode 100644 index 0000000..9a40718 --- /dev/null +++ b/definitions/$app.server.md @@ -0,0 +1,36 @@ +# $app/server Definition + +**Definition:** Server-only utilities for remote functions and server +helpers: `getRequestEvent`, `read`, and creators for `query`, `form`, +`command`, `prerender` (experimental ≥2.27). + +**Syntax:** +`import { getRequestEvent, read, query, form, command, prerender } from '$app/server'` + +**API:** + +- `getRequestEvent()` — current RequestEvent (sync in environments + without AsyncLocalStorage) +- `read(asset)` — read imported asset contents as a Response +- `query/schema` — create server query (supports validation, batch, + `.refresh()/.set()`) +- `form` — create spreadable form object with progressive enhancement +- `command` — create server mutation callable from code (not during + render) +- `prerender` — create build-time data function (with `inputs`, + `dynamic`) + +## Example + +```ts +import { getRequestEvent, query } from '$app/server'; + +export const me = query(async () => { + const { cookies, locals } = getRequestEvent(); + return await locals.userFrom(cookies.get('sessionid')); +}); +``` + +## Related + +- `remote-functions`, `hooks.server.handleValidationError` diff --git a/definitions/$app.state.md b/definitions/$app.state.md new file mode 100644 index 0000000..43e78aa --- /dev/null +++ b/definitions/$app.state.md @@ -0,0 +1,37 @@ +# $app/state Definition + +**Definition:** Read-only state module providing `page`, `navigating`, +and `updated` for reactive routing and version info. Supersedes +`$app/stores` in Kit ≥2.12. + +**Syntax:** `import { page, navigating, updated } from '$app/state'` + +**API:** + +- `page` — reactive object for `url`, `params`, `data`, `form`, + `route`, `status`, `error` +- `navigating` — navigation info (`from`, `to`, `type`, `delta`, null + on server or idle) +- `updated` — object with `current: boolean` and + `check(): Promise` + +Note: `$app/state` values update reactively only via runes (e.g. +`$derived`). + +## Example + +```svelte + + +

{path}

+{#if navigating?.to} +

Navigating…

+{/if} +``` + +## Related + +- `$app/navigation`, `$app/stores` diff --git a/definitions/$app.stores.md b/definitions/$app.stores.md new file mode 100644 index 0000000..4988955 --- /dev/null +++ b/definitions/$app.stores.md @@ -0,0 +1,30 @@ +# $app/stores Definition + +**Definition:** Client-accessible Svelte stores reflecting navigation +state. + +Note: Deprecated in SvelteKit 2.12+ in favor of `$app/state` (use +identical APIs via runes). Existing apps may still use `$app/stores`. + +**Syntax:** `import { page, navigating, updated } from '$app/stores'` + +**Stores:** + +- `page` — `Readable` with params, route, data +- `navigating` — `Readable` +- `updated` — `Readable & { check(): Promise }` + +## Example + +```svelte + +

{title}

+{#if $navigating}

Loading…

{/if} +``` + +## Related + +- `$app/state`, `$app/navigation`, `load` diff --git a/definitions/$derived.by.md b/definitions/$derived.by.md index 1eaf93b..d0fd880 100644 --- a/definitions/$derived.by.md +++ b/definitions/$derived.by.md @@ -12,10 +12,10 @@ computations ## Examples -```js +```ts // Expensive computation that should be memoized -let items = $state([1, 2, 3, 4, 5]); -let filter = $state('even'); +let items: number[] = $state([1, 2, 3, 4, 5]); +let filter: 'even' | 'odd' = $state('even'); const expensiveResult = $derived.by(() => { console.log('Computing expensive result...'); @@ -47,7 +47,7 @@ const processedData = $derived.by(() => { // When you need multiple statements const validation = $derived.by(() => { - const errors = []; + const errors: string[] = []; if (items.length === 0) { errors.push('Items cannot be empty'); @@ -62,6 +62,28 @@ const validation = $derived.by(() => { errors, }; }); + +// Override a derived temporarily (e.g., optimistic UI) +let likes = $derived(post.likes); +async function like() { + likes += 1; // override + try { + await sendLike(); + } catch { + likes -= 1; // rollback on error + } +} + +// Destructuring: each piece remains reactive +let { a, b } = $derived(getPair()); // each remains reactive + +// Dependency control +let total2 = $derived.by(() => { + // anything read synchronously is a dependency + return items.reduce((s, n) => s + n, 0); +}); + +// To exempt values from tracking, use untrack(...) ``` ## Related diff --git a/definitions/$env.dynamic.private.md b/definitions/$env.dynamic.private.md new file mode 100644 index 0000000..a128377 --- /dev/null +++ b/definitions/$env.dynamic.private.md @@ -0,0 +1,23 @@ +# $env/dynamic/private Definition + +**Definition:** Runtime (dynamic) private environment variables +available on the server. Excludes variables with `publicPrefix` and +includes those with `privatePrefix` (if configured). + +**Syntax:** `import { env } from '$env/dynamic/private'` + +**Notes:** + +- Server-only; cannot be imported in client code. +- In dev, includes vars from `.env`; in prod, depends on adapter. + +## Example + +```ts +import { env } from '$env/dynamic/private'; +const secret = env.SECRET_API_KEY; +``` + +## Related + +- `$env/static/private`, `$env/dynamic/public` diff --git a/definitions/$env.dynamic.public.md b/definitions/$env.dynamic.public.md new file mode 100644 index 0000000..a07c1ce --- /dev/null +++ b/definitions/$env.dynamic.public.md @@ -0,0 +1,23 @@ +# $env/dynamic/public Definition + +**Definition:** Runtime (dynamic) public environment variables safe +for client usage. Includes only variables with `publicPrefix` (default +`PUBLIC_`). + +**Syntax:** `import { env } from '$env/dynamic/public'` + +**Notes:** + +- Public dynamic vars are sent from server to client; prefer + `$env/static/public` when possible. + +## Example + +```ts +import { env } from '$env/dynamic/public'; +const base = env.PUBLIC_BASE_URL; +``` + +## Related + +- `$env/static/public`, `$env/dynamic/private` diff --git a/definitions/$env.static.private.md b/definitions/$env.static.private.md new file mode 100644 index 0000000..dbc5c63 --- /dev/null +++ b/definitions/$env.static.private.md @@ -0,0 +1,24 @@ +# $env/static/private Definition + +**Definition:** Build-time (static) private environment variables +injected by Vite from `.env` and `process.env`. Excludes +`publicPrefix` and includes `privatePrefix` (if configured). + +**Syntax:** `import { NAME } from '$env/static/private'` + +**Notes:** + +- Values are statically replaced at build time; enables dead code + elimination. +- Declare all referenced variables (even if empty) to avoid undefined + at build. + +## Example + +```ts +import { API_KEY } from '$env/static/private'; +``` + +## Related + +- `$env/dynamic/private`, `$env/static/public` diff --git a/definitions/$env.static.public.md b/definitions/$env.static.public.md new file mode 100644 index 0000000..41f03b0 --- /dev/null +++ b/definitions/$env.static.public.md @@ -0,0 +1,21 @@ +# $env/static/public Definition + +**Definition:** Build-time (static) public environment variables safe +for client usage. Includes only variables with `publicPrefix` (default +`PUBLIC_`). + +**Syntax:** `import { PUBLIC_... } from '$env/static/public'` + +**Notes:** + +- Values are statically replaced at build time. + +## Example + +```ts +import { PUBLIC_BASE_URL } from '$env/static/public'; +``` + +## Related + +- `$env/static/private`, `$env/dynamic/public` diff --git a/definitions/$state.md b/definitions/$state.md index 10ae26c..c74d338 100644 --- a/definitions/$state.md +++ b/definitions/$state.md @@ -1,33 +1,44 @@ # $state Definition -**Definition:** Creates reactive state that triggers UI updates when -the value changes -**Syntax:** `$state(initial: T): T` | -`$state(): T | undefined` -**Parameters:** - -- `initial` - The initial value (optional) - **Returns:** Reactive proxy of the initial value - **Variants:** -- `$state.raw(initial: T): T` - Non-deeply-reactive state -- `$state.snapshot(state: T): Snapshot` - Static snapshot of - reactive state +**Definition:** Declares reactive state. When the value changes, the +UI updates. Arrays and plain objects become deeply reactive proxies; +primitives (like numbers/strings/booleans) remain normal values. +**Also see:** `$state.raw`, `$state.snapshot` ## Examples -```js +```ts // Basic reactive state let count = $state(0); -count++; // Triggers reactivity +count++; // triggers an update -// Object state (deeply reactive) +// Object/array state (deeply reactive) let user = $state({ name: 'Alice', age: 30 }); -user.name = 'Bob'; // Triggers reactivity +user.name = 'Bob'; // triggers an update of only the places that read `user.name` -// Optional initial value +// You can declare without an initial value with generics let data = $state(); // undefined initially ``` +## Notes + +- Deep reactivity: Arrays and simple objects are proxied deeply; + property changes and array methods (e.g. `push`) trigger granular + updates. +- Raw state: Use `$state.raw` to avoid deep reactivity and update only + on reassignment for performance with large data. +- Snapshots: Use `$state.snapshot(obj)` when passing reactive objects + to APIs that don’t expect proxies (e.g., `structuredClone`, + logging). +- Classes: Use `$state` in class fields (or first assignment in + `constructor`) for reactive class instances; methods should be bound + if used as handlers. +- Destructuring: Values destructured from reactive objects are not + reactive; derive reactive pieces explicitly (e.g., + `const name = $derived(user.name)`). +- Passing to functions: JavaScript passes values, not variables — pass + getters or functions if you need ‘current’ values. + ## Related - `$derived` - For computed values based on state diff --git a/definitions/+layout.server.ts.md b/definitions/+layout.server.ts.md new file mode 100644 index 0000000..3531485 --- /dev/null +++ b/definitions/+layout.server.ts.md @@ -0,0 +1,32 @@ +# +layout.server.ts Definition + +**Definition:** Server-only layout module exporting a `load` that runs +on the server for a layout segment. Useful for auth checks and shared +server data. + +**Syntax:** `src/routes/(...)/+layout.server.ts` (or `.js`) + +**Exports:** + +- `export const load: LayoutServerLoad` — server-only loader (must + return serializable data) +- Page options: `prerender`, `ssr`, `csr` defaults for children + +**Returns:** Data merges downward to child layouts and pages. + +## Example + +```ts +// +layout.server.ts +import type { LayoutServerLoad } from './$types'; +import { error } from '@sveltejs/kit'; + +export const load: LayoutServerLoad = async ({ locals }) => { + if (!locals.user) throw error(401, 'not logged in'); + return { user: locals.user }; +}; +``` + +## Related + +- `+layout.svelte`, `+layout.ts`, `load`, `hooks.server` diff --git a/definitions/+layout.svelte.md b/definitions/+layout.svelte.md new file mode 100644 index 0000000..c86bc48 --- /dev/null +++ b/definitions/+layout.svelte.md @@ -0,0 +1,31 @@ +# +layout.svelte Definition + +**Definition:** SvelteKit layout component that wraps pages and nested +layouts. Receives `data` from its layout `load` and a `children` +snippet to render. + +**Syntax:** `src/routes/(...)/+layout.svelte` + +**Props typing (Kit ≥2.16):** +`let { data, children }: import('./$types').LayoutProps = $props();` + +**Returns:** A wrapper component for shared UI/state across a route +segment. + +## Example + +```svelte + + + +{@render children()} +``` + +## Related + +- `+page.svelte` — rendered inside the nearest layout +- `load` — layout data loader +- `+layout.ts` — options and typing diff --git a/definitions/+layout.ts.md b/definitions/+layout.ts.md new file mode 100644 index 0000000..67f37fc --- /dev/null +++ b/definitions/+layout.ts.md @@ -0,0 +1,30 @@ +# +layout.ts Definition + +**Definition:** Companion module for a layout that declares options +and exposes `LayoutData` typing. + +**Syntax:** `src/routes/(...)/+layout.ts` (or `.js`) + +**Parameters:** + +- `export const prerender` — `true | 'auto' | false` +- `export const csr` — `boolean` +- `export const ssr` — `boolean` +- `export const trailingSlash` — `'always' | 'never' | 'ignore'` +- `export const config` — adapter-specific options merged top-level + with child pages + +**Returns:** Controls how the layout and its children render. + +## Example + +```ts +export const prerender = 'auto'; +export type LayoutLoad = import('./$types').LayoutLoad; +export type LayoutData = import('./$types').LayoutData; +``` + +## Related + +- `+layout.svelte` — layout component +- `load` — layout loader diff --git a/definitions/+page.server.ts.md b/definitions/+page.server.ts.md new file mode 100644 index 0000000..6897eca --- /dev/null +++ b/definitions/+page.server.ts.md @@ -0,0 +1,51 @@ +# +page.server.ts Definition + +**Definition:** Server-only page module exporting a `load` that runs +on the server and optional form `actions`. Suitable for accessing +databases, private env, and cookies. + +**Syntax:** `src/routes/(...)/+page.server.ts` (or `.js`) + +**Exports:** + +- `export const load: PageServerLoad` — server-only loader (must + return serializable data) +- `export const actions` — form actions map (`default` or named) +- Page options: `prerender`, `ssr`, `csr` + +**Returns:** Data is serialized and sent to the client; during client +navigation, fetched from the server. + +## Example + +```ts +// +page.server.ts +import type { PageServerLoad, Actions } from './$types'; +import { error, redirect, fail } from '@sveltejs/kit'; + +export const load: PageServerLoad = async ({ + params, + cookies, + locals, +}) => { + const session = cookies.get('sessionid'); + if (!session) throw redirect(307, '/login'); + const user = await locals.db.getUser(session); + if (!user) throw error(401, 'not logged in'); + return { user }; +}; + +export const actions: Actions = { + default: async ({ request, locals }) => { + const data = await request.formData(); + const name = data.get('name'); + if (!name) return fail(400, { missing: true }); + await locals.db.updateName(name as string); + return { success: true }; + }, +}; +``` + +## Related + +- `+page.svelte`, `+page.ts`, `actions`, `$env/*` diff --git a/definitions/+page.svelte.md b/definitions/+page.svelte.md new file mode 100644 index 0000000..28b0fdd --- /dev/null +++ b/definitions/+page.svelte.md @@ -0,0 +1,38 @@ +# +page.svelte Definition + +**Definition:** SvelteKit route component rendered for a page. Lives +alongside `+page.ts`/`+page.js` and optional `+page.server.ts`/`.js`. +Receives `data` (and `form`, when relevant) from its `load`/actions +and participates in the layout tree. + +**Syntax:** `src/routes/(...)/+page.svelte` + +**Props typing (Kit ≥2.16):** +`let { data, form }: import('./$types').PageProps = $props();` + +**Returns:** A client-rendered component hydrated according to project +`ssr/csr` settings. + +## Example + +```svelte + + +

Welcome {user.name}

+{#each posts as post} + {post.title} +{/each} +``` + +## Related + +- `+layout.svelte` — parent layout component +- `load` — page data loader +- `+page.ts` — page options and types +- `error` / `redirect` — control flow from loaders diff --git a/definitions/+page.ts.md b/definitions/+page.ts.md new file mode 100644 index 0000000..e4c309c --- /dev/null +++ b/definitions/+page.ts.md @@ -0,0 +1,42 @@ +# +page.ts Definition + +**Definition:** Companion module for a page that declares page +options, and (in TS) exposes helper types via `./$types`. + +**Syntax:** `src/routes/(...)/+page.ts` (or `+page.js`) + +**Parameters:** + +- `export const prerender` — `true | 'auto' | false` +- `export const csr` — `boolean` (enable/disable client-side + hydration) +- `export const ssr` — `boolean` (enable/disable server rendering) +- `export const trailingSlash` — `'always' | 'never' | 'ignore'` +- `export const entries` — function to enumerate dynamic entries for + prerendering +- `export const config` — adapter-specific options merged from parent + layout + +Notes: + +- Pages with form actions cannot be prerendered. +- `entries` applies to dynamic routes to seed the prerender crawler. + +**Returns:** Controls how the page is rendered and navigated. + +## Example + +```ts +export const prerender = true; +export const csr = true; +export const ssr = true; +export const trailingSlash = 'never'; + +export type PageLoad = import('./$types').PageLoad; +export type PageData = import('./$types').PageData; +``` + +## Related + +- `+page.svelte` — page component +- `load` — page loader diff --git a/definitions/+server.ts.md b/definitions/+server.ts.md new file mode 100644 index 0000000..447f730 --- /dev/null +++ b/definitions/+server.ts.md @@ -0,0 +1,36 @@ +# +server.ts Definition + +**Definition:** Route module that exports HTTP method handlers for +endpoints. Runs only on the server. + +**Syntax:** `src/routes/(...)/+server.ts` (or `.js`) + +**Parameters:** + +- `export const GET/POST/PATCH/PUT/DELETE/OPTIONS` — request handlers +- `export const fallback` — optional handler for all other methods +- `RequestHandler` — type for handlers, with `locals`, `cookies`, etc. + +**Returns:** Sends a `Response` using Web Fetch APIs or helper `json`. + +## Example + +```ts +import type { RequestHandler } from './$types'; +import { json, error } from '@sveltejs/kit'; + +export const GET: RequestHandler = async ({ url, locals }) => { + const id = url.searchParams.get('id'); + if (!id) throw error(400, 'id required'); + const item = await locals.db.get(id); + return json(item); +}; +``` + +## Related + +- `json` — helper for JSON responses +- `cookies`, `locals` — request utilities +- Note: `+layout` options don’t affect `+server` routes +- Notes: `HEAD` responses mirror `GET` body length; content + negotiation prefers page for Accept: text/html diff --git a/definitions/actions.md b/definitions/actions.md new file mode 100644 index 0000000..64e62b5 --- /dev/null +++ b/definitions/actions.md @@ -0,0 +1,40 @@ +# actions Definition + +**Definition:** Server-only form actions defined in `+page.server.ts` +to handle POSTed form data and mutations. + +**Syntax:** +`export const actions = { name: async (event) => { ... } }` + +**Parameters:** + +- `event.request` — form data via `await request.formData()` +- `event.locals`, `event.cookies` +- `fail(status, data)` — return validation errors +- `redirect(status, location)` — navigate after success + +**Returns:** Action result is available via the page `form` prop and +`page.form` until the next update. + +## Example + +```ts +// +page.server.ts +import type { Actions } from './$types'; +import { fail, redirect } from '@sveltejs/kit'; + +export const actions: Actions = { + login: async ({ request, locals }) => { + const data = await request.formData(); + const email = data.get('email'); + if (!email) return fail(400, { message: 'Email required' }); + await locals.auth.login(email as string); + throw redirect(303, '/dashboard'); + }, +}; +``` + +## Related + +- `enhance` — progressive enhancement for forms +- `fail`, `redirect` diff --git a/definitions/cookies.md b/definitions/cookies.md new file mode 100644 index 0000000..1983909 --- /dev/null +++ b/definitions/cookies.md @@ -0,0 +1,35 @@ +# cookies Definition + +**Definition:** Server utilities for reading/writing cookies on +requests. + +**Syntax:** in server `load`/endpoints: `event.cookies` + +**API:** + +- `get(name)` — read a cookie (optionally `getAll()`) +- `set(name, value, { path, ...options })` — set cookie (path is + required) +- `delete(name, { path, ...options })` — delete cookie (path must + match) + +**Returns:** Cookie helpers bound to the current request. + +## Example + +```ts +export const load = ({ cookies }) => { + const theme = cookies.get('theme') ?? 'light'; + cookies.set('seen', '1', { path: '/', httpOnly: true }); + return { theme }; +}; +``` + +## Related + +- `locals`, `+server.ts`, `hooks.server` + +Notes: + +- `event.fetch` forwards cookies for same-origin requests; to forward + to other origins, add headers in `handleFetch`. diff --git a/definitions/depends.md b/definitions/depends.md new file mode 100644 index 0000000..5b755c1 --- /dev/null +++ b/definitions/depends.md @@ -0,0 +1,30 @@ +# depends Definition + +**Definition:** Declare a cache dependency key that ties `load` +results to invalidation. + +**Syntax:** `depends(...keys: string[])` + +**Parameters:** + +- `keys` — strings like `app:resource` used by + `invalidate`/`invalidateAll`. For custom identifiers, use a + lowercase prefix followed by `:` to conform to URI rules. + +**Returns:** Void — registers dependency for the current `load`. + +## Example + +```ts +export const load = ({ depends }) => { + depends('app:posts'); + return { + /* data */ + }; +}; +``` + +## Related + +- `$app/navigation.invalidate`, `invalidateAll` +- `load` diff --git a/definitions/enhance.md b/definitions/enhance.md new file mode 100644 index 0000000..b82282c --- /dev/null +++ b/definitions/enhance.md @@ -0,0 +1,40 @@ +# enhance Definition + +**Definition:** Client-side helper to progressively enhance `
` +submissions by calling actions via fetch and updating UI without a +full navigation. + +**Syntax:** `import { enhance } from '$app/forms'` + +**Parameters:** + +- `use:enhance` — enhance a `` +- Callback (SubmitFunction): + `({ action, formData, formElement, controller, submitter, cancel }) => ( { formData, formElement, action, result, update } ) => void` +- `update({ reset?, invalidateAll? })` — run default post-submit + behavior +- Requires `method="POST"` and an action in `+page.server.*` + +**Returns:** Unsubscribable cleanup function. + +## Example + +```svelte + + + { + return async ({ result, update }) => { + await update(); // default behavior (updates form/page.form, invalidates) + }; +}}> + +
+``` + +## Related + +- `actions`, `fail` +- `$app/forms` diff --git a/definitions/error-boundaries.md b/definitions/error-boundaries.md new file mode 100644 index 0000000..bffd833 --- /dev/null +++ b/definitions/error-boundaries.md @@ -0,0 +1,29 @@ +# error-boundaries Definition + +**Definition:** Add `+error.svelte` to render a custom error page for +errors thrown during `load`/rendering in the corresponding route +subtree. + +**Syntax:** `src/routes/+error.svelte`, or nested +`.../route/+error.svelte` + +**Notes:** + +- SvelteKit walks up to the nearest `+error.svelte` if a child doesn’t + exist. +- Errors in `+server` handlers and `handle` do not use + `+error.svelte`; they return JSON or fallback error page. +- For 404s with no matched route, root `+error.svelte` is used. + +## Example + +```svelte + +

{page.status}: {page.error.message}

+``` + +## Related + +- `advanced-routing`, `hooks.server.handleError` diff --git a/definitions/error.md b/definitions/error.md new file mode 100644 index 0000000..adb1b0f --- /dev/null +++ b/definitions/error.md @@ -0,0 +1,22 @@ +# error Definition + +**Definition:** Throw an HTTP error from `load`/actions/`+server` +handlers. + +**Syntax (Kit 2+):** `throw error(status, messageOrBody)` + +Important: + +- You must `throw error(...)` — do not call it without throwing. +- Use inside server/universal `load`, actions, and `+server` handlers. + +## Example + +```ts +import { error } from '@sveltejs/kit'; +if (!item) throw error(404, 'Not found'); +``` + +## Related + +- `redirect`, `json` diff --git a/definitions/event-delegation.md b/definitions/event-delegation.md index ae8e99b..29ed31f 100644 --- a/definitions/event-delegation.md +++ b/definitions/event-delegation.md @@ -1,9 +1,14 @@ # event-delegation Definition +Note: This page describes a common JavaScript pattern and is not an +official Svelte/SvelteKit API reference. For canonical event handling +docs see Svelte’s template syntax (e.g. `onclick`) and events +reference. + **Definition:** Advanced event handling patterns using event delegation for performance and dynamic content -**Syntax:** Single parent event listener handling events from multiple -child elements +**Syntax:** Single parent event listener (e.g., `onclick`) handling +events from multiple child elements **Benefits:** - Better performance for many similar elements @@ -17,7 +22,7 @@ child elements ## Examples ```svelte - -
+
{#each items as item (item.id)}
- + - - +
{#each tableData as row (row.id)} diff --git a/definitions/fail.md b/definitions/fail.md new file mode 100644 index 0000000..0996e9c --- /dev/null +++ b/definitions/fail.md @@ -0,0 +1,24 @@ +# fail Definition + +**Definition:** Helper to return a failed action result with an HTTP +status and data. Does not throw. + +**Syntax:** `fail(status: number, data?: unknown)` + +**Parameters:** + +- `status` — HTTP status code (e.g., 400, 422) +- `data` — serializable error payload + +**Returns:** An `ActionFailure` consumed by SvelteKit. + +## Example + +```ts +import { fail } from '@sveltejs/kit'; +return fail(400, { field: 'email', message: 'Email required' }); +``` + +## Related + +- `actions`, `enhance` diff --git a/definitions/hooks.server.md b/definitions/hooks.server.md new file mode 100644 index 0000000..482ddb2 --- /dev/null +++ b/definitions/hooks.server.md @@ -0,0 +1,60 @@ +# hooks.server Definition + +**Definition:** Server hook module that customizes request handling. + +**Syntax:** `src/hooks.server.ts` + +**Exports:** + +- `handle` — wraps all requests +- `handleFetch` — intercepts server-side fetch +- `handleError` — central error logging/formatting +- `init` — optional async initialization on server startup + (ServerInit) +- `handleValidationError` — customize remote function validation + errors + +## Example + +```ts +// src/hooks.server.ts +import type { Handle, HandleFetch, HandleError } from '@sveltejs/kit'; + +export const handle: Handle = async ({ event, resolve }) => { + event.locals.user = await getUserFromSession(event.cookies); + return resolve(event); +}; + +export const handleFetch: HandleFetch = async ({ + request, + fetch, +}) => { + return fetch(request); +}; + +export const handleError: HandleError = ({ error, event }) => { + console.error('Error', event.route.id, error); +}; + +// Optional: run once before first request is handled +import type { + ServerInit, + HandleValidationError, +} from '@sveltejs/kit'; + +export const init: ServerInit = async () => { + // warm caches, connect to services, etc. +}; + +export const handleValidationError: HandleValidationError = ({ + issues, + event, +}) => { + return { message: 'Invalid request' }; +}; +``` + +## Related + +- `locals`, `cookies` +- `+server.ts` diff --git a/definitions/json.md b/definitions/json.md new file mode 100644 index 0000000..3ca8c84 --- /dev/null +++ b/definitions/json.md @@ -0,0 +1,24 @@ +# json Definition + +**Definition:** Helper to create a JSON `Response` with proper +headers. + +**Syntax:** `json(data: unknown, init?: ResponseInit)` + +**Parameters:** + +- `data` — serializable data +- `init` — headers/status + +**Returns:** `Response` + +## Example + +```ts +import { json } from '@sveltejs/kit'; +export const GET = () => json({ ok: true }, { status: 200 }); +``` + +## Related + +- `+server.ts`, `error`, `redirect` diff --git a/definitions/layout-groups.md b/definitions/layout-groups.md new file mode 100644 index 0000000..db4fde5 --- /dev/null +++ b/definitions/layout-groups.md @@ -0,0 +1,29 @@ +# layout-groups Definition + +**Definition:** Parentheses-named directories `(group)` organize +routes under separate layout hierarchies without affecting the URL +pathname. + +**Syntax:** `src/routes/(app)/...` and `src/routes/(marketing)/...` + +**Returns:** Layouts inside a group apply only to routes in that +group. + +## Example + +```txt +src/routes/ +├ (app)/ +│ ├ dashboard/ +│ ├ item/ +│ └ +layout.svelte +├ (marketing)/ +│ ├ about/ +│ ├ testimonials/ +│ └ +layout.svelte +└ +layout.svelte +``` + +## Related + +- `page-reset-layout`, `layout-reset`, `advanced-routing` diff --git a/definitions/layout-reset.md b/definitions/layout-reset.md new file mode 100644 index 0000000..b7729cf --- /dev/null +++ b/definitions/layout-reset.md @@ -0,0 +1,14 @@ +# layout-reset Definition + +**Definition:** Use `+layout@.svelte` (or `+layout@.svelte` +for root) to reset the layout hierarchy for all child routes. + +**Syntax:** `+layout@[id].svelte`, `+layout@item.svelte`, +`+layout@(group).svelte`, `+layout@.svelte` + +**Returns:** Resets the ancestor used for the layout and its +descendants. + +## Related + +- `page-reset-layout`, `layout-groups`, `advanced-routing` diff --git a/definitions/lifecycle-equivalents.md b/definitions/lifecycle-equivalents.md index d364ed5..7de320e 100644 --- a/definitions/lifecycle-equivalents.md +++ b/definitions/lifecycle-equivalents.md @@ -1,9 +1,10 @@ # lifecycle-equivalents Definition -**Definition:** Direct equivalents of Svelte 4 lifecycle functions -using Svelte 5 `$effect` patterns -**Syntax:** `$effect` replacements for `onMount`, `onDestroy`, -`beforeUpdate`, `afterUpdate` +**Definition:** Legacy Svelte 4 lifecycle functions (`onMount`, +`onDestroy`, `beforeUpdate`, `afterUpdate`) mapped to Svelte 5 +`$effect` patterns. Prefer `$effect` in Svelte 5. **Syntax:** +`$effect` replacements for `onMount`, `onDestroy`, `beforeUpdate`, +`afterUpdate` **Conversions:** - `onMount` → `$effect` with empty dependency @@ -15,27 +16,27 @@ using Svelte 5 `$effect` patterns ## Examples -```js +```ts // onMount equivalent -// Svelte 4 +// Svelte 4 (legacy) import { onMount } from 'svelte'; onMount(() => { console.log('Component mounted'); }); -// Svelte 5 +// Svelte 5 (preferred) $effect(() => { console.log('Component mounted'); }); // onDestroy equivalent -// Svelte 4 +// Svelte 4 (legacy) import { onDestroy } from 'svelte'; onDestroy(() => { console.log('Component destroyed'); }); -// Svelte 5 +// Svelte 5 (preferred) $effect(() => { return () => { console.log('Component destroyed'); @@ -56,25 +57,25 @@ $effect(() => { }); // beforeUpdate equivalent -// Svelte 4 +// Svelte 4 (legacy) import { beforeUpdate } from 'svelte'; beforeUpdate(() => { console.log('Before DOM updates'); }); -// Svelte 5 +// Svelte 5 (preferred) $effect.pre(() => { console.log('Before DOM updates'); }); // afterUpdate equivalent -// Svelte 4 +// Svelte 4 (legacy) import { afterUpdate } from 'svelte'; afterUpdate(() => { console.log('After DOM updates'); }); -// Svelte 5 +// Svelte 5 (preferred) let count = $state(0); $effect(() => { count; // Track state dependency @@ -103,4 +104,5 @@ $effect(() => { - `$effect` - Main lifecycle replacement rune - `$effect.pre` - beforeUpdate equivalent - `migration-patterns` - Complete Svelte 4→5 conversion guide +- `$effect` - Primary lifecycle mechanism in Svelte 5 - `common-mistakes` - Pitfalls when converting lifecycle code diff --git a/definitions/load.md b/definitions/load.md new file mode 100644 index 0000000..0c55dce --- /dev/null +++ b/definitions/load.md @@ -0,0 +1,48 @@ +# load Definition + +**Definition:** Data loading function for pages and layouts. Page +`load` runs in the browser (and server on the first render); layout +`load` runs where it is invoked. A `load` in `+page.server.ts`/`.js` +or `+layout.server.ts`/`.js` runs only on the server. + +**Syntax:** + +- Page: + `export const load: PageLoad = ({ fetch, params, data, depends, parent }) => { ... }` +- Layout: + `export const load: LayoutLoad = ({ fetch, params, data, depends, parent }) => { ... }` +- Server: + `export const load: PageServerLoad | LayoutServerLoad = ({ cookies, locals, setHeaders, fetch }) => { ... }` + +**Parameters:** + +- `fetch` — SvelteKit-aware fetch +- `params` — route parameters +- `data` — parent data (layout→child) +- `depends` — declare cache dependencies +- `parent` — await parent data +- `cookies`, `locals`, `setHeaders` — server-only + +**Returns:** Object merged into `data` for the corresponding +component. + +## Example + +```ts +// +page.ts +export const load: import('./$types').PageLoad = async ({ + fetch, + params, + depends, +}) => { + depends('app:posts'); + const res = await fetch(`/api/posts?tag=${params.tag}`); + return { posts: await res.json() }; +}; +``` + +## Related + +- `depends`, `parent`, `setHeaders` +- `+page.svelte`, `+layout.svelte` +- `error`, `redirect` diff --git a/definitions/locals.md b/definitions/locals.md new file mode 100644 index 0000000..a18ac5c --- /dev/null +++ b/definitions/locals.md @@ -0,0 +1,26 @@ +# locals Definition + +**Definition:** Per-request mutable object available on the server for +storing authenticated user/session or request-scoped data. + +**Access:** `event.locals` in server `load`, form actions, and +`+server` endpoints. + +**Typing:** Extend `App.Locals` in `src/app.d.ts` to define shape. + +## Example + +```ts +// src/hooks.server.ts +export const handle = async ({ event, resolve }) => { + event.locals.user = await getUser(event.cookies.get('sessionid')); + return resolve(event); +}; + +// +page.server.ts +export const load = ({ locals }) => ({ user: locals.user }); +``` + +## Related + +- `hooks.server`, `cookies` diff --git a/definitions/migration-patterns.md b/definitions/migration-patterns.md index fce28e0..60a60a0 100644 --- a/definitions/migration-patterns.md +++ b/definitions/migration-patterns.md @@ -8,13 +8,18 @@ direct equivalents - State management: `let` → `$state` - Reactivity: `$:` → `$derived` or `$effect` - Props: `export let` → `$props()` -- Lifecycle: `onMount` → `$effect` +- Lifecycle: `onMount` → `$effect` +- Events: `on:click` → `onclick` +- Slots: ``/named slots → `{#snippet}`/`{@render}` +- Component events: `createEventDispatcher` → event props (see + `component-events`, `custom-events`) +- Bindings: `bind:` remains; add `$bindable` for 2‑way prop binding **Returns:** Direct migration patterns for upgrading components **Purpose:** Systematic conversion guide from Svelte 4 patterns ## Examples -```js +```ts // STATE MIGRATION // Svelte 4 let count = 0; diff --git a/definitions/optional-parameters.md b/definitions/optional-parameters.md new file mode 100644 index 0000000..42bcdc0 --- /dev/null +++ b/definitions/optional-parameters.md @@ -0,0 +1,16 @@ +# optional-parameters Definition + +**Definition:** Wrap a dynamic segment in double brackets `[[param]]` +to make it optional. + +**Syntax:** `src/routes/[[lang]]/home/+page.svelte` matches `/home` +and `/en/home`. + +Notes: + +- An optional parameter cannot follow a rest parameter (e.g., + `[...rest]/[[opt]]`). + +## Related + +- `rest-parameters`, `param-matchers` diff --git a/definitions/page-reset-layout.md b/definitions/page-reset-layout.md new file mode 100644 index 0000000..d9b0b44 --- /dev/null +++ b/definitions/page-reset-layout.md @@ -0,0 +1,14 @@ +# page-reset-layout Definition + +**Definition:** Use `+page@.svelte` (or `+page@.svelte` for +root) to reset which ancestor layout a page inherits from. + +**Syntax:** `+page@[id].svelte`, `+page@item.svelte`, +`+page@(group).svelte`, `+page@.svelte` + +**Returns:** The page uses the chosen ancestor layout instead of the +nearest one. + +## Related + +- `layout-reset`, `layout-groups`, `advanced-routing` diff --git a/definitions/param-matchers.md b/definitions/param-matchers.md new file mode 100644 index 0000000..b23e048 --- /dev/null +++ b/definitions/param-matchers.md @@ -0,0 +1,22 @@ +# param-matchers Definition + +**Definition:** Validate dynamic segments with matchers implemented in +`src/params/`. Use `[param=name]` in route path. + +**Syntax:** + +- `src/params/fruit.(js|ts)` exports `match(param): boolean` +- `src/routes/fruits/[page=fruit]/+page.svelte` + +## Example + +```ts +// src/params/fruit.ts +import type { ParamMatcher } from '@sveltejs/kit'; +export const match = ((param: string): param is 'apple' | 'orange' => + param === 'apple' || param === 'orange') satisfies ParamMatcher; +``` + +## Related + +- `advanced-routing`, `optional-parameters`, `rest-parameters` diff --git a/definitions/parent.md b/definitions/parent.md new file mode 100644 index 0000000..b105f87 --- /dev/null +++ b/definitions/parent.md @@ -0,0 +1,21 @@ +# parent Definition + +**Definition:** Function available in `load` that returns a promise +resolving to parent data (layout→child). + +**Syntax:** `const data = await parent()` + +**Returns:** The parent loader’s returned data object. + +## Example + +```ts +export const load = async ({ parent }) => { + const { user } = await parent(); + return { user }; +}; +``` + +## Related + +- `load`, `+layout.svelte` diff --git a/definitions/redirect.md b/definitions/redirect.md new file mode 100644 index 0000000..b176b0b --- /dev/null +++ b/definitions/redirect.md @@ -0,0 +1,22 @@ +# redirect Definition + +**Definition:** Throw an HTTP redirect with status and location. + +**Syntax (Kit 2+):** `throw redirect(status, location)` + +Important: + +- You must `throw redirect(...)` — do not call it without throwing. +- Use inside server/universal `load`, actions, and `+server` handlers. + +## Example + +```ts +import { redirect } from '@sveltejs/kit'; +throw redirect(303, '/login'); +``` + +## Related + +- `error`, `json` +- `actions` diff --git a/definitions/remote-functions.md b/definitions/remote-functions.md index f291d2c..155395f 100644 --- a/definitions/remote-functions.md +++ b/definitions/remote-functions.md @@ -1,94 +1,54 @@ # remote-functions Definition -**Definition:** SvelteKit experimental feature for type-safe -client-server communication without manual API endpoints -**Syntax:** `export async function myFunction() { ... }` in -`+page.server.js` with client import -**Parameters:** - -- Server-side function definitions -- Client-side imports and calls **Returns:** Type-safe function calls - across client-server boundary - **Status:** Experimental SvelteKit feature - -## Examples - -```js -// src/routes/+page.server.js -export async function getUserData(userId) { - // This runs on the server - const user = await db.users.findById(userId); - return { - id: user.id, - name: user.name, - email: user.email - }; -} - -export async function updateUser(userId, data) { - // Server-side validation and update - const updatedUser = await db.users.update(userId, data); - return updatedUser; -} - -// src/routes/+page.svelte - - -
- {#if userData} -

{userData.name}

-

{userData.email}

- - {:else} -

Loading...

- {/if} -
- -// TypeScript support -// src/routes/api/+page.server.ts -export async function getTypedData(): Promise<{ count: number; items: string[] }> { - return { - count: 42, - items: ['a', 'b', 'c'] - }; -} - -// Client gets full type safety -// src/routes/+page.svelte - -``` +- Remote files live under `src/` and export functions; client calls + fetch generated endpoints. +- Use `getRequestEvent()` inside to access cookies/locals. +- Validation uses Standard Schema (e.g., Zod/Valibot). Use + `'unchecked'` to skip. +- `redirect(...)` allowed in `query/form/prerender`, not in `command`. ## Related -- `await-expressions` - For handling async calls in templates -- `$effect` - For calling remote functions reactively -- `$state` - For storing remote function results +- `$app/server`, `$app/navigation.refreshAll`, `await-expressions`, + `$derived` diff --git a/definitions/rest-parameters.md b/definitions/rest-parameters.md new file mode 100644 index 0000000..2ec512d --- /dev/null +++ b/definitions/rest-parameters.md @@ -0,0 +1,22 @@ +# rest-parameters Definition + +**Definition:** Route segment syntax `[...name]` captures the +remainder of a path into `params.name`, possibly empty. + +**Syntax:** `src/routes/a/[...rest]/z/+page.svelte` matches `/a/z`, +`/a/b/z`, `/a/b/c/z`, ... + +**Returns:** `params.rest` with `/`-joined remainder. + +## Example + +```txt +/[org]/[repo]/tree/[branch]/[...file] +``` + +`/sveltejs/kit/tree/main/documentation/docs/file.md` → +`{ org, repo, branch, file: 'documentation/docs/file.md' }` + +## Related + +- `optional-parameters`, `param-matchers`, `advanced-routing` diff --git a/definitions/setHeaders.md b/definitions/setHeaders.md new file mode 100644 index 0000000..ec39fe0 --- /dev/null +++ b/definitions/setHeaders.md @@ -0,0 +1,32 @@ +# setHeaders Definition + +**Definition:** Helper available in `load` (server and universal) to +set HTTP headers on the response during SSR. + +**Syntax:** `setHeaders(headers: Record)` + +Important: + +- No effect in the browser; only works during SSR/build. +- You cannot set `set-cookie` — use `cookies.set(...)` in server + `load`/actions. +- Each header can be set at most once across all `load` functions. + +## Example + +```ts +export const load: import('./$types').PageLoad = async ({ + fetch, + setHeaders, +}) => { + const res = await fetch('/api/data'); + setHeaders({ + 'cache-control': res.headers.get('cache-control') ?? 'max-age=60', + }); + return { data: await res.json() }; +}; +``` + +## Related + +- `load`, `cookies`, `+server.ts`