From d16099ef0fa666f3610ef75ad9fca3252b0b47d0 Mon Sep 17 00:00:00 2001 From: Simon H <5968653+dummdidumm@users.noreply.github.com> Date: Wed, 9 Sep 2026 10:58:29 +0200 Subject: [PATCH 01/29] fix: remove `WAS_MARKED` flag in favor of `Set` (#18127) Removes the `WAS_MARKED` logic in favor of a simple `Set` heuristic: If `mark_reactions` goes beyond a certain count, initialize it, otherwise keep it `null`. Balances the common case of not having many transitive dependencies with the edge case of cyclic dependencies as was seen in #16658 (I rechecked that reproduction and it remains fast with this change). I ran the benchmark against this and it doesn't hit the `Seen` heuristic once (i.e. even the benchmark doesn't have this extreme level of dependencies where it becomes noticeable). Fixes #18123, supersedes #18124 --------- Co-authored-by: Rich Harris --- .changeset/grumpy-pens-press.md | 5 +++ benchmarking/benchmarks/reactivity/index.js | 5 ++- .../svelte/src/internal/client/constants.js | 9 ---- .../svelte/src/internal/client/dev/debug.js | 2 - .../internal/client/reactivity/deriveds.js | 3 -- .../src/internal/client/reactivity/sources.js | 44 ++++++++++++------- .../src/internal/client/reactivity/utils.js | 25 +---------- .../svelte/src/internal/client/runtime.js | 8 ---- 8 files changed, 38 insertions(+), 63 deletions(-) create mode 100644 .changeset/grumpy-pens-press.md diff --git a/.changeset/grumpy-pens-press.md b/.changeset/grumpy-pens-press.md new file mode 100644 index 0000000000..0ba87ab0c5 --- /dev/null +++ b/.changeset/grumpy-pens-press.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: remove `WAS_MARKED` flag in favor of `Set` diff --git a/benchmarking/benchmarks/reactivity/index.js b/benchmarking/benchmarks/reactivity/index.js index 3fe9639376..d971b25e9b 100644 --- a/benchmarking/benchmarks/reactivity/index.js +++ b/benchmarking/benchmarks/reactivity/index.js @@ -13,7 +13,7 @@ import { sbench_create_4to1, sbench_create_signals } from './sbench.js'; -import { fileURLToPath } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { create_test } from './util.js'; // This benchmark has been adapted from the js-reactivity-benchmark (https://github.com/milomg/js-reactivity-benchmark) @@ -39,7 +39,8 @@ for (const file of fs.readdirSync(`${dirname}/tests`)) { const name = file.replace('.bench.js', ''); - const module = await import(`${dirname}/tests/${file}`); + const module_url = pathToFileURL(path.join(dirname, 'tests', file)); + const module = await import(module_url.href); const { owned, unowned } = create_test(name, module.default); reactivity_benchmarks.push(owned, unowned); diff --git a/packages/svelte/src/internal/client/constants.js b/packages/svelte/src/internal/client/constants.js index e0b7a8779b..b086bfedff 100644 --- a/packages/svelte/src/internal/client/constants.js +++ b/packages/svelte/src/internal/client/constants.js @@ -51,15 +51,6 @@ export const EFFECT_PRESERVED = 1 << 19; export const USER_EFFECT = 1 << 20; export const EFFECT_OFFSCREEN = 1 << 25; -// Flags exclusive to deriveds -/** - * Tells that we marked this derived and its reactions as visited during the "mark as (maybe) dirty"-phase. - * Will be lifted during execution of the derived and during checking its dirty state (both are necessary - * because a derived might be checked but not executed). This is a pure performance optimization flag and - * should not be used for any other purpose! - */ -export const WAS_MARKED = 1 << 16; - // Flags used for async export const REACTION_IS_UPDATING = 1 << 21; export const ASYNC = 1 << 22; diff --git a/packages/svelte/src/internal/client/dev/debug.js b/packages/svelte/src/internal/client/dev/debug.js index 83cc510ae2..2513d15c97 100644 --- a/packages/svelte/src/internal/client/dev/debug.js +++ b/packages/svelte/src/internal/client/dev/debug.js @@ -15,7 +15,6 @@ import { MAYBE_DIRTY, RENDER_EFFECT, ROOT_EFFECT, - WAS_MARKED, MANAGED_EFFECT } from '#client/constants'; import { snapshot } from '../../shared/clone.js'; @@ -204,7 +203,6 @@ export function log_reactions(signal) { if ((flags & DIRTY) !== 0) names.push('DIRTY'); if ((flags & MAYBE_DIRTY) !== 0) names.push('MAYBE_DIRTY'); if ((flags & CONNECTED) !== 0) names.push('CONNECTED'); - if ((flags & WAS_MARKED) !== 0) names.push('WAS_MARKED'); if ((flags & INERT) !== 0) names.push('INERT'); if ((flags & DESTROYED) !== 0) names.push('DESTROYED'); diff --git a/packages/svelte/src/internal/client/reactivity/deriveds.js b/packages/svelte/src/internal/client/reactivity/deriveds.js index 6b48bc8a23..728ef1d214 100644 --- a/packages/svelte/src/internal/client/reactivity/deriveds.js +++ b/packages/svelte/src/internal/client/reactivity/deriveds.js @@ -9,7 +9,6 @@ import { EFFECT_PRESERVED, STALE_REACTION, ASYNC, - WAS_MARKED, DESTROYED, CLEAN, REACTION_RAN, @@ -365,7 +364,6 @@ export function execute_derived(derived) { stack.push(derived); - derived.f &= ~WAS_MARKED; destroy_derived_effects(derived); value = update_reaction(derived); } finally { @@ -375,7 +373,6 @@ export function execute_derived(derived) { } } else { try { - derived.f &= ~WAS_MARKED; destroy_derived_effects(derived); value = update_reaction(derived); } finally { diff --git a/packages/svelte/src/internal/client/reactivity/sources.js b/packages/svelte/src/internal/client/reactivity/sources.js index 70be6489a4..006494f0b5 100644 --- a/packages/svelte/src/internal/client/reactivity/sources.js +++ b/packages/svelte/src/internal/client/reactivity/sources.js @@ -25,10 +25,7 @@ import { MAYBE_DIRTY, BLOCK_EFFECT, ROOT_EFFECT, - ASYNC, - WAS_MARKED, - CONNECTED, - REACTION_IS_UPDATING + ASYNC } from '#client/constants'; import * as e from '../errors.js'; import { legacy_mode_flag, tracing_mode_flag } from '../../flags/index.js'; @@ -171,6 +168,17 @@ export function set(source, value, should_proxy = false) { return internal_set(source, new_value, legacy_updates); } +/** + * A set of signals we have already seen while traversing in mark_reactions. + * Not always set to balance the common case of sources only having a couple + * of (transitive) dependencies (where always creating a Set would be bad for perf) + * with the edge case of extremely deep or wide dependency arrays with cycles. + * @type {Set | null} + */ +var seen = null; +/** Number of transitive dependencies, see {@link seen} for more info */ +var count_deps = 0; + /** * @template V * @param {Source} source @@ -240,7 +248,10 @@ export function internal_set(source, value, updated_during_traversal = null) { // For debugging, in case you want to know which reactions are being scheduled: // log_reactions(source); + seen = null; + count_deps = 0; mark_reactions(source, DIRTY, updated_during_traversal); + seen = null; // It's possible that the current reaction might not have up-to-date dependencies // whilst it's actively running. So in the case of ensuring it registers the reaction @@ -347,6 +358,18 @@ function mark_reactions(signal, status, updated_during_traversal) { var runes = is_runes(); var length = reactions.length; + count_deps += length; + // Activate the `seen` Set if we think from the unusually high number of deps that + // there might be cycles in the graph, to avoid repeated lookups for reactions + // Example: https://github.com/sveltejs/svelte/issues/16658 has a graph with one source + // reaching ~10000 distinct deriveds/effects each, resulting in 65 million walks through repeated visits. + if (count_deps > 100000 && seen === null) seen = new Set(); + + if (seen !== null) { + if (seen.has(signal)) return; + seen.add(signal); + } + for (var i = 0; i < length; i++) { var reaction = reactions[i]; var flags = reaction.f; @@ -370,18 +393,7 @@ function mark_reactions(signal, status, updated_during_traversal) { var derived = /** @type {Derived} */ (reaction); batch_values?.delete(derived); - - if ((flags & WAS_MARKED) === 0) { - // Only connected deriveds being executed outside the update cycle can be reliably unmarked right away - if ( - flags & CONNECTED && - (active_effect === null || (active_effect.f & REACTION_IS_UPDATING) === 0) - ) { - reaction.f |= WAS_MARKED; - } - - mark_reactions(derived, MAYBE_DIRTY, updated_during_traversal); - } + mark_reactions(derived, MAYBE_DIRTY, updated_during_traversal); } else if (not_dirty) { var effect = /** @type {Effect} */ (reaction); diff --git a/packages/svelte/src/internal/client/reactivity/utils.js b/packages/svelte/src/internal/client/reactivity/utils.js index 0d27cb8b84..3280f2372e 100644 --- a/packages/svelte/src/internal/client/reactivity/utils.js +++ b/packages/svelte/src/internal/client/reactivity/utils.js @@ -1,24 +1,7 @@ -/** @import { Derived, Effect, Value } from '#client' */ -import { CLEAN, DERIVED, DIRTY, MAYBE_DIRTY, WAS_MARKED } from '#client/constants'; +/** @import { Effect } from '#client' */ +import { CLEAN, DIRTY, MAYBE_DIRTY } from '#client/constants'; import { set_signal_status } from './status.js'; -/** - * @param {Value[] | null} deps - */ -function clear_marked(deps) { - if (deps === null) return; - - for (const dep of deps) { - if ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) { - continue; - } - - dep.f ^= WAS_MARKED; - - clear_marked(/** @type {Derived} */ (dep).deps); - } -} - /** * @param {Effect} effect * @param {Set} dirty_effects @@ -31,10 +14,6 @@ export function defer_effect(effect, dirty_effects, maybe_dirty_effects) { maybe_dirty_effects.add(effect); } - // Since we're not executing these effects now, we need to clear any WAS_MARKED flags - // so that other batches can correctly reach these effects during their own traversal - clear_marked(effect.deps); - // mark as clean so they get scheduled if they depend on pending async state set_signal_status(effect, CLEAN); } diff --git a/packages/svelte/src/internal/client/runtime.js b/packages/svelte/src/internal/client/runtime.js index d86c349445..27def05300 100644 --- a/packages/svelte/src/internal/client/runtime.js +++ b/packages/svelte/src/internal/client/runtime.js @@ -21,7 +21,6 @@ import { REACTION_IS_UPDATING, STALE_REACTION, ERROR_VALUE, - WAS_MARKED, MANAGED_EFFECT, REACTION_RAN } from './constants.js'; @@ -164,10 +163,6 @@ export function is_dirty(reaction) { return true; } - if (flags & DERIVED) { - reaction.f &= ~WAS_MARKED; - } - if ((flags & MAYBE_DIRTY) !== 0) { var dependencies = /** @type {Value[]} */ (reaction.deps); var length = dependencies.length; @@ -408,11 +403,8 @@ function remove_reaction(signal, dependency) { ) { var derived = /** @type {Derived} */ (dependency); - // If we are working with a derived that is owned by an effect, then mark it as being - // disconnected and remove the mark flag, as it cannot be reliably removed otherwise if ((derived.f & CONNECTED) !== 0) { derived.f ^= CONNECTED; - derived.f &= ~WAS_MARKED; } // In a fork it's possible that a derived is executed and gets reactions, then commits, but is From ce89035ecbf88ee131838527d29584b968d450fb Mon Sep 17 00:00:00 2001 From: Simon H <5968653+dummdidumm@users.noreply.github.com> Date: Wed, 9 Sep 2026 11:47:41 +0200 Subject: [PATCH 02/29] fix: prevent effect tree of batches from interfering with each other (#18508) While working on another Svelte feature I noticed a bug that boils down to batches interfering with each other through the effect tree: If batch A schedules an effect, it is walked up to the root (possibly). Now if in the meantime batch B also wants to schedule effects, it can have unintended consequences. Normally this does not happen, since it's extremely hard to run into this situation. There's basically two cases: Either an unfortunate timing of microtasks, or during flushing effects are scheduling new effects which messes with a `#commit()` right after (the test case does this). To fix this we now defer walking up the tree until the batch is actually processed. That way we set + unset the markers on the branches synchronously so there's no chance of another batch interfering. --- .changeset/gold-trams-knock.md | 5 + .../src/internal/client/reactivity/batch.js | 162 ++++++++++-------- .../async-commit-effect-overlap/_config.js | 41 +++++ .../async-commit-effect-overlap/main.svelte | 38 ++++ 4 files changed, 175 insertions(+), 71 deletions(-) create mode 100644 .changeset/gold-trams-knock.md create mode 100644 packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/_config.js create mode 100644 packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/main.svelte diff --git a/.changeset/gold-trams-knock.md b/.changeset/gold-trams-knock.md new file mode 100644 index 0000000000..8006d13fef --- /dev/null +++ b/.changeset/gold-trams-knock.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: prevent effect tree of batches from interfering with each other diff --git a/packages/svelte/src/internal/client/reactivity/batch.js b/packages/svelte/src/internal/client/reactivity/batch.js index 8251f79298..75ce33b1c5 100644 --- a/packages/svelte/src/internal/client/reactivity/batch.js +++ b/packages/svelte/src/internal/client/reactivity/batch.js @@ -22,7 +22,6 @@ import { import { async_mode_flag } from '../../flags/index.js'; import { deferred, define_property, includes } from '../../shared/utils.js'; import { - active_effect, active_reaction, get, increment_write_version, @@ -38,7 +37,6 @@ import { eager_effect, teardown, unlink_effect } from './effects.js'; import { defer_effect } from './utils.js'; import { UNINITIALIZED } from '../../../constants.js'; import { set_signal_status } from './status.js'; -import { legacy_is_updating_store } from './store.js'; import { invariant } from '../../shared/dev.js'; import { log_effect_tree } from '../dev/debug.js'; import { OBSOLETE } from './deriveds.js'; @@ -160,10 +158,17 @@ export class Batch { #deferred = null; /** - * The root effects that need to be flushed + * Effects that were scheduled in this batch but not yet 'resolved' into the + * root effects that need to be flushed. Resolving — the upwards traversal that + * marks the path to each effect on the shared effect tree (see #resolve) — is + * deferred until the batch is processed, so that the markers are created and + * consumed within a single traversal. Scheduling into other batches (which can + * happen concurrently, e.g. while a batch is committed) can therefore never + * observe (and be confused by) this batch's markers. + * May contain duplicates — deduplication happens during resolving * @type {Effect[]} */ - #roots = []; + #scheduled = []; /** * Effects created while this batch was active. @@ -273,14 +278,57 @@ export class Batch { this.#unskipped_branches.add(effect); } - #process() { - this.#started = true; + /** + * Convert the effects that were scheduled in this batch into the root effects + * that need to be traversed, marking the path to each effect (by clearing the + * `CLEAN` flag on ancestor branches) so that the traversal can find them. + * This happens right before traversal rather than at scheduling time, so that + * the markers left on the (shared) effect tree are created and consumed within + * a single traversal — scheduling into other batches can never observe them + * @returns {Effect[]} + */ + #resolve() { + /** @type {Effect[]} */ + var roots = []; - if (flush_count++ > 1000) { - this.#unlink(); - infinite_loop_guard(); + for (const effect of this.#scheduled) { + // skip effects that are destroyed, or that already ran (e.g. because + // they were reached by the traversal that preceded a drain iteration, + // or because they were scheduled twice) + if ((effect.f & DESTROYED) !== 0 || (effect.f & (DIRTY | MAYBE_DIRTY)) === 0) continue; + + var e = effect; + var covered = false; + + while (e.parent !== null) { + e = e.parent; + var flags = e.f; + + if ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) { + if ((flags & CLEAN) === 0) { + // the path to the root was already marked, meaning the + // root was already collected — nothing left to do + covered = true; + break; + } + + e.f ^= CLEAN; + } + } + + if (!covered) { + roots.push(e); + } } + this.#scheduled = []; + + return roots; + } + + #process() { + this.#started = true; + if (DEV) { // track all the values that were updated during this flush, // so that they can be reset afterwards @@ -304,9 +352,6 @@ export class Batch { this.schedule(e); } - const roots = this.#roots; - this.#roots = []; - this.apply(); /** @type {Effect[]} */ @@ -321,18 +366,28 @@ export class Batch { */ var updates = (legacy_updates = []); - for (const root of roots) { - try { - this.#traverse(root, effects, render_effects); - } catch (e) { - reset_all(root); - // If there's no async work left, this branch is now dead and needs - // to be discarded to not become a zombie that is never cleaned up. - // See https://github.com/sveltejs/svelte/issues/18221#issuecomment-4497918414 - // for a (non-minimal) reproduction that demonstrates a case where this is necessary - // to not get follow-up false-positives via "batch has scheduled roots" invariant errors. - if (!this.#is_deferred()) this.discard(); - throw e; + // Effects can be scheduled during traversal (e.g. because a parent each/await/etc + // block updated an internal source, or because an effect invalidated itself) + // hence we loop until there are no more scheduled effects. + while (this.#scheduled.length > 0) { + if (flush_count++ > 1000) { + this.#unlink(); + infinite_loop_guard(); // TODO try to reset_all() here? + } + + for (const root of this.#resolve()) { + try { + this.#traverse(root, effects, render_effects); + } catch (e) { + reset_all(root); + // If there's no async work left, this branch is now dead and needs + // to be discarded to not become a zombie that is never cleaned up. + // See https://github.com/sveltejs/svelte/issues/18221#issuecomment-4497918414 + // for a (non-minimal) reproduction that demonstrates a case where this is necessary + // to not get follow-up false-positives via "batch has scheduled roots" invariant errors. + if (!this.#is_deferred()) this.discard(); + throw e; + } } } @@ -393,7 +448,7 @@ export class Batch { var next_batch = /** @type {Batch | null} */ (/** @type {unknown} */ (current_batch)); - if (this.#pending === 0 && (this.#roots.length === 0 || next_batch !== null)) { + if (this.#pending === 0 && (this.#scheduled.length === 0 || next_batch !== null)) { this.#unlink(); // Order matters here - we need to commit and THEN continue flushing new batches, not the other way around, @@ -408,12 +463,15 @@ export class Batch { } // Edge case: During traversal new branches might create effects that run immediately and set state, - // causing an effect and therefore a root to be scheduled again. We need to traverse the current batch + // causing an effect to be scheduled again. We need to traverse the current batch // once more in that case - most of the time this will just clean up dirty branches. - if (this.#roots.length > 0) { + if (this.#scheduled.length > 0) { if (next_batch !== null) { - const batch = next_batch; - batch.#roots.push(...this.#roots.filter((r) => !batch.#roots.includes(r))); + for (const e of this.#scheduled) { + next_batch.#scheduled.push(e); + } + + this.#scheduled = []; } else { next_batch = this; } @@ -712,7 +770,7 @@ export class Batch { // The microtask queue can contain the batch already scheduled to run right // after this one is finished, so throwing the invariant would be wrong here. if (DEV && !batch.#decrement_queued) { - invariant(batch.#roots.length === 0, 'Batch has scheduled roots'); + invariant(batch.#scheduled.length === 0, 'Batch has scheduled effects'); } // A batch was unskipped in a later batch -> tell prior batches to unskip it, too @@ -768,14 +826,12 @@ export class Batch { // Only apply and traverse when we know we triggered async work with marking the effects // and know this won't run anyway right afterwards - if (batch.#roots.length > 0 && !batch.#decrement_queued) { + if (batch.#scheduled.length > 0 && !batch.#decrement_queued) { batch.apply(); - for (var root of batch.#roots) { + for (var root of batch.#resolve()) { batch.#traverse(root, [], []); } - - batch.#roots = []; } batch.deactivate(); @@ -939,43 +995,7 @@ export class Batch { return; } - var e = effect; - - while (e.parent !== null) { - e = e.parent; - var flags = e.f; - - // if the effect is being scheduled because a parent (each/await/etc) block - // updated an internal source, or because a branch is being unskipped, - // bail out or we'll cause a second flush - if (collected_effects !== null && e === active_effect) { - if (async_mode_flag) return; - - // in sync mode, render effects run during traversal. in an extreme edge case - // — namely that we're setting a value inside a derived read during traversal — - // they can be made dirty after they have already been visited, in which - // case we shouldn't bail out. we also shouldn't bail out if we're - // updating a store inside a `$:`, since this might invalidate - // effects that were already visited - if ( - (active_reaction === null || (active_reaction.f & DERIVED) === 0) && - !legacy_is_updating_store - ) { - return; - } - } - - if ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) { - if ((flags & CLEAN) === 0) { - // branch is already dirty, bail - return; - } - - e.f ^= CLEAN; - } - } - - this.#roots.push(e); + this.#scheduled.push(effect); } #unlink() { diff --git a/packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/_config.js b/packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/_config.js new file mode 100644 index 0000000000..5557c7ebbb --- /dev/null +++ b/packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/_config.js @@ -0,0 +1,41 @@ +import { tick } from 'svelte'; +import { test } from '../../test'; + +const buttons = ' '; + +export default test({ + async test({ assert, target }) { + await tick(); + + const [a, b, , pop] = target.querySelectorAll('button'); + const shift = target.querySelectorAll('button')[2]; + + assert.htmlEqual(target.innerHTML, `${buttons}

a

a

aa

1

`); + + // start two independent batches, both blocked on their awaited expression + a.click(); + await tick(); + assert.htmlEqual(target.innerHTML, `${buttons}

a

a

aa

1

`); + + b.click(); + await tick(); + assert.htmlEqual(target.innerHTML, `${buttons}

a

a

aa

1

`); + + // resolve the newer (b) batch first. Committing it must not commit the + // still-pending `a` batch, whose async work has not completed — `a` must + // still read 'a', and the unrelated `c` update must not be blocked + pop.click(); + await tick(); + assert.htmlEqual(target.innerHTML, `${buttons}

a

b

ab

2

`); + + // stale promise from the `a` batch's first run — resolving it does nothing + shift.click(); + await tick(); + assert.htmlEqual(target.innerHTML, `${buttons}

a

b

ab

2

`); + + // the `a` batch's re-run await ('bb') resolves — everything is committed + shift.click(); + await tick(); + assert.htmlEqual(target.innerHTML, `${buttons}

b

b

bb

2

`); + } +}); diff --git a/packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/main.svelte b/packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/main.svelte new file mode 100644 index 0000000000..ae2746a3b8 --- /dev/null +++ b/packages/svelte/tests/runtime-runes/samples/async-commit-effect-overlap/main.svelte @@ -0,0 +1,38 @@ + + + + + + + +

{a}

+

{b}

+

{await push(a + b)}

+

{c}

From 34b13ac3e4a8c7919eb8d044a7c31d2d16f72678 Mon Sep 17 00:00:00 2001 From: Xia Chao Date: Fri, 11 Sep 2026 18:35:15 +0800 Subject: [PATCH 03/29] fix: keep `$state.eager` when used as a variable initializer (#18809) fixes #18808 If you write `let x = $state.eager(...)`, the client compiler used to delete that line and then still read `x`. The page crashed with `x is not defined`. Server rendering kept the binding. Using `$state.eager(...)` directly in the markup already worked. This puts the `let` / `const` form on the same path as `$state.snapshot`. Added a runtime-runes sample that fails without this change. Co-authored-by: Xia Chao <236466140+bun-unsafe@users.noreply.github.com> --- .changeset/state-eager-let-declaration.md | 5 +++++ .../3-transform/client/visitors/VariableDeclaration.js | 1 + .../samples/state-eager-declaration/_config.js | 5 +++++ .../samples/state-eager-declaration/main.svelte | 7 +++++++ 4 files changed, 18 insertions(+) create mode 100644 .changeset/state-eager-let-declaration.md create mode 100644 packages/svelte/tests/runtime-runes/samples/state-eager-declaration/_config.js create mode 100644 packages/svelte/tests/runtime-runes/samples/state-eager-declaration/main.svelte diff --git a/.changeset/state-eager-let-declaration.md b/.changeset/state-eager-let-declaration.md new file mode 100644 index 0000000000..6939094109 --- /dev/null +++ b/.changeset/state-eager-let-declaration.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: keep `$state.eager` when used as a variable initializer diff --git a/packages/svelte/src/compiler/phases/3-transform/client/visitors/VariableDeclaration.js b/packages/svelte/src/compiler/phases/3-transform/client/visitors/VariableDeclaration.js index 246feaccf6..0ad52dc457 100644 --- a/packages/svelte/src/compiler/phases/3-transform/client/visitors/VariableDeclaration.js +++ b/packages/svelte/src/compiler/phases/3-transform/client/visitors/VariableDeclaration.js @@ -35,6 +35,7 @@ export function VariableDeclaration(node, context) { rune === '$inspect' || rune === '$inspect.trace' || rune === '$state.snapshot' || + rune === '$state.eager' || rune === '$host' ) { declarations.push(/** @type {VariableDeclarator} */ (context.visit(declarator))); diff --git a/packages/svelte/tests/runtime-runes/samples/state-eager-declaration/_config.js b/packages/svelte/tests/runtime-runes/samples/state-eager-declaration/_config.js new file mode 100644 index 0000000000..61811ad0d6 --- /dev/null +++ b/packages/svelte/tests/runtime-runes/samples/state-eager-declaration/_config.js @@ -0,0 +1,5 @@ +import { test } from '../../test'; + +export default test({ + html: `

20

` +}); diff --git a/packages/svelte/tests/runtime-runes/samples/state-eager-declaration/main.svelte b/packages/svelte/tests/runtime-runes/samples/state-eager-declaration/main.svelte new file mode 100644 index 0000000000..ed5e175c55 --- /dev/null +++ b/packages/svelte/tests/runtime-runes/samples/state-eager-declaration/main.svelte @@ -0,0 +1,7 @@ + + +

{x}

From 6be176df2f760e314023e3ddbf42b45fc5575dbb Mon Sep 17 00:00:00 2001 From: Nic Polumeyv Date: Fri, 11 Sep 2026 07:24:55 -0400 Subject: [PATCH 04/29] fix: resolve the fallback of an each block in the enclosing scope (#18803) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In `phases/scope.js`, `EachBlock` visits `node.fallback` with the block's own scope, so `{:else}` resolves the loop's name to the each context. With `let item = $state('outer')` outside and `{#each items as item}…{:else}', + + test({ assert, target }) { + const button = target.querySelector('button'); + flushSync(() => { + button?.click(); + }); + assert.htmlEqual(target.innerHTML, ''); + } +}); diff --git a/packages/svelte/tests/runtime-runes/samples/each-fallback-outer-scope/main.svelte b/packages/svelte/tests/runtime-runes/samples/each-fallback-outer-scope/main.svelte new file mode 100644 index 0000000000..7ebb37e2f7 --- /dev/null +++ b/packages/svelte/tests/runtime-runes/samples/each-fallback-outer-scope/main.svelte @@ -0,0 +1,10 @@ + + +{#each items as item} +

{item}

+{:else} + +{/each} From a8a9b02e380ce8c22e1893c0964cfc9a4916a468 Mon Sep 17 00:00:00 2001 From: "svelte-triage-bot[bot]" <316883489+svelte-triage-bot[bot]@users.noreply.github.com> Date: Fri, 11 Sep 2026 13:35:22 +0200 Subject: [PATCH 05/29] fix: reduce SSR render result garbage collection (#18798) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #18797. ### Problem SSR `render()` is lazy, but the wrapper benchmark discarded its result and therefore measured almost no rendering work. When `.body` was consumed, each render result's own accessor properties caused substantial garbage-collection overhead. ### Fix - Consume `render(App).body` in both the warmup and measured SSR benchmark loops. - Move lazy render-result properties onto a shared `RenderResult` prototype. - Memoize synchronous output and the asynchronous render promise while preserving lazy sync/async API behavior. - Add a regression test ensuring exposed render-result properties are inherited. - Add a patch changeset for `svelte`. The benchmark now deliberately selects the synchronous lazy-render path by reading `.body`, so the process-wide async flag imported by the reactivity benchmarks does not determine this benchmark's render mode. ### Performance on this host | Case | Time | GC time | | --- | ---: | ---: | | main, output discarded | 0.20 ms | 0.00 ms | | main, `.body` consumed before fix | 163.04 ms | 62.68 ms | | `svelte@5.38.10` | 110.05 ms | 1.39 ms | | fixed, `.body` consumed | 104.79 ms | 2.43 ms | ### Tests - `pnpm test packages/svelte/src/internal/server/renderer.test.ts` — 53 passed - `pnpm test server-side-rendering` — 234 passed, 2 skipped - `pnpm test` — 7,771 passed, 55 skipped - `pnpm lint` - `pnpm check` - `pnpm format` - `git diff --check` Co-authored-by: svelte-triage-bot --- .changeset/calm-render-results.md | 5 + .../benchmarks/ssr/wrapper/wrapper_bench.js | 4 +- .../svelte/src/internal/server/renderer.js | 157 ++++++++++-------- .../src/internal/server/renderer.test.ts | 10 ++ 4 files changed, 108 insertions(+), 68 deletions(-) create mode 100644 .changeset/calm-render-results.md diff --git a/.changeset/calm-render-results.md b/.changeset/calm-render-results.md new file mode 100644 index 0000000000..f3073ec4b5 --- /dev/null +++ b/.changeset/calm-render-results.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: reduce SSR render result garbage collection diff --git a/benchmarking/benchmarks/ssr/wrapper/wrapper_bench.js b/benchmarking/benchmarks/ssr/wrapper/wrapper_bench.js index 9a8dda617d..50634ff4e6 100644 --- a/benchmarking/benchmarks/ssr/wrapper/wrapper_bench.js +++ b/benchmarking/benchmarks/ssr/wrapper/wrapper_bench.js @@ -25,12 +25,12 @@ export const wrapper_bench = { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { - render(App); + render(App).body; } return await fastest_test(10, () => { for (let i = 0; i < 100; i++) { - render(App); + render(App).body; } }); } diff --git a/packages/svelte/src/internal/server/renderer.js b/packages/svelte/src/internal/server/renderer.js index 6b3c1b28dd..49061c0b0f 100644 --- a/packages/svelte/src/internal/server/renderer.js +++ b/packages/svelte/src/internal/server/renderer.js @@ -23,6 +23,87 @@ import { escape_html } from '../../escaping.js'; * @typedef {string | Renderer} RendererItem */ +class RenderResult { + /** @type {() => AccumulatedContent} */ + #render; + + /** @type {() => Promise} */ + #render_async; + + /** @type {AccumulatedContent | undefined} */ + #sync; + + /** @type {{ script: '' }} */ + #hashes = { script: '' }; + + /** @type {Promise | undefined} */ + #promise; + + /** + * @param {() => AccumulatedContent} render + * @param {() => Promise} render_async + */ + constructor(render, render_async) { + this.#render = render; + this.#render_async = render_async; + } + + #get() { + return (this.#sync ??= this.#render()); + } + + get html() { + return this.#get().body; + } + + get head() { + return this.#get().head; + } + + get body() { + return this.#get().body; + } + + get hashes() { + return this.#hashes; + } + + /** + * This is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. + * + * @template TResult1 + * @template [TResult2=never] + * @param {(value: SyncRenderOutput) => TResult1} onfulfilled + * @param {(reason: unknown) => TResult2} onrejected + */ + then(onfulfilled, onrejected) { + if (!async_mode_flag) { + const result = this.#get(); + const user_result = onfulfilled({ + head: result.head, + body: result.body, + html: result.body, + hashes: { script: [] } + }); + return Promise.resolve(user_result); + } + + this.#promise ??= this.#render_async().then((result) => { + Object.defineProperty(result, 'html', { + // eslint-disable-next-line getter-return + get: () => { + e.html_deprecated(); + } + }); + return result; + }); + return this.#promise.then( + (result) => onfulfilled(/** @type {SyncRenderOutput} */ (result)), + onrejected + ); + } +} + /** * Renderers are basically a tree of `string | Renderer`s, where each `Renderer` in the tree represents * work that may or may not have completed. A renderer can be {@link collect}ed to aggregate the @@ -534,73 +615,17 @@ export class Renderer { * @returns {RenderOutput} */ static render(component, options = {}) { - /** @type {AccumulatedContent | undefined} */ - let sync; - /** @type {Promise | undefined} */ - let async; - - const result = /** @type {RenderOutput} */ ({}); - // making these properties non-enumerable so that console.logging - // doesn't trigger a sync render - Object.defineProperties(result, { - html: { - get: () => { - return (sync ??= Renderer.#render(component, options)).body; - } - }, - head: { - get: () => { - return (sync ??= Renderer.#render(component, options)).head; - } - }, - body: { - get: () => { - return (sync ??= Renderer.#render(component, options)).body; - } - }, - hashes: { - value: { - script: '' - } - }, - then: { - value: - /** - * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. - * - * @template TResult1 - * @template [TResult2=never] - * @param { (value: SyncRenderOutput) => TResult1 } onfulfilled - * @param { (reason: unknown) => TResult2 } onrejected - */ - (onfulfilled, onrejected) => { - if (!async_mode_flag) { - const result = (sync ??= Renderer.#render(component, options)); - const user_result = onfulfilled({ - head: result.head, - body: result.body, - html: result.body, - hashes: { script: [] } - }); - return Promise.resolve(user_result); - } - async ??= init_render_context().then(() => + return /** @type {RenderOutput} */ ( + /** @type {unknown} */ ( + new RenderResult( + () => Renderer.#render(component, options), + () => + init_render_context().then(() => with_render_context(() => Renderer.#render_async(component, options)) - ); - return async.then((result) => { - Object.defineProperty(result, 'html', { - // eslint-disable-next-line getter-return - get: () => { - e.html_deprecated(); - } - }); - return onfulfilled(/** @type {SyncRenderOutput} */ (result)); - }, onrejected); - } - } - }); - - return result; + ) + ) + ) + ); } /** diff --git a/packages/svelte/src/internal/server/renderer.test.ts b/packages/svelte/src/internal/server/renderer.test.ts index 1adfdda64c..f35df5d571 100644 --- a/packages/svelte/src/internal/server/renderer.test.ts +++ b/packages/svelte/src/internal/server/renderer.test.ts @@ -4,6 +4,16 @@ import type { Component } from 'svelte'; import { disable_async_mode_flag, enable_async_mode_flag } from '../flags/index.js'; import { getAbortSignal } from './abort-signal.js'; +test('render result properties are inherited', () => { + const result = Renderer.render((() => {}) as unknown as Component); + + expect(Object.hasOwn(result, 'head')).toBe(false); + expect(Object.hasOwn(result, 'body')).toBe(false); + expect(Object.hasOwn(result, 'html')).toBe(false); + expect(Object.hasOwn(result, 'hashes')).toBe(false); + expect(Object.hasOwn(result, 'then')).toBe(false); +}); + test('collects synchronous body content by default', () => { const component = (renderer: Renderer) => { renderer.push('a'); From f2ad10ecd2bbb090ce32af54796490ab8332b991 Mon Sep 17 00:00:00 2001 From: "svelte-triage-bot[bot]" <316883489+svelte-triage-bot[bot]@users.noreply.github.com> Date: Fri, 11 Sep 2026 13:40:31 +0200 Subject: [PATCH 06/29] fix: preserve global CSS without scopable elements (#18793) ## Summary - mark fully global selectors as used without requiring a scopable component element - preserve exact ICSS `:export` rules under the same conditions - keep elements inside `` excluded from CSS hash injection - add a regression test covering both reported selector forms Fixes #18792 --- .changeset/calm-heads-glow.md | 5 +++++ .../phases/2-analyze/css/css-prune.js | 20 +++++++++++++------ .../css/samples/global-head-only/_config.js | 5 +++++ .../css/samples/global-head-only/expected.css | 2 ++ .../css/samples/global-head-only/input.svelte | 6 ++++++ 5 files changed, 32 insertions(+), 6 deletions(-) create mode 100644 .changeset/calm-heads-glow.md create mode 100644 packages/svelte/tests/css/samples/global-head-only/_config.js create mode 100644 packages/svelte/tests/css/samples/global-head-only/expected.css create mode 100644 packages/svelte/tests/css/samples/global-head-only/input.svelte diff --git a/.changeset/calm-heads-glow.md b/.changeset/calm-heads-glow.md new file mode 100644 index 0000000000..ee21d566bb --- /dev/null +++ b/.changeset/calm-heads-glow.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: preserve global CSS in components without scopable elements diff --git a/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js b/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js index dff6bb9b5a..125f096783 100644 --- a/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js +++ b/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js @@ -145,6 +145,19 @@ export function prune(stylesheet, elements) { }, ComplexSelector(node) { const selectors = get_relative_selectors(node); + const rule = /** @type {Compiler.AST.CSS.Rule} */ (node.metadata.rule); + const first = selectors[0]?.selectors[0]; + const is_icss_export = + selectors.length === 1 && + selectors[0].selectors.length === 1 && + first?.type === 'PseudoClassSelector' && + first.name === 'export' && + first.args === null; + + // Global and ICSS export rules do not depend on an element in this component + if (every_is_global(selectors, 0, selectors.length, rule) || is_icss_export) { + node.metadata.used = true; + } for (const element of elements) { seen.clear(); @@ -153,12 +166,7 @@ export function prune(stylesheet, elements) { // Elements rendered through are not style-scopable. // Prevent css hash injection (class="s-...") on tags like , , + + + +

{Object.hasOwn(state, 'y')}

From 8030ff2a2c8b84231f1d8f3bbc7d9974f12669b9 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Fri, 18 Sep 2026 17:23:42 -0400 Subject: [PATCH 11/29] fix: remove incorrect special handling of :export pseudo-selectors (#18839) #18793 added special handling for `:export` selectors, but this is incorrect. `:export` is (apparently) part of [Interoperable CSS](https://github.com/css-modules/icss) but Svelte doesn't (and shouldn't) know what that is. No changeset because #18793 is unreleased, and the changeset in that PR didn't mention ICSS --- .../src/compiler/phases/2-analyze/css/css-prune.js | 9 +-------- .../tests/css/samples/global-head-only/expected.css | 1 - .../tests/css/samples/global-head-only/input.svelte | 1 - 3 files changed, 1 insertion(+), 10 deletions(-) diff --git a/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js b/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js index 125f096783..0c8fdb79f2 100644 --- a/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js +++ b/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js @@ -146,16 +146,9 @@ export function prune(stylesheet, elements) { ComplexSelector(node) { const selectors = get_relative_selectors(node); const rule = /** @type {Compiler.AST.CSS.Rule} */ (node.metadata.rule); - const first = selectors[0]?.selectors[0]; - const is_icss_export = - selectors.length === 1 && - selectors[0].selectors.length === 1 && - first?.type === 'PseudoClassSelector' && - first.name === 'export' && - first.args === null; // Global and ICSS export rules do not depend on an element in this component - if (every_is_global(selectors, 0, selectors.length, rule) || is_icss_export) { + if (every_is_global(selectors, 0, selectors.length, rule)) { node.metadata.used = true; } diff --git a/packages/svelte/tests/css/samples/global-head-only/expected.css b/packages/svelte/tests/css/samples/global-head-only/expected.css index 0496468076..d2047e57d2 100644 --- a/packages/svelte/tests/css/samples/global-head-only/expected.css +++ b/packages/svelte/tests/css/samples/global-head-only/expected.css @@ -1,2 +1 @@ -:export { foo: red; } :is(td, th) { color: red; } diff --git a/packages/svelte/tests/css/samples/global-head-only/input.svelte b/packages/svelte/tests/css/samples/global-head-only/input.svelte index 3b0e647728..2ade1defdf 100644 --- a/packages/svelte/tests/css/samples/global-head-only/input.svelte +++ b/packages/svelte/tests/css/samples/global-head-only/input.svelte @@ -1,6 +1,5 @@ From 636eaaaa6f064b55072e7d192bb76dc9d8c4516e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 18 Sep 2026 19:43:30 -0400 Subject: [PATCH 12/29] Version Packages (#18750) This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated. # Releases ## svelte@5.57.1 ### Patch Changes - fix: cancel deferred event listeners during cleanup ([#18749](https://github.com/sveltejs/svelte/pull/18749)) - fix: preserve global CSS in components without scopable elements ([#18793](https://github.com/sveltejs/svelte/pull/18793)) - fix: reduce SSR render result garbage collection ([#18798](https://github.com/sveltejs/svelte/pull/18798)) - fix: resolve the fallback of an each block in the enclosing scope ([#18803](https://github.com/sveltejs/svelte/pull/18803)) - perf: speed up parser interactions with Acorn or avoid them where possible ([#18740](https://github.com/sveltejs/svelte/pull/18740)) - fix: prevent effect tree of batches from interfering with each other ([#18508](https://github.com/sveltejs/svelte/pull/18508)) - fix: serialize input default values during server rendering ([#18733](https://github.com/sveltejs/svelte/pull/18733)) - fix: remove `WAS_MARKED` flag in favor of `Set` ([#18127](https://github.com/sveltejs/svelte/pull/18127)) - fix: throw `set_context_after_init` when `setContext` is called after an `await` during SSR ([#18739](https://github.com/sveltejs/svelte/pull/18739)) - fix: make Object.hasOwn reactive for state proxy ownership changes ([#18838](https://github.com/sveltejs/svelte/pull/18838)) - fix: keep `$state.eager` when used as a variable initializer ([#18809](https://github.com/sveltejs/svelte/pull/18809)) - perf: avoid regex matching in parser where possible ([#18736](https://github.com/sveltejs/svelte/pull/18736)) - fix: in non-async mode, only push variable to current_sources when active_reaction is updating ([#18550](https://github.com/sveltejs/svelte/pull/18550)) - fix: recognise `aria-braillelabel` and `aria-brailleroledescription` as known ARIA attributes ([#18765](https://github.com/sveltejs/svelte/pull/18765)) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .changeset/calm-events-cleanup.md | 5 ---- .changeset/calm-heads-glow.md | 5 ---- .changeset/calm-render-results.md | 5 ---- .changeset/each-fallback-scope.md | 5 ---- .changeset/easy-points-tan.md | 5 ---- .changeset/gold-trams-knock.md | 5 ---- .changeset/green-inputs-ssr.md | 5 ---- .changeset/grumpy-pens-press.md | 5 ---- .changeset/olive-mice-argue.md | 5 ---- .changeset/reactive-has-own.md | 5 ---- .changeset/state-eager-let-declaration.md | 5 ---- .changeset/tall-kids-juggle.md | 5 ---- .changeset/tricky-cooks-help.md | 5 ---- .changeset/wild-cases-smile.md | 5 ---- packages/svelte/CHANGELOG.md | 32 +++++++++++++++++++++++ packages/svelte/package.json | 2 +- packages/svelte/src/version.js | 2 +- 17 files changed, 34 insertions(+), 72 deletions(-) delete mode 100644 .changeset/calm-events-cleanup.md delete mode 100644 .changeset/calm-heads-glow.md delete mode 100644 .changeset/calm-render-results.md delete mode 100644 .changeset/each-fallback-scope.md delete mode 100644 .changeset/easy-points-tan.md delete mode 100644 .changeset/gold-trams-knock.md delete mode 100644 .changeset/green-inputs-ssr.md delete mode 100644 .changeset/grumpy-pens-press.md delete mode 100644 .changeset/olive-mice-argue.md delete mode 100644 .changeset/reactive-has-own.md delete mode 100644 .changeset/state-eager-let-declaration.md delete mode 100644 .changeset/tall-kids-juggle.md delete mode 100644 .changeset/tricky-cooks-help.md delete mode 100644 .changeset/wild-cases-smile.md diff --git a/.changeset/calm-events-cleanup.md b/.changeset/calm-events-cleanup.md deleted file mode 100644 index 4f5c2357f1..0000000000 --- a/.changeset/calm-events-cleanup.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: cancel deferred event listeners during cleanup diff --git a/.changeset/calm-heads-glow.md b/.changeset/calm-heads-glow.md deleted file mode 100644 index ee21d566bb..0000000000 --- a/.changeset/calm-heads-glow.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: preserve global CSS in components without scopable elements diff --git a/.changeset/calm-render-results.md b/.changeset/calm-render-results.md deleted file mode 100644 index f3073ec4b5..0000000000 --- a/.changeset/calm-render-results.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: reduce SSR render result garbage collection diff --git a/.changeset/each-fallback-scope.md b/.changeset/each-fallback-scope.md deleted file mode 100644 index 5134fc462b..0000000000 --- a/.changeset/each-fallback-scope.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: resolve the fallback of an each block in the enclosing scope diff --git a/.changeset/easy-points-tan.md b/.changeset/easy-points-tan.md deleted file mode 100644 index 60edbf94eb..0000000000 --- a/.changeset/easy-points-tan.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -perf: speed up parser interactions with Acorn or avoid them where possible diff --git a/.changeset/gold-trams-knock.md b/.changeset/gold-trams-knock.md deleted file mode 100644 index 8006d13fef..0000000000 --- a/.changeset/gold-trams-knock.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: prevent effect tree of batches from interfering with each other diff --git a/.changeset/green-inputs-ssr.md b/.changeset/green-inputs-ssr.md deleted file mode 100644 index e034d0e79a..0000000000 --- a/.changeset/green-inputs-ssr.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: serialize input default values during server rendering diff --git a/.changeset/grumpy-pens-press.md b/.changeset/grumpy-pens-press.md deleted file mode 100644 index 0ba87ab0c5..0000000000 --- a/.changeset/grumpy-pens-press.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: remove `WAS_MARKED` flag in favor of `Set` diff --git a/.changeset/olive-mice-argue.md b/.changeset/olive-mice-argue.md deleted file mode 100644 index 6d749bcc3b..0000000000 --- a/.changeset/olive-mice-argue.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: throw `set_context_after_init` when `setContext` is called after an `await` during SSR diff --git a/.changeset/reactive-has-own.md b/.changeset/reactive-has-own.md deleted file mode 100644 index 2ec5d27cee..0000000000 --- a/.changeset/reactive-has-own.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: make Object.hasOwn reactive for state proxy ownership changes diff --git a/.changeset/state-eager-let-declaration.md b/.changeset/state-eager-let-declaration.md deleted file mode 100644 index 6939094109..0000000000 --- a/.changeset/state-eager-let-declaration.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: keep `$state.eager` when used as a variable initializer diff --git a/.changeset/tall-kids-juggle.md b/.changeset/tall-kids-juggle.md deleted file mode 100644 index f116590a28..0000000000 --- a/.changeset/tall-kids-juggle.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -perf: avoid regex matching in parser where possible diff --git a/.changeset/tricky-cooks-help.md b/.changeset/tricky-cooks-help.md deleted file mode 100644 index f61c7944a1..0000000000 --- a/.changeset/tricky-cooks-help.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: in non-async mode, only push variable to current_sources when active_reaction is updating diff --git a/.changeset/wild-cases-smile.md b/.changeset/wild-cases-smile.md deleted file mode 100644 index ac5edacfd1..0000000000 --- a/.changeset/wild-cases-smile.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'svelte': patch ---- - -fix: recognise `aria-braillelabel` and `aria-brailleroledescription` as known ARIA attributes diff --git a/packages/svelte/CHANGELOG.md b/packages/svelte/CHANGELOG.md index e88e078486..75592eba84 100644 --- a/packages/svelte/CHANGELOG.md +++ b/packages/svelte/CHANGELOG.md @@ -1,5 +1,37 @@ # svelte +## 5.57.1 + +### Patch Changes + +- fix: cancel deferred event listeners during cleanup ([#18749](https://github.com/sveltejs/svelte/pull/18749)) + +- fix: preserve global CSS in components without scopable elements ([#18793](https://github.com/sveltejs/svelte/pull/18793)) + +- fix: reduce SSR render result garbage collection ([#18798](https://github.com/sveltejs/svelte/pull/18798)) + +- fix: resolve the fallback of an each block in the enclosing scope ([#18803](https://github.com/sveltejs/svelte/pull/18803)) + +- perf: speed up parser interactions with Acorn or avoid them where possible ([#18740](https://github.com/sveltejs/svelte/pull/18740)) + +- fix: prevent effect tree of batches from interfering with each other ([#18508](https://github.com/sveltejs/svelte/pull/18508)) + +- fix: serialize input default values during server rendering ([#18733](https://github.com/sveltejs/svelte/pull/18733)) + +- fix: remove `WAS_MARKED` flag in favor of `Set` ([#18127](https://github.com/sveltejs/svelte/pull/18127)) + +- fix: throw `set_context_after_init` when `setContext` is called after an `await` during SSR ([#18739](https://github.com/sveltejs/svelte/pull/18739)) + +- fix: make Object.hasOwn reactive for state proxy ownership changes ([#18838](https://github.com/sveltejs/svelte/pull/18838)) + +- fix: keep `$state.eager` when used as a variable initializer ([#18809](https://github.com/sveltejs/svelte/pull/18809)) + +- perf: avoid regex matching in parser where possible ([#18736](https://github.com/sveltejs/svelte/pull/18736)) + +- fix: in non-async mode, only push variable to current_sources when active_reaction is updating ([#18550](https://github.com/sveltejs/svelte/pull/18550)) + +- fix: recognise `aria-braillelabel` and `aria-brailleroledescription` as known ARIA attributes ([#18765](https://github.com/sveltejs/svelte/pull/18765)) + ## 5.57.0 ### Minor Changes diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 53e5516bf6..6404eb0596 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -2,7 +2,7 @@ "name": "svelte", "description": "Cybernetically enhanced web apps", "license": "MIT", - "version": "5.57.0", + "version": "5.57.1", "type": "module", "types": "./types/index.d.ts", "engines": { diff --git a/packages/svelte/src/version.js b/packages/svelte/src/version.js index 46620a618b..d925d3eb2e 100644 --- a/packages/svelte/src/version.js +++ b/packages/svelte/src/version.js @@ -4,5 +4,5 @@ * The current version, as set in package.json. * @type {string} */ -export const VERSION = '5.57.0'; +export const VERSION = '5.57.1'; export const PUBLIC_VERSION = '5'; From 803f59b171e1f962c0b0acb20dba2074bc9d2e84 Mon Sep 17 00:00:00 2001 From: Kunpeng Xie <68572236+pentaoa@users.noreply.github.com> Date: Tue, 22 Sep 2026 22:09:26 +0800 Subject: [PATCH 13/29] fix: avoid reinserting dynamic elements during hydration (#18855) Hydrating a `` currently removes and reinserts the DOM node that was already claimed from the server-rendered HTML. This can restart CSS animations and disconnect/reconnect custom elements inside it. Keep claimed elements in place while preserving insertion for client-created elements and later tag changes. Capture the hydration state before rendering children, since empty or void elements can temporarily turn hydration off. Fixes #18852. ### Before submitting the PR, please make sure you do the following - [x] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs - [x] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`. - [x] This message body should clearly illustrate what problems it solves. - [x] Ideally, include a test that fails without this PR but passes with it. - [x] If this PR changes code within `packages/svelte/src`, add a changeset (`npx changeset`). ### Tests and linting - [x] Run the tests with `pnpm test` and lint the project with `pnpm lint` Validation: - The real Chromium regression fails on unchanged `636eaaaa`: hydration removes all four server-rendered dynamic elements. Client mounting and server rendering pass. - The regression checks node removals and custom-element connection callbacks for ordinary, empty, void, and custom dynamic elements, then changes the tags and removes/recreates an element. - A hydration mismatch regression verifies that different client/server child branches recover while retaining the outer element and its following sibling. - `pnpm test hydration runtime-browser`: 219 passed. - Full `CI=true pnpm test`: 34 test files passed, 7,790 tests passed, 55 existing skips. The real-browser suite ran with Chromium. - `pnpm check`: passed, including build, generated type checks, and treeshakeability checks. - `pnpm lint`: passed. AI assistance: This change and its tests were prepared with OpenAI Codex. The PR description is also AI-assisted. --------- Co-authored-by: paoloricciuti --- .changeset/tidy-trees-stay.md | 5 ++ .../client/dom/blocks/svelte-element.js | 4 +- .../dynamic-element-child-mismatch/_config.js | 10 +++ .../_expected.html | 2 + .../main.svelte | 9 +++ .../svelte/tests/runtime-browser/assert.js | 1 + .../_config.js | 71 +++++++++++++++++++ .../main.svelte | 11 +++ 8 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 .changeset/tidy-trees-stay.md create mode 100644 packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_config.js create mode 100644 packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_expected.html create mode 100644 packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/main.svelte create mode 100644 packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/_config.js create mode 100644 packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/main.svelte diff --git a/.changeset/tidy-trees-stay.md b/.changeset/tidy-trees-stay.md new file mode 100644 index 0000000000..65bf7de619 --- /dev/null +++ b/.changeset/tidy-trees-stay.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: preserve dynamic element connections during hydration diff --git a/packages/svelte/src/internal/client/dom/blocks/svelte-element.js b/packages/svelte/src/internal/client/dom/blocks/svelte-element.js index 84217c57e3..adca73b181 100644 --- a/packages/svelte/src/internal/client/dom/blocks/svelte-element.js +++ b/packages/svelte/src/internal/client/dom/blocks/svelte-element.js @@ -71,6 +71,7 @@ export function element(node, get_tag, is_svg, render_fn, get_namespace, locatio branches.ensure(next_tag, (anchor) => { if (next_tag) { + var is_hydrating = hydrating; element = hydrating ? /** @type {Element} */ (element) : create_element(next_tag, ns); if (DEV && location) { @@ -123,7 +124,8 @@ export function element(node, get_tag, is_svg, render_fn, get_namespace, locatio // we do this after calling `render_fn` so that child effects don't override `nodes.end` /** @type {Effect & { nodes: EffectNodes }} */ (active_effect).nodes.end = element; - anchor.before(element); + // we only move the node if we are not hydrating since a claimed element is already in place + if (!is_hydrating) anchor.before(element); } if (hydrating) { diff --git a/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_config.js b/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_config.js new file mode 100644 index 0000000000..cdd8f4484b --- /dev/null +++ b/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_config.js @@ -0,0 +1,10 @@ +import { test } from '../../test'; + +export default test({ + server_props: { condition: false }, + props: { condition: true }, + + snapshot(target) { + return { element: target.querySelector('div'), sibling: target.querySelector(':scope > p') }; + } +}); diff --git a/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_expected.html b/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_expected.html new file mode 100644 index 0000000000..5f68a45e48 --- /dev/null +++ b/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/_expected.html @@ -0,0 +1,2 @@ +

client

+

after

diff --git a/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/main.svelte b/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/main.svelte new file mode 100644 index 0000000000..839a06981f --- /dev/null +++ b/packages/svelte/tests/hydration/samples/dynamic-element-child-mismatch/main.svelte @@ -0,0 +1,9 @@ + + + + {#if condition}

client

{:else}server{/if} +
+

after

diff --git a/packages/svelte/tests/runtime-browser/assert.js b/packages/svelte/tests/runtime-browser/assert.js index 249c5ad33d..9fdb917048 100644 --- a/packages/svelte/tests/runtime-browser/assert.js +++ b/packages/svelte/tests/runtime-browser/assert.js @@ -128,6 +128,7 @@ function normalize_children(node) { * id_prefix?: string; * props?: Props; * compileOptions?: Partial; + * before_test?: () => void; * test?: (args: { * assert: typeof assert & { * htmlEqual(a: string, b: string, description?: string): void; diff --git a/packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/_config.js b/packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/_config.js new file mode 100644 index 0000000000..beabb5b1fa --- /dev/null +++ b/packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/_config.js @@ -0,0 +1,71 @@ +import { flushSync } from 'svelte'; +import { assert_ok, test } from '../../assert'; + +/** @type {Record} */ +const connections = {}; +/** @type {string[]} */ +const disconnections = []; +/** @type {Element[]} */ +let claimed; +/** @type {MutationObserver} */ +let observer; + +export default test({ + before_test() { + const target = document.querySelector('main'); + assert_ok(target); + claimed = Array.from(target.children); + customElements.define( + 'connection-probe', + class extends HTMLElement { + connectedCallback() { + connections[this.id] = (connections[this.id] || 0) + 1; + } + disconnectedCallback() { + disconnections.push(this.id); + } + } + ); + observer = new MutationObserver(() => {}); + observer.observe(target, { childList: true }); + }, + + test({ assert, component, target }) { + const removed = observer.takeRecords().flatMap((record) => Array.from(record.removedNodes)); + observer.disconnect(); + assert.deepEqual( + removed + .filter((node) => node instanceof Element) + .filter((node) => claimed.includes(node)) + .map((node) => node.id), + [] + ); + assert.deepEqual(connections, { child: 1, custom: 1 }); + assert.deepEqual(disconnections, []); + + flushSync(() => { + component.tag = 'section'; + component.empty_tag = 'span'; + component.void_tag = 'hr'; + component.custom_tag = 'aside'; + }); + assert.equal(target.querySelector('#parent')?.tagName, 'SECTION'); + assert.equal(target.querySelector('#empty')?.tagName, 'SPAN'); + assert.equal(target.querySelector('#void')?.tagName, 'HR'); + assert.equal(target.querySelector('#custom')?.tagName, 'ASIDE'); + assert.deepEqual(connections, { child: 2, custom: 1 }); + assert.deepEqual(disconnections, ['child', 'custom']); + + flushSync(() => { + component.tag = null; + }); + assert.equal(target.querySelector('#parent'), null); + assert.deepEqual(disconnections, ['child', 'custom', 'child']); + + flushSync(() => { + component.tag = 'div'; + }); + assert.equal(target.querySelector('#parent')?.tagName, 'DIV'); + assert.deepEqual(connections, { child: 3, custom: 1 }); + } +}); diff --git a/packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/main.svelte b/packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/main.svelte new file mode 100644 index 0000000000..44e902188c --- /dev/null +++ b/packages/svelte/tests/runtime-browser/samples/dynamic-element-hydration-preserves-connection/main.svelte @@ -0,0 +1,11 @@ + + + + + + From 325620ba63eeff13c9f36e42806a545aaa7ee242 Mon Sep 17 00:00:00 2001 From: Tee Ming Date: Thu, 24 Sep 2026 00:37:04 +0800 Subject: [PATCH 14/29] fix: bypass error boundaries for hydration recovery (#18841) Fixes #18840 This PR rethrows the hydration error rather than catching it at the boundaries so that the svelte hydration warning can surface ### Before submitting the PR, please make sure you do the following - [x] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs - [x] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`. - [x] This message body should clearly illustrate what problems it solves. - [x] Ideally, include a test that fails without this PR but passes with it. - [x] If this PR changes code within `packages/svelte/src`, add a changeset (`npx changeset`). ### Tests and linting - [x] Run the tests with `pnpm test` and lint the project with `pnpm lint` --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/tidy-pandas-hydrate.md | 5 +++++ .../svelte/src/internal/client/dom/blocks/boundary.js | 10 +++++++++- packages/svelte/src/internal/client/error-handling.js | 6 +++++- .../samples/boundary-mismatch-recovery/_config.js | 5 +++++ .../samples/boundary-mismatch-recovery/_expected.html | 1 + .../samples/boundary-mismatch-recovery/main.svelte | 7 +++++++ 6 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 .changeset/tidy-pandas-hydrate.md create mode 100644 packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_config.js create mode 100644 packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_expected.html create mode 100644 packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/main.svelte diff --git a/.changeset/tidy-pandas-hydrate.md b/.changeset/tidy-pandas-hydrate.md new file mode 100644 index 0000000000..944797a760 --- /dev/null +++ b/.changeset/tidy-pandas-hydrate.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: prevent hydration mismatch recovery from being intercepted by error boundaries diff --git a/packages/svelte/src/internal/client/dom/blocks/boundary.js b/packages/svelte/src/internal/client/dom/blocks/boundary.js index fd6bbdf5b4..979d3e50b4 100644 --- a/packages/svelte/src/internal/client/dom/blocks/boundary.js +++ b/packages/svelte/src/internal/client/dom/blocks/boundary.js @@ -1,6 +1,10 @@ /** @import { Effect, Source, TemplateNode, } from '#client' */ import { BOUNDARY_EFFECT, EFFECT_PRESERVED, EFFECT_TRANSPARENT } from '#client/constants'; -import { HYDRATION_START_ELSE, HYDRATION_START_FAILED } from '../../../../constants.js'; +import { + HYDRATION_ERROR, + HYDRATION_START_ELSE, + HYDRATION_START_FAILED +} from '../../../../constants.js'; import { component_context, set_component_context } from '../../context.js'; import { invoke_error_boundary } from '../../error-handling.js'; import { @@ -445,6 +449,10 @@ export class Boundary { /** @param {unknown} error */ error(error) { + if (error === HYDRATION_ERROR) { + throw error; + } + // If we have nothing to capture the error, or if we hit an error while // rendering the fallback, re-throw for another boundary to handle if (!this.#props.onerror && !this.#props.failed) { diff --git a/packages/svelte/src/internal/client/error-handling.js b/packages/svelte/src/internal/client/error-handling.js index a46281d36c..7c69f05dcc 100644 --- a/packages/svelte/src/internal/client/error-handling.js +++ b/packages/svelte/src/internal/client/error-handling.js @@ -1,7 +1,7 @@ /** @import { Derived, Effect } from '#client' */ /** @import { Boundary } from './dom/blocks/boundary.js' */ import { DEV } from 'esm-env'; -import { FILENAME } from '../../constants.js'; +import { FILENAME, HYDRATION_ERROR } from '../../constants.js'; import { is_firefox } from './dom/operations.js'; import { ERROR_VALUE, @@ -52,6 +52,10 @@ export function handle_error(error) { * @param {Effect | null} effect */ export function invoke_error_boundary(error, effect) { + if (error === HYDRATION_ERROR) { + throw error; + } + if (effect !== null && (effect.f & DESTROYED) !== 0) { return; } diff --git a/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_config.js b/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_config.js new file mode 100644 index 0000000000..cf22ff2c85 --- /dev/null +++ b/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_config.js @@ -0,0 +1,5 @@ +import { test } from '../../test'; + +export default test({ + expect_hydration_error: true +}); diff --git a/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_expected.html b/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_expected.html new file mode 100644 index 0000000000..8286c59709 --- /dev/null +++ b/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/_expected.html @@ -0,0 +1 @@ +

Valid HTML fragment

diff --git a/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/main.svelte b/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/main.svelte new file mode 100644 index 0000000000..8b9cc0770e --- /dev/null +++ b/packages/svelte/tests/hydration/samples/boundary-mismatch-recovery/main.svelte @@ -0,0 +1,7 @@ + +

{@html '

Valid HTML fragment

'}

+ + {#snippet failed()} +

boundary fallback

+ {/snippet} +
From 38098a931142dfef6ca7330d33264d1908b698fa Mon Sep 17 00:00:00 2001 From: Mariana Castro <121824373+maricastroc@users.noreply.github.com> Date: Wed, 23 Sep 2026 13:58:28 -0300 Subject: [PATCH 15/29] fix: don't overwrite an unchanged spread `value` (#18864) Fixes #18862 When a `value` is applied through a spread (``), `set_attributes` always writes `element.value`, even if the element already has that value. Writing `value` on a number input clears any incomplete text: typing `250.` makes `input.value` `''` (the text is still visible, but `validity.badInput` is `true`). If the spread `value` then becomes `''` too, writing `''` erases what the user typed. This is what happens with SvelteKit remote forms: `fields.quantity.as('number')` coerces `''` to `undefined`, the spread `value` becomes `''`, and Svelte writes it back to the input. When `.` is typed: - Chromium clears the input in every locale, because `250.` is always incomplete input there. - WebKit/Safari clears it in locales where `.` is not the decimal separator (e.g. `fr-CH`), which is where the reporter saw it. A plain `` never clears. Neither does the same `value` in Svelte without a spread (`value={...}`), because `set_value` already skips writing when `element.value === value`. This PR adds the same check to the spread path. Svelte 3 had this check too (#3426, #3495); it was lost in Svelte 5. The first write still always happens. Writing `value` sets the input's dirty value flag, and without that flag a `defaultValue` applied afterwards would change the current value (covered by `form-default-value-spread`). This also likely affects sveltejs/kit#16270 (same symptom, plus a cursor jump caused by redundant writes). That issue is handled on the kit side in sveltejs/kit#16320; this PR is independent of it. The test runs in a real browser (`runtime-browser`). It types with `document.execCommand('insertText')`, which goes through Chromium's own editing, so `250.` is real incomplete input. The locale is not mocked. The test fails without this change and passes with it. ### Before submitting the PR, please make sure you do the following - [x] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs - [x] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`. - [x] This message body should clearly illustrate what problems it solves. - [x] Ideally, include a test that fails without this PR but passes with it. - [x] If this PR changes code within `packages/svelte/src`, add a changeset (`npx changeset`). ### Tests and linting - [x] Run the tests with `pnpm test` and lint the project with `pnpm lint` --------- Co-authored-by: Paolo Ricciuti --- .changeset/quiet-inputs-keep.md | 5 ++++ .../client/dom/elements/attributes.js | 16 ++++++++++- .../_config.js | 28 +++++++++++++++++++ .../main.svelte | 5 ++++ 4 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 .changeset/quiet-inputs-keep.md create mode 100644 packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/_config.js create mode 100644 packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/main.svelte diff --git a/.changeset/quiet-inputs-keep.md b/.changeset/quiet-inputs-keep.md new file mode 100644 index 0000000000..0efcfcc058 --- /dev/null +++ b/.changeset/quiet-inputs-keep.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: don't overwrite an unchanged spread `value`, preserving incomplete number input diff --git a/packages/svelte/src/internal/client/dom/elements/attributes.js b/packages/svelte/src/internal/client/dom/elements/attributes.js index 0fe1b8b2d3..7d2dd62baf 100644 --- a/packages/svelte/src/internal/client/dom/elements/attributes.js +++ b/packages/svelte/src/internal/client/dom/elements/attributes.js @@ -422,7 +422,21 @@ function set_attributes( } else if (!is_custom_element && (key === '__value' || (key === 'value' && value != null))) { // @ts-ignore We're not running this for custom elements because __value is actually // how Lit stores the current value on the element, and messing with that would break things. - element.value = element.__value = value; + element.__value = value; + // we don't set the value if it hasn't changed. This supports invalid number inputs like `1e` because + // 1. user types 1e + // 2. the state is updated reading e.target.value which is '' + // 3. the spreaded value is '' + // 4. updating input.value would thus, clear the user value + if ( + prev_value == null || + // @ts-ignore + element.value !== value || + (value === 0 && element.nodeName === PROGRESS_TAG) + ) { + // @ts-ignore + element.value = value; + } } else if (key === 'selected' && is_option_element) { set_selected(/** @type {HTMLOptionElement} */ (element), value); } else { diff --git a/packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/_config.js b/packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/_config.js new file mode 100644 index 0000000000..cec1e179ac --- /dev/null +++ b/packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/_config.js @@ -0,0 +1,28 @@ +import { flushSync } from 'svelte'; +import { ok, test } from '../../assert'; + +export default test({ + async test({ assert, target }) { + const input = target.querySelector('input'); + ok(input); + + input.focus(); + + // we need to use `document.execCommand('insertText', false, ...)` to simulate user input + // because directly setting an invalid value to `input.value` would simply clear the input + // and dispatching an event would not update the input correctly + document.execCommand('insertText', false, '1'); + flushSync(); + // `1e` is incomplete on every platform, unlike `1.` which Chromium on Linux accepts as `1` + document.execCommand('insertText', false, 'e'); + flushSync(); + + assert.equal(input.value, ''); + assert.equal(input.validity.badInput, true); + + document.execCommand('insertText', false, '5'); + flushSync(); + + assert.equal(input.value, '1e5'); + } +}); diff --git a/packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/main.svelte b/packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/main.svelte new file mode 100644 index 0000000000..3e7a5cc335 --- /dev/null +++ b/packages/svelte/tests/runtime-browser/samples/spread-input-number-incomplete-value/main.svelte @@ -0,0 +1,5 @@ + + + (value = e.currentTarget.value)} /> From 58297c5a73e6a06687c3892efbfc807eec3f23af Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Thu, 24 Sep 2026 04:19:37 -0400 Subject: [PATCH 16/29] chore: extract some minor changes from #18861 (#18866) doing my usual thing of extracting no-brainer changes from a giant PR to try and make it slightly less giant --- packages/svelte/src/internal/client/dev/tracing.js | 4 +++- packages/svelte/src/internal/client/dom/blocks/each.js | 4 ++-- packages/svelte/src/internal/client/reactivity/batch.js | 4 ++++ packages/svelte/src/internal/client/reactivity/sources.js | 6 +++--- packages/svelte/src/internal/client/runtime.js | 6 +++--- packages/svelte/src/reactivity/date.js | 4 ++-- 6 files changed, 17 insertions(+), 11 deletions(-) diff --git a/packages/svelte/src/internal/client/dev/tracing.js b/packages/svelte/src/internal/client/dev/tracing.js index c6edfde933..9fea8175bd 100644 --- a/packages/svelte/src/internal/client/dev/tracing.js +++ b/packages/svelte/src/internal/client/dev/tracing.js @@ -131,8 +131,10 @@ export function trace(label, fn) { } /** - * @param {Value} source + * @template {Value} T + * @param {T} source * @param {string} label + * @returns {T} */ export function tag(source, label) { source.label = label; diff --git a/packages/svelte/src/internal/client/dom/blocks/each.js b/packages/svelte/src/internal/client/dom/blocks/each.js index 9a2504f887..ea828f893b 100644 --- a/packages/svelte/src/internal/client/dom/blocks/each.js +++ b/packages/svelte/src/internal/client/dom/blocks/each.js @@ -1,4 +1,4 @@ -/** @import { EachItem, EachOutroGroup, EachState, Effect, EffectNodes, MaybeSource, Source, TemplateNode, TransitionManager, Value } from '#client' */ +/** @import { EachItem, EachOutroGroup, EachState, Effect, EffectNodes, MaybeSource, TemplateNode, TransitionManager } from '#client' */ /** @import { Batch } from '../../reactivity/batch.js'; */ import { EACH_INDEX_REACTIVE, @@ -664,7 +664,7 @@ function reconcile(state, array, anchor, flags, get_key) { * @param {V} value * @param {unknown} key * @param {number} index - * @param {(anchor: Node, item: V | Source, index: number | Value, collection: () => V[]) => void} render_fn + * @param {(anchor: Node, item: MaybeSource, index: MaybeSource, collection: () => V[]) => void} render_fn * @param {number} flags * @param {() => V[]} get_collection * @returns {EachItem} diff --git a/packages/svelte/src/internal/client/reactivity/batch.js b/packages/svelte/src/internal/client/reactivity/batch.js index 75ce33b1c5..f620c2b4c8 100644 --- a/packages/svelte/src/internal/client/reactivity/batch.js +++ b/packages/svelte/src/internal/client/reactivity/batch.js @@ -1295,6 +1295,10 @@ export function eager(fn) { let version = version_map.get(parent) ?? source(0); version_map.set(parent, version); + if (DEV) { + version.label ??= '$state.eager version'; + } + teardown(() => { if (parent.f & DESTROYING) version_map.delete(parent); }); diff --git a/packages/svelte/src/internal/client/reactivity/sources.js b/packages/svelte/src/internal/client/reactivity/sources.js index 006494f0b5..4b10ddbd31 100644 --- a/packages/svelte/src/internal/client/reactivity/sources.js +++ b/packages/svelte/src/internal/client/reactivity/sources.js @@ -46,7 +46,7 @@ import { set_signal_status, update_derived_status } from './status.js'; /** @type {Set} */ export let eager_effects = new Set(); -/** @type {Map} */ +/** @type {Map} */ export const old_values = new Map(); /** @@ -141,7 +141,7 @@ export function mutate(source, value) { /** * @template V - * @param {Source} source + * @param {Value} source * @param {V} value * @param {boolean} [should_proxy] * @returns {V} @@ -181,7 +181,7 @@ var count_deps = 0; /** * @template V - * @param {Source} source + * @param {Value} source * @param {V} value * @param {Effect[] | null} [updated_during_traversal] * @returns {V} diff --git a/packages/svelte/src/internal/client/runtime.js b/packages/svelte/src/internal/client/runtime.js index 27def05300..6212605008 100644 --- a/packages/svelte/src/internal/client/runtime.js +++ b/packages/svelte/src/internal/client/runtime.js @@ -93,7 +93,7 @@ export function set_active_effect(effect) { /** * When sources are created within a reaction, reading and writing * them within that reaction should not cause a re-run - * @type {null | Set} + * @type {null | Set} */ export let current_sources = null; @@ -121,11 +121,11 @@ export let skipped_deps = 0; /** * Tracks writes that the effect it's executed in doesn't listen to yet, * so that the dependency can be added to the effect later on if it then reads it - * @type {null | Source[]} + * @type {null | Value[]} */ export let untracked_writes = null; -/** @param {null | Source[]} value */ +/** @param {null | Value[]} value */ export function set_untracked_writes(value) { untracked_writes = value; } diff --git a/packages/svelte/src/reactivity/date.js b/packages/svelte/src/reactivity/date.js index f882c05d76..b70ba7969a 100644 --- a/packages/svelte/src/reactivity/date.js +++ b/packages/svelte/src/reactivity/date.js @@ -1,4 +1,4 @@ -/** @import { Source } from '#client' */ +/** @import { Derived } from '#client' */ import { derived } from '../internal/client/index.js'; import { set, state } from '../internal/client/reactivity/sources.js'; import { tag } from '../internal/client/dev/tracing.js'; @@ -42,7 +42,7 @@ var inited = false; export class SvelteDate extends Date { #time = state(super.getTime()); - /** @type {Map>} */ + /** @type {Map>} */ #deriveds = new Map(); #reaction = active_reaction; From da2f83343bf5e2fb183881b74ef06fac24f0e249 Mon Sep 17 00:00:00 2001 From: Simon H <5968653+dummdidumm@users.noreply.github.com> Date: Thu, 24 Sep 2026 22:47:52 +0200 Subject: [PATCH 17/29] fix: read batch-local array on each-block commit (#18879) Another extraction from #18861 which I'm pretty sure you can also construct a buggy reproduction for today, but with #18861 it's strictly necessary so we don't need to come up with one now --- .changeset/short-radios-sneeze.md | 5 +++++ packages/svelte/src/internal/client/dom/blocks/each.js | 10 ++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 .changeset/short-radios-sneeze.md diff --git a/.changeset/short-radios-sneeze.md b/.changeset/short-radios-sneeze.md new file mode 100644 index 0000000000..847c3eef17 --- /dev/null +++ b/.changeset/short-radios-sneeze.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: read batch-local array on each-block commit diff --git a/packages/svelte/src/internal/client/dom/blocks/each.js b/packages/svelte/src/internal/client/dom/blocks/each.js index ea828f893b..58d59a6825 100644 --- a/packages/svelte/src/internal/client/dom/blocks/each.js +++ b/packages/svelte/src/internal/client/dom/blocks/each.js @@ -216,9 +216,6 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f tag(each_array, '{#each ...}'); } - /** @type {V[]} */ - var array; - /** @type {Map>} */ var pending = new Map(); @@ -234,6 +231,11 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f state.pending.delete(batch); + // The effect doesn't necessarily re-run in a batch right before that batch commits + // (its view of the collection may not have changed), so we read the collection + // as the committing batch sees it rather than using the most recent block run's result + var array = get(each_array); + state.fallback = fallback; reconcile(state, array, anchor, flags, get_key); @@ -264,7 +266,7 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f } var effect = block(() => { - array = /** @type {V[]} */ (get(each_array)); + var array = /** @type {V[]} */ (get(each_array)); var length = array.length; /** `true` if there was a hydration mismatch. Needs to be a `let` or else it isn't treeshaken out */ From 98e547535d9286cfd4163fe3a6d85c7053db6c6e Mon Sep 17 00:00:00 2001 From: Simon H <5968653+dummdidumm@users.noreply.github.com> Date: Thu, 24 Sep 2026 22:49:15 +0200 Subject: [PATCH 18/29] fix: flush anything pending before invoking flushSync callback function (#18878) no new test here but it's necessary for #18861 to work, and we might as well extract it --- .changeset/major-papayas-run.md | 5 +++++ .../svelte/src/internal/client/reactivity/batch.js | 12 ++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) create mode 100644 .changeset/major-papayas-run.md diff --git a/.changeset/major-papayas-run.md b/.changeset/major-papayas-run.md new file mode 100644 index 0000000000..59909fb448 --- /dev/null +++ b/.changeset/major-papayas-run.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: flush anything pending before invoking flushSync callback function diff --git a/packages/svelte/src/internal/client/reactivity/batch.js b/packages/svelte/src/internal/client/reactivity/batch.js index f620c2b4c8..05f7586072 100644 --- a/packages/svelte/src/internal/client/reactivity/batch.js +++ b/packages/svelte/src/internal/client/reactivity/batch.js @@ -1032,15 +1032,15 @@ export class Batch { */ export function flushSync(fn) { var was_flushing_sync = is_flushing_sync; + var prev_previous_batch = previous_batch; + previous_batch = null; is_flushing_sync = true; try { var result; if (fn) { - if (current_batch !== null && !current_batch.is_fork) { - current_batch.flush(); - } + flushSync(); // flush anything pending through the while loop below result = fn(); } @@ -1056,6 +1056,7 @@ export function flushSync(fn) { } } finally { is_flushing_sync = was_flushing_sync; + previous_batch = prev_previous_batch; } } @@ -1406,6 +1407,8 @@ export function fork(fn) { e.fork_timing(); } + flushSync(); + var batch = Batch.ensure(); batch.is_fork = true; batch_values = new Map(); @@ -1413,7 +1416,8 @@ export function fork(fn) { var committed = false; var settled = batch.settled(); - flushSync(fn); + fn(); + flushSync(); return { commit: async () => { From f7ca0a44a5d198d600521afa44341736c9bee0c8 Mon Sep 17 00:00:00 2001 From: Dex Date: Fri, 25 Sep 2026 00:04:17 +0200 Subject: [PATCH 19/29] chore: fix typos in code comments (#18860) Fixes four typos in code comments (no behavioral change): - `packages/svelte/src/index-client.js`: `noone` -> `no one` - `packages/svelte/src/internal/client/dom/css.js`: `Therfore` -> `Therefore` - `packages/svelte/src/internal/client/runtime.js`: `loosing` -> `losing` - `packages/svelte/src/internal/server/index.js`: `aswell` -> `as well` Checklist: title prefixed with `chore:`; comment-only change so no changeset and no behavior affected. Co-authored-by: Dextheking1 --- packages/svelte/src/index-client.js | 2 +- packages/svelte/src/internal/client/dom/css.js | 2 +- packages/svelte/src/internal/client/runtime.js | 2 +- packages/svelte/src/internal/server/index.js | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/svelte/src/index-client.js b/packages/svelte/src/index-client.js index 0eb1b80315..3da59eb7f7 100644 --- a/packages/svelte/src/index-client.js +++ b/packages/svelte/src/index-client.js @@ -17,7 +17,7 @@ if (DEV) { if (!(rune in globalThis)) { // TODO if people start adjusting the "this can contain runes" config through v-p-s more, adjust this message /** @type {any} */ - let value; // let's hope noone modifies this global, but belts and braces + let value; // let's hope no one modifies this global, but belts and braces Object.defineProperty(globalThis, rune, { configurable: true, // eslint-disable-next-line getter-return diff --git a/packages/svelte/src/internal/client/dom/css.js b/packages/svelte/src/internal/client/dom/css.js index 23f4eff4f7..78a32901fe 100644 --- a/packages/svelte/src/internal/client/dom/css.js +++ b/packages/svelte/src/internal/client/dom/css.js @@ -12,7 +12,7 @@ export function append_styles(anchor, css) { // Use an effect to ensure `anchor` is in the DOM, otherwise getRootNode() will yield wrong results effect(() => { // Bit of a hack: branches.js/each.js use offscreen fragments with temporary text nodes that will - // never be connected to the real dom. Therfore walk up to the branch that has created the component + // never be connected to the real dom. Therefore walk up to the branch that has created the component // whose styles we want to append, and check its node instead. It will be connected by the time we get here. anchor = active_effect?.parent?.nodes?.start ?? anchor; var root = anchor.getRootNode(); diff --git a/packages/svelte/src/internal/client/runtime.js b/packages/svelte/src/internal/client/runtime.js index 6212605008..76802974b7 100644 --- a/packages/svelte/src/internal/client/runtime.js +++ b/packages/svelte/src/internal/client/runtime.js @@ -410,7 +410,7 @@ function remove_reaction(signal, dependency) { // In a fork it's possible that a derived is executed and gets reactions, then commits, but is // never re-executed. This is possible when the derived is only executed once in the context // of a new branch which happens before fork.commit() runs. In this case, the derived still has - // UNINITIALIZED as its value, and then when it's loosing its reactions we need to ensure it stays + // UNINITIALIZED as its value, and then when it's losing its reactions we need to ensure it stays // DIRTY so it is reexecuted once someone wants its value again. if (derived.v !== UNINITIALIZED) { update_derived_status(derived); diff --git a/packages/svelte/src/internal/server/index.js b/packages/svelte/src/internal/server/index.js index 20bef78306..6a63bd9fd6 100644 --- a/packages/svelte/src/internal/server/index.js +++ b/packages/svelte/src/internal/server/index.js @@ -168,7 +168,7 @@ export function attributes(attrs, css_hash, classes, styles, flags = 0) { // value/checked takes precedence over defaultValue/defaultChecked name = name === 'defaultvalue' ? 'value' : 'checked'; if (name in attrs) continue; - // We're checking prior entries aswell because "name in attrs" is not enough as the attributes may have different casing + // We're checking prior entries as well because "name in attrs" is not enough as the attributes may have different casing for (let j = 0; j < names.length; j++) { if (names[j].toLowerCase() === name) continue outer; } From 75aa6ba38d58c83ff012bed77c39edb814e43bc6 Mon Sep 17 00:00:00 2001 From: G Date: Fri, 25 Sep 2026 04:44:00 +0200 Subject: [PATCH 20/29] fix: don't warn about redundant `link` role on `` without `href` (#18872) Since #11737, `` without an `href` no longer triggers `a11y_no_redundant_roles`, but `` without an `href` still does. Per [ARIA in HTML](https://www.w3.org/TR/html-aria/#el-area-no-href), an `` without `href` has the implicit role `generic` and `link` is one of its allowed roles, so the role isn't redundant. This applies the existing `` exception to `` and adds test cases for `` with and without `href`. Closes #9261. The `` example in that issue was already fixed by #11737, but the issue was left open. ### Before submitting the PR, please make sure you do the following - [x] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs - [x] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`. - [x] This message body should clearly illustrate what problems it solves. - [x] Ideally, include a test that fails without this PR but passes with it. - [x] If this PR changes code within `packages/svelte/src`, add a changeset (`npx changeset`). ### Tests and linting - [x] Run the tests with `pnpm test` and lint the project with `pnpm lint` --- .changeset/quiet-areas-link.md | 5 +++++ .../phases/2-analyze/visitors/shared/a11y/index.js | 4 ++-- .../samples/a11y-no-redundant-roles/input.svelte | 5 +++++ .../samples/a11y-no-redundant-roles/warnings.json | 12 ++++++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 .changeset/quiet-areas-link.md diff --git a/.changeset/quiet-areas-link.md b/.changeset/quiet-areas-link.md new file mode 100644 index 0000000000..af4e31f3cb --- /dev/null +++ b/.changeset/quiet-areas-link.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: don't warn about a redundant `link` role on `` elements without an `href` diff --git a/packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/index.js b/packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/index.js index f06a41d088..c38b03bf69 100644 --- a/packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/index.js +++ b/packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/index.js @@ -173,8 +173,8 @@ export function check_element(node, context) { current_role === get_implicit_role(node.name, attribute_map) && //