pull/18118/head
Rich Harris 2 months ago
commit 2792ac74c2

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: reapply context after transforming error during SSR

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: don't rebase just-created batches

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: flush eager effects in production

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: rethrow error of failed iterable after calling `return()`

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: account for proxified instance when updating `bind:this`

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: ensure scheduled batch is flushed if not obsolete

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: resolve stale deriveds with latest value

@ -0,0 +1,5 @@
---
'svelte': patch
---
chore: remove unnecessary `increment_pending` calls

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: allow `@debug` tags to reference awaited variables

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: re-run fallback props if dependencies update

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: ignore comments when reading CSS values

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: wrap `Promise.all` in `save` during SSR

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: ignore false-positive errors of `$inspect` dependencies

@ -167,6 +167,8 @@ To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snaps
This is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`.
If a value has a `toJSON` method, the snapshot will clone the value returned from `toJSON` instead of the original object.
## `$state.eager`
When state changes, it may not be reflected in the UI immediately if it is used by an `await` expression, because [updates are synchronized](await-expressions#Synchronized-updates).

@ -241,7 +241,7 @@ When the value of an `<option>` matches its text content, the attribute can be o
</select>
```
You can give the `<select>` a default value by adding a `selected` attribute to the`<option>` (or options, in the case of `<select multiple>`) that should be initially selected. If the `<select>` is part of a form, it will revert to that selection when the form is reset. Note that for the initial render the value of the binding takes precedence if it's not `undefined`.
You can give the `<select>` a default value by adding a `selected` attribute to the `<option>` (or options, in the case of `<select multiple>`) that should be initially selected. If the `<select>` is part of a form, it will revert to that selection when the form is reset. Note that for the initial render the value of the binding takes precedence if it's not `undefined`.
```svelte
<select bind:value={selected}>

@ -38,6 +38,21 @@ You can now write unit tests for code inside your `.js/.ts` files:
```js
/// file: multiplier.svelte.test.js
// @filename: multiplier.svelte.ts
export function multiplier(initial: number, k: number) {
let count = $state(initial);
return {
get value() {
return count * k;
},
set: (c: number) => {
count = c;
}
};
}
// @filename: multiplier.svelte.test.js
// ---cut---
import { flushSync } from 'svelte';
import { expect, test } from 'vitest';
import { multiplier } from './multiplier.svelte.js';
@ -80,6 +95,16 @@ Since Vitest processes your test files the same way as your source files, you ca
```js
/// file: multiplier.svelte.test.js
// @filename: multiplier.svelte.ts
export function multiplier(getCount: () => number, k: number) {
return {
get value() {
return getCount() * k;
}
};
}
// @filename: multiplier.svelte.test.js
// ---cut---
import { flushSync } from 'svelte';
import { expect, test } from 'vitest';
import { multiplier } from './multiplier.svelte.js';
@ -115,6 +140,10 @@ If the code being tested uses effects, you need to wrap the test inside `$effect
```js
/// file: logger.svelte.test.js
// @filename: logger.svelte.ts
export function logger(fn: () => void) {}
// @filename: logger.svelte.test.js
// ---cut---
import { flushSync } from 'svelte';
import { expect, test } from 'vitest';
import { logger } from './logger.svelte.js';
@ -213,7 +242,7 @@ test('Component', () => {
expect(document.body.innerHTML).toBe('<button>0</button>');
// Click the button, then flush the changes so you can synchronously write expectations
document.body.querySelector('button').click();
document.body.querySelector('button')?.click();
flushSync();
expect(document.body.innerHTML).toBe('<button>1</button>');
@ -226,6 +255,7 @@ test('Component', () => {
While the process is very straightforward, it is also low level and somewhat brittle, as the precise structure of your component may change frequently. Tools like [@testing-library/svelte](https://testing-library.com/docs/svelte-testing-library/intro/) can help streamline your tests. The above test could be rewritten like this:
```js
// @errors: 2339
/// file: component.test.js
import { render, screen } from '@testing-library/svelte';
import userEvent from '@testing-library/user-event';
@ -270,9 +300,9 @@ You can create stories for component variations and test interactions with the [
}
});
</script>
<Story name="Empty Form" />
<Story
name="Filled Form"
play={async ({ args, canvas, userEvent }) => {

@ -1,5 +1,13 @@
# svelte
## 5.55.5
### Patch Changes
- fix: don't mark deriveds while an effect is updating ([#18124](https://github.com/sveltejs/svelte/pull/18124))
- fix: do not dispatch introstart event with animation of animate directive ([#18122](https://github.com/sveltejs/svelte/pull/18122))
## 5.55.4
### Patch Changes

@ -2,7 +2,7 @@
"name": "svelte",
"description": "Cybernetically enhanced web apps",
"license": "MIT",
"version": "5.55.4",
"version": "5.55.5",
"type": "module",
"types": "./types/index.d.ts",
"engines": {

@ -147,6 +147,8 @@ declare namespace $state {
* </script>
* ```
*
* If `state` has a `toJSON` method, the snapshot will clone the value returned from `toJSON` instead of the original object.
*
* @see {@link https://svelte.dev/docs/svelte/$state#$state.snapshot Documentation}
*
* @param state The value to snapshot

@ -524,6 +524,21 @@ function read_value(parser) {
in_url = true;
} else if ((char === ';' || char === '{' || char === '}') && !in_url && !quote_mark) {
return value.trim();
} else if (
char === '/' &&
!in_url &&
!quote_mark &&
parser.template[parser.index + 1] === '*'
) {
parser.index += 2;
while (parser.index < parser.template.length) {
if (parser.template[parser.index] === '*' && parser.template[parser.index + 1] === '/') {
parser.index += 2;
break;
}
parser.index++;
}
continue;
}
value += char;

@ -8,6 +8,10 @@ import * as b from '#compiler/builders';
* @param {ComponentContext} context
*/
export function DebugTag(node, context) {
const blockers = node.identifiers
.map((identifier) => context.state.scope.get(identifier.name)?.blocker)
.filter((blocker) => blocker != null);
const object = b.object(
node.identifiers.map((identifier) => {
const visited = b.call('$.snapshot', /** @type {Expression} */ (context.visit(identifier)));
@ -20,9 +24,11 @@ export function DebugTag(node, context) {
})
);
const call = b.call('console.log', object);
const args = [b.thunk(b.block([b.stmt(b.call('console.log', object)), b.debugger]))];
context.state.init.push(
b.stmt(b.call('$.template_effect', b.thunk(b.block([b.stmt(call), b.debugger]))))
);
if (blockers.length > 0) {
args.push(b.array([]), b.array([]), b.array(blockers));
}
context.state.init.push(b.stmt(b.call('$.template_effect', ...args)));
}

@ -2,23 +2,34 @@
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { create_child_block } from './shared/utils.js';
/**
* @param {AST.DebugTag} node
* @param {ComponentContext} context
*/
export function DebugTag(node, context) {
const blockers = node.identifiers
.map((identifier) => context.state.scope.get(identifier.name)?.blocker)
.filter((blocker) => blocker != null);
context.state.template.push(
b.stmt(
b.call(
'console.log',
b.object(
node.identifiers.map((identifier) =>
b.prop('init', identifier, /** @type {Expression} */ (context.visit(identifier)))
...create_child_block(
[
b.stmt(
b.call(
'console.log',
b.object(
node.identifiers.map((identifier) =>
b.prop('init', identifier, /** @type {Expression} */ (context.visit(identifier)))
)
)
)
)
)
),
b.debugger
),
b.debugger
],
b.array(blockers),
false
)
);
}

@ -12,7 +12,7 @@ import {
import * as b from '#compiler/builders';
import { sanitize_template_string } from '../../../../../utils/sanitize_template_string.js';
import { regex_whitespaces_strict } from '../../../../patterns.js';
import { has_await_expression } from '../../../../../utils/ast.js';
import { has_await_expression, save } from '../../../../../utils/ast.js';
import { ExpressionMetadata } from '../../../../nodes.js';
/** Opens an if/each block, so that we can remove nodes in the case of a mismatch */
@ -360,7 +360,7 @@ export class PromiseOptimiser {
return b.const(
b.array_pattern(this.expressions.map((_, i) => b.id(`$$${i}`))),
b.await(b.call('Promise.all', promises))
save(b.call('Promise.all', promises))
);
}

@ -48,7 +48,8 @@ export const EFFECT_OFFSCREEN = 1 << 25;
/**
* 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).
* 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;

@ -20,6 +20,8 @@ export function inspect(get_value, inspector, show_stack = false) {
// in an error (an `$inspect(object.property)` will run before the
// `{#if object}...{/if}` that contains it)
eager_effect(() => {
error = UNINITIALIZED;
try {
var value = get_value();
} catch (e) {

@ -1,5 +1,5 @@
/** @import { Blocker, TemplateNode, Value } from '#client' */
import { flatten, increment_pending } from '../../reactivity/async.js';
import { flatten } from '../../reactivity/async.js';
import { get } from '../../runtime.js';
import {
hydrate_next,
@ -42,36 +42,26 @@ export function async(node, blockers = [], expressions = [], fn) {
return;
}
const decrement_pending = increment_pending();
if (was_hydrating) {
var previous_hydrate_node = hydrate_node;
set_hydrate_node(end);
}
flatten(
blockers,
[],
expressions,
(values) => {
if (was_hydrating) {
set_hydrating(true);
set_hydrate_node(previous_hydrate_node);
}
try {
// get values eagerly to avoid creating blocks if they reject
for (const d of values) get(d);
flatten(blockers, [], expressions, (values) => {
if (was_hydrating) {
set_hydrating(true);
set_hydrate_node(previous_hydrate_node);
}
fn(node, ...values);
} finally {
if (was_hydrating) {
set_hydrating(false);
}
try {
// get values eagerly to avoid creating blocks if they reject
for (const d of values) get(d);
decrement_pending();
fn(node, ...values);
} finally {
if (was_hydrating) {
set_hydrating(false);
}
},
() => decrement_pending()
);
}
});
}

@ -584,7 +584,7 @@ function get_setters(element) {
var element_proto = Element.prototype;
// Stop at Element, from there on there's only unnecessary setters we're not interested in
// Do not use contructor.name here as that's unreliable in some browser environments
// Do not use constructor.name here as that's unreliable in some browser environments
while (element_proto !== proto) {
descriptors = get_descriptors(proto);

@ -40,7 +40,7 @@ export function bind_this(element_or_component = {}, update, get_value, get_part
parts = get_parts?.() || [];
untrack(() => {
if (element_or_component !== get_value(...parts)) {
if (!is_bound_this(get_value(...parts), element_or_component)) {
update(element_or_component, ...parts);
// If this is an effect rerun (cause: each block context changes), then nullify the binding at
// the previous position if it isn't already taken over by a different effect.

@ -115,10 +115,17 @@ export function animation(element, get_fn, get_params) {
) {
const options = get_fn()(this.element, { from, to }, get_params?.());
animation = animate(this.element, options, undefined, 1, () => {
animation?.abort();
animation = undefined;
});
animation = animate(
this.element,
options,
undefined,
1,
() => {},
() => {
animation?.abort();
animation = undefined;
}
);
}
},
fix() {
@ -239,15 +246,24 @@ export function transition(flags, element, get_fn, get_params) {
intro?.abort();
}
intro = animate(element, get_options(), outro, 1, () => {
dispatch_event(element, 'introend');
// Ensure we cancel the animation to prevent leaking
intro?.abort();
intro = current_options = undefined;
element.style.overflow = overflow;
});
intro = animate(
element,
get_options(),
outro,
1,
() => {
dispatch_event(element, 'introstart');
},
() => {
dispatch_event(element, 'introend');
// Ensure we cancel the animation to prevent leaking
intro?.abort();
intro = current_options = undefined;
element.style.overflow = overflow;
}
);
},
out(fn) {
if (!is_outro) {
@ -258,10 +274,19 @@ export function transition(flags, element, get_fn, get_params) {
element.inert = true;
outro = animate(element, get_options(), intro, 0, () => {
dispatch_event(element, 'outroend');
fn?.();
});
outro = animate(
element,
get_options(),
intro,
0,
() => {
dispatch_event(element, 'outrostart');
},
() => {
dispatch_event(element, 'outroend');
fn?.();
}
);
},
stop: () => {
intro?.abort();
@ -306,10 +331,11 @@ export function transition(flags, element, get_fn, get_params) {
* @param {AnimationConfig | ((opts: { direction: 'in' | 'out' }) => AnimationConfig)} options
* @param {Animation | undefined} counterpart The corresponding intro/outro to this outro/intro
* @param {number} t2 The target `t` value `1` for intro, `0` for outro
* @param {(() => void)} on_begin Called just before beginning the animation
* @param {(() => void)} on_finish Called after successfully completing the animation
* @returns {Animation}
*/
function animate(element, options, counterpart, t2, on_finish) {
function animate(element, options, counterpart, t2, on_begin, on_finish) {
var is_intro = t2 === 1;
if (is_function(options)) {
@ -323,7 +349,7 @@ function animate(element, options, counterpart, t2, on_finish) {
queue_micro_task(() => {
if (aborted) return;
var o = options({ direction: is_intro ? 'in' : 'out' });
a = animate(element, o, counterpart, t2, on_finish);
a = animate(element, o, counterpart, t2, on_begin, on_finish);
});
// ...but we want to do so without using `async`/`await` everywhere, so
@ -342,7 +368,7 @@ function animate(element, options, counterpart, t2, on_finish) {
counterpart?.deactivate();
if (!options?.duration && !options?.delay) {
dispatch_event(element, is_intro ? 'introstart' : 'outrostart');
on_begin();
on_finish();
return {
@ -382,7 +408,7 @@ function animate(element, options, counterpart, t2, on_finish) {
// remove dummy animation from the stack to prevent conflict with main animation
animation.cancel();
dispatch_event(element, is_intro ? 'introstart' : 'outrostart');
on_begin();
// for bidirectional transitions, we start from the current position,
// rather than doing a full intro/outro

@ -216,22 +216,35 @@ export async function* for_await_track_reactivity_loss(iterable) {
throw new TypeError('value is not async iterable');
}
/** Whether the completion of the iterator was "normal", meaning it wasn't ended via `break` or a similar method */
let normal_completion = false;
// eslint-disable-next-line no-useless-assignment
let invoke_return = true;
try {
while (true) {
const { done, value } = (await track_reactivity_loss(iterator.next()))();
if (done) {
normal_completion = true;
invoke_return = false;
break;
}
var prev = reactivity_loss_tracker;
yield value;
try {
yield value;
} catch (e) {
set_reactivity_loss_tracker(prev);
// If the yield throws, we need to call `return` but not return its value, instead rethrow
if (iterator.return !== undefined) {
(await track_reactivity_loss(iterator.return()))();
}
throw e;
}
set_reactivity_loss_tracker(prev);
}
} catch (error) {
invoke_return = false;
throw error;
} finally {
// If the iterator had an abrupt completion and `return` is defined on the iterator, call it and return the value
if (!normal_completion && iterator.return !== undefined) {
// If the iterator had an abrupt completion (break) and `return` is defined on the iterator, call it and return the value
if (invoke_return && iterator.return !== undefined) {
// eslint-disable-next-line no-unsafe-finally
return /** @type {TReturn} */ ((await track_reactivity_loss(iterator.return()))().value);
}

@ -92,6 +92,9 @@ let uid = 1;
export class Batch {
id = uid++;
/** True as soon as `#process()` was called */
#started = false;
/**
* The current values of any signals that are updated in this batch.
* Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)
@ -255,6 +258,8 @@ export class Batch {
}
#process() {
this.#started = true;
if (flush_count++ > 1000) {
batches.delete(this);
infinite_loop_guard();
@ -344,6 +349,14 @@ export class Batch {
var next_batch = /** @type {Batch | null} */ (/** @type {unknown} */ (current_batch));
// Order matters here - we need to commit and THEN continue flushing new batches, not the other way around,
// else we could start flushing a new batch and then, if it has pending work, rebase it right afterwards, which is wrong.
// In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode
// TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed
if (async_mode_flag && !batches.has(this)) {
this.#commit();
}
// 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
// once more in that case - most of the time this will just clean up dirty branches.
@ -363,12 +376,6 @@ export class Batch {
next_batch.#process();
}
// In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode
// TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed
if (async_mode_flag && !batches.has(this)) {
this.#commit();
}
}
/**
@ -535,6 +542,8 @@ export class Batch {
sources.push(source);
}
if (!batch.#started) continue;
// Re-run async/block effects that depend on distinct values changed in both batches
var others = [...batch.current.keys()].filter((s) => !this.current.has(s));
@ -575,19 +584,23 @@ export class Batch {
checked = new Map();
var current_unequal = [...batch.current.keys()].filter((c) =>
this.current.has(c) ? /** @type {[any, boolean]} */ (this.current.get(c))[0] !== c : true
this.current.has(c)
? /** @type {[any, boolean]} */ (this.current.get(c))[0] !== c.v
: true
);
for (const effect of this.#new_effects) {
if (
(effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 &&
depends_on(effect, current_unequal, checked)
) {
if ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) {
set_signal_status(effect, DIRTY);
batch.schedule(effect);
} else {
batch.#dirty_effects.add(effect);
if (current_unequal.length > 0) {
for (const effect of this.#new_effects) {
if (
(effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 &&
depends_on(effect, current_unequal, checked)
) {
if ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) {
set_signal_status(effect, DIRTY);
batch.schedule(effect);
} else {
batch.#dirty_effects.add(effect);
}
}
}
}
@ -716,7 +729,7 @@ export class Batch {
if (!is_flushing_sync) {
queue_micro_task(() => {
if (current_batch !== batch) {
if (batch.#started) {
// a flushSync happened in the meantime
return;
}

@ -43,7 +43,7 @@ import { get_error } from '../../shared/dev.js';
import { async_mode_flag, tracing_mode_flag } from '../../flags/index.js';
import { component_context } from '../context.js';
import { UNINITIALIZED } from '../../../constants.js';
import { batch_values, current_batch } from './batch.js';
import { batch_values, current_batch, previous_batch } from './batch.js';
import { increment_pending, unset_context } from './async.js';
import { deferred, includes, noop } from '../../shared/utils.js';
import { set_signal_status, update_derived_status } from './status.js';
@ -232,7 +232,7 @@ export function async_derived(fn, label, location) {
for (const [b, d] of deferreds) {
deferreds.delete(b);
if (b === batch) break;
d.reject(STALE_REACTION);
d.resolve(value);
}
if (DEV && location !== undefined) {
@ -399,7 +399,14 @@ export function update_derived(derived) {
// change, `derived.equals` may incorrectly return `true`
if (!current_batch?.is_fork || derived.deps === null) {
if (current_batch !== null) {
// We also write to previous_batch because if it exists, it is a sign that we're
// currently in the process of flushing effects. These updates to deriveds may belong
// to the previous batch, not the new one (which can already exist if an earlier
// effect wrote to a source). This can cause bugs when running batch.#commit() later,
// but not adding it to current_batch can, too, so we add it to both.
// See https://github.com/sveltejs/svelte/pull/18117 for more details.
current_batch.capture(derived, value, true);
previous_batch?.capture(derived, value, true);
} else {
derived.v = value;
}

@ -43,7 +43,7 @@ import { define_property } from '../../shared/utils.js';
import { get_next_sibling } from '../dom/operations.js';
import { component_context, dev_current_component_function, dev_stack } from '../context.js';
import { Batch, collected_effects, current_batch } from './batch.js';
import { flatten, increment_pending } from './async.js';
import { flatten } from './async.js';
import { without_reactive_context } from '../dom/elements/bindings/shared.js';
import { set_signal_status } from './status.js';
@ -396,22 +396,9 @@ export function template_effect(fn, sync = [], async = [], blockers = []) {
* @param {Blocker[]} blockers
*/
export function deferred_template_effect(fn, sync = [], async = [], blockers = []) {
if (async.length > 0 || blockers.length > 0) {
var decrement_pending = increment_pending();
}
flatten(
blockers,
sync,
async,
(values) => {
create_effect(EFFECT, () => fn(...values.map(get)));
decrement_pending?.();
},
() => {
decrement_pending?.();
}
);
flatten(blockers, sync, async, (values) => {
create_effect(EFFECT, () => fn(...values.map(get)));
});
}
/**

@ -1,4 +1,4 @@
/** @import { Effect, Source } from './types.js' */
/** @import { Derived, Effect, Source } from './types.js' */
import { DEV } from 'esm-env';
import {
PROPS_IS_BINDABLE,
@ -283,8 +283,14 @@ export function prop(props, key, flags, fallback) {
var fallback_value = /** @type {V} */ (fallback);
var fallback_dirty = true;
var fallback_signal = /** @type {Derived<V> | undefined} */ (undefined);
var get_fallback = () => {
if (lazy && runes) {
fallback_signal ??= derived(/** @type {() => V} */ (fallback));
return get(fallback_signal);
}
if (fallback_dirty) {
fallback_dirty = false;

@ -27,7 +27,8 @@ import {
ROOT_EFFECT,
ASYNC,
WAS_MARKED,
CONNECTED
CONNECTED,
REACTION_IS_UPDATING
} from '#client/constants';
import * as e from '../errors.js';
import { legacy_mode_flag, tracing_mode_flag } from '../../flags/index.js';
@ -46,7 +47,7 @@ import { proxy } from '../proxy.js';
import { execute_derived } from './deriveds.js';
import { set_signal_status, update_derived_status } from './status.js';
/** @type {Set<any>} */
/** @type {Set<Effect>} */
export let eager_effects = new Set();
/** @type {Map<Source, any>} */
@ -271,7 +272,18 @@ export function flush_eager_effects() {
set_signal_status(effect, MAYBE_DIRTY);
}
if (is_dirty(effect)) {
let dirty;
try {
dirty = is_dirty(effect);
} catch {
// Dirty-checking can evaluate derived dependencies and throw in cases where
// parent effects are about to destroy this eager effect. Run the effect so
// its own error handling can deal with transient failures.
dirty = true;
}
if (dirty) {
update_effect(effect);
}
}
@ -337,12 +349,6 @@ function mark_reactions(signal, status, updated_during_traversal) {
// In legacy mode, skip the current effect to prevent infinite loops
if (!runes && reaction === active_effect) continue;
// Inspect effects need to run immediately, so that the stack trace makes sense
if (DEV && (flags & EAGER_EFFECT) !== 0) {
eager_effects.add(reaction);
continue;
}
var not_dirty = (flags & DIRTY) === 0;
// don't set a DIRTY reaction to MAYBE_DIRTY
@ -350,14 +356,22 @@ function mark_reactions(signal, status, updated_during_traversal) {
set_signal_status(reaction, status);
}
if ((flags & DERIVED) !== 0) {
if ((flags & EAGER_EFFECT) !== 0) {
// Eager effects need to run immediately:
// - for $inspect so that the stack trace makes sense
// - for $state.eager because they might be without an effect parent
eager_effects.add(/** @type {Effect} */ (reaction));
} else if ((flags & DERIVED) !== 0) {
var derived = /** @type {Derived} */ (reaction);
batch_values?.delete(derived);
if ((flags & WAS_MARKED) === 0) {
// Only connected deriveds can be reliably unmarked right away
if (flags & CONNECTED) {
// 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;
}

@ -715,7 +715,12 @@ export class Renderer {
const { context, failed, transformError } = item.#boundary;
set_ssr_context(context);
let transformed = await transformError(error);
let promise = transformError(error);
set_ssr_context(null);
let transformed = await promise;
set_ssr_context(context);
// Render the failed snippet instead of the partial children content
const failed_renderer = new Renderer(item.global, item);

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

@ -0,0 +1,4 @@
p.svelte-xyz {
padding: 0 /* it's a comment */ 1em;
}

@ -0,0 +1,7 @@
<p>red</p>
<style>
p {
padding: 0 /* it's a comment */ 1em;
}
</style>

@ -201,7 +201,7 @@ export const async_mode = process.env.SVELTE_NO_ASYNC !== 'true';
* @param {any[]} logs
*/
export function normalise_inspect_logs(logs) {
/** @type {string[]} */
/** @type {any[]} */
const normalised = [];
for (const log of logs) {

@ -60,6 +60,8 @@ export interface RuntimeTest<Props extends Record<string, any> = Record<string,
id_prefix?: string;
before_test?: () => void;
after_test?: () => void;
/** If true, flushSync() will not be called before invoking test() */
skip_initial_flushSync?: boolean;
test?: (args: {
variant: 'dom' | 'hydrate';
assert: Assert;
@ -505,7 +507,7 @@ async function run_test_variant(
try {
if (config.test) {
flushSync();
if (!config.skip_initial_flushSync) flushSync();
if (variant === 'hydrate' && cwd.includes('async-')) {
// wait for pending boundaries to render
@ -543,7 +545,7 @@ async function run_test_variant(
}
} finally {
if (runes) {
unmount(instance);
await unmount(instance);
} else {
instance.$destroy();
}

@ -0,0 +1,23 @@
import { tick } from 'svelte';
import { test } from '../../test';
export default test({
async test({ assert, target }) {
await tick();
const [increment, shift] = target.querySelectorAll('button');
increment.click();
await tick();
assert.htmlEqual(
target.innerHTML,
`<button>clicks: 0 - 0 - 0</button> <button>shift</button> <p>true - true</p>`
);
shift.click();
await tick();
assert.htmlEqual(
target.innerHTML,
`<button>clicks: 1 - 1 - 1</button> <button>shift</button> <p>false - false</p>`
);
}
});

@ -0,0 +1,22 @@
<script>
let count = $state(0);
const delayedCount = $derived(await push(count));
const derivedCount = $derived(count);
let resolvers = [];
function push(value) {
if (!value) return value;
const { promise, resolve } = Promise.withResolvers();
resolvers.push(() => resolve(value));
return promise;
}
</script>
<button onclick={() => count += 1}>
clicks: {count} - {delayedCount} - {derivedCount}
</button>
<button onclick={() => resolvers.shift()?.()}>shift</button>
<p>{$state.eager(count) !== count} - {$state.eager(derivedCount) !== derivedCount}</p>

@ -0,0 +1,31 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
test({ assert, raf, target, logs }) {
let divs = target.querySelectorAll('div');
divs.forEach((div) => {
// @ts-expect-error
div.getBoundingClientRect = function () {
// @ts-expect-error
const index = [...this.parentNode.children].indexOf(this);
const top = index * 30;
return {
left: 0,
right: 100,
top,
bottom: top + 20
};
};
});
const [btn] = target.querySelectorAll('button');
flushSync(() => btn.click());
raf.tick(1);
assert.deepEqual(logs, []);
raf.tick(100);
assert.deepEqual(logs, []);
}
});

@ -0,0 +1,19 @@
<script>
import { flip } from "svelte/animate";
let numbers = $state([0,1]);
</script>
<button onclick={() => numbers.reverse()}>reverse</button>
{#each numbers as num (num)}
<div
onintrostart={() => console.log("intro start")}
onoutrostart={() => console.log("outro start")}
onintroend={() => console.log("intro end")}
onoutroend={() => console.log("outro end")}
animate:flip={{ duration: 100 }}
>
{num}
</div>
{/each}

@ -0,0 +1,19 @@
import { tick } from 'svelte';
import { test } from '../../test';
// Tests that batch.#commit() does not null out a potentially new current_batch
export default test({
skip_initial_flushSync: true, // test that the initial batch is flushed without an explicit flushSync() call
async test({ assert, target }) {
await tick();
const [button] = target.querySelectorAll('button');
const [updates] = target.querySelectorAll('p');
assert.htmlEqual(updates.innerHTML, 'false');
button.click();
await tick();
assert.htmlEqual(updates.innerHTML, 'true');
}
});

@ -0,0 +1,30 @@
<script>
let count = $state(-1);
let payload = $state(false);
let updated = $state(false);
$effect(() => {
if (payload) {
updated = true;
}
});
function update() {
count = 0;
queueMicrotask(() => {
payload = true;
});
}
</script>
<button onclick={update}>update</button>
<p>{updated}</p>
<svelte:boundary>
{await new Promise(() => {})}
{#snippet pending()}
<p>pending</p>
{/snippet}
</svelte:boundary>

@ -0,0 +1,18 @@
import { tick } from 'svelte';
import { test } from '../../test';
export default test({
compileOptions: {
dev: true
},
mode: ['client', 'async-server'],
async test({ assert, logs }) {
await tick();
assert.deepEqual(logs, [{ data: 'works' }]);
},
test_ssr({ assert, logs }) {
assert.deepEqual(logs, [{ data: 'works' }]);
}
});

@ -0,0 +1,4 @@
<svelte:boundary>
{@const data = await Promise.resolve("works")}
{@debug data}
</svelte:boundary>

@ -0,0 +1,27 @@
import { tick } from 'svelte';
import { test } from '../../test';
// Tests that a newly created batch during an effect flush isn't rebased right away by the previous batch.#commit(),
// rescheduling an effect on the new batch that shouldn't run.
export default test({
async test({ assert, target, logs }) {
await tick();
const [increment, resolve] = target.querySelectorAll('button');
increment.click();
await tick();
assert.deepEqual(logs, []);
// This resolve
// - shouldn't result in the derived execution capturing the new derived value on the new batch, but on the previous batch which is currently flushing
// - shouldn't result in #commit() rebasing the new batch
resolve.click();
await tick();
assert.deepEqual(logs, [2]);
// As a result, this resolve shouldn't result in another execution of the effect depending on the derived
resolve.click();
await tick();
assert.deepEqual(logs, [2]);
}
});

@ -0,0 +1,32 @@
<script>
let count = $state(0);
let double = $derived(count * 2);
let count_mirror = $state(0);
const queued = [];
function delay(v) {
if (!v) return v;
return new Promise(resolve => {
queued.push(() => resolve(v));
});
}
</script>
<button onclick={() => count++}>count {await delay(count)} | count_mirror {await delay(count_mirror)}</button>
<button onclick={() => queued.shift()?.()}>resolve</button>
{#if count}
<!-- inside if block so effects are newly created and therefore added to batch.#new_effects -->
<!-- first $effect creates new batch ... -->
{(() => {
$effect(() => {
count_mirror = count;
})
})()}
<!-- ... which second $effect shouldn't write to because the derived execution belongs to the previous batch -->
{(() => {
$effect(() => {
console.log(double);
})
})()}
{/if}

@ -0,0 +1,25 @@
import { tick } from 'svelte';
import { test } from '../../test';
// Tests that a newly created batch during an effect flush isn't rebased right away by the previous batch.#commit(),
// rescheduling an effect on the new batch that shouldn't run.
export default test({
async test({ assert, target, logs }) {
await tick();
const [increment, resolve] = target.querySelectorAll('button');
assert.deepEqual(logs, ['delay 0']);
increment.click();
await tick();
assert.deepEqual(logs, ['delay 0', 'delay 2']);
// This resolve should trigger the async effect only once
resolve.click();
await tick();
assert.deepEqual(logs, ['delay 0', 'delay 2', 'effect run', 'delay 4']);
resolve.click();
await tick();
assert.deepEqual(logs, ['delay 0', 'delay 2', 'effect run', 'delay 4']);
}
});

@ -0,0 +1,29 @@
<script>
import { untrack } from "svelte";
let a = $state(0);
let b = $state(0);
let c = $state(0);
const queued = [];
function delay(v) {
console.log('delay ' + v);
if (!v) return v;
return new Promise(resolve => {
queued.push(() => resolve(v));
});
}
$effect(() => {
if (b + c === 0 || b + c > 2) return;
console.log('effect run')
untrack(() => {
b++;
c++;
})
})
</script>
<button onclick={() => { a++; b++; }}>increment</button>
<button onclick={() => queued.shift()?.()}>resolve</button>
{await delay(a + b + c)}

@ -0,0 +1,31 @@
import { tick } from 'svelte';
import { test } from '../../test';
// Tests that a newly created batch during an effect flush isn't rebased right away by the previous batch.#commit(),
// rescheduling an effect on the new batch that shouldn't run.
export default test({
async test({ assert, target, logs }) {
await tick();
const [increment, shift, pop] = target.querySelectorAll('button');
increment.click();
await tick();
assert.deepEqual(logs, []);
// Resolve the blocking await which shouldn't result in the derived execution capturing
// the new derived value on the new batch, but on the previous batch which is currently flushing
pop.click();
await tick();
assert.deepEqual(logs, [2]);
// Resolve the non-blocking await which shouldn't result in #commit() rebasing the new batch
shift.click();
await tick();
assert.deepEqual(logs, [2]);
// Resolve the new batch's await
shift.click();
await tick();
assert.deepEqual(logs, [2]);
}
});

@ -0,0 +1,37 @@
<script>
let count = $state(0);
let double = $derived(count * 2);
let count_mirror = $state(0);
const queued = [];
function delay(v) {
if (!v) return v;
return new Promise(resolve => {
queued.push(() => resolve(v));
});
}
</script>
<button onclick={() => count++}>count {await delay(count)} | count_mirror {await delay(count_mirror)}</button>
<button onclick={() => queued.shift()?.()}>shift</button>
<button onclick={() => queued.pop()?.()}>pop</button>
{#if count}
<svelte:boundary>
{await delay(count)}
{#snippet pending()}loading{/snippet}
</svelte:boundary>
<!-- inside if block so effects are newly created and therefore added to batch.#new_effects -->
<!-- first $effect creates new batch ... -->
{(() => {
$effect(() => {
count_mirror = count;
})
})()}
<!-- ... which second $effect shouldn't write to because the derived execution belongs to the previous batch -->
{(() => {
$effect(() => {
console.log(double);
})
})()}
{/if}

@ -0,0 +1,58 @@
import { tick } from 'svelte';
import { test } from '../../test';
// Tests that a newly created batch during an effect flush isn't rebased right away by the previous batch.#commit(),
// rescheduling an effect on the new batch that shouldn't run.
export default test({
async test({ assert, target, logs }) {
await tick();
const [increment, unrelated, resolve] = target.querySelectorAll('button');
increment.click();
await tick();
assert.deepEqual(logs, []);
// This resolve
// - shouldn't result in the derived execution capturing the new derived value on the new batch, but on the previous batch which is currently flushing
// - shouldn't result in #commit() rebasing the new batch
resolve.click();
await tick();
assert.deepEqual(logs, [2]);
assert.htmlEqual(
target.innerHTML,
`
<button>count 1 | count_mirror 0 | count_mirror_d 0 | unrelated 0</button>
<button>unrelated++</button>
<button>resolve</button>
`
);
// This resolve
// - shouldn't result in the derived execution capturing the new derived value on the new batch, but on the previous batch which is currently flushing
// - shouldn't result in #commit() rebasing the new batch
unrelated.click();
await tick();
assert.deepEqual(logs, [2]);
assert.htmlEqual(
target.innerHTML,
`
<button>count 1 | count_mirror 0 | count_mirror_d 0 | unrelated 1</button>
<button>unrelated++</button>
<button>resolve</button>
`
);
// As a result, this resolve shouldn't result in another execution of the effect depending on the derived
resolve.click();
await tick();
assert.deepEqual(logs, [2]);
assert.htmlEqual(
target.innerHTML,
`
<button>count 1 | count_mirror 1 | count_mirror_d 2 | unrelated 1</button>
<button>unrelated++</button>
<button>resolve</button>
`
);
}
});

@ -0,0 +1,38 @@
<script>
import { untrack } from "svelte";
let count = $state(0);
let double = $derived(count * 2);
let count_mirror = $state(0);
let unrelated = $state(0);
let count_mirror_d = $derived(count_mirror * 2);
const queued = [];
function delay(v) {
if (!v) return v;
return new Promise(resolve => {
queued.push(() => resolve(v));
});
}
</script>
<button onclick={() => count++}>count {await delay(count)} | count_mirror {await delay(count_mirror)} | count_mirror_d {count_mirror_d} | unrelated {unrelated}</button>
<button onclick={() => unrelated++}>unrelated++</button>
<button onclick={() => queued.shift()?.()}>resolve</button>
{#if count}
<!-- inside if block so effects are newly created and therefore added to batch.#new_effects -->
<!-- first $effect creates new batch ... -->
{(() => {
$effect(() => {
count_mirror = count;
untrack(() => count_mirror_d); // execute derived; should associate value with the right batch
})
})()}
<!-- ... which second $effect shouldn't write to because the derived execution belongs to the previous batch -->
{(() => {
$effect(() => {
console.log(double);
})
})()}
{/if}

@ -0,0 +1,24 @@
import { tick } from 'svelte';
import { test } from '../../test';
import { normalise_trace_logs } from '../../../helpers.js';
export default test({
compileOptions: {
dev: true
},
html: '<p>pending</p>',
async test({ assert, target, warnings }) {
await tick();
assert.htmlEqual(
target.innerHTML,
'<h1>number -> number -> number -> return -> body failed -> ended</h1>'
);
assert.deepEqual(normalise_trace_logs(warnings), [
{
log: 'Detected reactivity loss when reading `values[1]`. This happens when state is read in an async function after an earlier `await`'
}
]);
}
});

@ -0,0 +1,45 @@
<script>
let values = $state([0, 1, 2]);
async function get_result() {
const logs = [];
const iterator = {
index: 0,
async next() {
if (this.index > 2) { done: true }
return { done: false, value: values[this.index++] };
},
async return() {
logs.push('return');
},
[Symbol.asyncIterator]() {
return this;
}
};
try {
for await (const value of iterator) {
logs.push('number');
// Read reactive state after async iterator await.
if (values.length === 3 && value === 2) {
throw new Error('body failed');
}
}
logs.push('done');
} catch (error) {
logs.push(error.message);
}
logs.push('ended');
return logs.join(' -> ');
}
</script>
<svelte:boundary>
<h1>{await get_result()}</h1>
{#snippet pending()}
<p>pending</p>
{/snippet}
</svelte:boundary>

@ -0,0 +1,21 @@
import { tick } from 'svelte';
import { test } from '../../test';
import { normalise_trace_logs } from '../../../helpers.js';
export default test({
compileOptions: {
dev: true
},
html: '<p>pending</p>',
async test({ assert, target, warnings }) {
await tick();
assert.htmlEqual(target.innerHTML, '<h1>number -> number -> next failed -> ended</h1>');
assert.deepEqual(normalise_trace_logs(warnings), [
{
log: 'Detected reactivity loss when reading `values[1]`. This happens when state is read in an async function after an earlier `await`'
}
]);
}
});

@ -0,0 +1,43 @@
<script>
let values = $state([0, 1, 2]);
async function get_result() {
const logs = [];
const iterator = {
index: 0,
async next() {
if (this.index > 1) throw new Error('next failed');
return { done: false, value: values[this.index++] };
},
async return() {
logs.push('return');
},
[Symbol.asyncIterator]() {
return this;
}
};
try {
for await (const value of iterator) {
logs.push('number');
// Read reactive state after async iterator await.
values.length === value;
}
logs.push('done');
} catch (error) {
logs.push(error.message);
}
logs.push('ended');
return logs.join(' -> ');
}
</script>
<svelte:boundary>
<h1>{await get_result()}</h1>
{#snippet pending()}
<p>pending</p>
{/snippet}
</svelte:boundary>

@ -0,0 +1,29 @@
import { tick } from 'svelte';
import { test } from '../../test';
export default test({
async test({ assert, target }) {
await tick();
const [increment, pop] = target.querySelectorAll('button');
increment.click();
await tick();
increment.click();
await tick();
assert.htmlEqual(
target.innerHTML,
`<button>increment</button><button>pop</button><p>0 0 0</p>`
);
pop.click();
await tick();
assert.htmlEqual(
target.innerHTML,
`<button>increment</button><button>pop</button><p>2 2 1</p>`
);
}
});

@ -0,0 +1,22 @@
<script>
let count = $state(0);
let other = $state(0);
const queue = [];
function push(v) {
if (v === 0) return v;
return new Promise((fulfil) => {
queue.push(() => fulfil(v));
});
}
</script>
<button onclick={() => {
if (count === 0) other++;
count++;
}}>increment</button>
<button onclick={() => queue.pop()?.()}>pop</button>
<p>{await push(count)} {count} {other}</p>

@ -0,0 +1,15 @@
import { tick } from 'svelte';
import { test } from '../../test';
// Ensure that microtask timing doesn't influence whether or not a scheduled batch is flushed.
// Timing can be such that the current_batch is reset before the scheduled flush runs, which
// would cause the flush to skip without the fix.
export default test({
async test({ assert, target }) {
const [btn] = target.querySelectorAll('button');
btn.click();
await tick();
assert.htmlEqual(target.innerHTML, '1 1');
}
});

@ -0,0 +1,18 @@
<script>
let a = $state(0);
let b = $state(0);
</script>
{#if a}
{@const toShow = await a}
{toShow}
{b}
{:else}
<button
onclick={async () => {
a = 1;
await 1;
await 1; // two microtasks needed to get timing right to reproduce the bug
b = 1;
}}>click</button>
{/if}

@ -0,0 +1,5 @@
<script>
const props = $props();
// svelte-ignore state_referenced_locally
export const name = props.name;
</script>

@ -0,0 +1,22 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
async test({ assert, target, logs }) {
const btn = target.querySelector('button');
flushSync(() => {
btn?.click();
});
flushSync(() => {
btn?.click();
});
assert.deepEqual(logs, [
{},
{ 0: { name: 'Row 0' } },
{ 0: { name: 'Row 0' }, 1: { name: 'Row 1' } }
]);
}
});

@ -0,0 +1,16 @@
<script>
import Row from "./Component.svelte";
const nums = $state([]);
const rows = $derived(nums.map(n => ({id: n, name: `Row ${n}` })));
const refs = $state({});
$effect(() => {
console.log({...refs});
})
</script>
<button onclick={() => nums.push(nums.length)}>Add</button>
{#each rows as row (row.id)}
<Row name={row.name} bind:this={refs[row.id]} />
{/each}

@ -0,0 +1,7 @@
<script>
import { store } from "./store.svelte.js";
// This write marks the derived in main.svelte before it has reactions added to it.
// This test checks that this does not cause the WAS_MARKED logic to incorrectly skip marking the derived subsequently.
store.set("child-init-write", Math.random());
</script>

@ -0,0 +1,29 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
async test({ assert, target }) {
const [show, hide] = target.querySelectorAll('button');
hide.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<button>show</button>
<button>hide</button>
`
);
show.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<button>show</button>
<button>hide</button>
<div>visible</div>
`
);
}
});

@ -0,0 +1,14 @@
<script>
import Child from "./Child.svelte";
import { store } from "./store.svelte.js";
const visible = $derived(store.get("visible"));
const visible2 = $derived(visible);
</script>
<button onclick={() => store.set("visible", true)}>show</button>
<button onclick={() => store.set("visible", false)}>hide</button>
{#if visible2}
<Child />
<div>visible</div>
{/if}

@ -0,0 +1,13 @@
class RawStore {
values = $state.raw({ visible: true });
get(key) {
return this.values[key];
}
set(key, value) {
this.values = { ...this.values, [key]: value };
}
}
export const store = new RawStore();

@ -0,0 +1,11 @@
<script>
let {things} = $props();
$inspect(things);
</script>
<ul>
{#each things as thing}
<li>thing {thing.id}</li>
{/each}
</ul>

@ -0,0 +1,21 @@
import { normalise_inspect_logs } from '../../../helpers';
import { test } from '../../test';
import { flushSync } from 'svelte';
export default test({
compileOptions: {
dev: true
},
async test({ assert, target, errors, logs }) {
const button = target.querySelector('button');
flushSync(() => {
button?.click();
});
assert.htmlEqual(target.innerHTML, '<button>clear</button>');
assert.equal(errors.length, 0);
assert.deepEqual(normalise_inspect_logs(logs), [[{ id: 1 }, { id: 2 }]]);
}
});

@ -0,0 +1,15 @@
<script>
import List from "./List.svelte"
let data = $state({things: [{id:1}, {id:2}]})
function reloadData() {
data = null
}
</script>
{#if data}
<List things={data.things.map((t) => t)} />
{/if}
<button onclick={() => reloadData()}>clear</button>

@ -1,5 +1,5 @@
<script>
let log = $state([]);
let log = [];
const fallback_value = 1;
const nested = {

@ -1,5 +1,5 @@
<script>
let log = $state([]);
let log = [];
const fallback_value = 1;
const nested = {

@ -0,0 +1,19 @@
import { flushSync, tick } from 'svelte';
import { test } from '../../test';
export default test({
accessors: false,
test({ assert, target }) {
const btn = target.querySelector('button');
btn?.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<p>greeting: Hola</p>
<button>Change Language</button>
`
);
}
});

@ -0,0 +1,10 @@
<script>
import Sub from './sub.svelte';
import { set_translation } from './translations.svelte.js';
</script>
<Sub />
<button onclick={() => set_translation('Hola')}>
Change Language
</button>

@ -0,0 +1,9 @@
<script>
import { get_translation } from './translations.svelte.js';
const {
p0 = get_translation()
} = $props();
</script>
<p>greeting: {p0}</p>

@ -0,0 +1,9 @@
let greeting = $state('Hello');
export function get_translation() {
return greeting;
}
export function set_translation(value) {
greeting = value;
}

@ -0,0 +1,8 @@
import { test } from '../../test';
export default test({
mode: ['async'],
compileOptions: {
dev: true
}
});

@ -0,0 +1 @@
<!--1410iyz--><!----><title>Async multiple attributes</title>

@ -0,0 +1,15 @@
<script>
const user = $derived(Promise.resolve({
name: 'test',
image: '',
}))
</script>
<svelte:head>
<title>Async multiple attributes</title>
</svelte:head>
<img
alt={(await user).name}
src={(await user).image}
/>

@ -3345,6 +3345,8 @@ declare namespace $state {
* </script>
* ```
*
* If `state` has a `toJSON` method, the snapshot will clone the value returned from `toJSON` instead of the original object.
*
* @see {@link https://svelte.dev/docs/svelte/$state#$state.snapshot Documentation}
*
* @param state The value to snapshot

@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { parseArgs } from 'node:util';
import { execSync } from 'node:child_process';
import readline from 'node:readline/promises';
import { chromium } from 'playwright';
const { values, positionals } = parseArgs({
@ -546,9 +547,9 @@ function convert_vite_project(repo_dir) {
/**
* Process a local or cloned directory
* @param {string} dir_path
* @returns {Array<{name: string, contents: string}>}
* @returns {Promise<Array<{name: string, contents: string}> | null>}
*/
function process_directory(dir_path) {
async function process_directory(dir_path) {
const all_files = get_all_files(dir_path);
const project_info = detect_project_type(all_files);
@ -558,7 +559,18 @@ function process_directory(dir_path) {
if (project_info.has_app_imports) {
console.error('Error: This SvelteKit project uses $app/* imports which cannot be converted.');
console.error('The playground does not support SvelteKit runtime features.');
process.exit(1);
const fallback_dir = path.resolve(base_dir, '..', '..', 'kit-sandbox-tmp');
const should_copy = await prompt_download_to_kit_sandbox_tmp(fallback_dir);
if (!should_copy) {
process.exit(1);
}
copy_project_to_directory(dir_path, fallback_dir);
console.log(`Project copied to ${fallback_dir}`);
return null;
}
// Convert based on project type
@ -571,6 +583,66 @@ function process_directory(dir_path) {
}
}
/**
* Ask whether to copy the project to playgrounds/kit-sandbox-tmp
* @param {string} fallback_dir
* @returns {Promise<boolean>}
*/
async function prompt_download_to_kit_sandbox_tmp(fallback_dir) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
return false;
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
try {
const answer = await rl.question(
`Would you like to copy this project into ${fallback_dir} instead? [y/N] `
);
return /^(y|yes)$/i.test(answer.trim());
} finally {
rl.close();
}
}
/**
* Copy a project directory while skipping generated and dependency folders
* @param {string} source_dir
* @param {string} target_dir
*/
function copy_project_to_directory(source_dir, target_dir) {
const skip_dirs = new Set(['node_modules', '.git', '.svelte-kit', 'build', 'dist']);
if (fs.existsSync(target_dir)) {
fs.rmSync(target_dir, { recursive: true, force: true });
}
/** @param {string} from_dir */
function copy_recursive(from_dir) {
const relative_dir = path.relative(source_dir, from_dir);
const to_dir = relative_dir ? path.join(target_dir, relative_dir) : target_dir;
fs.mkdirSync(to_dir, { recursive: true });
for (const entry of fs.readdirSync(from_dir, { withFileTypes: true })) {
if (entry.isDirectory() && skip_dirs.has(entry.name)) {
continue;
}
const source_path = path.join(from_dir, entry.name);
const target_path = path.join(to_dir, entry.name);
if (entry.isDirectory()) {
copy_recursive(source_path);
} else if (entry.isFile()) {
fs.copyFileSync(source_path, target_path);
}
}
}
copy_recursive(source_dir);
}
/**
* Reset a directory so it exists and is empty
* @param {string} dir_path
@ -602,7 +674,7 @@ let files;
// Check if it's a local directory first (before URL parsing)
if (is_local) {
console.log(`Processing local directory: ${url_arg}`);
files = process_directory(url_arg);
files = await process_directory(url_arg);
} else if (resolved_test_path) {
// Copy files from test
console.log(`Processing test ${url_arg}`);
@ -616,21 +688,21 @@ if (is_local) {
});
} else if (url && is_github_url(url)) {
// GitHub repository handling
await with_tmp_dir(base_dir, (tmp_dir) => {
await with_tmp_dir(base_dir, async (tmp_dir) => {
clone_github_repo(url, tmp_dir);
files = process_directory(tmp_dir);
files = await process_directory(tmp_dir);
});
} else if (url && is_stackblitz_github_url(url)) {
// StackBlitz GitHub project handling (redirect to GitHub clone)
await with_tmp_dir(base_dir, (tmp_dir) => {
await with_tmp_dir(base_dir, async (tmp_dir) => {
clone_stackblitz_github_project(url, tmp_dir);
files = process_directory(tmp_dir);
files = await process_directory(tmp_dir);
});
} else if (url && is_stackblitz_edit_url(url)) {
// StackBlitz edit URLs - use browser automation to download
await with_tmp_dir(base_dir, async (tmp_dir) => {
await download_stackblitz_project(url, tmp_dir);
files = process_directory(tmp_dir);
files = await process_directory(tmp_dir);
});
} else if (url && url.origin === 'https://svelte.dev' && url.pathname.startsWith('/playground/')) {
// Svelte playground URL handling (existing logic)
@ -680,6 +752,10 @@ if (is_local) {
process.exit(1);
}
if (files === null) {
process.exit(0);
}
// Output files
if (create_test_name) {
const test_parts = create_test_name.split('/').filter(Boolean);

Loading…
Cancel
Save