Skip to content

Commit 4481110

Browse files
committed
fix: disallow static state fields
1 parent 90a7aec commit 4481110

File tree

4 files changed

+35
-9
lines changed

4 files changed

+35
-9
lines changed

.changeset/slimy-jeans-hide.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: disallow static state fields

packages/svelte/src/compiler/phases/2-analyze/validation.js

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -490,18 +490,25 @@ function validate_call_expression(node, scope, path) {
490490
const rune = get_rune(node, scope);
491491
if (rune === null) return;
492492

493-
if (rune === '$props' && path.at(-1)?.type !== 'VariableDeclarator') {
493+
const parent = /** @type {import('#compiler').SvelteNode} */ (path.at(-1));
494+
495+
if (rune === '$props') {
496+
if (parent.type === 'VariableDeclarator') return;
494497
error(node, 'invalid-props-location');
495-
} else if (
496-
(rune === '$state' || rune === '$derived') &&
497-
path.at(-1)?.type !== 'VariableDeclarator' &&
498-
path.at(-1)?.type !== 'PropertyDefinition'
499-
) {
498+
}
499+
500+
if (rune === '$state' || rune === '$derived') {
501+
if (parent.type === 'VariableDeclarator') return;
502+
if (parent.type === 'PropertyDefinition' && !parent.static && !parent.computed) return;
500503
error(node, rune === '$derived' ? 'invalid-derived-location' : 'invalid-state-location');
501-
} else if (rune === '$effect') {
502-
if (path.at(-1)?.type !== 'ExpressionStatement') {
504+
}
505+
506+
if (rune === '$effect') {
507+
if (parent.type !== 'ExpressionStatement') {
503508
error(node, 'invalid-effect-location');
504-
} else if (node.arguments.length !== 1) {
509+
}
510+
511+
if (node.arguments.length !== 1) {
505512
error(node, 'invalid-rune-args-length', '$effect', [1]);
506513
}
507514
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { test } from '../../test';
2+
3+
export default test({
4+
error: {
5+
code: 'invalid-state-location',
6+
message: '$state() can only be used as a variable declaration initializer or a class field',
7+
position: [33, 41]
8+
}
9+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<script>
2+
class X {
3+
static x = $state();
4+
}
5+
</script>

0 commit comments

Comments
 (0)