Skip to content

feat: async fragments #16542

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Aug 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/brave-baboons-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: allow `await` inside `@const` declarations
3 changes: 2 additions & 1 deletion packages/svelte/src/compiler/phases/1-parse/utils/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export function create_fragment(transparent = false) {
nodes: [],
metadata: {
transparent,
dynamic: false
dynamic: false,
has_await: false
}
};
}
5 changes: 5 additions & 0 deletions packages/svelte/src/compiler/phases/2-analyze/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { ExportNamedDeclaration } from './visitors/ExportNamedDeclaration.js';
import { ExportSpecifier } from './visitors/ExportSpecifier.js';
import { ExpressionStatement } from './visitors/ExpressionStatement.js';
import { ExpressionTag } from './visitors/ExpressionTag.js';
import { Fragment } from './visitors/Fragment.js';
import { FunctionDeclaration } from './visitors/FunctionDeclaration.js';
import { FunctionExpression } from './visitors/FunctionExpression.js';
import { HtmlTag } from './visitors/HtmlTag.js';
Expand Down Expand Up @@ -156,6 +157,7 @@ const visitors = {
ExportSpecifier,
ExpressionStatement,
ExpressionTag,
Fragment,
FunctionDeclaration,
FunctionExpression,
HtmlTag,
Expand Down Expand Up @@ -300,6 +302,7 @@ export function analyze_module(source, options) {
function_depth: 0,
has_props_rune: false,
options: /** @type {ValidatedCompileOptions} */ (options),
fragment: null,
parent_element: null,
reactive_statement: null
},
Expand Down Expand Up @@ -687,6 +690,7 @@ export function analyze_component(root, source, options) {
analysis,
options,
ast_type: ast === instance.ast ? 'instance' : ast === template.ast ? 'template' : 'module',
fragment: ast === template.ast ? ast : null,
parent_element: null,
has_props_rune: false,
component_slots: new Set(),
Expand Down Expand Up @@ -752,6 +756,7 @@ export function analyze_component(root, source, options) {
scopes,
analysis,
options,
fragment: ast === template.ast ? ast : null,
parent_element: null,
has_props_rune: false,
ast_type: ast === instance.ast ? 'instance' : ast === template.ast ? 'template' : 'module',
Expand Down
1 change: 1 addition & 0 deletions packages/svelte/src/compiler/phases/2-analyze/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface AnalysisState {
analysis: ComponentAnalysis;
options: ValidatedCompileOptions;
ast_type: 'instance' | 'template' | 'module';
fragment: AST.Fragment | null;
/**
* Tag name of the parent element. `null` if the parent is `svelte:element`, `#snippet`, a component or the root.
* Parent doesn't necessarily mean direct path predecessor because there could be `#each`, `#if` etc in-between.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ export function AwaitExpression(node, context) {

if (context.state.expression) {
context.state.expression.has_await = true;

if (
context.state.fragment &&
// TODO there's probably a better way to do this
context.path.some((node) => node.type === 'ConstTag')
) {
context.state.fragment.metadata.has_await = true;
}

suspend = true;
}

Expand Down
10 changes: 10 additions & 0 deletions packages/svelte/src/compiler/phases/2-analyze/visitors/Fragment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/** @import { AST } from '#compiler' */
/** @import { Context } from '../types.js' */

/**
* @param {AST.Fragment} node
* @param {Context} context
*/
export function Fragment(node, context) {
context.next({ ...context.state, fragment: node });
}
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ export function client_component(analysis, options) {

// these are set inside the `Fragment` visitor, and cannot be used until then
init: /** @type {any} */ (null),
consts: /** @type {any} */ (null),
update: /** @type {any} */ (null),
after_update: /** @type {any} */ (null),
template: /** @type {any} */ (null),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import type {
Expression,
AssignmentExpression,
UpdateExpression,
VariableDeclaration
VariableDeclaration,
Declaration
} from 'estree';
import type { AST, Namespace, ValidatedCompileOptions } from '#compiler';
import type { TransformState } from '../types.js';
Expand Down Expand Up @@ -57,6 +58,8 @@ export interface ComponentClientTransformState extends ClientTransformState {
readonly update: Statement[];
/** Stuff that happens after the render effect (control blocks, dynamic elements, bindings, actions, etc) */
readonly after_update: Statement[];
/** Transformed `{@const }` declarations */
readonly consts: Statement[];
/** Memoized expressions */
readonly memoizer: Memoizer;
/** The HTML template string */
Expand Down
15 changes: 11 additions & 4 deletions packages/svelte/src/compiler/phases/3-transform/client/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** @import { ArrowFunctionExpression, AssignmentExpression, Expression, FunctionDeclaration, FunctionExpression, Identifier, Node, Pattern, UpdateExpression } from 'estree' */
/** @import { ArrowFunctionExpression, AssignmentExpression, BlockStatement, Expression, FunctionDeclaration, FunctionExpression, Identifier, Node, Pattern, UpdateExpression } from 'estree' */
/** @import { Binding } from '#compiler' */
/** @import { ClientTransformState, ComponentClientTransformState, ComponentContext } from './types.js' */
/** @import { Analysis } from '../../types.js' */
Expand Down Expand Up @@ -289,8 +289,15 @@ export function should_proxy(node, scope) {
/**
* Svelte legacy mode should use safe equals in most places, runes mode shouldn't
* @param {ComponentClientTransformState} state
* @param {Expression} arg
* @param {Expression | BlockStatement} expression
* @param {boolean} [async]
*/
export function create_derived(state, arg) {
return b.call(state.analysis.runes ? '$.derived' : '$.derived_safe_equal', arg);
export function create_derived(state, expression, async = false) {
const thunk = b.thunk(expression, async);

if (async) {
return b.call(b.await(b.call('$.save', b.call('$.async_derived', thunk))));
} else {
return b.call(state.analysis.runes ? '$.derived' : '$.derived_safe_equal', thunk);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ function create_derived_block_argument(node, context) {
b.return(b.object(identifiers.map((identifier) => b.prop('init', identifier, identifier))))
]);

const declarations = [b.var(value, create_derived(context.state, b.thunk(block)))];
const declarations = [b.var(value, create_derived(context.state, block))];

for (const id of identifiers) {
context.state.transform[id.name] = { read: get_value };

declarations.push(
b.var(id, create_derived(context.state, b.thunk(b.member(b.call('$.get', value), id))))
b.var(id, create_derived(context.state, b.member(b.call('$.get', value), id)))
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,26 @@ export function ConstTag(node, context) {
const declaration = node.declaration.declarations[0];
// TODO we can almost certainly share some code with $derived(...)
if (declaration.id.type === 'Identifier') {
const init = build_expression(context, declaration.init, node.metadata.expression);
let expression = create_derived(context.state, b.thunk(init));
const init = build_expression(
{ ...context, state: { ...context.state, in_derived: true } },
declaration.init,
node.metadata.expression
);

let expression = create_derived(context.state, init, node.metadata.expression.has_await);

if (dev) {
expression = b.call('$.tag', expression, b.literal(declaration.id.name));
}

context.state.init.push(b.const(declaration.id, expression));
context.state.consts.push(b.const(declaration.id, expression));

context.state.transform[declaration.id.name] = { read: get_value };

// we need to eagerly evaluate the expression in order to hit any
// 'Cannot access x before initialization' errors
if (dev) {
context.state.init.push(b.stmt(b.call('$.get', declaration.id)));
context.state.consts.push(b.stmt(b.call('$.get', declaration.id)));
}
} else {
const identifiers = extract_identifiers(declaration.id);
Expand All @@ -44,7 +49,11 @@ export function ConstTag(node, context) {
delete transform[node.name];
}

const child_state = { ...context.state, transform };
const child_state = /** @type {ComponentContext['state']} */ ({
...context.state,
transform,
in_derived: true
});

// TODO optimise the simple `{ x } = y` case — we can just return `y`
// instead of destructuring it only to return a new object
Expand All @@ -53,26 +62,24 @@ export function ConstTag(node, context) {
declaration.init,
node.metadata.expression
);
const fn = b.arrow(
[],
b.block([
b.const(/** @type {Pattern} */ (context.visit(declaration.id, child_state)), init),
b.return(b.object(identifiers.map((node) => b.prop('init', node, node))))
])
);

let expression = create_derived(context.state, fn);
const block = b.block([
b.const(/** @type {Pattern} */ (context.visit(declaration.id, child_state)), init),
b.return(b.object(identifiers.map((node) => b.prop('init', node, node))))
]);

let expression = create_derived(context.state, block, node.metadata.expression.has_await);

if (dev) {
expression = b.call('$.tag', expression, b.literal('[@const]'));
}

context.state.init.push(b.const(tmp, expression));
context.state.consts.push(b.const(tmp, expression));

// we need to eagerly evaluate the expression in order to hit any
// 'Cannot access x before initialization' errors
if (dev) {
context.state.init.push(b.stmt(b.call('$.get', tmp)));
context.state.consts.push(b.stmt(b.call('$.get', tmp)));
}

for (const node of identifiers) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ export function Fragment(node, context) {
const is_single_child_not_needing_template =
trimmed.length === 1 &&
(trimmed[0].type === 'SvelteFragment' || trimmed[0].type === 'TitleElement');
const has_await = context.state.init !== null && (node.metadata.has_await || false);

const template_name = context.state.scope.root.unique('root'); // TODO infer name from parent
const unsuspend = b.id('$$unsuspend');

/** @type {Statement[]} */
const body = [];
Expand All @@ -61,6 +63,7 @@ export function Fragment(node, context) {
const state = {
...context.state,
init: [],
consts: [],
update: [],
after_update: [],
memoizer: new Memoizer(),
Expand All @@ -76,11 +79,6 @@ export function Fragment(node, context) {
context.visit(node, state);
}

if (is_text_first) {
// skip over inserted comment
body.push(b.stmt(b.call('$.next')));
}

if (is_single_element) {
const element = /** @type {AST.RegularElement} */ (trimmed[0]);

Expand All @@ -96,13 +94,13 @@ export function Fragment(node, context) {
const template = transform_template(state, namespace, flags);
state.hoisted.push(b.var(template_name, template));

body.push(b.var(id, b.call(template_name)));
state.init.unshift(b.var(id, b.call(template_name)));
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
} else if (is_single_child_not_needing_template) {
context.visit(trimmed[0], state);
} else if (trimmed.length === 1 && trimmed[0].type === 'Text') {
const id = b.id(context.state.scope.generate('text'));
body.push(b.var(id, b.call('$.text', b.literal(trimmed[0].data))));
state.init.unshift(b.var(id, b.call('$.text', b.literal(trimmed[0].data))));
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
} else if (trimmed.length > 0) {
const id = b.id(context.state.scope.generate('fragment'));
Expand All @@ -120,7 +118,7 @@ export function Fragment(node, context) {
state
});

body.push(b.var(id, b.call('$.text')));
state.init.unshift(b.var(id, b.call('$.text')));
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
} else {
if (is_standalone) {
Expand All @@ -140,19 +138,34 @@ export function Fragment(node, context) {

if (state.template.nodes.length === 1 && state.template.nodes[0].type === 'comment') {
// special case — we can use `$.comment` instead of creating a unique template
body.push(b.var(id, b.call('$.comment')));
state.init.unshift(b.var(id, b.call('$.comment')));
} else {
const template = transform_template(state, namespace, flags);
state.hoisted.push(b.var(template_name, template));

body.push(b.var(id, b.call(template_name)));
state.init.unshift(b.var(id, b.call(template_name)));
}

close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
}
}
}

if (has_await) {
body.push(b.var(unsuspend, b.call('$.suspend')));
}

body.push(...state.consts);

if (has_await) {
body.push(b.if(b.call('$.aborted'), b.return()));
}

if (is_text_first) {
// skip over inserted comment
body.push(b.stmt(b.call('$.next')));
}

body.push(...state.init);

if (state.update.length > 0) {
Expand All @@ -168,5 +181,9 @@ export function Fragment(node, context) {
body.push(close);
}

if (has_await) {
body.push(b.stmt(b.call(unsuspend)));
}

return b.block(body);
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,6 @@ export function LetDirective(node, context) {
read: (node) => b.call('$.get', node)
};

return b.const(
name,
create_derived(context.state, b.thunk(b.member(b.id('$$slotProps'), node.name)))
);
return b.const(name, create_derived(context.state, b.member(b.id('$$slotProps'), node.name)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,14 @@ export function SnippetBlock(node, context) {
// TODO hoist where possible
/** @type {(Identifier | AssignmentPattern)[]} */
const args = [b.id('$$anchor')];
const has_await = node.body.metadata.has_await || false;

/** @type {BlockStatement} */
let body;

/** @type {Statement[]} */
const declarations = [];

if (dev) {
declarations.push(b.stmt(b.call('$.validate_snippet_args', b.spread(b.id('arguments')))));
}

const transform = { ...context.state.transform };
const child_state = { ...context.state, transform };

Expand Down Expand Up @@ -72,16 +69,21 @@ export function SnippetBlock(node, context) {
}
}
}

const block = /** @type {BlockStatement} */ (context.visit(node.body, child_state)).body;
body = b.block([
dev ? b.stmt(b.call('$.validate_snippet_args', b.spread(b.id('arguments')))) : b.empty,
...declarations,
.../** @type {BlockStatement} */ (context.visit(node.body, child_state)).body
...block
]);

// in dev we use a FunctionExpression (not arrow function) so we can use `arguments`
let snippet = dev
? b.call('$.wrap_snippet', b.id(context.state.analysis.name), b.function(null, args, body))
: b.arrow(args, body);
? b.call(
'$.wrap_snippet',
b.id(context.state.analysis.name),
b.function(null, args, body, has_await)
)
: b.arrow(args, body, has_await);

const declaration = b.const(node.expression, snippet);

Expand Down
Loading
Loading