pull/16197/head
Rich Harris 5 months ago
commit cc2b888c36

@ -274,6 +274,12 @@ A `:global` selector cannot modify an existing selector
A `:global` selector can only be modified if it is a descendant of other selectors
```
### css_global_block_invalid_placement
```
A `:global` selector cannot be inside a pseudoclass
```
### css_global_invalid_placement
```

@ -1,5 +1,21 @@
# svelte
## 5.28.1
### Patch Changes
- fix: ensure `<svelte:boundary>` properly removes error content in production mode ([#15793](https://github.com/sveltejs/svelte/pull/15793))
- fix: `update_version` after `delete` if `source` is `undefined` and `prop` in `target` ([#15796](https://github.com/sveltejs/svelte/pull/15796))
- fix: emit error on wrong placement of the `:global` block selector ([#15794](https://github.com/sveltejs/svelte/pull/15794))
## 5.28.0
### Minor Changes
- feat: partially evaluate more expressions ([#15781](https://github.com/sveltejs/svelte/pull/15781))
## 5.27.3
### Patch Changes

@ -50,6 +50,10 @@ x y {
> A `:global` selector can only be modified if it is a descendant of other selectors
## css_global_block_invalid_placement
> A `:global` selector cannot be inside a pseudoclass
## css_global_invalid_placement
> `:global(...)` can be at the start or end of a selector sequence, but not in the middle

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

@ -599,6 +599,15 @@ export function css_global_block_invalid_modifier_start(node) {
e(node, 'css_global_block_invalid_modifier_start', `A \`:global\` selector can only be modified if it is a descendant of other selectors\nhttps://svelte.dev/e/css_global_block_invalid_modifier_start`);
}
/**
* A `:global` selector cannot be inside a pseudoclass
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_block_invalid_placement(node) {
e(node, 'css_global_block_invalid_placement', `A \`:global\` selector cannot be inside a pseudoclass\nhttps://svelte.dev/e/css_global_block_invalid_placement`);
}
/**
* `:global(...)` can be at the start or end of a selector sequence, but not in the middle
* @param {null | number | NodeLike} node

@ -68,8 +68,12 @@ const css_visitors = {
const global = node.children.find(is_global);
if (global) {
const idx = node.children.indexOf(global);
const is_nested = context.path.at(-2)?.type === 'PseudoClassSelector';
if (is_nested && !global.selectors[0].args) {
e.css_global_block_invalid_placement(global.selectors[0]);
}
const idx = node.children.indexOf(global);
if (global.selectors[0].args !== null && idx !== 0 && idx !== node.children.length - 1) {
// ensure `:global(...)` is not used in the middle of a selector (but multiple `global(...)` in sequence are ok)
for (let i = idx + 1; i < node.children.length; i++) {

@ -77,12 +77,18 @@ export function build_template_chunk(
node.metadata.expression
);
const evaluated = state.scope.evaluate(value);
has_await ||= node.metadata.expression.has_await;
has_state ||= has_await || node.metadata.expression.has_state;
has_state ||= has_await || (node.metadata.expression.has_state && !evaluated.is_known);
if (values.length === 1) {
// If we have a single expression, then pass that in directly to possibly avoid doing
// extra work in the template_effect (instead we do the work in set_text).
if (evaluated.is_known) {
value = b.literal(evaluated.value);
}
return { value, has_state };
}
@ -98,8 +104,6 @@ export function build_template_chunk(
}
}
const evaluated = state.scope.evaluate(value);
if (evaluated.is_known) {
quasi.value.cooked += evaluated.value + '';
} else {

@ -1,4 +1,4 @@
/** @import { ArrowFunctionExpression, BinaryOperator, ClassDeclaration, Expression, FunctionDeclaration, FunctionExpression, Identifier, ImportDeclaration, MemberExpression, LogicalOperator, Node, Pattern, UnaryOperator, VariableDeclarator } from 'estree' */
/** @import { ArrowFunctionExpression, BinaryOperator, ClassDeclaration, Expression, FunctionDeclaration, FunctionExpression, Identifier, ImportDeclaration, MemberExpression, LogicalOperator, Node, Pattern, UnaryOperator, VariableDeclarator, Super } from 'estree' */
/** @import { Context, Visitor } from 'zimmerframe' */
/** @import { AST, BindingKind, DeclarationKind } from '#compiler' */
import is_reference from 'is-reference';
@ -18,8 +18,71 @@ import { validate_identifier_name } from './2-analyze/visitors/shared/utils.js';
const UNKNOWN = Symbol('unknown');
/** Includes `BigInt` */
const NUMBER = Symbol('number');
const STRING = Symbol('string');
export const NUMBER = Symbol('number');
export const STRING = Symbol('string');
/** @type {Record<string, [type: NUMBER | STRING | UNKNOWN, fn?: Function]>} */
const globals = {
BigInt: [NUMBER, BigInt],
'Math.min': [NUMBER, Math.min],
'Math.max': [NUMBER, Math.max],
'Math.random': [NUMBER],
'Math.floor': [NUMBER, Math.floor],
// @ts-expect-error
'Math.f16round': [NUMBER, Math.f16round],
'Math.round': [NUMBER, Math.round],
'Math.abs': [NUMBER, Math.abs],
'Math.acos': [NUMBER, Math.acos],
'Math.asin': [NUMBER, Math.asin],
'Math.atan': [NUMBER, Math.atan],
'Math.atan2': [NUMBER, Math.atan2],
'Math.ceil': [NUMBER, Math.ceil],
'Math.cos': [NUMBER, Math.cos],
'Math.sin': [NUMBER, Math.sin],
'Math.tan': [NUMBER, Math.tan],
'Math.exp': [NUMBER, Math.exp],
'Math.log': [NUMBER, Math.log],
'Math.pow': [NUMBER, Math.pow],
'Math.sqrt': [NUMBER, Math.sqrt],
'Math.clz32': [NUMBER, Math.clz32],
'Math.imul': [NUMBER, Math.imul],
'Math.sign': [NUMBER, Math.sign],
'Math.log10': [NUMBER, Math.log10],
'Math.log2': [NUMBER, Math.log2],
'Math.log1p': [NUMBER, Math.log1p],
'Math.expm1': [NUMBER, Math.expm1],
'Math.cosh': [NUMBER, Math.cosh],
'Math.sinh': [NUMBER, Math.sinh],
'Math.tanh': [NUMBER, Math.tanh],
'Math.acosh': [NUMBER, Math.acosh],
'Math.asinh': [NUMBER, Math.asinh],
'Math.atanh': [NUMBER, Math.atanh],
'Math.trunc': [NUMBER, Math.trunc],
'Math.fround': [NUMBER, Math.fround],
'Math.cbrt': [NUMBER, Math.cbrt],
Number: [NUMBER, Number],
'Number.isInteger': [NUMBER, Number.isInteger],
'Number.isFinite': [NUMBER, Number.isFinite],
'Number.isNaN': [NUMBER, Number.isNaN],
'Number.isSafeInteger': [NUMBER, Number.isSafeInteger],
'Number.parseFloat': [NUMBER, Number.parseFloat],
'Number.parseInt': [NUMBER, Number.parseInt],
String: [STRING, String],
'String.fromCharCode': [STRING, String.fromCharCode],
'String.fromCodePoint': [STRING, String.fromCodePoint]
};
/** @type {Record<string, any>} */
const global_constants = {
'Math.PI': Math.PI,
'Math.E': Math.E,
'Math.LN10': Math.LN10,
'Math.LN2': Math.LN2,
'Math.LOG10E': Math.LOG10E,
'Math.LOG2E': Math.LOG2E,
'Math.SQRT2': Math.SQRT2,
'Math.SQRT1_2': Math.SQRT1_2
};
export class Binding {
/** @type {Scope} */
@ -107,7 +170,7 @@ export class Binding {
class Evaluation {
/** @type {Set<any>} */
values = new Set();
values;
/**
* True if there is exactly one possible value
@ -147,8 +210,11 @@ class Evaluation {
*
* @param {Scope} scope
* @param {Expression} expression
* @param {Set<any>} values
*/
constructor(scope, expression) {
constructor(scope, expression, values) {
this.values = values;
switch (expression.type) {
case 'Literal': {
this.values.add(expression.value);
@ -172,15 +238,18 @@ class Evaluation {
binding.kind === 'rest_prop' ||
binding.kind === 'bindable_prop';
if (!binding.updated && binding.initial !== null && !is_prop) {
const evaluation = binding.scope.evaluate(/** @type {Expression} */ (binding.initial));
for (const value of evaluation.values) {
this.values.add(value);
}
if (binding.initial?.type === 'EachBlock' && binding.initial.index === expression.name) {
this.values.add(NUMBER);
break;
}
// TODO each index is always defined
if (!binding.updated && binding.initial !== null && !is_prop) {
binding.scope.evaluate(/** @type {Expression} */ (binding.initial), this.values);
break;
}
} else if (expression.name === 'undefined') {
this.values.add(undefined);
break;
}
// TODO glean what we can from reassignments
@ -336,6 +405,101 @@ class Evaluation {
break;
}
case 'CallExpression': {
const keypath = get_global_keypath(expression.callee, scope);
if (keypath) {
if (is_rune(keypath)) {
const arg = /** @type {Expression | undefined} */ (expression.arguments[0]);
switch (keypath) {
case '$state':
case '$state.raw':
case '$derived':
if (arg) {
scope.evaluate(arg, this.values);
} else {
this.values.add(undefined);
}
break;
case '$props.id':
this.values.add(STRING);
break;
case '$effect.tracking':
this.values.add(false);
this.values.add(true);
break;
case '$derived.by':
if (arg?.type === 'ArrowFunctionExpression' && arg.body.type !== 'BlockStatement') {
scope.evaluate(arg.body, this.values);
break;
}
this.values.add(UNKNOWN);
break;
default: {
this.values.add(UNKNOWN);
}
}
break;
}
if (
Object.hasOwn(globals, keypath) &&
expression.arguments.every((arg) => arg.type !== 'SpreadElement')
) {
const [type, fn] = globals[keypath];
const values = expression.arguments.map((arg) => scope.evaluate(arg));
if (fn && values.every((e) => e.is_known)) {
this.values.add(fn(...values.map((e) => e.value)));
} else {
this.values.add(type);
}
break;
}
}
this.values.add(UNKNOWN);
break;
}
case 'TemplateLiteral': {
let result = expression.quasis[0].value.cooked;
for (let i = 0; i < expression.expressions.length; i += 1) {
const e = scope.evaluate(expression.expressions[i]);
if (e.is_known) {
result += e.value + expression.quasis[i + 1].value.cooked;
} else {
this.values.add(STRING);
break;
}
}
this.values.add(result);
break;
}
case 'MemberExpression': {
const keypath = get_global_keypath(expression, scope);
if (keypath && Object.hasOwn(global_constants, keypath)) {
this.values.add(global_constants[keypath]);
break;
}
this.values.add(UNKNOWN);
break;
}
default: {
this.values.add(UNKNOWN);
}
@ -548,10 +712,10 @@ export class Scope {
* Only call this once scope has been fully generated in a first pass,
* else this evaluates on incomplete data and may yield wrong results.
* @param {Expression} expression
* @param {Set<any>} values
* @param {Set<any>} [values]
*/
evaluate(expression, values = new Set()) {
return new Evaluation(this, expression);
return new Evaluation(this, expression, values);
}
}
@ -1133,7 +1297,19 @@ export function get_rune(node, scope) {
if (!node) return null;
if (node.type !== 'CallExpression') return null;
let n = node.callee;
const keypath = get_global_keypath(node.callee, scope);
if (!keypath || !is_rune(keypath)) return null;
return keypath;
}
/**
* Returns the name of the rune if the given expression is a `CallExpression` using a rune.
* @param {Expression | Super} node
* @param {Scope} scope
*/
function get_global_keypath(node, scope) {
let n = node;
let joined = '';
@ -1151,12 +1327,8 @@ export function get_rune(node, scope) {
if (n.type !== 'Identifier') return null;
joined = n.name + joined;
if (!is_rune(joined)) return null;
const binding = scope.get(n.name);
if (binding !== null) return null; // rune name, but references a variable or store
return joined;
return n.name + joined;
}

@ -100,6 +100,7 @@ export function proxy(value) {
prop,
with_parent(() => source(UNINITIALIZED, stack))
);
update_version(version);
}
} else {
// When working with arrays, we need to also ensure we update the length when removing

@ -314,31 +314,21 @@ export function handle_error(error, effect, previous_effect, component_context)
is_throwing_error = true;
}
if (
!DEV ||
component_context === null ||
!(error instanceof Error) ||
handled_errors.has(error)
) {
propagate_error(error, effect);
return;
}
handled_errors.add(error);
if (DEV && component_context !== null && error instanceof Error && !handled_errors.has(error)) {
handled_errors.add(error);
const component_stack = [];
const component_stack = [];
const effect_name = effect.fn?.name;
const effect_name = effect.fn?.name;
if (effect_name) {
component_stack.push(effect_name);
}
if (effect_name) {
component_stack.push(effect_name);
}
/** @type {ComponentContext | null} */
let current_context = component_context;
/** @type {ComponentContext | null} */
let current_context = component_context;
while (current_context !== null) {
if (DEV) {
while (current_context !== null) {
/** @type {string} */
var filename = current_context.function?.[FILENAME];
@ -346,35 +336,36 @@ export function handle_error(error, effect, previous_effect, component_context)
const file = filename.split('/').pop();
component_stack.push(file);
}
current_context = current_context.p;
}
current_context = current_context.p;
}
const indent = is_firefox ? ' ' : '\t';
define_property(error, 'message', {
value:
error.message + `\n${component_stack.map((name) => `\n${indent}in ${name}`).join('')}\n`
});
define_property(error, 'component_stack', {
value: component_stack
});
const indent = is_firefox ? ' ' : '\t';
define_property(error, 'message', {
value: error.message + `\n${component_stack.map((name) => `\n${indent}in ${name}`).join('')}\n`
});
define_property(error, 'component_stack', {
value: component_stack
});
const stack = error.stack;
// Filter out internal files from callstack
if (stack) {
const lines = stack.split('\n');
const new_lines = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.includes('svelte/src/internal')) {
continue;
const stack = error.stack;
// Filter out internal files from callstack
if (stack) {
const lines = stack.split('\n');
const new_lines = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.includes('svelte/src/internal')) {
continue;
}
new_lines.push(line);
}
new_lines.push(line);
define_property(error, 'stack', {
value: new_lines.join('\n')
});
}
define_property(error, 'stack', {
value: new_lines.join('\n')
});
}
propagate_error(error, effect);

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

@ -0,0 +1,9 @@
import { test } from '../../test';
export default test({
error: {
code: 'css_global_block_invalid_placement',
message: 'A `:global` selector cannot be inside a pseudoclass',
position: [28, 35]
}
});

@ -0,0 +1,4 @@
<style>
/* invalid */
:is(:global) { color: red }
</style>

@ -0,0 +1,13 @@
import { test } from '../../test';
import { flushSync } from 'svelte';
export default test({
html: `<button>delete</button><p>test</p>`,
async test({ assert, target }) {
const btn = target.querySelector('button');
flushSync(() => btn?.click());
assert.htmlEqual(target.innerHTML, '<button>delete</button>');
}
});

@ -0,0 +1,13 @@
<script>
let obj = $state({test: 0})
let keys = $derived(Object.keys(obj));
</script>
<button onclick={() => delete obj.test}>
delete
</button>
{#each keys as key}
<p>{key}</p>
{/each}

@ -0,0 +1,11 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
mode: ['client'],
test({ assert, target }) {
flushSync();
assert.htmlEqual(target.innerHTML, '<p>error occurred</p>');
}
});

@ -0,0 +1,15 @@
<script>
import Child from "./Child.svelte"
</script>
<svelte:boundary>
<p>This should be removed</p>
{#if true}
<Child />
{/if}
{#snippet failed()}
<p>error occurred</p>
{/snippet}
</svelte:boundary>

@ -0,0 +1,3 @@
import { test } from '../../test';
export default test({});

@ -0,0 +1,19 @@
import 'svelte/internal/disclose-version';
import 'svelte/internal/flags/legacy';
import * as $ from 'svelte/internal/client';
var root_1 = $.template(`<p></p>`);
export default function Each_index_non_null($$anchor) {
var fragment = $.comment();
var node = $.first_child(fragment);
$.each(node, 0, () => Array(10), $.index, ($$anchor, $$item, i) => {
var p = root_1();
p.textContent = `index: ${i}`;
$.append($$anchor, p);
});
$.append($$anchor, fragment);
}

@ -0,0 +1,13 @@
import * as $ from 'svelte/internal/server';
export default function Each_index_non_null($$payload) {
const each_array = $.ensure_array_like(Array(10));
$$payload.out += `<!--[-->`;
for (let i = 0, $$length = each_array.length; i < $$length; i++) {
$$payload.out += `<p>index: ${$.escape(i)}</p>`;
}
$$payload.out += `<!--]-->`;
}

@ -0,0 +1,3 @@
{#each Array(10), i}
<p>index: {i}</p>
{/each}

@ -8,7 +8,7 @@ export default function Purity($$anchor) {
var fragment = root();
var p = $.first_child(fragment);
p.textContent = Math.max(0, Math.min(0, 100));
p.textContent = 0;
var p_1 = $.sibling(p, 2);

@ -1,7 +1,7 @@
import * as $ from 'svelte/internal/server';
export default function Purity($$payload) {
$$payload.out += `<p>${$.escape(Math.max(0, Math.min(0, 100)))}</p> <p>${$.escape(location.href)}</p> `;
$$payload.out += `<p>0</p> <p>${$.escape(location.href)}</p> `;
Child($$payload, { prop: encodeURIComponent('hello') });
$$payload.out += `<!---->`;
}
Loading…
Cancel
Save