33/** @import { Context } from '../types' */
44import { dev } from '../../../../state.js' ;
55import * as b from '../../../../utils/builders.js' ;
6+ import { get_rune } from '../../../scope.js' ;
67
78/**
89 * @param {AwaitExpression } node
910 * @param {Context } context
1011 */
1112export function AwaitExpression ( node , context ) {
12- const tla = context . state . is_instance && context . state . scope . function_depth === 1 ;
13-
14- const save = tla || ! is_last_evaluated_expression ( context . path , node ) ;
13+ const save =
14+ // preserve context if this is a top-level await in `<script>`
15+ ( context . state . is_instance && context . state . scope . function_depth === 1 ) ||
16+ // or if this is a derived/template expression
17+ ( is_reactive_expression ( context ) && ! is_last_evaluated_expression ( context . path , node ) ) ;
1518
1619 if ( dev || save ) {
1720 const expression = /** @type {Expression } */ ( context . visit ( node . argument ) ) ;
@@ -22,11 +25,40 @@ export function AwaitExpression(node, context) {
2225}
2326
2427/**
25- *
28+ * @param {Context } context
29+ */
30+ function is_reactive_expression ( context ) {
31+ let i = context . path . length ;
32+
33+ while ( i -- ) {
34+ const parent = context . path [ i ] ;
35+
36+ if (
37+ parent . type === 'ArrowFunctionExpression' ||
38+ parent . type === 'FunctionExpression' ||
39+ parent . type === 'FunctionDeclaration'
40+ ) {
41+ return false ;
42+ }
43+
44+ if ( parent . type === 'CallExpression' && get_rune ( parent , context . state . scope ) === '$derived' ) {
45+ return true ;
46+ }
47+
48+ // @ts -expect-error we could probably use a neater/more robust mechanism
49+ if ( parent . metadata ) {
50+ return true ;
51+ }
52+ }
53+
54+ return false ;
55+ }
56+
57+ /**
2658 * @param {AST.SvelteNode[] } path
2759 * @param {Expression | SpreadElement | Property } node
2860 */
29- export function is_last_evaluated_expression ( path , node ) {
61+ function is_last_evaluated_expression ( path , node ) {
3062 let i = path . length ;
3163
3264 while ( i -- ) {
0 commit comments