Merge branch 'main' into elliott/class-constructor-state

pull/15820/head
Rich Harris 4 months ago
commit 4a19fd18c0

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: handle more hydration mismatches

@ -67,19 +67,29 @@ for (let i = 0; i < results[0].length; i += 1) {
for (const metric of ['time', 'gc_time']) {
const times = results.map((result) => +result[i][metric]);
let min = Infinity;
let max = -Infinity;
let min_index = -1;
for (let b = 0; b < times.length; b += 1) {
if (times[b] < min) {
min = times[b];
const time = times[b];
if (time < min) {
min = time;
min_index = b;
}
if (time > max) {
max = time;
}
}
if (min !== 0) {
console.group(`${metric}: fastest is ${branches[min_index]}`);
console.group(`${metric}: fastest is ${char(min_index)} (${branches[min_index]})`);
times.forEach((time, b) => {
console.log(`${branches[b]}: ${time.toFixed(2)}ms (${((time / min) * 100).toFixed(2)}%)`);
const SIZE = 20;
const n = Math.round(SIZE * (time / max));
console.log(`${char(b)}: ${'◼'.repeat(n)}${' '.repeat(SIZE - n)} ${time.toFixed(2)}ms`);
});
console.groupEnd();
}
@ -87,3 +97,7 @@ for (let i = 0; i < results[0].length; i += 1) {
console.groupEnd();
}
function char(i) {
return String.fromCharCode(97 + i);
}

@ -20,7 +20,7 @@ Unlike other frameworks you may have encountered, there is no API for interactin
If `$state` is used with an array or a simple object, the result is a deeply reactive _state proxy_. [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow Svelte to run code when you read or write properties, including via methods like `array.push(...)`, triggering granular updates.
> [!NOTE] Classes like `Set` and `Map` will not be proxied, but Svelte provides reactive implementations for various built-ins like these that can be imported from [`svelte/reactivity`](./svelte-reactivity).
> [!NOTE] Class instances are not proxied. You can create [reactive state fields](#Classes) on classes that you define. Svelte provides reactive implementations of built-ins like `Set` and `Map` that can be imported from [`svelte/reactivity`](svelte-reactivity).
State is proxified recursively until Svelte finds something other than an array or simple object. In a case like this...

@ -52,6 +52,7 @@ This rune, added in 5.14, causes the surrounding function to be _traced_ in deve
import { doSomeWork } from './elsewhere';
$effect(() => {
+++// $inspect.trace must be the first statement of a function body+++
+++$inspect.trace();+++
doSomeWork();
});

@ -82,12 +82,14 @@ As with elements, `name={name}` can be replaced with the `{name}` shorthand.
<Widget foo={bar} answer={42} text="hello" />
```
## Spread attributes
_Spread attributes_ allow many attributes or properties to be passed to an element or component at once.
An element or component can have multiple spread attributes, interspersed with regular ones.
An element or component can have multiple spread attributes, interspersed with regular ones. Order matters — if `things.a` exists it will take precedence over `a="b"`, while `c="d"` would take precedence over `things.c`:
```svelte
<Widget {...things} />
<Widget a="b" {...things} c="d" />
```
## Events

@ -43,7 +43,9 @@ An each block can also specify an _index_, equivalent to the second argument in
{#each expression as name, index (key)}...{/each}
```
If a _key_ expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.
If a _key_ expression is provided — which must uniquely identify each list item — Svelte will use it to intelligently update the list when data changes by inserting, moving and deleting items, rather than adding or removing items at the end and updating the state in the middle.
The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.
```svelte
{#each items as item (item.id)}

@ -0,0 +1,131 @@
---
title: {@attach ...}
---
Attachments are functions that run when an element is mounted to the DOM. Optionally, they can return a function that is called when the element is later removed from the DOM.
> [!NOTE]
> Attachments are available in Svelte 5.29 and newer.
```svelte
<!--- file: App.svelte --->
<script>
/** @type {import('svelte/attachments').Attachment} */
function myAttachment(element) {
console.log(element.nodeName); // 'DIV'
return () => {
console.log('cleaning up');
};
}
</script>
<div {@attach myAttachment}>...</div>
```
An element can have any number of attachments.
## Attachment factories
A useful pattern is for a function, such as `tooltip` in this example, to _return_ an attachment ([demo](/playground/untitled#H4sIAAAAAAAAE3VT0XLaMBD8lavbDiaNCUlbHhTItG_5h5AH2T5ArdBppDOEMv73SkbGJGnH47F9t3un3TsfMyO3mInsh2SW1Sa7zlZKo8_E0zHjg42pGAjxBPxp7cTvUHOMldLjv-IVGUbDoUw295VTlh-WZslqa8kxsLL2ACtHWxh175NffnQfAAGikSGxYQGfPEvGfPSIWtOH0TiBVo2pWJEBJtKhQp4YYzjG9JIdcuMM5IZqHMPioY8vOSA997zQoevf4a7heO7cdp34olRiTGr07OhwH1IdoO2A7dLMbwahZq6MbRhKZWqxk7rBxTGVbuHmhCgb5qDgmIx_J6XtHHukHTrYYqx_YpzYng8aO4RYayql7hU-1ZJl0akqHBE_D9KLolwL-Dibzc7iSln9XjtqTF1UpMkJ2EmXR-BgQErsN4pxIJKr0RVO1qrxAqaTO4fbc9bKulZm3cfDY3aZDgvFGErWjmzhN7KmfX5rXyDeX8Pt1mU-hXjdBOrtuB97vK4GPUtmJ41XcRMEGDLD8do0nJ73zhUhSlyRw0t3vPqD8cjfLs-axiFgNBrkUd9Ulp50c-GLxlXAVlJX-ffpZyiSn7H0eLCUySZQcQdXlxj4El0Yv_FZvIKElqqGTruVLhzu7VRKCh22_5toOyxsWqLwwzK-cCbYNdg-hy-p9D7sbiZWUnts_wLUOF3CJgQAAA==)):
```svelte
<!--- file: App.svelte --->
<script>
import tippy from 'tippy.js';
let content = $state('Hello!');
/**
* @param {string} content
* @returns {import('svelte/attachments').Attachment}
*/
function tooltip(content) {
return (element) => {
const tooltip = tippy(element, { content });
return tooltip.destroy;
};
}
</script>
<input bind:value={content} />
<button {@attach tooltip(content)}>
Hover me
</button>
```
Since the `tooltip(content)` expression runs inside an [effect]($effect), the attachment will be destroyed and recreated whenever `content` changes.
## Inline attachments
Attachments can also be created inline ([demo](/playground/untitled#H4sIAAAAAAAAE71Wf3OaWBT9KoyTTnW3MS-I3dYmnWXVtnRAazRJzbozRSQEApiRhwKO333vuY8m225m_9yZGOT9OPfcc84D943UTfxGr_G7K6Xr3TVeNW7D2M8avT_3DVk-YAoDNF4vNB8e2tnWjyXGlm7mPzfurVPpp5JgGmeZtwkf5PtFupCxLzVvHa832rl2lElX-s2Xm2DZFNqp_hs-rZetd4v07ORpT3qmQHu7MF2td0BZp8k6z_xkvfXP902_pZ2_1_aYWEiqm0kN8I4r79qbdZ6umnq3q_2iNf22F4dE6qt2oimwdpim_uY6XMm7Fuo-IQT_iTD_CeGTHwZ38ieIJUFQRxirR1Xf39Dw0X5z0I72Af4tD61vvPNwWKQnqmfPTbduhsEd2J3vO_oBd3dc6fF2X7umNdWGf0vBRhSS6qoV7cCXfTXWfKmvWG61_si_vfU92Wz-E4RhsLhNIYinsox9QKGVd8-tuACCeKXRX12P-T_eKf7fhTq0Hvt-f3ailtSeoxJHRo1-58NoPe1UiBc1hkL8Yeh45y_vQ3mcuNl9T8s3cXPRWLnS7YWJG_gn2Tb4tUjid8jua-PVl08j_ab8I14mH8Llx0s5Tz5Err4ql52r_GYg0mVy1bEGZuD0ze64b5TWYFiM-16wSuJ4JT5vfVpDcztrcG_YkRU4s6HxufzDWF4XuVeJ1P10IbzBemt3Vp1V2e04ZXfrJd7Wicyd039brRIv_RIVu_nXi7X1cfL2sy66ztToUp1TO7qJ7NlwZ0f30pld5qNSVE5o6PbMojFHjgZB7oSicPpGteyLclQap7SvY0dXtM_LR1NT2JFHey3aaxa0VxCeYJ7RMHemoiCcgPZV9pR7o7kgcOjeGliYk9hjDZx8FAq6enwlTPSZj_vYPw9Il64dXdIY8ZmapzwfEd8-1ZyaxWhqkIZOibXUd-6Upqi1pD4uMicCV1GA_7zi73UN8BaF4sC8peJtMjfmjbHZBFwq5ov50qRaE0l96NZggnW4KqypYRAW-uhSz9ADvklwJF2J-5W0Z5fQPBhDX92R6I_0IFxRgDftge4l4dP-gH1hjD7uqU6fsOEZ9UNrCdPB-nys6uXgY6O3ZMd9sy5T9PghqrWHdjo4jB51CgLiKJaDYYA-7WgYONf1FbjkI-mE3EAfUY_rijfuJ_CVPaR50oe9JF7Q0pI8Dw3osxxYHdYPGbp2CnwHF8KvwJv2wEv0Z3ilQI6U9uwbZxbYJXvEmjjQjjCHkvNLvNg3yhzXQd1olamsT4IRrZmX0MUDpwL7R8zzHj7pSh9hPHFSHjLezKqAST51uC5zmtQ87skDUaneLokT5RbXkPWSYz53Abgjc8_o4KFGUZ-Hgv2Z1l5OTYM9D-HfUD0L-EwxH5wRnIG61gS-khfgY1bq7IAP_DA4l5xRuh9xlm8yGjutc8t-wHtkhWv3hc7aqGwiK5KzgvM5xRkZYn193uEln-su55j1GaIv7oM4iPrsVHiG0Dx7TR9-1lBfqFdwfvSd5LNL5xyZVp5NoHFZ57FkfiF6vKs4k5zvIfrX5xX6MXmt0gM5MTu8DjnhukrHHzTRd3jm0dma0_f_x5cxP9f4jBdqHvmbq2fUjzqcKh2Cp-yWj9ntcHanXmBXxhu7Q--eyjhfNFpaV7zgz4nWEUb7zUOhpevjjf_gu_KZ99pxFlZ-T3sttkmYqrco_26q35v0Ewzv5EZPbnL_8BfduWGMnyyN3q0bZ_7hb_7KG_L4CQAA)):
```svelte
<!--- file: App.svelte --->
<canvas
width={32}
height={32}
{@attach (canvas) => {
const context = canvas.getContext('2d');
$effect(() => {
context.fillStyle = color;
context.fillRect(0, 0, canvas.width, canvas.height);
});
}}
></canvas>
```
> [!NOTE]
> The nested effect runs whenever `color` changes, while the outer effect (where `canvas.getContext(...)` is called) only runs once, since it doesn't read any reactive state.
## Passing attachments to components
When used on a component, `{@attach ...}` will create a prop whose key is a [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol). If the component then [spreads](/tutorial/svelte/spread-props) props onto an element, the element will receive those attachments.
This allows you to create _wrapper components_ that augment elements ([demo](/playground/untitled#H4sIAAAAAAAAE3VUS3ObMBD-KxvajnFqsJM2PhA7TXrKob31FjITAbKtRkiMtDhJPfz3LiAMdpxhGJvdb1_fPnaeYjn3Iu-WIbJ04028lZDcetHDzsO3olbVApI74F1RhHbLJdayhFl-Sp5qhVwhufEWNjWiwJtYxSjyQhsEFEXxBiujcxg1_8O_dnQ9APwsEbVyiHDafjrvDZCgkiO4MLCEzxYZcn90z6XUZ6OxA61KlaIgV6i1pFC-sxjDrlbHaDiWRoGvdMbHsLzp5DES0mJnRxGaRBvcBHb7yFUTCQeunEWYcYtGv12TqgFUDbCK1WLaM6IWQhUlQiJUFm2ZLPly51xXMG0Rjoyd69C7UqqG2nu95QZyXvtvLVpri2-SN4hoLXXCZFfhQ8aQBU1VgdEaH_vSgyBZR_BpPp_vi0tY-rw2ulRZkGqpTQRbZvwa2BPgFC8bgbw31CbjJjAsE6WNYBZeGp7vtQXLMqHWnZx-5kM1TR5ycpkZXQR2wzL94l8Ur1C_3-g168SfQf1MyfRi3LW9fs77emJEw5QV9SREoLTq06tcczq7d6xEUcJX2vAhO1b843XK34e5unZEMBr15ekuKEusluWAF8lXhE2ZTP2r2RcIHJ-163FPKerCgYJLOB9i4GvNwviI5-gAQiFFBk3tBTOU3HFXEk0R8o86WvUD64aINhv5K3oRmpJXkw8uxMG6Hh6JY9X7OwGSqfUy9tDG3sHNoEi0d_d_fv9qndxRU0VClFqo3KVo3U655Hnt1PXB3Qra2Y2QGdEwgTAMCxopsoxOe6SD0gD8movDhT0LAnhqlE8gVCpLWnRoV7OJCkFAwEXitrYL1W7p7pbiE_P7XH6E_rihODm5s52XtiH9Ekaw0VgI9exadWL1uoEYjPtg2672k5szsxbKyWB2fdT0w5Y_0hcT8oXOlRetmLS8-g-6TLXXQgYAAA==)):
```svelte
<!--- file: Button.svelte --->
<script>
/** @type {import('svelte/elements').HTMLButtonAttributes} */
let { children, ...props } = $props();
</script>
<!-- `props` includes attachments -->
<button {...props}>
{@render children?.()}
</button>
```
```svelte
<!--- file: App.svelte --->
<script>
import tippy from 'tippy.js';
import Button from './Button.svelte';
let content = $state('Hello!');
/**
* @param {string} content
* @returns {import('svelte/attachments').Attachment}
*/
function tooltip(content) {
return (element) => {
const tooltip = tippy(element, { content });
return tooltip.destroy;
};
}
</script>
<input bind:value={content} />
<Button {@attach tooltip(content)}>
Hover me
</Button>
```
## Creating attachments programmatically
To add attachments to an object that will be spread onto a component or element, use [`createAttachmentKey`](svelte-attachments#createAttachmentKey).

@ -117,6 +117,29 @@ Since 5.6.0, if an `<input>` has a `defaultChecked` attribute and is part of a f
</form>
```
## `<input bind:indeterminate>`
Checkboxes can be in an [indeterminate](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/indeterminate) state, independently of whether they are checked or unchecked:
```svelte
<script>
let checked = $state(false);
let indeterminate = $state(true);
</script>
<form>
<input type="checkbox" bind:checked bind:indeterminate>
{#if indeterminate}
waiting...
{:else if checked}
checked
{:else}
unchecked
{/if}
</form>
```
## `<input bind:group>`
Inputs that work together can use `bind:group`.
@ -227,6 +250,7 @@ You can give the `<select>` a default value by adding a `selected` attribute to
- [`seeking`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seeking_event)
- [`ended`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended)
- [`readyState`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState)
- [`played`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/played)
```svelte
<audio src={clip} bind:duration bind:currentTime bind:paused></audio>
@ -254,6 +278,10 @@ You can give the `<select>` a default value by adding a `selected` attribute to
</details>
```
## `window` and `document`
To bind to properties of `window` and `document`, see [`<svelte:window>`](svelte-window) and [`<svelte:document>`](svelte-document).
## Contenteditable bindings
Elements with the `contenteditable` attribute support the following bindings:
@ -278,6 +306,10 @@ All visible elements have the following readonly bindings, measured with a `Resi
- [`clientHeight`](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight)
- [`offsetWidth`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth)
- [`offsetHeight`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight)
- [`contentRect`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentRect)
- [`contentBoxSize`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize)
- [`borderBoxSize`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/borderBoxSize)
- [`devicePixelContentBoxSize`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/devicePixelContentBoxSize)
```svelte
<div bind:offsetWidth={width} bind:offsetHeight={height}>
@ -285,7 +317,7 @@ All visible elements have the following readonly bindings, measured with a `Resi
</div>
```
> [!NOTE] `display: inline` elements do not have a width or height (except for elements with 'intrinsic' dimensions, like `<img>` and `<canvas>`), and cannot be observed with a `ResizeObserver`. You will need to change the `display` style of these elements to something else, such as `inline-block`.
> [!NOTE] `display: inline` elements do not have a width or height (except for elements with 'intrinsic' dimensions, like `<img>` and `<canvas>`), and cannot be observed with a `ResizeObserver`. You will need to change the `display` style of these elements to something else, such as `inline-block`. Note that CSS transformations do not trigger `ResizeObserver` callbacks.
## bind:this

@ -2,6 +2,9 @@
title: use:
---
> [!NOTE]
> In Svelte 5.29 and newer, consider using [attachments](@attach) instead, as they are more flexible and composable.
Actions are functions that are called when an element is mounted. They are added with the `use:` directive, and will typically use an `$effect` so that they can reset any state when the element is unmounted:
```svelte

@ -6,9 +6,9 @@ Testing helps you write and maintain your code and guard against regressions. Te
## Unit and integration testing using Vitest
Unit tests allow you to test small isolated parts of your code. Integration tests allow you to test parts of your application to see if they work together. If you're using Vite (including via SvelteKit), we recommend using [Vitest](https://vitest.dev/).
Unit tests allow you to test small isolated parts of your code. Integration tests allow you to test parts of your application to see if they work together. If you're using Vite (including via SvelteKit), we recommend using [Vitest](https://vitest.dev/). You can use the Svelte CLI to [setup Vitest](/docs/cli/vitest) either during project creation or later on.
To get started, install Vitest:
To setup Vitest manually, first install it:
```bash
npm install -D vitest
@ -254,9 +254,9 @@ When writing component tests that involve two-way bindings, context or snippet p
E2E (short for 'end to end') tests allow you to test your full application through the eyes of the user. This section uses [Playwright](https://playwright.dev/) as an example, but you can also use other solutions like [Cypress](https://www.cypress.io/) or [NightwatchJS](https://nightwatchjs.org/).
To get started with Playwright, either install it via [the VS Code extension](https://playwright.dev/docs/getting-started-vscode), or install it from the command line using `npm init playwright`. It is also part of the setup CLI when you run `npx sv create`.
You can use the Svelte CLI to [setup Playwright](/docs/cli/playwright) either during project creation or later on. You can also [set it up with `npm init playwright`](https://playwright.dev/docs/intro). Additionally, you may also want to install an IDE plugin such as [the VS Code extension](https://playwright.dev/docs/getting-started-vscode) to be able to execute tests from inside your IDE.
After you've done that, you should have a `tests` folder and a Playwright config. You may need to adjust that config to tell Playwright what to do before running the tests - mainly starting your application at a certain port:
If you've run `npm init playwright` or are not using Vite, you may need to adjust the Playwright config to tell Playwright what to do before running the tests - mainly starting your application at a certain port. For example:
```js
/// file: playwright.config.js

@ -81,9 +81,10 @@ _End-to-End Tests_: To ensure your users are able to interact with your applicat
Some resources for getting started with testing:
- [Svelte docs on testing](/docs/svelte/testing)
- [Setup Vitest using the Svelte CLI](/docs/cli/vitest)
- [Svelte Testing Library](https://testing-library.com/docs/svelte-testing-library/example/)
- [Svelte Component Testing in Cypress](https://docs.cypress.io/guides/component-testing/svelte/overview)
- [Example using vitest](https://github.com/vitest-dev/vitest/tree/main/examples/sveltekit)
- [Example using uvu test runner with JSDOM](https://github.com/lukeed/uvu/tree/master/examples/svelte)
- [Test Svelte components using Vitest & Playwright](https://davipon.hashnode.dev/test-svelte-component-using-vitest-playwright)
- [Component testing with WebdriverIO](https://webdriver.io/docs/component-testing/svelte)

@ -586,6 +586,14 @@ Attributes should not contain ':' characters to prevent ambiguity with Svelte di
Quoted attributes on components and custom elements will be stringified in a future version of Svelte. If this isn't what you want, remove the quotes
```
### bidirectional_control_characters
```
A bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences
```
Bidirectional control characters can alter the direction in which text appears to be in. For example, via control characters, you can make `defabc` look like `abcdef`. As a result, if you were to unknowingly copy and paste some code that has these control characters, they may alter the behavior of your code in ways you did not intend. See [trojansource.codes](https://trojansource.codes/) for more information.
### bind_invalid_each_rest
```

@ -0,0 +1,5 @@
---
title: svelte/attachments
---
> MODULE: svelte/attachments

@ -1,5 +1,69 @@
# svelte
## 5.30.1
### Patch Changes
- fix: add `typeParams` to `SnippetBlock` for legacy parser ([#15921](https://github.com/sveltejs/svelte/pull/15921))
## 5.30.0
### Minor Changes
- feat: allow generics on snippets ([#15915](https://github.com/sveltejs/svelte/pull/15915))
## 5.29.0
### Minor Changes
- feat: attachments ([#15000](https://github.com/sveltejs/svelte/pull/15000))
## 5.28.7
### Patch Changes
- fix: remove unncessary guards that require CSP privilege when removing event attributes ([#15846](https://github.com/sveltejs/svelte/pull/15846))
- fix: rewrite destructuring logic to handle iterators ([#15813](https://github.com/sveltejs/svelte/pull/15813))
## 5.28.6
### Patch Changes
- fix: use `transform.read` for `ownership_validator.mutation` array ([#15848](https://github.com/sveltejs/svelte/pull/15848))
- fix: don't redeclare `$slots` ([#15849](https://github.com/sveltejs/svelte/pull/15849))
## 5.28.5
### Patch Changes
- fix: proxify the value in assignment shorthands to the private field ([#15862](https://github.com/sveltejs/svelte/pull/15862))
- fix: more frequently update `bind:buffered` to actual value ([#15874](https://github.com/sveltejs/svelte/pull/15874))
## 5.28.4
### Patch Changes
- fix: treat nullish expression as empty string ([#15901](https://github.com/sveltejs/svelte/pull/15901))
- fix: prevent invalid BigInt calls from blowing up at compile time ([#15900](https://github.com/sveltejs/svelte/pull/15900))
- fix: warn on bidirectional control characters ([#15893](https://github.com/sveltejs/svelte/pull/15893))
- fix: emit right error for a shadowed invalid rune ([#15892](https://github.com/sveltejs/svelte/pull/15892))
## 5.28.3
### Patch Changes
- chore: avoid microtasks when flushing sync ([#15895](https://github.com/sveltejs/svelte/pull/15895))
- fix: improve error message for migration errors when slot would be renamed ([#15841](https://github.com/sveltejs/svelte/pull/15841))
- fix: allow characters in the supplementary special-purpose plane ([#15823](https://github.com/sveltejs/svelte/pull/15823))
## 5.28.2
### Patch Changes

@ -31,6 +31,8 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import type { Attachment } from 'svelte/attachments';
// Note: We also allow `null` as a valid value because Svelte treats this the same as `undefined`
type Booleanish = boolean | 'true' | 'false';
@ -860,6 +862,9 @@ export interface HTMLAttributes<T extends EventTarget> extends AriaAttributes, D
// allow any data- attribute
[key: `data-${string}`]: any;
// allow any attachment
[key: symbol]: Attachment<T>;
}
export type HTMLAttributeAnchorTarget = '_self' | '_blank' | '_parent' | '_top' | (string & {});

@ -1,3 +1,9 @@
## bidirectional_control_characters
> A bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences
Bidirectional control characters can alter the direction in which text appears to be in. For example, via control characters, you can make `defabc` look like `abcdef`. As a result, if you were to unknowingly copy and paste some code that has these control characters, they may alter the behavior of your code in ways you did not intend. See [trojansource.codes](https://trojansource.codes/) for more information.
## legacy_code
> `%code%` is no longer valid — please use `%suggestion%` instead

@ -2,7 +2,7 @@
"name": "svelte",
"description": "Cybernetically enhanced web apps",
"license": "MIT",
"version": "5.28.2",
"version": "5.30.1",
"type": "module",
"types": "./types/index.d.ts",
"engines": {
@ -34,6 +34,10 @@
"types": "./types/index.d.ts",
"default": "./src/animate/index.js"
},
"./attachments": {
"types": "./types/index.d.ts",
"default": "./src/attachments/index.js"
},
"./compiler": {
"types": "./types/index.d.ts",
"require": "./compiler/index.js",

@ -35,6 +35,7 @@ await createBundle({
[pkg.name]: `${dir}/src/index.d.ts`,
[`${pkg.name}/action`]: `${dir}/src/action/public.d.ts`,
[`${pkg.name}/animate`]: `${dir}/src/animate/public.d.ts`,
[`${pkg.name}/attachments`]: `${dir}/src/attachments/public.d.ts`,
[`${pkg.name}/compiler`]: `${dir}/src/compiler/public.d.ts`,
[`${pkg.name}/easing`]: `${dir}/src/easing/index.js`,
[`${pkg.name}/legacy`]: `${dir}/src/legacy/legacy-client.js`,

@ -0,0 +1,27 @@
import { ATTACHMENT_KEY } from '../constants.js';
/**
* Creates an object key that will be recognised as an attachment when the object is spread onto an element,
* as a programmatic alternative to using `{@attach ...}`. This can be useful for library authors, though
* is generally not needed when building an app.
*
* ```svelte
* <script>
* import { createAttachmentKey } from 'svelte/attachments';
*
* const props = {
* class: 'cool',
* onclick: () => alert('clicked'),
* [createAttachmentKey()]: (node) => {
* node.textContent = 'attached!';
* }
* };
* </script>
*
* <button {...props}>click me</button>
* ```
* @since 5.29
*/
export function createAttachmentKey() {
return Symbol(ATTACHMENT_KEY);
}

@ -0,0 +1,12 @@
/**
* An [attachment](https://svelte.dev/docs/svelte/@attach) is a function that runs when an element is mounted
* to the DOM, and optionally returns a function that is called when the element is later removed.
*
* It can be attached to an element with an `{@attach ...}` tag, or by spreading an object containing
* a property created with [`createAttachmentKey`](https://svelte.dev/docs/svelte/svelte-attachments#createAttachmentKey).
*/
export interface Attachment<T extends EventTarget = Element> {
(element: T): void | (() => void);
}
export * from './index.js';

@ -378,7 +378,8 @@ export function convert(source, ast) {
end: node.end,
expression: node.expression,
parameters: node.parameters,
children: node.body.nodes.map((child) => visit(child))
children: node.body.nodes.map((child) => visit(child)),
typeParams: node.typeParams
};
},
// @ts-expect-error

@ -1307,7 +1307,7 @@ const template = {
name = state.scope.generate(slot_name);
if (name !== slot_name) {
throw new MigrationError(
'This migration would change the name of a slot making the component unusable'
`This migration would change the name of a slot (${slot_name} to ${name}) making the component unusable`
);
}
}
@ -1880,7 +1880,7 @@ function handle_identifier(node, state, path) {
let new_name = state.scope.generate(name);
if (new_name !== name) {
throw new MigrationError(
'This migration would change the name of a slot making the component unusable'
`This migration would change the name of a slot (${name} to ${new_name}) making the component unusable`
);
}
}

@ -1,7 +1,7 @@
/** @import { Location } from 'locate-character' */
/** @import { Pattern } from 'estree' */
/** @import { Parser } from '../index.js' */
import { is_bracket_open, is_bracket_close, get_bracket_close } from '../utils/bracket.js';
import { match_bracket } from '../utils/bracket.js';
import { parse_expression_at } from '../acorn.js';
import { regex_not_newline_characters } from '../../patterns.js';
import * as e from '../../../errors.js';
@ -33,7 +33,9 @@ export default function read_pattern(parser) {
};
}
if (!is_bracket_open(parser.template[i])) {
const char = parser.template[i];
if (char !== '{' && char !== '[') {
e.expected_pattern(i);
}
@ -71,75 +73,6 @@ export default function read_pattern(parser) {
}
}
/**
* @param {Parser} parser
* @param {number} start
*/
function match_bracket(parser, start) {
const bracket_stack = [];
let i = start;
while (i < parser.template.length) {
let char = parser.template[i++];
if (char === "'" || char === '"' || char === '`') {
i = match_quote(parser, i, char);
continue;
}
if (is_bracket_open(char)) {
bracket_stack.push(char);
} else if (is_bracket_close(char)) {
const popped = /** @type {string} */ (bracket_stack.pop());
const expected = /** @type {string} */ (get_bracket_close(popped));
if (char !== expected) {
e.expected_token(i - 1, expected);
}
if (bracket_stack.length === 0) {
return i;
}
}
}
e.unexpected_eof(parser.template.length);
}
/**
* @param {Parser} parser
* @param {number} start
* @param {string} quote
*/
function match_quote(parser, start, quote) {
let is_escaped = false;
let i = start;
while (i < parser.template.length) {
const char = parser.template[i++];
if (is_escaped) {
is_escaped = false;
continue;
}
if (char === quote) {
return i;
}
if (char === '\\') {
is_escaped = true;
}
if (quote === '`' && char === '$' && parser.template[i] === '{') {
i = match_bracket(parser, i);
}
}
e.unterminated_string_constant(start);
}
/**
* @param {Parser} parser
* @returns {any}

@ -16,7 +16,7 @@ const ALLOWED_ATTRIBUTES = ['context', 'generics', 'lang', 'module'];
/**
* @param {Parser} parser
* @param {number} start
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive>} attributes
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag>} attributes
* @returns {AST.Script}
*/
export function read_script(parser, start, attributes) {

@ -18,7 +18,7 @@ const REGEX_HTML_COMMENT_CLOSE = /-->/;
/**
* @param {Parser} parser
* @param {number} start
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive>} attributes
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag>} attributes
* @returns {AST.CSS.StyleSheet}
*/
export default function read_style(parser, start, attributes) {

@ -480,7 +480,7 @@ function read_static_attribute(parser) {
/**
* @param {Parser} parser
* @returns {AST.Attribute | AST.SpreadAttribute | AST.Directive | null}
* @returns {AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag | null}
*/
function read_attribute(parser) {
const start = parser.index;
@ -488,6 +488,27 @@ function read_attribute(parser) {
if (parser.eat('{')) {
parser.allow_whitespace();
if (parser.eat('@attach')) {
parser.require_whitespace();
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
/** @type {AST.AttachTag} */
const attachment = {
type: 'AttachTag',
start,
end: parser.index,
expression,
metadata: {
expression: create_expression_metadata()
}
};
return attachment;
}
if (parser.eat('...')) {
const expression = read_expression(parser);

@ -8,9 +8,12 @@ import { parse_expression_at } from '../acorn.js';
import read_pattern from '../read/context.js';
import read_expression, { get_loose_identifier } from '../read/expression.js';
import { create_fragment } from '../utils/create.js';
import { match_bracket } from '../utils/bracket.js';
const regex_whitespace_with_closing_curly_brace = /^\s*}/;
const pointy_bois = { '<': '>' };
/** @param {Parser} parser */
export default function tag(parser) {
const start = parser.index;
@ -351,6 +354,22 @@ function open(parser) {
const params_start = parser.index;
// snippets could have a generic signature, e.g. `#snippet foo<T>(...)`
/** @type {string | undefined} */
let type_params;
// if we match a generic opening
if (parser.ts && parser.match('<')) {
const start = parser.index;
const end = match_bracket(parser, start, pointy_bois);
type_params = parser.template.slice(start + 1, end - 1);
parser.index = end;
}
parser.allow_whitespace();
const matched = parser.eat('(', true, false);
if (matched) {
@ -388,6 +407,7 @@ function open(parser) {
end: name_end,
name
},
typeParams: type_params,
parameters: function_expression.params,
body: create_fragment(),
metadata: {

@ -1,34 +1,5 @@
const SQUARE_BRACKET_OPEN = '[';
const SQUARE_BRACKET_CLOSE = ']';
const CURLY_BRACKET_OPEN = '{';
const CURLY_BRACKET_CLOSE = '}';
const PARENTHESES_OPEN = '(';
const PARENTHESES_CLOSE = ')';
/** @param {string} char */
export function is_bracket_open(char) {
return char === SQUARE_BRACKET_OPEN || char === CURLY_BRACKET_OPEN;
}
/** @param {string} char */
export function is_bracket_close(char) {
return char === SQUARE_BRACKET_CLOSE || char === CURLY_BRACKET_CLOSE;
}
/** @param {string} open */
export function get_bracket_close(open) {
if (open === SQUARE_BRACKET_OPEN) {
return SQUARE_BRACKET_CLOSE;
}
if (open === CURLY_BRACKET_OPEN) {
return CURLY_BRACKET_CLOSE;
}
if (open === PARENTHESES_OPEN) {
return PARENTHESES_CLOSE;
}
}
/** @import { Parser } from '../index.js' */
import * as e from '../../../errors.js';
/**
* @param {number} num
@ -121,7 +92,7 @@ function count_leading_backslashes(string, search_start_index) {
* @returns {number | undefined} The index of the closing bracket, or undefined if not found.
*/
export function find_matching_bracket(template, index, open) {
const close = get_bracket_close(open);
const close = default_brackets[open];
let brackets = 1;
let i = index;
while (brackets > 0 && i < template.length) {
@ -162,3 +133,81 @@ export function find_matching_bracket(template, index, open) {
}
return undefined;
}
/** @type {Record<string, string>} */
const default_brackets = {
'{': '}',
'(': ')',
'[': ']'
};
/**
* @param {Parser} parser
* @param {number} start
* @param {Record<string, string>} brackets
*/
export function match_bracket(parser, start, brackets = default_brackets) {
const close = Object.values(brackets);
const bracket_stack = [];
let i = start;
while (i < parser.template.length) {
let char = parser.template[i++];
if (char === "'" || char === '"' || char === '`') {
i = match_quote(parser, i, char);
continue;
}
if (char in brackets) {
bracket_stack.push(char);
} else if (close.includes(char)) {
const popped = /** @type {string} */ (bracket_stack.pop());
const expected = /** @type {string} */ (brackets[popped]);
if (char !== expected) {
e.expected_token(i - 1, expected);
}
if (bracket_stack.length === 0) {
return i;
}
}
}
e.unexpected_eof(parser.template.length);
}
/**
* @param {Parser} parser
* @param {number} start
* @param {string} quote
*/
function match_quote(parser, start, quote) {
let is_escaped = false;
let i = start;
while (i < parser.template.length) {
const char = parser.template[i++];
if (is_escaped) {
is_escaped = false;
continue;
}
if (char === quote) {
return i;
}
if (char === '\\') {
is_escaped = true;
}
if (quote === '`' && char === '$' && parser.template[i] === '{') {
i = match_bracket(parser, i);
}
}
e.unterminated_string_constant(start);
}

@ -72,6 +72,8 @@ const NUL = 0;
// to replace them ourselves
//
// Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters
// Also see: https://en.wikipedia.org/wiki/Plane_(Unicode)
// Also see: https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream
/** @param {number} code */
function validate_code(code) {
@ -116,5 +118,10 @@ function validate_code(code) {
return code;
}
// supplementary special-purpose plane 0xe0000 - 0xe07f and 0xe0100 - 0xe01ef
if ((code >= 917504 && code <= 917631) || (code >= 917760 && code <= 917999)) {
return code;
}
return NUL;
}

@ -18,6 +18,7 @@ import { extract_svelte_ignore } from '../../utils/extract_svelte_ignore.js';
import { ignore_map, ignore_stack, pop_ignore, push_ignore } from '../../state.js';
import { ArrowFunctionExpression } from './visitors/ArrowFunctionExpression.js';
import { AssignmentExpression } from './visitors/AssignmentExpression.js';
import { AttachTag } from './visitors/AttachTag.js';
import { Attribute } from './visitors/Attribute.js';
import { AwaitBlock } from './visitors/AwaitBlock.js';
import { BindDirective } from './visitors/BindDirective.js';
@ -42,6 +43,7 @@ import { ImportDeclaration } from './visitors/ImportDeclaration.js';
import { KeyBlock } from './visitors/KeyBlock.js';
import { LabeledStatement } from './visitors/LabeledStatement.js';
import { LetDirective } from './visitors/LetDirective.js';
import { Literal } from './visitors/Literal.js';
import { MemberExpression } from './visitors/MemberExpression.js';
import { NewExpression } from './visitors/NewExpression.js';
import { OnDirective } from './visitors/OnDirective.js';
@ -63,6 +65,7 @@ import { SvelteSelf } from './visitors/SvelteSelf.js';
import { SvelteWindow } from './visitors/SvelteWindow.js';
import { SvelteBoundary } from './visitors/SvelteBoundary.js';
import { TaggedTemplateExpression } from './visitors/TaggedTemplateExpression.js';
import { TemplateElement } from './visitors/TemplateElement.js';
import { Text } from './visitors/Text.js';
import { TitleElement } from './visitors/TitleElement.js';
import { TransitionDirective } from './visitors/TransitionDirective.js';
@ -131,6 +134,7 @@ const visitors = {
},
ArrowFunctionExpression,
AssignmentExpression,
AttachTag,
Attribute,
AwaitBlock,
BindDirective,
@ -155,6 +159,7 @@ const visitors = {
KeyBlock,
LabeledStatement,
LetDirective,
Literal,
MemberExpression,
NewExpression,
OnDirective,
@ -176,6 +181,7 @@ const visitors = {
SvelteWindow,
SvelteBoundary,
TaggedTemplateExpression,
TemplateElement,
Text,
TransitionDirective,
TitleElement,

@ -0,0 +1,13 @@
/** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.AttachTag} node
* @param {Context} context
*/
export function AttachTag(node, context) {
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.expression });
}

@ -39,7 +39,7 @@ export function Identifier(node, context) {
if (
is_rune(node.name) &&
context.state.scope.get(node.name) === null &&
context.state.scope.get(node.name.slice(1)) === null
context.state.scope.get(node.name.slice(1))?.kind !== 'store_sub'
) {
/** @type {Expression} */
let current = node;

@ -0,0 +1,14 @@
/** @import { Literal } from 'estree' */
import * as w from '../../../warnings.js';
import { regex_bidirectional_control_characters } from '../../patterns.js';
/**
* @param {Literal} node
*/
export function Literal(node) {
if (typeof node.value === 'string') {
if (regex_bidirectional_control_characters.test(node.value)) {
w.bidirectional_control_characters(node);
}
}
}

@ -0,0 +1,12 @@
/** @import { TemplateElement } from 'estree' */
import * as w from '../../../warnings.js';
import { regex_bidirectional_control_characters } from '../../patterns.js';
/**
* @param {TemplateElement} node
*/
export function TemplateElement(node) {
if (regex_bidirectional_control_characters.test(node.value.cooked ?? '')) {
w.bidirectional_control_characters(node);
}
}

@ -1,20 +1,52 @@
/** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { is_tag_valid_with_parent } from '../../../../html-tree-validation.js';
import { regex_not_whitespace } from '../../patterns.js';
import { regex_bidirectional_control_characters, regex_not_whitespace } from '../../patterns.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { extract_svelte_ignore } from '../../../utils/extract_svelte_ignore.js';
/**
* @param {AST.Text} node
* @param {Context} context
*/
export function Text(node, context) {
const in_template = context.path.at(-1)?.type === 'Fragment';
const parent = /** @type {AST.SvelteNode} */ (context.path.at(-1));
if (in_template && context.state.parent_element && regex_not_whitespace.test(node.data)) {
if (
parent.type === 'Fragment' &&
context.state.parent_element &&
regex_not_whitespace.test(node.data)
) {
const message = is_tag_valid_with_parent('#text', context.state.parent_element);
if (message) {
e.node_invalid_placement(node, message);
}
}
regex_bidirectional_control_characters.lastIndex = 0;
for (const match of node.data.matchAll(regex_bidirectional_control_characters)) {
let is_ignored = false;
// if we have a svelte-ignore comment earlier in the text, bail
// (otherwise we can only use svelte-ignore on parent elements/blocks)
if (parent.type === 'Fragment') {
for (const child of parent.nodes) {
if (child === node) break;
if (child.type === 'Comment') {
is_ignored ||= extract_svelte_ignore(
child.start + 4,
child.data,
context.state.analysis.runes
).includes('bidirectional_control_characters');
}
}
}
if (!is_ignored) {
let start = match.index + node.start;
w.bidirectional_control_characters({ start, end: start + match[0].length });
}
}
}

@ -1,3 +1,4 @@
/** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { AnalysisState, Context } from '../../types' */
import * as e from '../../../../errors.js';
@ -74,7 +75,8 @@ export function visit_component(node, context) {
attribute.type !== 'SpreadAttribute' &&
attribute.type !== 'LetDirective' &&
attribute.type !== 'OnDirective' &&
attribute.type !== 'BindDirective'
attribute.type !== 'BindDirective' &&
attribute.type !== 'AttachTag'
) {
e.component_invalid_directive(attribute);
}
@ -91,15 +93,10 @@ export function visit_component(node, context) {
validate_attribute(attribute, node);
if (is_expression_attribute(attribute)) {
const expression = get_attribute_expression(attribute);
if (expression.type === 'SequenceExpression') {
let i = /** @type {number} */ (expression.start);
while (--i > 0) {
const char = context.state.analysis.source[i];
if (char === '(') break; // parenthesized sequence expressions are ok
if (char === '{') e.attribute_invalid_sequence_expression(expression);
}
}
disallow_unparenthesized_sequences(
get_attribute_expression(attribute),
context.state.analysis.source
);
}
}
@ -113,6 +110,10 @@ export function visit_component(node, context) {
if (attribute.type === 'BindDirective' && attribute.name !== 'this') {
context.state.analysis.uses_component_bindings = true;
}
if (attribute.type === 'AttachTag') {
disallow_unparenthesized_sequences(attribute.expression, context.state.analysis.source);
}
}
// If the component has a slot attribute — `<Foo slot="whatever" .../>` —
@ -158,3 +159,18 @@ export function visit_component(node, context) {
context.visit({ ...node.fragment, nodes: nodes[slot_name] }, state);
}
}
/**
* @param {Expression} expression
* @param {string} source
*/
function disallow_unparenthesized_sequences(expression, source) {
if (expression.type === 'SequenceExpression') {
let i = /** @type {number} */ (expression.start);
while (--i > 0) {
const char = source[i];
if (char === '(') break; // parenthesized sequence expressions are ok
if (char === '{') e.attribute_invalid_sequence_expression(expression);
}
}
}

@ -56,6 +56,7 @@ import { TitleElement } from './visitors/TitleElement.js';
import { TransitionDirective } from './visitors/TransitionDirective.js';
import { UpdateExpression } from './visitors/UpdateExpression.js';
import { UseDirective } from './visitors/UseDirective.js';
import { AttachTag } from './visitors/AttachTag.js';
import { VariableDeclaration } from './visitors/VariableDeclaration.js';
/** @type {Visitors} */
@ -131,6 +132,7 @@ const visitors = {
TransitionDirective,
UpdateExpression,
UseDirective,
AttachTag,
VariableDeclaration
};

@ -0,0 +1,21 @@
/** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '../../../../utils/builders.js';
/**
* @param {AST.AttachTag} node
* @param {ComponentContext} context
*/
export function AttachTag(node, context) {
context.state.init.push(
b.stmt(
b.call(
'$.attach',
context.state.node,
b.thunk(/** @type {Expression} */ (context.visit(node.expression)))
)
)
);
context.next();
}

@ -83,7 +83,7 @@ export function RegularElement(node, context) {
/** @type {AST.StyleDirective[]} */
const style_directives = [];
/** @type {Array<AST.AnimateDirective | AST.BindDirective | AST.OnDirective | AST.TransitionDirective | AST.UseDirective>} */
/** @type {Array<AST.AnimateDirective | AST.BindDirective | AST.OnDirective | AST.TransitionDirective | AST.UseDirective | AST.AttachTag>} */
const other_directives = [];
/** @type {ExpressionStatement[]} */
@ -153,6 +153,10 @@ export function RegularElement(node, context) {
has_use = true;
other_directives.push(attribute);
break;
case 'AttachTag':
other_directives.push(attribute);
break;
}
}

@ -2,7 +2,7 @@
/** @import { Binding } from '#compiler' */
/** @import { ComponentClientTransformState, ComponentContext } from '../types' */
import { dev } from '../../../../state.js';
import { extract_paths } from '../../../../utils/ast.js';
import { build_pattern, extract_paths } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import * as assert from '../../../../utils/assert.js';
import { get_rune } from '../../../scope.js';
@ -141,20 +141,20 @@ export function VariableDeclaration(node, context) {
b.declarator(declarator.id, create_state_declarator(declarator.id, value))
);
} else {
const tmp = context.state.scope.generate('tmp');
const paths = extract_paths(declarator.id);
const [pattern, replacements] = build_pattern(declarator.id, context.state.scope);
declarations.push(
b.declarator(b.id(tmp), value),
...paths.map((path) => {
const value = path.expression?.(b.id(tmp));
const binding = context.state.scope.get(/** @type {Identifier} */ (path.node).name);
return b.declarator(
path.node,
binding?.kind === 'state' || binding?.kind === 'raw_state'
? create_state_declarator(binding.node, value)
: value
);
})
b.declarator(pattern, value),
.../** @type {[Identifier, Identifier][]} */ ([...replacements]).map(
([original, replacement]) => {
const binding = context.state.scope.get(original.name);
return b.declarator(
original,
binding?.kind === 'state' || binding?.kind === 'raw_state'
? create_state_declarator(binding.node, replacement)
: replacement
);
}
)
);
}
@ -170,8 +170,7 @@ export function VariableDeclaration(node, context) {
)
);
} else {
const bindings = extract_paths(declarator.id);
const [pattern, replacements] = build_pattern(declarator.id, context.state.scope);
const init = /** @type {CallExpression} */ (declarator.init);
/** @type {Identifier} */
@ -189,10 +188,16 @@ export function VariableDeclaration(node, context) {
);
}
for (let i = 0; i < bindings.length; i++) {
const binding = bindings[i];
for (let i = 0; i < replacements.size; i++) {
const [original, replacement] = [...replacements][i];
declarations.push(
b.declarator(binding.node, b.call('$.derived', b.thunk(binding.expression(rhs))))
b.declarator(
original,
b.call(
'$.derived',
b.arrow([], b.block([b.let(pattern, rhs), b.return(replacement)]))
)
)
);
}
}
@ -304,19 +309,19 @@ function create_state_declarators(declarator, { scope, analysis }, value) {
];
}
const tmp = scope.generate('tmp');
const paths = extract_paths(declarator.id);
const [pattern, replacements] = build_pattern(declarator.id, scope);
return [
b.declarator(b.id(tmp), value),
...paths.map((path) => {
const value = path.expression?.(b.id(tmp));
const binding = scope.get(/** @type {Identifier} */ (path.node).name);
return b.declarator(
path.node,
binding?.kind === 'state'
? b.call('$.mutable_source', value, analysis.immutable ? b.true : undefined)
: value
);
})
b.declarator(pattern, value),
.../** @type {[Identifier, Identifier][]} */ ([...replacements]).map(
([original, replacement]) => {
const binding = scope.get(original.name);
return b.declarator(
original,
binding?.kind === 'state'
? b.call('$.mutable_source', replacement, analysis.immutable ? b.true : undefined)
: replacement
);
}
)
];
}

@ -257,6 +257,14 @@ export function build_component(node, component_name, context, anchor = context.
);
}
}
} else if (attribute.type === 'AttachTag') {
let expression = /** @type {Expression} */ (context.visit(attribute.expression));
if (attribute.metadata.expression.has_state) {
expression = b.arrow([b.id('$$node')], b.call(expression, b.id('$$node')));
}
push_prop(b.prop('get', b.call('$.attachment'), expression, true));
}
}

@ -77,7 +77,7 @@ export function build_template_chunk(
// If we have a single expression, then pass that in directly to possibly avoid doing
// extra work in the template_effect (instead we do the work in set_text).
if (evaluated.is_known) {
value = b.literal(evaluated.value);
value = b.literal((evaluated.value ?? '') + '');
}
return { value, has_state };
@ -96,7 +96,7 @@ export function build_template_chunk(
}
if (evaluated.is_known) {
quasi.value.cooked += evaluated.value + '';
quasi.value.cooked += (evaluated.value ?? '') + '';
} else {
if (!evaluated.is_defined) {
// add `?? ''` where necessary
@ -324,15 +324,18 @@ export function validate_mutation(node, context, expression) {
const state = /** @type {ComponentClientTransformState} */ (context.state);
state.analysis.needs_mutation_validation = true;
/** @type {Array<Identifier | Literal>} */
/** @type {Array<Identifier | Literal | Expression>} */
const path = [];
while (left.type === 'MemberExpression') {
if (left.property.type === 'Literal') {
path.unshift(left.property);
} else if (left.property.type === 'Identifier') {
const transform = Object.hasOwn(context.state.transform, left.property.name)
? context.state.transform[left.property.name]
: null;
if (left.computed) {
path.unshift(left.property);
path.unshift(transform?.read ? transform.read(left.property) : left.property);
} else {
path.unshift(b.literal(left.property.name));
}

@ -1,8 +1,9 @@
/** @import { VariableDeclaration, VariableDeclarator, Expression, CallExpression, Pattern, Identifier } from 'estree' */
/** @import { Binding } from '#compiler' */
/** @import { Context } from '../types.js' */
/** @import { ComponentAnalysis } from '../../../types.js' */
/** @import { Scope } from '../../../scope.js' */
import { build_fallback, extract_paths } from '../../../../utils/ast.js';
import { build_pattern, build_fallback, extract_paths } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.js';
import { walk } from 'zimmerframe';
@ -50,20 +51,26 @@ export function VariableDeclaration(node, context) {
}
}
});
// if `$$slots` is declared separately, deconflict
const slots_name = /** @type {ComponentAnalysis} */ (context.state.analysis).uses_slots
? b.id('$$slots_')
: b.id('$$slots');
if (id.type === 'ObjectPattern' && has_rest) {
// If a rest pattern is used within an object pattern, we need to ensure we don't expose $$slots or $$events
id.properties.splice(
id.properties.length - 1,
0,
// @ts-ignore
b.prop('init', b.id('$$slots'), b.id('$$slots')),
b.prop('init', b.id('$$slots'), slots_name),
b.prop('init', b.id('$$events'), b.id('$$events'))
);
} else if (id.type === 'Identifier') {
// If $props is referenced as an identifier, we need to ensure we don't expose $$slots or $$events as properties
// on the identifier reference
id = b.object_pattern([
b.prop('init', b.id('$$slots'), b.id('$$slots')),
b.prop('init', b.id('$$slots'), slots_name),
b.prop('init', b.id('$$events'), b.id('$$events')),
b.rest(b.id(id.name))
]);
@ -181,13 +188,10 @@ function create_state_declarators(declarator, scope, value) {
return [b.declarator(declarator.id, value)];
}
const tmp = scope.generate('tmp');
const paths = extract_paths(declarator.id);
const [pattern, replacements] = build_pattern(declarator.id, scope);
return [
b.declarator(b.id(tmp), value), // TODO inject declarator for opts, so we can use it below
...paths.map((path) => {
const value = path.expression?.(b.id(tmp));
return b.declarator(path.node, value);
})
b.declarator(pattern, value),
// TODO inject declarator for opts, so we can use it below
...[...replacements].map(([original, replacement]) => b.declarator(original, replacement))
];
}

@ -1,7 +1,7 @@
/** @import { AssignmentExpression, AssignmentOperator, Expression, Node, Pattern } from 'estree' */
/** @import { AssignmentExpression, AssignmentOperator, Expression, Identifier, Node, Pattern } from 'estree' */
/** @import { Context as ClientContext } from '../client/types.js' */
/** @import { Context as ServerContext } from '../server/types.js' */
import { extract_paths, is_expression_async } from '../../../utils/ast.js';
import { build_pattern, is_expression_async } from '../../../utils/ast.js';
import * as b from '#compiler/builders';
/**
@ -23,21 +23,23 @@ export function visit_assignment_expression(node, context, build_assignment) {
let changed = false;
const assignments = extract_paths(node.left).map((path) => {
const value = path.expression?.(rhs);
const [pattern, replacements] = build_pattern(node.left, context.state.scope);
let assignment = build_assignment('=', path.node, value, context);
if (assignment !== null) changed = true;
return (
assignment ??
b.assignment(
'=',
/** @type {Pattern} */ (context.visit(path.node)),
/** @type {Expression} */ (context.visit(value))
)
);
});
const assignments = [
b.let(pattern, rhs),
...[...replacements].map(([original, replacement]) => {
let assignment = build_assignment(node.operator, original, replacement, context);
if (assignment !== null) changed = true;
return b.stmt(
assignment ??
b.assignment(
node.operator,
/** @type {Identifier} */ (context.visit(original)),
/** @type {Expression} */ (context.visit(replacement))
)
);
})
];
if (!changed) {
// No change to output -> nothing to transform -> we can keep the original assignment
@ -45,25 +47,36 @@ export function visit_assignment_expression(node, context, build_assignment) {
}
const is_standalone = /** @type {Node} */ (context.path.at(-1)).type.endsWith('Statement');
const sequence = b.sequence(assignments);
const block = b.block(assignments);
if (!is_standalone) {
// this is part of an expression, we need the sequence to end with the value
sequence.expressions.push(rhs);
block.body.push(b.return(rhs));
}
if (should_cache) {
// the right hand side is a complex expression, wrap in an IIFE to cache it
const iife = b.arrow([rhs], sequence);
if (is_standalone && !should_cache) {
return block;
}
const iife_is_async =
is_expression_async(value) ||
assignments.some((assignment) => is_expression_async(assignment));
const iife = b.arrow(should_cache ? [rhs] : [], block);
return iife_is_async ? b.await(b.call(b.async(iife), value)) : b.call(iife, value);
}
const iife_is_async =
is_expression_async(value) ||
assignments.some(
(assignment) =>
(assignment.type === 'ExpressionStatement' &&
is_expression_async(assignment.expression)) ||
(assignment.type === 'VariableDeclaration' &&
assignment.declarations.some(
(declaration) =>
is_expression_async(declaration.id) ||
(declaration.init && is_expression_async(declaration.init))
))
);
return sequence;
return iife_is_async
? b.await(b.call(b.async(iife), should_cache ? value : undefined))
: b.call(iife, should_cache ? value : undefined);
}
if (node.left.type !== 'Identifier' && node.left.type !== 'MemberExpression') {

@ -21,3 +21,5 @@ export const regex_invalid_identifier_chars = /(^[^a-zA-Z_$]|[^a-zA-Z0-9_$])/g;
export const regex_starts_with_vowel = /^[aeiou]/;
export const regex_heading_tags = /^h[1-6]$/;
export const regex_illegal_attribute_character = /(^[0-9-.])|[\^$@%&#?!|()[\]{}^*+~;]/;
export const regex_bidirectional_control_characters =
/[\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069]+/g;

@ -23,12 +23,12 @@ export const STRING = Symbol('string');
/** @type {Record<string, [type: NUMBER | STRING | UNKNOWN, fn?: Function]>} */
const globals = {
BigInt: [NUMBER, BigInt],
BigInt: [NUMBER],
'Math.min': [NUMBER, Math.min],
'Math.max': [NUMBER, Math.max],
'Math.random': [NUMBER],
'Math.floor': [NUMBER, Math.floor],
// @ts-expect-error
// @ts-ignore
'Math.f16round': [NUMBER, Math.f16round],
'Math.round': [NUMBER, Math.round],
'Math.abs': [NUMBER, Math.abs],
@ -630,9 +630,10 @@ export class Scope {
/**
* @param {string} preferred_name
* @param {(name: string, counter: number) => string} [generator]
* @returns {string}
*/
generate(preferred_name) {
generate(preferred_name, generator = (name, counter) => `${name}_${counter}`) {
if (this.#porous) {
return /** @type {Scope} */ (this.parent).generate(preferred_name);
}
@ -647,7 +648,7 @@ export class Scope {
this.root.conflicts.has(name) ||
is_reserved(name)
) {
name = `${preferred_name}_${n++}`;
name = generator(preferred_name, n++);
}
this.references.set(name, []);

@ -174,6 +174,16 @@ export namespace AST {
};
}
/** A `{@attach foo(...)} tag */
export interface AttachTag extends BaseNode {
type: 'AttachTag';
expression: Expression;
/** @internal */
metadata: {
expression: ExpressionMetadata;
};
}
/** An `animate:` directive */
export interface AnimateDirective extends BaseNode {
type: 'AnimateDirective';
@ -273,7 +283,7 @@ export namespace AST {
interface BaseElement extends BaseNode {
name: string;
attributes: Array<Attribute | SpreadAttribute | Directive>;
attributes: Array<Attribute | SpreadAttribute | Directive | AttachTag>;
fragment: Fragment;
}
@ -458,6 +468,7 @@ export namespace AST {
type: 'SnippetBlock';
expression: Identifier;
parameters: Pattern[];
typeParams?: string;
body: Fragment;
/** @internal */
metadata: {
@ -546,6 +557,7 @@ export namespace AST {
| AST.Attribute
| AST.SpreadAttribute
| Directive
| AST.AttachTag
| AST.Comment
| Block;

@ -1,7 +1,8 @@
/** @import { AST } from '#compiler' */
/** @import { AST, Scope } from '#compiler' */
/** @import * as ESTree from 'estree' */
import { walk } from 'zimmerframe';
import * as b from '#compiler/builders';
import is_reference from 'is-reference';
/**
* Gets the left-most identifier of a member expression or identifier.
@ -128,6 +129,49 @@ export function unwrap_pattern(pattern, nodes = []) {
return nodes;
}
/**
* @param {ESTree.Pattern} id
* @param {Scope} scope
* @returns {[ESTree.Pattern, Map<ESTree.Identifier | ESTree.MemberExpression, ESTree.Identifier>]}
*/
export function build_pattern(id, scope) {
/** @type {Map<ESTree.Identifier | ESTree.MemberExpression, ESTree.Identifier>} */
const map = new Map();
/** @type {Map<string, string>} */
const names = new Map();
let counter = 0;
for (const node of unwrap_pattern(id)) {
const name = scope.generate(`$$${++counter}`, (_, counter) => `$$${counter}`);
map.set(node, b.id(name));
if (node.type === 'Identifier') {
names.set(node.name, name);
}
}
const pattern = walk(id, null, {
Identifier(node, context) {
if (is_reference(node, /** @type {ESTree.Pattern} */ (context.path.at(-1)))) {
const name = names.get(node.name);
if (name) return b.id(name);
}
},
MemberExpression(node, context) {
const n = map.get(node);
if (n) return n;
context.next();
}
});
return [pattern, map];
}
/**
* Extracts all identifiers from a pattern.
* @param {ESTree.Pattern} pattern
@ -580,5 +624,7 @@ export function build_assignment_value(operator, left, right) {
return operator === '='
? right
: // turn something like x += 1 into x = x + 1
b.binary(/** @type {ESTree.BinaryOperator} */ (operator.slice(0, -1)), left, right);
['||=', '&&=', '??='].includes(operator)
? b.logical(/** @type {ESTree.LogicalOperator} */ (operator.slice(0, -1)), left, right)
: b.binary(/** @type {ESTree.BinaryOperator} */ (operator.slice(0, -1)), left, right);
}

@ -86,6 +86,7 @@ export const codes = [
'a11y_role_supports_aria_props_implicit',
'a11y_unknown_aria_attribute',
'a11y_unknown_role',
'bidirectional_control_characters',
'legacy_code',
'unknown_code',
'options_deprecated_accessors',
@ -506,6 +507,14 @@ export function a11y_unknown_role(node, role, suggestion) {
w(node, 'a11y_unknown_role', `${suggestion ? `Unknown role '${role}'. Did you mean '${suggestion}'?` : `Unknown role '${role}'`}\nhttps://svelte.dev/e/a11y_unknown_role`);
}
/**
* A bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences
* @param {null | NodeLike} node
*/
export function bidirectional_control_characters(node) {
w(node, 'bidirectional_control_characters', `A bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences\nhttps://svelte.dev/e/bidirectional_control_characters`);
}
/**
* `%code%` is no longer valid please use `%suggestion%` instead
* @param {null | NodeLike} node

@ -55,3 +55,5 @@ export const IGNORABLE_RUNTIME_WARNINGS = /** @type {const} */ ([
* TODO this is currently unused
*/
export const ELEMENTS_WITHOUT_TEXT = ['audio', 'datalist', 'dl', 'optgroup', 'select', 'video'];
export const ATTACHMENT_KEY = '@attach';

@ -12,6 +12,7 @@ import {
hydrate_next,
hydrate_node,
hydrating,
read_hydration_instruction,
remove_nodes,
set_hydrate_node,
set_hydrating
@ -160,7 +161,7 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f
let mismatch = false;
if (hydrating) {
var is_else = /** @type {Comment} */ (anchor).data === HYDRATION_START_ELSE;
var is_else = read_hydration_instruction(anchor) === HYDRATION_START_ELSE;
if (is_else !== (length === 0)) {
// hydration mismatch — remove the server-rendered DOM and start over

@ -4,6 +4,7 @@ import {
hydrate_next,
hydrate_node,
hydrating,
read_hydration_instruction,
remove_nodes,
set_hydrate_node,
set_hydrating
@ -56,7 +57,8 @@ export function if_block(node, fn, [root_index, hydrate_index] = [0, 0]) {
if (hydrating && hydrate_index !== -1) {
if (root_index === 0) {
const data = /** @type {Comment} */ (anchor).data;
const data = read_hydration_instruction(anchor);
if (data === HYDRATION_START) {
hydrate_index = 0;
} else if (data === HYDRATION_START_ELSE) {

@ -0,0 +1,15 @@
import { effect } from '../../reactivity/effects.js';
/**
* @param {Element} node
* @param {() => (node: Element) => void} get_fn
*/
export function attach(node, get_fn) {
effect(() => {
const fn = get_fn();
// we use `&&` rather than `?.` so that things like
// `{@attach DEV && something_dev_only()}` work
return fn && fn(node);
});
}

@ -13,10 +13,11 @@ import {
set_active_effect,
set_active_reaction
} from '../../runtime.js';
import { attach } from './attachments.js';
import { clsx } from '../../../shared/attributes.js';
import { set_class } from './class.js';
import { set_style } from './style.js';
import { NAMESPACE_HTML } from '../../../../constants.js';
import { ATTACHMENT_KEY, NAMESPACE_HTML } from '../../../../constants.js';
export const CLASS = Symbol('class');
export const STYLE = Symbol('style');
@ -446,6 +447,12 @@ export function set_attributes(element, prev, next, css_hash, skip_warning = fal
set_hydrating(true);
}
for (let symbol of Object.getOwnPropertySymbols(next)) {
if (symbol.description === ATTACHMENT_KEY) {
attach(element, () => next[symbol]);
}
}
return current;
}

@ -62,7 +62,23 @@ export function bind_current_time(media, get, set = get) {
* @param {(array: Array<{ start: number; end: number }>) => void} set
*/
export function bind_buffered(media, set) {
listen(media, ['loadedmetadata', 'progress'], () => set(time_ranges_to_array(media.buffered)));
/** @type {{ start: number; end: number; }[]} */
var current;
// `buffered` can update without emitting any event, so we check it on various events.
// By specs, `buffered` always returns a new object, so we have to compare deeply.
listen(media, ['loadedmetadata', 'progress', 'timeupdate', 'seeking'], () => {
var ranges = media.buffered;
if (
!current ||
current.length !== ranges.length ||
current.some((range, i) => ranges.start(i) !== range.start || ranges.end(i) !== range.end)
) {
current = time_ranges_to_array(ranges);
set(current);
}
});
}
/**

@ -26,12 +26,8 @@ export const root_event_handles = new Set();
export function replay_events(dom) {
if (!hydrating) return;
if (dom.onload) {
dom.removeAttribute('onload');
}
if (dom.onerror) {
dom.removeAttribute('onerror');
}
dom.removeAttribute('onload');
dom.removeAttribute('onerror');
// @ts-expect-error
const event = dom.__e;
if (event !== undefined) {

@ -103,3 +103,16 @@ export function remove_nodes() {
node = next;
}
}
/**
*
* @param {TemplateNode} node
*/
export function read_hydration_instruction(node) {
if (!node || node.nodeType !== 8) {
w.hydration_mismatch();
throw HYDRATION_ERROR;
}
return /** @type {Comment} */ (node).data;
}

@ -1,3 +1,4 @@
export { createAttachmentKey as attachment } from '../../attachments/index.js';
export { FILENAME, HMR, NAMESPACE_SVG } from '../../constants.js';
export { push, pop } from './context.js';
export { assign, assign_and, assign_or, assign_nullish } from './dev/assign.js';
@ -22,6 +23,7 @@ export { element } from './dom/blocks/svelte-element.js';
export { head } from './dom/blocks/svelte-head.js';
export { append_styles } from './dom/css.js';
export { action } from './dom/elements/actions.js';
export { attach } from './dom/elements/attachments.js';
export {
remove_input_defaults,
set_attribute,

@ -218,9 +218,15 @@ const spread_props_handler = {
for (let p of target.props) {
if (is_function(p)) p = p();
if (!p) continue;
for (const key in p) {
if (!keys.includes(key)) keys.push(key);
}
for (const key of Object.getOwnPropertySymbols(p)) {
if (!keys.includes(key)) keys.push(key);
}
}
return keys;

@ -823,18 +823,21 @@ export function flushSync(fn) {
if (fn) {
is_flushing = true;
flush_queued_root_effects();
is_flushing = true;
result = fn();
}
flush_tasks();
while (true) {
flush_tasks();
if (queued_root_effects.length === 0) {
return /** @type {T} */ (result);
}
while (queued_root_effects.length > 0) {
is_flushing = true;
flush_queued_root_effects();
flush_tasks();
}
return /** @type {T} */ (result);
}
/**

@ -4,5 +4,5 @@
* The current version, as set in package.json.
* @type {string}
*/
export const VERSION = '5.28.2';
export const VERSION = '5.30.1';
export const PUBLIC_VERSION = '5';

@ -0,0 +1,8 @@
import { test } from '../../test';
export default test({
error: {
code: 'rune_invalid_name',
message: '`$state.foo` is not a valid rune'
}
});

@ -0,0 +1,5 @@
class State {
value = $state.foo();
}
export const state = new State();

@ -0,0 +1,6 @@
import { test } from '../../test';
// https://github.com/sveltejs/svelte/issues/15819
export default test({
expect_hydration_error: true
});

@ -0,0 +1 @@
<!--[--> <p>start</p><!--[--><p>cond</p><!--]--><!--]-->

@ -0,0 +1,5 @@
<script>
const cond = true;
</script>
<p>start</p>{#if cond}<p>cond</p>{/if}

@ -0,0 +1,6 @@
import { test } from '../../test';
// https://github.com/sveltejs/svelte/issues/15819
export default test({
expect_hydration_error: true
});

@ -0,0 +1 @@
<!--[--><p>start</p>pre<a>123</a> <!--[-->mid<!--]--><!--]-->

@ -0,0 +1,9 @@
<script>
let cond = true;
</script>
<p>start</p>
pre123
{#if cond}
mid
{/if}

@ -1,4 +1,4 @@
<!-- @migration-task Error while migrating Svelte code: This migration would change the name of a slot making the component unusable -->
<!-- @migration-task Error while migrating Svelte code: This migration would change the name of a slot (derived to derived_1) making the component unusable -->
<script>
let derived;
</script>

@ -1,4 +1,4 @@
<!-- @migration-task Error while migrating Svelte code: This migration would change the name of a slot making the component unusable -->
<!-- @migration-task Error while migrating Svelte code: This migration would change the name of a slot (body to body_1) making the component unusable -->
<script>
let body;
</script>

@ -1,2 +1,2 @@
<!-- @migration-task Error while migrating Svelte code: This migration would change the name of a slot making the component unusable -->
<!-- @migration-task Error while migrating Svelte code: This migration would change the name of a slot (dashed-name to dashed_name) making the component unusable -->
<slot name="dashed-name"></slot>

@ -0,0 +1,10 @@
<script lang="ts">
</script>
{#snippet generic<T extends string>(val: T)}
{val}
{/snippet}
{#snippet complex_generic<T extends { bracket: "<" } | "<" | Set<"<>">>(val: T)}
{val}
{/snippet}

@ -0,0 +1,244 @@
{
"html": {
"type": "Fragment",
"start": 30,
"end": 192,
"children": [
{
"type": "Text",
"start": 28,
"end": 30,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "SnippetBlock",
"start": 30,
"end": 92,
"expression": {
"type": "Identifier",
"start": 40,
"end": 47,
"name": "generic"
},
"parameters": [
{
"type": "Identifier",
"start": 66,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 36
},
"end": {
"line": 4,
"column": 42
}
},
"name": "val",
"typeAnnotation": {
"type": "TSTypeAnnotation",
"start": 69,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 39
},
"end": {
"line": 4,
"column": 42
}
},
"typeAnnotation": {
"type": "TSTypeReference",
"start": 71,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 41
},
"end": {
"line": 4,
"column": 42
}
},
"typeName": {
"type": "Identifier",
"start": 71,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 41
},
"end": {
"line": 4,
"column": 42
}
},
"name": "T"
}
}
}
}
],
"children": [
{
"type": "MustacheTag",
"start": 76,
"end": 81,
"expression": {
"type": "Identifier",
"start": 77,
"end": 80,
"loc": {
"start": {
"line": 5,
"column": 2
},
"end": {
"line": 5,
"column": 5
}
},
"name": "val"
}
}
],
"typeParams": "T extends string"
},
{
"type": "Text",
"start": 92,
"end": 94,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "SnippetBlock",
"start": 94,
"end": 192,
"expression": {
"type": "Identifier",
"start": 104,
"end": 119,
"name": "complex_generic"
},
"parameters": [
{
"type": "Identifier",
"start": 166,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 72
},
"end": {
"line": 8,
"column": 78
}
},
"name": "val",
"typeAnnotation": {
"type": "TSTypeAnnotation",
"start": 169,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 75
},
"end": {
"line": 8,
"column": 78
}
},
"typeAnnotation": {
"type": "TSTypeReference",
"start": 171,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 77
},
"end": {
"line": 8,
"column": 78
}
},
"typeName": {
"type": "Identifier",
"start": 171,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 77
},
"end": {
"line": 8,
"column": 78
}
},
"name": "T"
}
}
}
}
],
"children": [
{
"type": "MustacheTag",
"start": 176,
"end": 181,
"expression": {
"type": "Identifier",
"start": 177,
"end": 180,
"loc": {
"start": {
"line": 9,
"column": 2
},
"end": {
"line": 9,
"column": 5
}
},
"name": "val"
}
}
],
"typeParams": "T extends { bracket: \"<\" } | \"<\" | Set<\"<>\">"
}
]
},
"instance": {
"type": "Script",
"start": 0,
"end": 28,
"context": "default",
"content": {
"type": "Program",
"start": 18,
"end": 19,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 2,
"column": 0
}
},
"body": [],
"sourceType": "module"
}
}
}

@ -0,0 +1 @@
<div {@attach (node) => {}} {@attach (node) => {}}></div>

@ -0,0 +1,141 @@
{
"css": null,
"js": [],
"start": 0,
"end": 57,
"type": "Root",
"fragment": {
"type": "Fragment",
"nodes": [
{
"type": "RegularElement",
"start": 0,
"end": 57,
"name": "div",
"attributes": [
{
"type": "AttachTag",
"start": 5,
"end": 27,
"expression": {
"type": "ArrowFunctionExpression",
"start": 14,
"end": 26,
"loc": {
"start": {
"line": 1,
"column": 14
},
"end": {
"line": 1,
"column": 26
}
},
"id": null,
"expression": false,
"generator": false,
"async": false,
"params": [
{
"type": "Identifier",
"start": 15,
"end": 19,
"loc": {
"start": {
"line": 1,
"column": 15
},
"end": {
"line": 1,
"column": 19
}
},
"name": "node"
}
],
"body": {
"type": "BlockStatement",
"start": 24,
"end": 26,
"loc": {
"start": {
"line": 1,
"column": 24
},
"end": {
"line": 1,
"column": 26
}
},
"body": []
}
}
},
{
"type": "AttachTag",
"start": 28,
"end": 50,
"expression": {
"type": "ArrowFunctionExpression",
"start": 37,
"end": 49,
"loc": {
"start": {
"line": 1,
"column": 37
},
"end": {
"line": 1,
"column": 49
}
},
"id": null,
"expression": false,
"generator": false,
"async": false,
"params": [
{
"type": "Identifier",
"start": 38,
"end": 42,
"loc": {
"start": {
"line": 1,
"column": 38
},
"end": {
"line": 1,
"column": 42
}
},
"name": "node"
}
],
"body": {
"type": "BlockStatement",
"start": 47,
"end": 49,
"loc": {
"start": {
"line": 1,
"column": 47
},
"end": {
"line": 1,
"column": 49
}
},
"body": []
}
}
}
],
"fragment": {
"type": "Fragment",
"nodes": []
}
}
]
},
"options": null
}

@ -0,0 +1,10 @@
<script lang="ts">
</script>
{#snippet generic<T extends string>(val: T)}
{val}
{/snippet}
{#snippet complex_generic<T extends { bracket: "<" } | "<" | Set<"<>">>(val: T)}
{val}
{/snippet}

@ -0,0 +1,299 @@
{
"css": null,
"js": [],
"start": 30,
"end": 192,
"type": "Root",
"fragment": {
"type": "Fragment",
"nodes": [
{
"type": "Text",
"start": 28,
"end": 30,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "SnippetBlock",
"start": 30,
"end": 92,
"expression": {
"type": "Identifier",
"start": 40,
"end": 47,
"name": "generic"
},
"typeParams": "T extends string",
"parameters": [
{
"type": "Identifier",
"start": 66,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 36
},
"end": {
"line": 4,
"column": 42
}
},
"name": "val",
"typeAnnotation": {
"type": "TSTypeAnnotation",
"start": 69,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 39
},
"end": {
"line": 4,
"column": 42
}
},
"typeAnnotation": {
"type": "TSTypeReference",
"start": 71,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 41
},
"end": {
"line": 4,
"column": 42
}
},
"typeName": {
"type": "Identifier",
"start": 71,
"end": 72,
"loc": {
"start": {
"line": 4,
"column": 41
},
"end": {
"line": 4,
"column": 42
}
},
"name": "T"
}
}
}
}
],
"body": {
"type": "Fragment",
"nodes": [
{
"type": "Text",
"start": 74,
"end": 76,
"raw": "\n\t",
"data": "\n\t"
},
{
"type": "ExpressionTag",
"start": 76,
"end": 81,
"expression": {
"type": "Identifier",
"start": 77,
"end": 80,
"loc": {
"start": {
"line": 5,
"column": 2
},
"end": {
"line": 5,
"column": 5
}
},
"name": "val"
}
},
{
"type": "Text",
"start": 81,
"end": 82,
"raw": "\n",
"data": "\n"
}
]
}
},
{
"type": "Text",
"start": 92,
"end": 94,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "SnippetBlock",
"start": 94,
"end": 192,
"expression": {
"type": "Identifier",
"start": 104,
"end": 119,
"name": "complex_generic"
},
"typeParams": "T extends { bracket: \"<\" } | \"<\" | Set<\"<>\">",
"parameters": [
{
"type": "Identifier",
"start": 166,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 72
},
"end": {
"line": 8,
"column": 78
}
},
"name": "val",
"typeAnnotation": {
"type": "TSTypeAnnotation",
"start": 169,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 75
},
"end": {
"line": 8,
"column": 78
}
},
"typeAnnotation": {
"type": "TSTypeReference",
"start": 171,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 77
},
"end": {
"line": 8,
"column": 78
}
},
"typeName": {
"type": "Identifier",
"start": 171,
"end": 172,
"loc": {
"start": {
"line": 8,
"column": 77
},
"end": {
"line": 8,
"column": 78
}
},
"name": "T"
}
}
}
}
],
"body": {
"type": "Fragment",
"nodes": [
{
"type": "Text",
"start": 174,
"end": 176,
"raw": "\n\t",
"data": "\n\t"
},
{
"type": "ExpressionTag",
"start": 176,
"end": 181,
"expression": {
"type": "Identifier",
"start": 177,
"end": 180,
"loc": {
"start": {
"line": 9,
"column": 2
},
"end": {
"line": 9,
"column": 5
}
},
"name": "val"
}
},
{
"type": "Text",
"start": 181,
"end": 182,
"raw": "\n",
"data": "\n"
}
]
}
}
]
},
"options": null,
"instance": {
"type": "Script",
"start": 0,
"end": 28,
"context": "default",
"content": {
"type": "Program",
"start": 18,
"end": 19,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 2,
"column": 0
}
},
"body": [],
"sourceType": "module"
},
"attributes": [
{
"type": "Attribute",
"start": 8,
"end": 17,
"name": "lang",
"value": [
{
"start": 14,
"end": 16,
"type": "Text",
"raw": "ts",
"data": "ts"
}
]
}
]
}
}

@ -0,0 +1,6 @@
import { test } from '../../test';
export default test({
ssrHtml: `<div></div>`,
html: `<div>DIV</div>`
});

@ -0,0 +1 @@
<div {@attach (node) => node.textContent = node.nodeName}></div>

@ -0,0 +1,5 @@
<script>
let props = $props();
</script>
<div {...props}></div>

@ -0,0 +1,15 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `<button>update</button><div></div>`,
test({ target, assert, logs }) {
const button = target.querySelector('button');
assert.deepEqual(logs, ['one DIV']);
flushSync(() => button?.click());
assert.deepEqual(logs, ['one DIV', 'cleanup one', 'two DIV']);
}
});

@ -0,0 +1,30 @@
<script>
import { createAttachmentKey } from 'svelte/attachments';
import Child from './Child.svelte';
let stuff = $state({
[createAttachmentKey()]: (node) => {
console.log(`one ${node.nodeName}`);
return () => {
console.log('cleanup one');
};
}
});
function update() {
stuff = {
[createAttachmentKey()]: (node) => {
console.log(`two ${node.nodeName}`);
return () => {
console.log('cleanup two');
}
}
};
}
</script>
<button onclick={update}>update</button>
<Child {...stuff} />

@ -0,0 +1,5 @@
<script>
let props = $props();
</script>
<div {...props}></div>

@ -0,0 +1,14 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
ssrHtml: `<button>update</button><div></div>`,
html: `<button>update</button><div>one</div>`,
test({ target, assert }) {
const button = target.querySelector('button');
flushSync(() => button?.click());
assert.htmlEqual(target.innerHTML, '<button>update</button><div>two</div>');
}
});

@ -0,0 +1,15 @@
<script>
import Child from './Child.svelte';
let message = $state('one');
function attachment(message) {
return (node) => {
node.textContent = message;
};
}
</script>
<button onclick={() => message = 'two'}>update</button>
<Child {@attach attachment(message)} />

@ -0,0 +1,14 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
ssrHtml: `<div></div><button>increment</button>`,
html: `<div>1</div><button>increment</button>`,
test: ({ assert, target }) => {
const btn = target.querySelector('button');
flushSync(() => btn?.click());
assert.htmlEqual(target.innerHTML, `<div>2</div><button>increment</button>`);
}
});

@ -0,0 +1,6 @@
<script>
let value = $state(1);
</script>
<div {@attach (node) => node.textContent = value}></div>
<button onclick={() => value += 1}>increment</button>

@ -0,0 +1,8 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
test({ assert, logs, target }) {
assert.deepEqual(logs, ['hello']);
}
});

@ -0,0 +1,9 @@
<script>
import { createAttachmentKey } from 'svelte/attachments';
let stuff = $state({
[createAttachmentKey()]: () => console.log('hello')
});
</script>
<div {...stuff}></div>

@ -0,0 +1,6 @@
import { test } from '../../test';
export default test({
ssrHtml: `<div></div>`,
html: `<div>DIV</div>`
});

@ -0,0 +1 @@
<svelte:element this={'div'} {@attach (node) => node.textContent = node.nodeName}></svelte:element>

@ -0,0 +1,7 @@
import { test } from '../../test';
export default test({
// check that this is a runtime error, not a compile time error
// caused by over-eager partial-evaluation
error: 'Cannot convert invalid to a BigInt'
});

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save