svelte
Version:
Cybernetically enhanced web apps
1,559 lines (1,439 loc) • 108 kB
TypeScript
declare module 'svelte' {
/**
* @deprecated In Svelte 4, components are classes. In Svelte 5, they are functions.
* Use `mount` instead to instantiate components.
* See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
export interface ComponentConstructorOptions<
Props extends Record<string, any> = Record<string, any>
> {
target: Element | Document | ShadowRoot;
anchor?: Element;
props?: Props;
context?: Map<any, any>;
hydrate?: boolean;
intro?: boolean;
recover?: boolean;
sync?: boolean;
idPrefix?: string;
$$inline?: boolean;
}
/**
* Utility type for ensuring backwards compatibility on a type level that if there's a default slot, add 'children' to the props
*/
type Properties<Props, Slots> = Props &
(Slots extends { default: any }
? // This is unfortunate because it means "accepts no props" turns into "accepts any prop"
// but the alternative is non-fixable type errors because of the way TypeScript index
// signatures work (they will always take precedence and make an impossible-to-satisfy children type).
Props extends Record<string, never>
? any
: { children?: any }
: {});
/**
* This was the base class for Svelte components in Svelte 4. Svelte 5+ components
* are completely different under the hood. For typing, use `Component` instead.
* To instantiate components, use `mount` instead.
* See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
*/
export class SvelteComponent<
Props extends Record<string, any> = Record<string, any>,
Events extends Record<string, any> = any,
Slots extends Record<string, any> = any
> {
/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */
static element?: typeof HTMLElement;
[prop: string]: any;
/**
* @deprecated This constructor only exists when using the `asClassComponent` compatibility helper, which
* is a stop-gap solution. Migrate towards using `mount` instead. See
* [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
*/
constructor(options: ComponentConstructorOptions<Properties<Props, Slots>>);
/**
* For type checking capabilities only.
* Does not exist at runtime.
* ### DO NOT USE!
*/
$$prop_def: Props; // Without Properties: unnecessary, causes type bugs
/**
* For type checking capabilities only.
* Does not exist at runtime.
* ### DO NOT USE!
*/
$$events_def: Events;
/**
* For type checking capabilities only.
* Does not exist at runtime.
* ### DO NOT USE!
*/
$$slot_def: Slots;
/**
* For type checking capabilities only.
* Does not exist at runtime.
* ### DO NOT USE!
*/
$$bindings?: string;
/**
* @deprecated This method only exists when using one of the legacy compatibility helpers, which
* is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$destroy(): void;
/**
* @deprecated This method only exists when using one of the legacy compatibility helpers, which
* is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$on<K extends Extract<keyof Events, string>>(
type: K,
callback: (e: Events[K]) => void
): () => void;
/**
* @deprecated This method only exists when using one of the legacy compatibility helpers, which
* is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$set(props: Partial<Props>): void;
}
const brand: unique symbol;
type Brand<B> = { [brand]: B };
type Branded<T, B> = T & Brand<B>;
/**
* Internal implementation details that vary between environments
*/
export type ComponentInternals = Branded<{}, 'ComponentInternals'>;
/**
* Can be used to create strongly typed Svelte components.
*
* #### Example:
*
* You have component library on npm called `component-library`, from which
* you export a component called `MyComponent`. For Svelte+TypeScript users,
* you want to provide typings. Therefore you create a `index.d.ts`:
* ```ts
* import type { Component } from 'svelte';
* export declare const MyComponent: Component<{ foo: string }> {}
* ```
* Typing this makes it possible for IDEs like VS Code with the Svelte extension
* to provide intellisense and to use the component like this in a Svelte file
* with TypeScript:
* ```svelte
* <script lang="ts">
* import { MyComponent } from "component-library";
* </script>
* <MyComponent foo={'bar'} />
* ```
*/
export interface Component<
Props extends Record<string, any> = {},
Exports extends Record<string, any> = {},
Bindings extends keyof Props | '' = string
> {
/**
* @param internal An internal object used by Svelte. Do not use or modify.
* @param props The props passed to the component.
*/
(
this: void,
internals: ComponentInternals,
props: Props
): {
/**
* @deprecated This method only exists when using one of the legacy compatibility helpers, which
* is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$on?(type: string, callback: (e: any) => void): () => void;
/**
* @deprecated This method only exists when using one of the legacy compatibility helpers, which
* is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$set?(props: Partial<Props>): void;
} & Exports;
/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */
element?: typeof HTMLElement;
/** Does not exist at runtime, for typing capabilities only. DO NOT USE */
z_$$bindings?: Bindings;
}
/**
* @deprecated Use `Component` instead. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information.
*/
export class SvelteComponentTyped<
Props extends Record<string, any> = Record<string, any>,
Events extends Record<string, any> = any,
Slots extends Record<string, any> = any
> extends SvelteComponent<Props, Events, Slots> {}
/**
* @deprecated The new `Component` type does not have a dedicated Events type. Use `ComponentProps` instead.
*
* @description
* Convenience type to get the events the given component expects. Example:
* ```html
* <script lang="ts">
* import type { ComponentEvents } from 'svelte';
* import Component from './Component.svelte';
*
* function handleCloseEvent(event: ComponentEvents<Component>['close']) {
* console.log(event.detail);
* }
* </script>
*
* <Component on:close={handleCloseEvent} />
* ```
*/
export type ComponentEvents<Comp extends SvelteComponent> =
Comp extends SvelteComponent<any, infer Events> ? Events : never;
/**
* Convenience type to get the props the given component expects.
*
* Example: Ensure a variable contains the props expected by `MyComponent`:
*
* ```ts
* import type { ComponentProps } from 'svelte';
* import MyComponent from './MyComponent.svelte';
*
* // Errors if these aren't the correct props expected by MyComponent.
* const props: ComponentProps<typeof MyComponent> = { foo: 'bar' };
* ```
*
* > [!NOTE] In Svelte 4, you would do `ComponentProps<MyComponent>` because `MyComponent` was a class.
*
* Example: A generic function that accepts some component and infers the type of its props:
*
* ```ts
* import type { Component, ComponentProps } from 'svelte';
* import MyComponent from './MyComponent.svelte';
*
* function withProps<TComponent extends Component<any>>(
* component: TComponent,
* props: ComponentProps<TComponent>
* ) {};
*
* // Errors if the second argument is not the correct props expected by the component in the first argument.
* withProps(MyComponent, { foo: 'bar' });
* ```
*/
export type ComponentProps<Comp extends SvelteComponent | Component<any, any>> =
Comp extends SvelteComponent<infer Props>
? Props
: Comp extends Component<infer Props, any>
? Props
: never;
/**
* @deprecated This type is obsolete when working with the new `Component` type.
*
* @description
* Convenience type to get the type of a Svelte component. Useful for example in combination with
* dynamic components using `<svelte:component>`.
*
* Example:
* ```html
* <script lang="ts">
* import type { ComponentType, SvelteComponent } from 'svelte';
* import Component1 from './Component1.svelte';
* import Component2 from './Component2.svelte';
*
* const component: ComponentType = someLogic() ? Component1 : Component2;
* const componentOfCertainSubType: ComponentType<SvelteComponent<{ needsThisProp: string }>> = someLogic() ? Component1 : Component2;
* </script>
*
* <svelte:component this={component} />
* <svelte:component this={componentOfCertainSubType} needsThisProp="hello" />
* ```
*/
export type ComponentType<Comp extends SvelteComponent = SvelteComponent> = (new (
options: ComponentConstructorOptions<
Comp extends SvelteComponent<infer Props> ? Props : Record<string, any>
>
) => Comp) & {
/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */
element?: typeof HTMLElement;
};
const SnippetReturn: unique symbol;
// Use an interface instead of a type, makes for better intellisense info because the type is named in more situations.
/**
* The type of a `#snippet` block. You can use it to (for example) express that your component expects a snippet of a certain type:
* ```ts
* let { banner }: { banner: Snippet<[{ text: string }]> } = $props();
* ```
* You can only call a snippet through the `{@render ...}` tag.
*
* See the [snippet documentation](https://svelte.dev/docs/svelte/snippet) for more info.
*
* @template Parameters the parameters that the snippet expects (if any) as a tuple.
*/
export interface Snippet<Parameters extends unknown[] = []> {
(
this: void,
// this conditional allows tuples but not arrays. Arrays would indicate a
// rest parameter type, which is not supported. If rest parameters are added
// in the future, the condition can be removed.
...args: number extends Parameters['length'] ? never : Parameters
): {
'{@render ...} must be called with a Snippet': "import type { Snippet } from 'svelte'";
} & typeof SnippetReturn;
}
interface DispatchOptions {
cancelable?: boolean;
}
export interface EventDispatcher<EventMap extends Record<string, any>> {
// Implementation notes:
// - undefined extends X instead of X extends undefined makes this work better with both strict and nonstrict mode
// - | null | undefined is added for convenience, as they are equivalent for the custom event constructor (both result in a null detail)
<Type extends keyof EventMap>(
...args: null extends EventMap[Type]
? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]
: undefined extends EventMap[Type]
? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]
: [type: Type, parameter: EventMap[Type], options?: DispatchOptions]
): boolean;
}
/**
* Defines the options accepted by the `mount()` function.
*/
export type MountOptions<Props extends Record<string, any> = Record<string, any>> = {
/**
* Target element where the component will be mounted.
*/
target: Document | Element | ShadowRoot;
/**
* Optional node inside `target`. When specified, it is used to render the component immediately before it.
*/
anchor?: Node;
/**
* Allows the specification of events.
* @deprecated Use callback props instead.
*/
events?: Record<string, (e: any) => any>;
/**
* Can be accessed via `getContext()` at the component level.
*/
context?: Map<any, any>;
/**
* Whether or not to play transitions on initial render.
* @default true
*/
intro?: boolean;
} & ({} extends Props
? {
/**
* Component properties.
*/
props?: Props;
}
: {
/**
* Component properties.
*/
props: Props;
});
/**
* `onMount`, like [`$effect`](https://svelte.dev/docs/svelte/$effect), schedules a function to run as soon as the component has been mounted to the DOM.
* Unlike `$effect`, the provided function only runs once.
*
* It must be called during the component's initialisation (but doesn't need to live _inside_ the component;
* it can be called from an external module). If a function is returned _synchronously_ from `onMount`,
* it will be called when the component is unmounted.
*
* `onMount` functions do not run during [server-side rendering](https://svelte.dev/docs/svelte/svelte-server#render).
*
* */
export function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void;
/**
* Schedules a callback to run immediately before the component is unmounted.
*
* Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the
* only one that runs inside a server-side component.
*
* */
export function onDestroy(fn: () => any): void;
/**
* Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs/svelte/legacy-on#Component-events).
* Event dispatchers are functions that can take two arguments: `name` and `detail`.
*
* Component events created with `createEventDispatcher` create a
* [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).
* These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).
* The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)
* property and can contain any type of data.
*
* The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument:
* ```ts
* const dispatch = createEventDispatcher<{
* loaded: null; // does not take a detail argument
* change: string; // takes a detail argument of type string, which is required
* optional: number | null; // takes an optional detail argument of type number
* }>();
* ```
*
* @deprecated Use callback props and/or the `$host()` rune instead — see [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes-Component-events)
* */
export function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>;
/**
* Schedules a callback to run immediately before the component is updated after any state change.
*
* The first time the callback runs will be before the initial `onMount`.
*
* In runes mode use `$effect.pre` instead.
*
* @deprecated Use [`$effect.pre`](https://svelte.dev/docs/svelte/$effect#$effect.pre) instead
* */
export function beforeUpdate(fn: () => void): void;
/**
* Schedules a callback to run immediately after the component has been updated.
*
* The first time the callback runs will be after the initial `onMount`.
*
* In runes mode use `$effect` instead.
*
* @deprecated Use [`$effect`](https://svelte.dev/docs/svelte/$effect) instead
* */
export function afterUpdate(fn: () => void): void;
/**
* Create a snippet programmatically
* */
export function createRawSnippet<Params extends unknown[]>(fn: (...params: Getters<Params>) => {
render: () => string;
setup?: (element: Element) => void | (() => void);
}): Snippet<Params>;
/** Anything except a function */
type NotFunction<T> = T extends Function ? never : T;
/**
* Synchronously flush any pending updates.
* Returns void if no callback is provided, otherwise returns the result of calling the callback.
* */
export function flushSync<T = void>(fn?: (() => T) | undefined): T;
/**
* Returns a promise that resolves once any pending state changes have been applied.
* */
export function tick(): Promise<void>;
/**
* When used inside a [`$derived`](https://svelte.dev/docs/svelte/$derived) or [`$effect`](https://svelte.dev/docs/svelte/$effect),
* any state read inside `fn` will not be treated as a dependency.
*
* ```ts
* $effect(() => {
* // this will run when `data` changes, but not when `time` changes
* save(data, {
* timestamp: untrack(() => time)
* });
* });
* ```
* */
export function untrack<T>(fn: () => T): T;
/**
* Retrieves the context that belongs to the closest parent component with the specified `key`.
* Must be called during component initialisation.
*
* */
export function getContext<T>(key: any): T;
/**
* Associates an arbitrary `context` object with the current component and the specified `key`
* and returns that object. The context is then available to children of the component
* (including slotted content) with `getContext`.
*
* Like lifecycle functions, this must be called during component initialisation.
*
* */
export function setContext<T>(key: any, context: T): T;
/**
* Checks whether a given `key` has been set in the context of a parent component.
* Must be called during component initialisation.
*
* */
export function hasContext(key: any): boolean;
/**
* Retrieves the whole context map that belongs to the closest parent component.
* Must be called during component initialisation. Useful, for example, if you
* programmatically create a component and want to pass the existing context to it.
*
* */
export function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;
/**
* Mounts a component to the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component.
* Transitions will play during the initial render unless the `intro` option is set to `false`.
*
* */
export function mount<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: MountOptions<Props>): Exports;
/**
* Hydrates a component on the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component
*
* */
export function hydrate<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: {} extends Props ? {
target: Document | Element | ShadowRoot;
props?: Props;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
recover?: boolean;
} : {
target: Document | Element | ShadowRoot;
props: Props;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
recover?: boolean;
}): Exports;
/**
* Unmounts a component that was previously mounted using `mount` or `hydrate`.
*
* Since 5.13.0, if `options.outro` is `true`, [transitions](https://svelte.dev/docs/svelte/transition) will play before the component is removed from the DOM.
*
* Returns a `Promise` that resolves after transitions have completed if `options.outro` is true, or immediately otherwise (prior to 5.13.0, returns `void`).
*
* ```js
* import { mount, unmount } from 'svelte';
* import App from './App.svelte';
*
* const app = mount(App, { target: document.body });
*
* // later...
* unmount(app, { outro: true });
* ```
* */
export function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>;
type Getters<T> = {
[K in keyof T]: () => T[K];
};
export {};
}
declare module 'svelte/action' {
/**
* Actions can return an object containing the two properties defined in this interface. Both are optional.
* - update: An action can have a parameter. This method will be called whenever that parameter changes,
* immediately after Svelte has applied updates to the markup. `ActionReturn` and `ActionReturn<undefined>` both
* mean that the action accepts no parameters.
* - destroy: Method that is called after the element is unmounted
*
* Additionally, you can specify which additional attributes and events the action enables on the applied element.
* This applies to TypeScript typings only and has no effect at runtime.
*
* Example usage:
* ```ts
* interface Attributes {
* newprop?: string;
* 'on:event': (e: CustomEvent<boolean>) => void;
* }
*
* export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {
* // ...
* return {
* update: (updatedParameter) => {...},
* destroy: () => {...}
* };
* }
* ```
*/
export interface ActionReturn<
Parameter = undefined,
Attributes extends Record<string, any> = Record<never, any>
> {
update?: (parameter: Parameter) => void;
destroy?: () => void;
/**
* ### DO NOT USE THIS
* This exists solely for type-checking and has no effect at runtime.
* Set this through the `Attributes` generic instead.
*/
$$_attributes?: Attributes;
}
/**
* Actions are functions that are called when an element is created.
* You can use this interface to type such actions.
* The following example defines an action that only works on `<div>` elements
* and optionally accepts a parameter which it has a default value for:
* ```ts
* export const myAction: Action<HTMLDivElement, { someProperty: boolean } | undefined> = (node, param = { someProperty: true }) => {
* // ...
* }
* ```
* `Action<HTMLDivElement>` and `Action<HTMLDivElement, undefined>` both signal that the action accepts no parameters.
*
* You can return an object with methods `update` and `destroy` from the function and type which additional attributes and events it has.
* See interface `ActionReturn` for more details.
*/
export interface Action<
Element = HTMLElement,
Parameter = undefined,
Attributes extends Record<string, any> = Record<never, any>
> {
<Node extends Element>(
...args: undefined extends Parameter
? [node: Node, parameter?: Parameter]
: [node: Node, parameter: Parameter]
): void | ActionReturn<Parameter, Attributes>;
}
// Implementation notes:
// - undefined extends X instead of X extends undefined makes this work better with both strict and nonstrict mode
export {};
}
declare module 'svelte/animate' {
// todo: same as Transition, should it be shared?
export interface AnimationConfig {
delay?: number;
duration?: number;
easing?: (t: number) => number;
css?: (t: number, u: number) => string;
tick?: (t: number, u: number) => void;
}
export interface FlipParams {
delay?: number;
duration?: number | ((len: number) => number);
easing?: (t: number) => number;
}
/**
* The flip function calculates the start and end position of an element and animates between them, translating the x and y values.
* `flip` stands for [First, Last, Invert, Play](https://aerotwist.com/blog/flip-your-animations/).
*
* */
export function flip(node: Element, { from, to }: {
from: DOMRect;
to: DOMRect;
}, params?: FlipParams): AnimationConfig;
export {};
}
declare module 'svelte/compiler' {
import type { SourceMap } from 'magic-string';
import type { ArrayExpression, ArrowFunctionExpression, VariableDeclaration, VariableDeclarator, Expression, Identifier, MemberExpression, Node, ObjectExpression, Pattern, Program, ChainExpression, SimpleCallExpression, SequenceExpression } from 'estree';
import type { Location } from 'locate-character';
/**
* `compile` converts your `.svelte` source code into a JavaScript module that exports a component
*
* @param source The component source code
* @param options The compiler options
* */
export function compile(source: string, options: CompileOptions): CompileResult;
/**
* `compileModule` takes your JavaScript source code containing runes, and turns it into a JavaScript module.
*
* @param source The component source code
* */
export function compileModule(source: string, options: ModuleCompileOptions): CompileResult;
/**
* The parse function parses a component, returning only its abstract syntax tree.
*
* The `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST.
* `modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7.
*
* */
export function parse(source: string, options: {
filename?: string;
modern: true;
loose?: boolean;
}): AST.Root;
/**
* The parse function parses a component, returning only its abstract syntax tree.
*
* The `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST.
* `modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7.
*
* */
export function parse(source: string, options?: {
filename?: string;
modern?: false;
loose?: boolean;
} | undefined): Record<string, any>;
/**
* @deprecated Replace this with `import { walk } from 'estree-walker'`
* */
export function walk(): never;
/**
* The result of a preprocessor run. If the preprocessor does not return a result, it is assumed that the code is unchanged.
*/
export interface Processed {
/**
* The new code
*/
code: string;
/**
* A source map mapping back to the original code
*/
map?: string | object; // we are opaque with the type here to avoid dependency on the remapping module for our public types.
/**
* A list of additional files to watch for changes
*/
dependencies?: string[];
/**
* Only for script/style preprocessors: The updated attributes to set on the tag. If undefined, attributes stay unchanged.
*/
attributes?: Record<string, string | boolean>;
toString?: () => string;
}
/**
* A markup preprocessor that takes a string of code and returns a processed version.
*/
export type MarkupPreprocessor = (options: {
/**
* The whole Svelte file content
*/
content: string;
/**
* The filename of the Svelte file
*/
filename?: string;
}) => Processed | void | Promise<Processed | void>;
/**
* A script/style preprocessor that takes a string of code and returns a processed version.
*/
export type Preprocessor = (options: {
/**
* The script/style tag content
*/
content: string;
/**
* The attributes on the script/style tag
*/
attributes: Record<string, string | boolean>;
/**
* The whole Svelte file content
*/
markup: string;
/**
* The filename of the Svelte file
*/
filename?: string;
}) => Processed | void | Promise<Processed | void>;
/**
* A preprocessor group is a set of preprocessors that are applied to a Svelte file.
*/
export interface PreprocessorGroup {
/** Name of the preprocessor. Will be a required option in the next major version */
name?: string;
markup?: MarkupPreprocessor;
style?: Preprocessor;
script?: Preprocessor;
}
/** The return value of `compile` from `svelte/compiler` */
export interface CompileResult {
/** The compiled JavaScript */
js: {
/** The generated code */
code: string;
/** A source map */
map: SourceMap;
};
/** The compiled CSS */
css: null | {
/** The generated code */
code: string;
/** A source map */
map: SourceMap;
/** Whether or not the CSS includes global rules */
hasGlobal: boolean;
};
/**
* An array of warning objects that were generated during compilation. Each warning has several properties:
* - `code` is a string identifying the category of warning
* - `message` describes the issue in human-readable terms
* - `start` and `end`, if the warning relates to a specific location, are objects with `line`, `column` and `character` properties
*/
warnings: Warning[];
/**
* Metadata about the compiled component
*/
metadata: {
/**
* Whether the file was compiled in runes mode, either because of an explicit option or inferred from usage.
* For `compileModule`, this is always `true`
*/
runes: boolean;
};
/** The AST */
ast: any;
}
export interface Warning extends ICompileDiagnostic {}
export interface CompileError extends ICompileDiagnostic {}
type CssHashGetter = (args: {
name: string;
filename: string;
css: string;
hash: (input: string) => string;
}) => string;
export interface CompileOptions extends ModuleCompileOptions {
/**
* Sets the name of the resulting JavaScript class (though the compiler will rename it if it would otherwise conflict with other variables in scope).
* If unspecified, will be inferred from `filename`
*/
name?: string;
/**
* If `true`, tells the compiler to generate a custom element constructor instead of a regular Svelte component.
*
* @default false
*/
customElement?: boolean;
/**
* If `true`, getters and setters will be created for the component's props. If `false`, they will only be created for readonly exported values (i.e. those declared with `const`, `class` and `function`). If compiling with `customElement: true` this option defaults to `true`.
*
* @default false
* @deprecated This will have no effect in runes mode
*/
accessors?: boolean;
/**
* The namespace of the element; e.g., `"html"`, `"svg"`, `"mathml"`.
*
* @default 'html'
*/
namespace?: Namespace;
/**
* If `true`, tells the compiler that you promise not to mutate any objects.
* This allows it to be less conservative about checking whether values have changed.
*
* @default false
* @deprecated This will have no effect in runes mode
*/
immutable?: boolean;
/**
* - `'injected'`: styles will be included in the `head` when using `render(...)`, and injected into the document (if not already present) when the component mounts. For components compiled as custom elements, styles are injected to the shadow root.
* - `'external'`: the CSS will only be returned in the `css` field of the compilation result. Most Svelte bundler plugins will set this to `'external'` and use the CSS that is statically generated for better performance, as it will result in smaller JavaScript bundles and the output can be served as cacheable `.css` files.
* This is always `'injected'` when compiling with `customElement` mode.
*/
css?: 'injected' | 'external';
/**
* A function that takes a `{ hash, css, name, filename }` argument and returns the string that is used as a classname for scoped CSS.
* It defaults to returning `svelte-${hash(css)}`.
*
* @default undefined
*/
cssHash?: CssHashGetter;
/**
* If `true`, your HTML comments will be preserved in the output. By default, they are stripped out.
*
* @default false
*/
preserveComments?: boolean;
/**
* If `true`, whitespace inside and between elements is kept as you typed it, rather than removed or collapsed to a single space where possible.
*
* @default false
*/
preserveWhitespace?: boolean;
/**
* Set to `true` to force the compiler into runes mode, even if there are no indications of runes usage.
* Set to `false` to force the compiler into ignoring runes, even if there are indications of runes usage.
* Set to `undefined` (the default) to infer runes mode from the component code.
* Is always `true` for JS/TS modules compiled with Svelte.
* Will be `true` by default in Svelte 6.
* Note that setting this to `true` in your `svelte.config.js` will force runes mode for your entire project, including components in `node_modules`,
* which is likely not what you want. If you're using Vite, consider using [dynamicCompileOptions](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#dynamiccompileoptions) instead.
* @default undefined
*/
runes?: boolean | undefined;
/**
* If `true`, exposes the Svelte major version in the browser by adding it to a `Set` stored in the global `window.__svelte.v`.
*
* @default true
*/
discloseVersion?: boolean;
/**
* @deprecated Use these only as a temporary solution before migrating your code
*/
compatibility?: {
/**
* Applies a transformation so that the default export of Svelte files can still be instantiated the same way as in Svelte 4 —
* as a class when compiling for the browser (as though using `createClassComponent(MyComponent, {...})` from `svelte/legacy`)
* or as an object with a `.render(...)` method when compiling for the server
* @default 5
*/
componentApi?: 4 | 5;
};
/**
* An initial sourcemap that will be merged into the final output sourcemap.
* This is usually the preprocessor sourcemap.
*
* @default null
*/
sourcemap?: object | string;
/**
* Used for your JavaScript sourcemap.
*
* @default null
*/
outputFilename?: string;
/**
* Used for your CSS sourcemap.
*
* @default null
*/
cssOutputFilename?: string;
/**
* If `true`, compiles components with hot reloading support.
*
* @default false
*/
hmr?: boolean;
/**
* If `true`, returns the modern version of the AST.
* Will become `true` by default in Svelte 6, and the option will be removed in Svelte 7.
*
* @default false
*/
modernAst?: boolean;
}
export interface ModuleCompileOptions {
/**
* If `true`, causes extra code to be added that will perform runtime checks and provide debugging information during development.
*
* @default false
*/
dev?: boolean;
/**
* If `"client"`, Svelte emits code designed to run in the browser.
* If `"server"`, Svelte emits code suitable for server-side rendering.
* If `false`, nothing is generated. Useful for tooling that is only interested in warnings.
*
* @default 'client'
*/
generate?: 'client' | 'server' | false;
/**
* Used for debugging hints and sourcemaps. Your bundler plugin will set it automatically.
*/
filename?: string;
/**
* Used for ensuring filenames don't leak filesystem information. Your bundler plugin will set it automatically.
* @default process.cwd() on node-like environments, undefined elsewhere
*/
rootDir?: string;
/**
* A function that gets a `Warning` as an argument and returns a boolean.
* Use this to filter out warnings. Return `true` to keep the warning, `false` to discard it.
*/
warningFilter?: (warning: Warning) => boolean;
}
/**
* - `html` — the default, for e.g. `<div>` or `<span>`
* - `svg` — for e.g. `<svg>` or `<g>`
* - `mathml` — for e.g. `<math>` or `<mrow>`
*/
type Namespace = 'html' | 'svg' | 'mathml';
export namespace AST {
export interface BaseNode {
type: string;
start: number;
end: number;
}
export interface Fragment {
type: 'Fragment';
nodes: Array<Text | Tag | ElementLike | Block | Comment>;
}
export interface Root extends BaseNode {
type: 'Root';
/**
* Inline options provided by `<svelte:options>` — these override options passed to `compile(...)`
*/
options: SvelteOptions | null;
fragment: Fragment;
/** The parsed `<style>` element, if exists */
css: AST.CSS.StyleSheet | null;
/** The parsed `<script>` element, if exists */
instance: Script | null;
/** The parsed `<script module>` element, if exists */
module: Script | null;
}
export interface SvelteOptions {
// start/end info (needed for warnings and for our Prettier plugin)
start: number;
end: number;
// options
runes?: boolean;
immutable?: boolean;
accessors?: boolean;
preserveWhitespace?: boolean;
namespace?: Namespace;
css?: 'injected';
customElement?: {
tag?: string;
shadow?: 'open' | 'none';
props?: Record<
string,
{
attribute?: string;
reflect?: boolean;
type?: 'Array' | 'Boolean' | 'Number' | 'Object' | 'String';
}
>;
/**
* Is of type
* ```ts
* (ceClass: new () => HTMLElement) => new () => HTMLElement
* ```
*/
extend?: ArrowFunctionExpression | Identifier;
};
attributes: Attribute[];
}
/** Static text */
export interface Text extends BaseNode {
type: 'Text';
/** Text with decoded HTML entities */
data: string;
/** The original text, with undecoded HTML entities */
raw: string;
}
/** A (possibly reactive) template expression — `{...}` */
export interface ExpressionTag extends BaseNode {
type: 'ExpressionTag';
expression: Expression;
}
/** A (possibly reactive) HTML template expression — `{@html ...}` */
export interface HtmlTag extends BaseNode {
type: 'HtmlTag';
expression: Expression;
}
/** An HTML comment */
// TODO rename to disambiguate
export interface Comment extends BaseNode {
type: 'Comment';
/** the contents of the comment */
data: string;
}
/** A `{@const ...}` tag */
export interface ConstTag extends BaseNode {
type: 'ConstTag';
declaration: VariableDeclaration & {
declarations: [VariableDeclarator & { id: Pattern; init: Expression }];
};
}
/** A `{@debug ...}` tag */
export interface DebugTag extends BaseNode {
type: 'DebugTag';
identifiers: Identifier[];
}
/** A `{@render foo(...)} tag */
export interface RenderTag extends BaseNode {
type: 'RenderTag';
expression: SimpleCallExpression | (ChainExpression & { expression: SimpleCallExpression });
}
/** An `animate:` directive */
export interface AnimateDirective extends BaseNode {
type: 'AnimateDirective';
/** The 'x' in `animate:x` */
name: string;
/** The y in `animate:x={y}` */
expression: null | Expression;
}
/** A `bind:` directive */
export interface BindDirective extends BaseNode {
type: 'BindDirective';
/** The 'x' in `bind:x` */
name: string;
/** The y in `bind:x={y}` */
expression: Identifier | MemberExpression | SequenceExpression;
}
/** A `class:` directive */
export interface ClassDirective extends BaseNode {
type: 'ClassDirective';
/** The 'x' in `class:x` */
name: 'class';
/** The 'y' in `class:x={y}`, or the `x` in `class:x` */
expression: Expression;
}
/** A `let:` directive */
export interface LetDirective extends BaseNode {
type: 'LetDirective';
/** The 'x' in `let:x` */
name: string;
/** The 'y' in `let:x={y}` */
expression: null | Identifier | ArrayExpression | ObjectExpression;
}
/** An `on:` directive */
export interface OnDirective extends BaseNode {
type: 'OnDirective';
/** The 'x' in `on:x` */
name: string;
/** The 'y' in `on:x={y}` */
expression: null | Expression;
modifiers: string[];
}
/** A `style:` directive */
export interface StyleDirective extends BaseNode {
type: 'StyleDirective';
/** The 'x' in `style:x` */
name: string;
/** The 'y' in `style:x={y}` */
value: true | ExpressionTag | Array<ExpressionTag | Text>;
modifiers: Array<'important'>;
}
// TODO have separate in/out/transition directives
/** A `transition:`, `in:` or `out:` directive */
export interface TransitionDirective extends BaseNode {
type: 'TransitionDirective';
/** The 'x' in `transition:x` */
name: string;
/** The 'y' in `transition:x={y}` */
expression: null | Expression;
modifiers: Array<'local' | 'global'>;
/** True if this is a `transition:` or `in:` directive */
intro: boolean;
/** True if this is a `transition:` or `out:` directive */
outro: boolean;
}
/** A `use:` directive */
export interface UseDirective extends BaseNode {
type: 'UseDirective';
/** The 'x' in `use:x` */
name: string;
/** The 'y' in `use:x={y}` */
expression: null | Expression;
}
interface BaseElement extends BaseNode {
name: string;
attributes: Array<Attribute | SpreadAttribute | Directive>;
fragment: Fragment;
}
export interface Component extends BaseElement {
type: 'Component';
}
export interface TitleElement extends BaseElement {
type: 'TitleElement';
name: 'title';
}
export interface SlotElement extends BaseElement {
type: 'SlotElement';
name: 'slot';
}
export interface RegularElement extends BaseElement {
type: 'RegularElement';
}
export interface SvelteBody extends BaseElement {
type: 'SvelteBody';
name: 'svelte:body';
}
export interface SvelteComponent extends BaseElement {
type: 'SvelteComponent';
name: 'svelte:component';
expression: Expression;
}
export interface SvelteDocument extends BaseElement {
type: 'SvelteDocument';
name: 'svelte:document';
}
export interface SvelteElement extends BaseElement {
type: 'SvelteElement';
name: 'svelte:element';
tag: Expression;
}
export interface SvelteFragment extends BaseElement {
type: 'SvelteFragment';
name: 'svelte:fragment';
}
export interface SvelteBoundary extends BaseElement {
type: 'SvelteBoundary';
name: 'svelte:boundary';
}
export interface SvelteHead extends BaseElement {
type: 'SvelteHead';
name: 'svelte:head';
}
/** This is only an intermediate representation while parsing, it doesn't exist in the final AST */
export interface SvelteOptionsRaw extends BaseElement {
type: 'SvelteOptions';
name: 'svelte:options';
}
export interface SvelteSelf extends BaseElement {
type: 'SvelteSelf';
name: 'svelte:self';
}
export interface SvelteWindow extends BaseElement {
type: 'SvelteWindow';
name: 'svelte:window';
}
/** An `{#each ...}` block */
export interface EachBlock extends BaseNode {
type: 'EachBlock';
expression: Expression;
/** The `entry` in `{#each item as entry}`. `null` if `as` part is omitted */
context: Pattern | null;
body: Fragment;
fallback?: Fragment;
index?: string;
key?: Expression;
}
/** An `{#if ...}` block */
export interface IfBlock extends BaseNode {
type: 'IfBlock';
elseif: boolean;
test: Expression;
consequent: Fragment;
alternate: Fragment | null;
}
/** An `{#await ...}` block */
export interface AwaitBlock extends BaseNode {
type: 'AwaitBlock';
expression: Expression;
// TODO can/should we move these inside the ThenBlock and CatchBlock?
/** The resolved value inside the `then` block */
value: Pattern | null;
/** The rejection reason inside the `catch` block */
error: Pattern | null;
pending: Fragment | null;
then: Fragment | null;
catch: Fragment | null;
}
export interface KeyBlock extends BaseNode {
type: 'KeyBlock';
expression: Expression;
fragment: Fragment;
}
export interface SnippetBlock extends BaseNode {
type: 'SnippetBlock';
expression: Identifier;
parameters: Pattern[];
body: Fragment;
}
export interface Attribute extends BaseNode {
type: 'Attribute';
name: string;
/**
* Quoted/string values are represented by an array, even if they contain a single expression like `"{x}"`
*/
value: true | ExpressionTag | Array<Text | ExpressionTag>;
}
export interface SpreadAttribute extends BaseNode {
type: 'SpreadAttribute';
expression: Expression;
}
export interface Script extends BaseNode {
type: 'Script';
context: 'default' | 'module';
content: Program;
attributes: Attribute[];
}
export type AttributeLike = Attribute | SpreadAttribute | Directive;
export type Directive =
| AST.AnimateDirective
| AST.BindDirective
| AST.ClassDirective
| AST.LetDirective
| AST.OnDirective
| AST.StyleDirective
| AST.TransitionDirective
| AST.UseDirective;
export type Block =
| AST.EachBlock
| AST.IfBlock
| AST.AwaitBlock
| AST.KeyBlock
| AST.SnippetBlock;
export type ElementLike =
| AST.Component
| AST.TitleElement
| AST.SlotElement
| AST.RegularElement
| AST.SvelteBody
| AST.SvelteBoundary
| AST.SvelteComponent
| AST.SvelteDocument
| AST.SvelteElement
| AST.SvelteFragment
| AST.SvelteHead
| AST.SvelteOptionsRaw
| AST.SvelteSelf
| AST.SvelteWindow
| AST.SvelteBoundary;
export type Tag = AST.ExpressionTag | AST.HtmlTag | AST.ConstTag | AST.DebugTag | AST.RenderTag;
export type TemplateNode =
| AST.Root
| AST.Text
| Tag
| ElementLike
| AST.Attribute
| AST.SpreadAttribute
| Directive
| AST.Comment
| Block;
export type SvelteNode = Node | TemplateNode | AST.Fragment | _CSS.Node;
export type { _CSS as CSS };
}
/**
* The preprocess function provides convenient hooks for arbitrarily transforming component source code.
* For example, it can be used to convert a `<style lang="sass">` block into vanilla CSS.
*
* */
export function preprocess(source: string, preprocessor: PreprocessorGroup | PreprocessorGroup[], options?: {
filename?: string;
} | undefined): Promise<Processed>;
/**
* The current version, as set in package.json.
* */
export const VERSION: string;
/**
* Does a best-effort migration of Svelte code towards using runes, event attributes and render tags.
* May throw an error if the code is too complex to migrate automatically.
*
* */
export function migrate(source: string, { filename, use_ts }?: {
filename?: string;
use_ts?: boolean;
} | undefined): {
code: string;
};
type ICompileDiagnostic = {
code: string;
message: string;
stack?: string;
filename?: string;
start?: Location;
end?: Location;
position?: [number, number];
frame?: string;
};
namespace _CSS {
export interface BaseNode {
start: number;
end: number;
}
export interface StyleSheet extends BaseNode {
type: 'StyleSheet';
attributes: any[]; // TODO
children: Array<Atrule | Rule>;
content: {
start: number;
end: number;
styles: string;
/** Possible comment atop the style tag */
comment: AST.Comment | null;
};
}
export interface Atrule extends BaseNode {
type: 'Atrule';
name: string;
prelude: string;
block: Block | null;
}
export interface Rule extends BaseNode {
type: 'Rule';
prelude: SelectorList;
block: Block;
}
/**
* A list of selectors, e.g. `a, b, c {}`
*/
export interface SelectorList extends BaseNode {
type: 'SelectorList';
/**
* The `a`, `b` and `c` in `a, b, c {}`
*/
children: ComplexSelector[];
}
/**
* A complex selector, e.g. `a b c {}`
*/
export interface ComplexSelector extends BaseNode {
type: 'ComplexSelector';
/**
* The `a`, `b` and `c` in `a b c {}`
*/
children: RelativeSelector[];
}
/**
* A relative selector, e.g the `a` and `> b` in `a > b {}`
*/
export interface RelativeSelector extends BaseNode {
type: 'RelativeSelector';
/**
* In `a > b`, `> b` forms one relative selector, and `>` is the combinator. `null` for the first selector.
*/
combinator: null | Combinator;
/**
* The `b:is(...)` in `> b:is(...)`
*/
selectors: SimpleSelector[];
}
export interface TypeSelector extends BaseNode {
type: 'TypeSelector';
name: string;
}
export interface IdSelector extends BaseNode {
type: 'IdSelector';
name: string;
}
export interface ClassSelector extends BaseNode {
type: 'ClassSelector';
name: string;
}
export interface AttributeSelector extends BaseNode {
type: 'AttributeSelector';
name: string;
matcher: string | null;
value: string | null;
flags: string | null;
}
export interface PseudoElementSelector extends BaseNode {
type: 'PseudoElementSelector';
name: string;
}
export interface PseudoClassSelector extends BaseNode {
type: 'PseudoClassSelector';
name: string;
args: SelectorList | null;
}
export interface Percentage extends BaseNode {
type: 'Percentage';
value: string;
}
export interface NestingSelector extends BaseNode {
type: 'NestingSelector';
name: '&';
}
export interface Nth extends BaseNode {
type: 'Nth';
value: string;
}
export type SimpleSelector =
| TypeSelector
| IdSelector
| ClassSelector
| AttributeSelector
| PseudoElementSelector
| PseudoClassSelector
| Percentage
| Nth
| NestingSelector;
export interface Combinator extends BaseNode {
type: 'Combinator';
name: string;
}
export interface Block extends BaseNode {
type: 'Block';
children: Array<Declaration | Rule | Atrule>;
}
export interface Declaration extends BaseNode {
type: 'Declaration';
property: string;
value: string;
}
// for zimmerframe
export type Node =
| StyleSheet
| Rule
| Atrule
| SelectorList
| Block
| ComplexSelector
| RelativeSelector
| Combinator
| SimpleSelector
| Declaration;
}
export {};
}
declare module 'svelte/easing' {
export function linear(t: number): number;
export function backInOut(t: number): number;
export function backIn(t: number): number;
export function backOut(t: number): number;
export function bounceOut(t: number): number;
export function bounceInOut(t: number): number;
export function bounceIn(t: number): number;
export function circInOut(t: number): number;
export function circIn(t: number): number;
export function circOut(t: number): number;
export function cubicInOut(t: number): number;
export function cubicIn(t: number): number;
export function cubicOut(t: number): number;
export function elasticInOut(t: number): numbe