mirror of https://github.com/sveltejs/svelte
commit
35a3b473c7
@ -1,5 +0,0 @@
|
||||
---
|
||||
'svelte': patch
|
||||
---
|
||||
|
||||
fix: handle more hydration mismatches
|
@ -1,409 +1,441 @@
|
||||
// @ts-check
|
||||
import process from 'node:process';
|
||||
import fs from 'node:fs';
|
||||
import * as acorn from 'acorn';
|
||||
import { walk } from 'zimmerframe';
|
||||
import * as esrap from 'esrap';
|
||||
|
||||
/** @type {Record<string, Record<string, { messages: string[], details: string | null }>>} */
|
||||
const messages = {};
|
||||
const seen = new Set();
|
||||
|
||||
const DIR = '../../documentation/docs/98-reference/.generated';
|
||||
fs.rmSync(DIR, { force: true, recursive: true });
|
||||
fs.mkdirSync(DIR);
|
||||
|
||||
for (const category of fs.readdirSync('messages')) {
|
||||
if (category.startsWith('.')) continue;
|
||||
const watch = process.argv.includes('-w');
|
||||
|
||||
messages[category] = {};
|
||||
function run() {
|
||||
/** @type {Record<string, Record<string, { messages: string[], details: string | null }>>} */
|
||||
const messages = {};
|
||||
const seen = new Set();
|
||||
|
||||
for (const file of fs.readdirSync(`messages/${category}`)) {
|
||||
if (!file.endsWith('.md')) continue;
|
||||
fs.rmSync(DIR, { force: true, recursive: true });
|
||||
fs.mkdirSync(DIR);
|
||||
|
||||
const markdown = fs
|
||||
.readFileSync(`messages/${category}/${file}`, 'utf-8')
|
||||
.replace(/\r\n/g, '\n');
|
||||
for (const category of fs.readdirSync('messages')) {
|
||||
if (category.startsWith('.')) continue;
|
||||
|
||||
const sorted = [];
|
||||
messages[category] = {};
|
||||
|
||||
for (const match of markdown.matchAll(/## ([\w]+)\n\n([^]+?)(?=$|\n\n## )/g)) {
|
||||
const [_, code, text] = match;
|
||||
for (const file of fs.readdirSync(`messages/${category}`)) {
|
||||
if (!file.endsWith('.md')) continue;
|
||||
|
||||
if (seen.has(code)) {
|
||||
throw new Error(`Duplicate message code ${category}/${code}`);
|
||||
}
|
||||
const markdown = fs
|
||||
.readFileSync(`messages/${category}/${file}`, 'utf-8')
|
||||
.replace(/\r\n/g, '\n');
|
||||
|
||||
sorted.push({ code, _ });
|
||||
const sorted = [];
|
||||
|
||||
const sections = text.trim().split('\n\n');
|
||||
const details = [];
|
||||
for (const match of markdown.matchAll(/## ([\w]+)\n\n([^]+?)(?=$|\n\n## )/g)) {
|
||||
const [_, code, text] = match;
|
||||
|
||||
while (!sections[sections.length - 1].startsWith('> ')) {
|
||||
details.unshift(/** @type {string} */ (sections.pop()));
|
||||
}
|
||||
if (seen.has(code)) {
|
||||
throw new Error(`Duplicate message code ${category}/${code}`);
|
||||
}
|
||||
|
||||
sorted.push({ code, _ });
|
||||
|
||||
if (sections.length === 0) {
|
||||
throw new Error('No message text');
|
||||
const sections = text.trim().split('\n\n');
|
||||
const details = [];
|
||||
|
||||
while (!sections[sections.length - 1].startsWith('> ')) {
|
||||
details.unshift(/** @type {string} */ (sections.pop()));
|
||||
}
|
||||
|
||||
if (sections.length === 0) {
|
||||
throw new Error('No message text');
|
||||
}
|
||||
|
||||
seen.add(code);
|
||||
messages[category][code] = {
|
||||
messages: sections.map((section) => section.replace(/^> /gm, '').replace(/^>\n/gm, '\n')),
|
||||
details: details.join('\n\n')
|
||||
};
|
||||
}
|
||||
|
||||
seen.add(code);
|
||||
messages[category][code] = {
|
||||
messages: sections.map((section) => section.replace(/^> /gm, '').replace(/^>\n/gm, '\n')),
|
||||
details: details.join('\n\n')
|
||||
};
|
||||
sorted.sort((a, b) => (a.code < b.code ? -1 : 1));
|
||||
|
||||
fs.writeFileSync(
|
||||
`messages/${category}/${file}`,
|
||||
sorted.map((x) => x._.trim()).join('\n\n') + '\n'
|
||||
);
|
||||
}
|
||||
|
||||
sorted.sort((a, b) => (a.code < b.code ? -1 : 1));
|
||||
fs.writeFileSync(
|
||||
`messages/${category}/${file}`,
|
||||
sorted.map((x) => x._.trim()).join('\n\n') + '\n'
|
||||
`${DIR}/${category}.md`,
|
||||
'<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n' +
|
||||
Object.entries(messages[category])
|
||||
.map(([code, { messages, details }]) => {
|
||||
const chunks = [
|
||||
`### ${code}`,
|
||||
...messages.map((message) => '```\n' + message + '\n```')
|
||||
];
|
||||
|
||||
if (details) {
|
||||
chunks.push(details);
|
||||
}
|
||||
|
||||
return chunks.join('\n\n');
|
||||
})
|
||||
.sort()
|
||||
.join('\n\n') +
|
||||
'\n'
|
||||
);
|
||||
}
|
||||
|
||||
fs.writeFileSync(
|
||||
`${DIR}/${category}.md`,
|
||||
'<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n' +
|
||||
Object.entries(messages[category])
|
||||
.map(([code, { messages, details }]) => {
|
||||
const chunks = [`### ${code}`, ...messages.map((message) => '```\n' + message + '\n```')];
|
||||
|
||||
if (details) {
|
||||
chunks.push(details);
|
||||
}
|
||||
|
||||
return chunks.join('\n\n');
|
||||
})
|
||||
.sort()
|
||||
.join('\n\n') +
|
||||
'\n'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} name
|
||||
* @param {string} dest
|
||||
*/
|
||||
function transform(name, dest) {
|
||||
const source = fs
|
||||
.readFileSync(new URL(`./templates/${name}.js`, import.meta.url), 'utf-8')
|
||||
.replace(/\r\n/g, '\n');
|
||||
|
||||
/**
|
||||
* @type {Array<{
|
||||
* type: string;
|
||||
* value: string;
|
||||
* start: number;
|
||||
* end: number
|
||||
* }>}
|
||||
* @param {string} name
|
||||
* @param {string} dest
|
||||
*/
|
||||
const comments = [];
|
||||
|
||||
let ast = acorn.parse(source, {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
onComment: (block, value, start, end) => {
|
||||
if (block && /\n/.test(value)) {
|
||||
let a = start;
|
||||
while (a > 0 && source[a - 1] !== '\n') a -= 1;
|
||||
|
||||
let b = a;
|
||||
while (/[ \t]/.test(source[b])) b += 1;
|
||||
|
||||
const indentation = source.slice(a, b);
|
||||
value = value.replace(new RegExp(`^${indentation}`, 'gm'), '');
|
||||
}
|
||||
|
||||
comments.push({ type: block ? 'Block' : 'Line', value, start, end });
|
||||
}
|
||||
});
|
||||
function transform(name, dest) {
|
||||
const source = fs
|
||||
.readFileSync(new URL(`./templates/${name}.js`, import.meta.url), 'utf-8')
|
||||
.replace(/\r\n/g, '\n');
|
||||
|
||||
ast = walk(ast, null, {
|
||||
_(node, { next }) {
|
||||
let comment;
|
||||
/**
|
||||
* @type {Array<{
|
||||
* type: string;
|
||||
* value: string;
|
||||
* start: number;
|
||||
* end: number
|
||||
* }>}
|
||||
*/
|
||||
const comments = [];
|
||||
|
||||
let ast = acorn.parse(source, {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
onComment: (block, value, start, end) => {
|
||||
if (block && /\n/.test(value)) {
|
||||
let a = start;
|
||||
while (a > 0 && source[a - 1] !== '\n') a -= 1;
|
||||
|
||||
let b = a;
|
||||
while (/[ \t]/.test(source[b])) b += 1;
|
||||
|
||||
const indentation = source.slice(a, b);
|
||||
value = value.replace(new RegExp(`^${indentation}`, 'gm'), '');
|
||||
}
|
||||
|
||||
while (comments[0] && comments[0].start < node.start) {
|
||||
comment = comments.shift();
|
||||
// @ts-expect-error
|
||||
(node.leadingComments ||= []).push(comment);
|
||||
comments.push({ type: block ? 'Block' : 'Line', value, start, end });
|
||||
}
|
||||
});
|
||||
|
||||
next();
|
||||
|
||||
if (comments[0]) {
|
||||
const slice = source.slice(node.end, comments[0].start);
|
||||
ast = walk(ast, null, {
|
||||
_(node, { next }) {
|
||||
let comment;
|
||||
|
||||
if (/^[,) \t]*$/.test(slice)) {
|
||||
while (comments[0] && comments[0].start < node.start) {
|
||||
comment = comments.shift();
|
||||
// @ts-expect-error
|
||||
node.trailingComments = [comments.shift()];
|
||||
(node.leadingComments ||= []).push(comment);
|
||||
}
|
||||
}
|
||||
},
|
||||
// @ts-expect-error
|
||||
Identifier(node, context) {
|
||||
if (node.name === 'CODES') {
|
||||
return {
|
||||
type: 'ArrayExpression',
|
||||
elements: Object.keys(messages[name]).map((code) => ({
|
||||
type: 'Literal',
|
||||
value: code
|
||||
}))
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (comments.length > 0) {
|
||||
// @ts-expect-error
|
||||
(ast.trailingComments ||= []).push(...comments);
|
||||
}
|
||||
|
||||
const category = messages[name];
|
||||
|
||||
// find the `export function CODE` node
|
||||
const index = ast.body.findIndex((node) => {
|
||||
if (
|
||||
node.type === 'ExportNamedDeclaration' &&
|
||||
node.declaration &&
|
||||
node.declaration.type === 'FunctionDeclaration'
|
||||
) {
|
||||
return node.declaration.id.name === 'CODE';
|
||||
}
|
||||
});
|
||||
|
||||
if (index === -1) throw new Error(`missing export function CODE in ${name}.js`);
|
||||
|
||||
const template_node = ast.body[index];
|
||||
ast.body.splice(index, 1);
|
||||
next();
|
||||
|
||||
for (const code in category) {
|
||||
const { messages } = category[code];
|
||||
/** @type {string[]} */
|
||||
const vars = [];
|
||||
if (comments[0]) {
|
||||
const slice = source.slice(node.end, comments[0].start);
|
||||
|
||||
const group = messages.map((text, i) => {
|
||||
for (const match of text.matchAll(/%(\w+)%/g)) {
|
||||
const name = match[1];
|
||||
if (!vars.includes(name)) {
|
||||
vars.push(match[1]);
|
||||
if (/^[,) \t]*$/.test(slice)) {
|
||||
// @ts-expect-error
|
||||
node.trailingComments = [comments.shift()];
|
||||
}
|
||||
}
|
||||
},
|
||||
// @ts-expect-error
|
||||
Identifier(node, context) {
|
||||
if (node.name === 'CODES') {
|
||||
return {
|
||||
type: 'ArrayExpression',
|
||||
elements: Object.keys(messages[name]).map((code) => ({
|
||||
type: 'Literal',
|
||||
value: code
|
||||
}))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text,
|
||||
vars: vars.slice()
|
||||
};
|
||||
});
|
||||
|
||||
/** @type {import('estree').Expression} */
|
||||
let message = { type: 'Literal', value: '' };
|
||||
let prev_vars;
|
||||
if (comments.length > 0) {
|
||||
// @ts-expect-error
|
||||
(ast.trailingComments ||= []).push(...comments);
|
||||
}
|
||||
|
||||
for (let i = 0; i < group.length; i += 1) {
|
||||
const { text, vars } = group[i];
|
||||
const category = messages[name];
|
||||
|
||||
if (vars.length === 0) {
|
||||
message = {
|
||||
type: 'Literal',
|
||||
value: text
|
||||
};
|
||||
prev_vars = vars;
|
||||
continue;
|
||||
// find the `export function CODE` node
|
||||
const index = ast.body.findIndex((node) => {
|
||||
if (
|
||||
node.type === 'ExportNamedDeclaration' &&
|
||||
node.declaration &&
|
||||
node.declaration.type === 'FunctionDeclaration'
|
||||
) {
|
||||
return node.declaration.id.name === 'CODE';
|
||||
}
|
||||
});
|
||||
|
||||
const parts = text.split(/(%\w+%)/);
|
||||
if (index === -1) throw new Error(`missing export function CODE in ${name}.js`);
|
||||
|
||||
/** @type {import('estree').Expression[]} */
|
||||
const expressions = [];
|
||||
const template_node = ast.body[index];
|
||||
ast.body.splice(index, 1);
|
||||
|
||||
/** @type {import('estree').TemplateElement[]} */
|
||||
const quasis = [];
|
||||
for (const code in category) {
|
||||
const { messages } = category[code];
|
||||
/** @type {string[]} */
|
||||
const vars = [];
|
||||
|
||||
for (let i = 0; i < parts.length; i += 1) {
|
||||
const part = parts[i];
|
||||
if (i % 2 === 0) {
|
||||
const str = part.replace(/(`|\${)/g, '\\$1');
|
||||
quasis.push({
|
||||
type: 'TemplateElement',
|
||||
value: { raw: str, cooked: str },
|
||||
tail: i === parts.length - 1
|
||||
});
|
||||
} else {
|
||||
expressions.push({
|
||||
type: 'Identifier',
|
||||
name: part.slice(1, -1)
|
||||
});
|
||||
const group = messages.map((text, i) => {
|
||||
for (const match of text.matchAll(/%(\w+)%/g)) {
|
||||
const name = match[1];
|
||||
if (!vars.includes(name)) {
|
||||
vars.push(match[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text,
|
||||
vars: vars.slice()
|
||||
};
|
||||
});
|
||||
|
||||
/** @type {import('estree').Expression} */
|
||||
const expression = {
|
||||
type: 'TemplateLiteral',
|
||||
expressions,
|
||||
quasis
|
||||
};
|
||||
|
||||
if (prev_vars) {
|
||||
if (vars.length === prev_vars.length) {
|
||||
throw new Error('Message overloads must have new parameters');
|
||||
let message = { type: 'Literal', value: '' };
|
||||
let prev_vars;
|
||||
|
||||
for (let i = 0; i < group.length; i += 1) {
|
||||
const { text, vars } = group[i];
|
||||
|
||||
if (vars.length === 0) {
|
||||
message = {
|
||||
type: 'Literal',
|
||||
value: text
|
||||
};
|
||||
prev_vars = vars;
|
||||
continue;
|
||||
}
|
||||
|
||||
message = {
|
||||
type: 'ConditionalExpression',
|
||||
test: {
|
||||
type: 'Identifier',
|
||||
name: vars[prev_vars.length]
|
||||
},
|
||||
consequent: expression,
|
||||
alternate: message
|
||||
};
|
||||
} else {
|
||||
message = expression;
|
||||
}
|
||||
const parts = text.split(/(%\w+%)/);
|
||||
|
||||
prev_vars = vars;
|
||||
}
|
||||
/** @type {import('estree').Expression[]} */
|
||||
const expressions = [];
|
||||
|
||||
const clone = walk(/** @type {import('estree').Node} */ (template_node), null, {
|
||||
// @ts-expect-error Block is a block comment, which is not recognised
|
||||
Block(node, context) {
|
||||
if (!node.value.includes('PARAMETER')) return;
|
||||
|
||||
const value = /** @type {string} */ (node.value)
|
||||
.split('\n')
|
||||
.map((line) => {
|
||||
if (line === ' * MESSAGE') {
|
||||
return messages[messages.length - 1]
|
||||
.split('\n')
|
||||
.map((line) => ` * ${line}`)
|
||||
.join('\n');
|
||||
}
|
||||
/** @type {import('estree').TemplateElement[]} */
|
||||
const quasis = [];
|
||||
|
||||
if (line.includes('PARAMETER')) {
|
||||
return vars
|
||||
.map((name, i) => {
|
||||
const optional = i >= group[0].vars.length;
|
||||
for (let i = 0; i < parts.length; i += 1) {
|
||||
const part = parts[i];
|
||||
if (i % 2 === 0) {
|
||||
const str = part.replace(/(`|\${)/g, '\\$1');
|
||||
quasis.push({
|
||||
type: 'TemplateElement',
|
||||
value: { raw: str, cooked: str },
|
||||
tail: i === parts.length - 1
|
||||
});
|
||||
} else {
|
||||
expressions.push({
|
||||
type: 'Identifier',
|
||||
name: part.slice(1, -1)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return optional
|
||||
? ` * @param {string | undefined | null} [${name}]`
|
||||
: ` * @param {string} ${name}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
/** @type {import('estree').Expression} */
|
||||
const expression = {
|
||||
type: 'TemplateLiteral',
|
||||
expressions,
|
||||
quasis
|
||||
};
|
||||
|
||||
return line;
|
||||
})
|
||||
.filter((x) => x !== '')
|
||||
.join('\n');
|
||||
if (prev_vars) {
|
||||
if (vars.length === prev_vars.length) {
|
||||
throw new Error('Message overloads must have new parameters');
|
||||
}
|
||||
|
||||
if (value !== node.value) {
|
||||
return { ...node, value };
|
||||
message = {
|
||||
type: 'ConditionalExpression',
|
||||
test: {
|
||||
type: 'Identifier',
|
||||
name: vars[prev_vars.length]
|
||||
},
|
||||
consequent: expression,
|
||||
alternate: message
|
||||
};
|
||||
} else {
|
||||
message = expression;
|
||||
}
|
||||
},
|
||||
FunctionDeclaration(node, context) {
|
||||
if (node.id.name !== 'CODE') return;
|
||||
|
||||
const params = [];
|
||||
prev_vars = vars;
|
||||
}
|
||||
|
||||
for (const param of node.params) {
|
||||
if (param.type === 'Identifier' && param.name === 'PARAMETER') {
|
||||
params.push(...vars.map((name) => ({ type: 'Identifier', name })));
|
||||
} else {
|
||||
params.push(param);
|
||||
const clone = walk(/** @type {import('estree').Node} */ (template_node), null, {
|
||||
// @ts-expect-error Block is a block comment, which is not recognised
|
||||
Block(node, context) {
|
||||
if (!node.value.includes('PARAMETER')) return;
|
||||
|
||||
const value = /** @type {string} */ (node.value)
|
||||
.split('\n')
|
||||
.map((line) => {
|
||||
if (line === ' * MESSAGE') {
|
||||
return messages[messages.length - 1]
|
||||
.split('\n')
|
||||
.map((line) => ` * ${line}`)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
if (line.includes('PARAMETER')) {
|
||||
return vars
|
||||
.map((name, i) => {
|
||||
const optional = i >= group[0].vars.length;
|
||||
|
||||
return optional
|
||||
? ` * @param {string | undefined | null} [${name}]`
|
||||
: ` * @param {string} ${name}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
return line;
|
||||
})
|
||||
.filter((x) => x !== '')
|
||||
.join('\n');
|
||||
|
||||
if (value !== node.value) {
|
||||
return { ...node, value };
|
||||
}
|
||||
}
|
||||
},
|
||||
FunctionDeclaration(node, context) {
|
||||
if (node.id.name !== 'CODE') return;
|
||||
|
||||
const params = [];
|
||||
|
||||
return /** @type {import('estree').FunctionDeclaration} */ ({
|
||||
.../** @type {import('estree').FunctionDeclaration} */ (context.next()),
|
||||
params,
|
||||
id: {
|
||||
...node.id,
|
||||
name: code
|
||||
for (const param of node.params) {
|
||||
if (param.type === 'Identifier' && param.name === 'PARAMETER') {
|
||||
params.push(...vars.map((name) => ({ type: 'Identifier', name })));
|
||||
} else {
|
||||
params.push(param);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
TemplateLiteral(node, context) {
|
||||
/** @type {import('estree').TemplateElement} */
|
||||
let quasi = {
|
||||
type: 'TemplateElement',
|
||||
value: {
|
||||
...node.quasis[0].value
|
||||
},
|
||||
tail: node.quasis[0].tail
|
||||
};
|
||||
|
||||
/** @type {import('estree').TemplateLiteral} */
|
||||
let out = {
|
||||
type: 'TemplateLiteral',
|
||||
quasis: [quasi],
|
||||
expressions: []
|
||||
};
|
||||
return /** @type {import('estree').FunctionDeclaration} */ ({
|
||||
.../** @type {import('estree').FunctionDeclaration} */ (context.next()),
|
||||
params,
|
||||
id: {
|
||||
...node.id,
|
||||
name: code
|
||||
}
|
||||
});
|
||||
},
|
||||
TemplateLiteral(node, context) {
|
||||
/** @type {import('estree').TemplateElement} */
|
||||
let quasi = {
|
||||
type: 'TemplateElement',
|
||||
value: {
|
||||
...node.quasis[0].value
|
||||
},
|
||||
tail: node.quasis[0].tail
|
||||
};
|
||||
|
||||
for (let i = 0; i < node.expressions.length; i += 1) {
|
||||
const q = structuredClone(node.quasis[i + 1]);
|
||||
const e = node.expressions[i];
|
||||
/** @type {import('estree').TemplateLiteral} */
|
||||
let out = {
|
||||
type: 'TemplateLiteral',
|
||||
quasis: [quasi],
|
||||
expressions: []
|
||||
};
|
||||
|
||||
if (e.type === 'Literal' && e.value === 'CODE') {
|
||||
quasi.value.raw += code + q.value.raw;
|
||||
continue;
|
||||
}
|
||||
for (let i = 0; i < node.expressions.length; i += 1) {
|
||||
const q = structuredClone(node.quasis[i + 1]);
|
||||
const e = node.expressions[i];
|
||||
|
||||
if (e.type === 'Identifier' && e.name === 'MESSAGE') {
|
||||
if (message.type === 'Literal') {
|
||||
const str = /** @type {string} */ (message.value).replace(/(`|\${)/g, '\\$1');
|
||||
quasi.value.raw += str + q.value.raw;
|
||||
if (e.type === 'Literal' && e.value === 'CODE') {
|
||||
quasi.value.raw += code + q.value.raw;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (message.type === 'TemplateLiteral') {
|
||||
const m = structuredClone(message);
|
||||
quasi.value.raw += m.quasis[0].value.raw;
|
||||
out.quasis.push(...m.quasis.slice(1));
|
||||
out.expressions.push(...m.expressions);
|
||||
quasi = m.quasis[m.quasis.length - 1];
|
||||
quasi.value.raw += q.value.raw;
|
||||
continue;
|
||||
if (e.type === 'Identifier' && e.name === 'MESSAGE') {
|
||||
if (message.type === 'Literal') {
|
||||
const str = /** @type {string} */ (message.value).replace(/(`|\${)/g, '\\$1');
|
||||
quasi.value.raw += str + q.value.raw;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (message.type === 'TemplateLiteral') {
|
||||
const m = structuredClone(message);
|
||||
quasi.value.raw += m.quasis[0].value.raw;
|
||||
out.quasis.push(...m.quasis.slice(1));
|
||||
out.expressions.push(...m.expressions);
|
||||
quasi = m.quasis[m.quasis.length - 1];
|
||||
quasi.value.raw += q.value.raw;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
out.quasis.push((quasi = q));
|
||||
out.expressions.push(/** @type {import('estree').Expression} */ (context.visit(e)));
|
||||
}
|
||||
|
||||
out.quasis.push((quasi = q));
|
||||
out.expressions.push(/** @type {import('estree').Expression} */ (context.visit(e)));
|
||||
return out;
|
||||
},
|
||||
Literal(node) {
|
||||
if (node.value === 'CODE') {
|
||||
return {
|
||||
type: 'Literal',
|
||||
value: code
|
||||
};
|
||||
}
|
||||
},
|
||||
Identifier(node) {
|
||||
if (node.name !== 'MESSAGE') return;
|
||||
return message;
|
||||
}
|
||||
});
|
||||
|
||||
return out;
|
||||
},
|
||||
Literal(node) {
|
||||
if (node.value === 'CODE') {
|
||||
return {
|
||||
type: 'Literal',
|
||||
value: code
|
||||
};
|
||||
}
|
||||
},
|
||||
Identifier(node) {
|
||||
if (node.name !== 'MESSAGE') return;
|
||||
return message;
|
||||
}
|
||||
});
|
||||
// @ts-expect-error
|
||||
ast.body.push(clone);
|
||||
}
|
||||
|
||||
const module = esrap.print(ast);
|
||||
|
||||
// @ts-expect-error
|
||||
ast.body.push(clone);
|
||||
fs.writeFileSync(
|
||||
dest,
|
||||
`/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\n` +
|
||||
module.code,
|
||||
'utf-8'
|
||||
);
|
||||
}
|
||||
|
||||
const module = esrap.print(ast);
|
||||
transform('compile-errors', 'src/compiler/errors.js');
|
||||
transform('compile-warnings', 'src/compiler/warnings.js');
|
||||
|
||||
fs.writeFileSync(
|
||||
dest,
|
||||
`/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\n` +
|
||||
module.code,
|
||||
'utf-8'
|
||||
);
|
||||
transform('client-warnings', 'src/internal/client/warnings.js');
|
||||
transform('client-errors', 'src/internal/client/errors.js');
|
||||
transform('server-errors', 'src/internal/server/errors.js');
|
||||
transform('shared-errors', 'src/internal/shared/errors.js');
|
||||
transform('shared-warnings', 'src/internal/shared/warnings.js');
|
||||
}
|
||||
|
||||
transform('compile-errors', 'src/compiler/errors.js');
|
||||
transform('compile-warnings', 'src/compiler/warnings.js');
|
||||
if (watch) {
|
||||
let running = false;
|
||||
let timeout;
|
||||
|
||||
fs.watch('messages', { recursive: true }, (type, file) => {
|
||||
if (running) {
|
||||
timeout ??= setTimeout(() => {
|
||||
running = false;
|
||||
timeout = null;
|
||||
});
|
||||
} else {
|
||||
running = true;
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('Regenerating messages...');
|
||||
run();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
transform('client-warnings', 'src/internal/client/warnings.js');
|
||||
transform('client-errors', 'src/internal/client/errors.js');
|
||||
transform('server-errors', 'src/internal/server/errors.js');
|
||||
transform('shared-errors', 'src/internal/shared/errors.js');
|
||||
transform('shared-warnings', 'src/internal/shared/warnings.js');
|
||||
run();
|
||||
|
@ -1,30 +1,107 @@
|
||||
/** @import { ClassBody } from 'estree' */
|
||||
/** @import { AssignmentExpression, CallExpression, ClassBody, PropertyDefinition, Expression, PrivateIdentifier, MethodDefinition } from 'estree' */
|
||||
/** @import { StateField } from '#compiler' */
|
||||
/** @import { Context } from '../types' */
|
||||
import * as b from '#compiler/builders';
|
||||
import { get_rune } from '../../scope.js';
|
||||
import * as e from '../../../errors.js';
|
||||
import { is_state_creation_rune } from '../../../../utils.js';
|
||||
import { get_name } from '../../nodes.js';
|
||||
import { regex_invalid_identifier_chars } from '../../patterns.js';
|
||||
|
||||
/**
|
||||
* @param {ClassBody} node
|
||||
* @param {Context} context
|
||||
*/
|
||||
export function ClassBody(node, context) {
|
||||
/** @type {{name: string, private: boolean}[]} */
|
||||
const derived_state = [];
|
||||
if (!context.state.analysis.runes) {
|
||||
context.next();
|
||||
return;
|
||||
}
|
||||
|
||||
/** @type {string[]} */
|
||||
const private_ids = [];
|
||||
|
||||
for (const definition of node.body) {
|
||||
for (const prop of node.body) {
|
||||
if (
|
||||
definition.type === 'PropertyDefinition' &&
|
||||
(definition.key.type === 'PrivateIdentifier' || definition.key.type === 'Identifier') &&
|
||||
definition.value?.type === 'CallExpression'
|
||||
(prop.type === 'MethodDefinition' || prop.type === 'PropertyDefinition') &&
|
||||
prop.key.type === 'PrivateIdentifier'
|
||||
) {
|
||||
const rune = get_rune(definition.value, context.state.scope);
|
||||
if (rune === '$derived' || rune === '$derived.by') {
|
||||
derived_state.push({
|
||||
name: definition.key.name,
|
||||
private: definition.key.type === 'PrivateIdentifier'
|
||||
});
|
||||
private_ids.push(prop.key.name);
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {Map<string, StateField>} */
|
||||
const state_fields = new Map();
|
||||
|
||||
context.state.analysis.classes.set(node, state_fields);
|
||||
|
||||
/** @type {MethodDefinition | null} */
|
||||
let constructor = null;
|
||||
|
||||
/**
|
||||
* @param {PropertyDefinition | AssignmentExpression} node
|
||||
* @param {Expression | PrivateIdentifier} key
|
||||
* @param {Expression | null | undefined} value
|
||||
*/
|
||||
function handle(node, key, value) {
|
||||
const name = get_name(key);
|
||||
if (name === null) return;
|
||||
|
||||
const rune = get_rune(value, context.state.scope);
|
||||
|
||||
if (rune && is_state_creation_rune(rune)) {
|
||||
if (state_fields.has(name)) {
|
||||
e.state_field_duplicate(node, name);
|
||||
}
|
||||
|
||||
state_fields.set(name, {
|
||||
node,
|
||||
type: rune,
|
||||
// @ts-expect-error for public state this is filled out in a moment
|
||||
key: key.type === 'PrivateIdentifier' ? key : null,
|
||||
value: /** @type {CallExpression} */ (value)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const child of node.body) {
|
||||
if (child.type === 'PropertyDefinition' && !child.computed && !child.static) {
|
||||
handle(child, child.key, child.value);
|
||||
}
|
||||
|
||||
if (child.type === 'MethodDefinition' && child.kind === 'constructor') {
|
||||
constructor = child;
|
||||
}
|
||||
}
|
||||
|
||||
if (constructor) {
|
||||
for (const statement of constructor.value.body.body) {
|
||||
if (statement.type !== 'ExpressionStatement') continue;
|
||||
if (statement.expression.type !== 'AssignmentExpression') continue;
|
||||
|
||||
const { left, right } = statement.expression;
|
||||
|
||||
if (left.type !== 'MemberExpression') continue;
|
||||
if (left.object.type !== 'ThisExpression') continue;
|
||||
if (left.computed && left.property.type !== 'Literal') continue;
|
||||
|
||||
handle(statement.expression, left.property, right);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, field] of state_fields) {
|
||||
if (name[0] === '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let deconflicted = name.replace(regex_invalid_identifier_chars, '_');
|
||||
while (private_ids.includes(deconflicted)) {
|
||||
deconflicted = '_' + deconflicted;
|
||||
}
|
||||
|
||||
private_ids.push(deconflicted);
|
||||
field.key = b.private_id(deconflicted);
|
||||
}
|
||||
|
||||
context.next({ ...context.state, derived_state });
|
||||
context.next({ ...context.state, state_fields });
|
||||
}
|
||||
|
@ -0,0 +1,21 @@
|
||||
/** @import { PropertyDefinition } from 'estree' */
|
||||
/** @import { Context } from '../types' */
|
||||
import * as e from '../../../errors.js';
|
||||
import { get_name } from '../../nodes.js';
|
||||
|
||||
/**
|
||||
* @param {PropertyDefinition} node
|
||||
* @param {Context} context
|
||||
*/
|
||||
export function PropertyDefinition(node, context) {
|
||||
const name = get_name(node.key);
|
||||
const field = name && context.state.state_fields.get(name);
|
||||
|
||||
if (field && node !== field.node && node.value) {
|
||||
if (/** @type {number} */ (node.start) < /** @type {number} */ (field.node.start)) {
|
||||
e.state_field_invalid_assignment(node);
|
||||
}
|
||||
}
|
||||
|
||||
context.next();
|
||||
}
|
@ -1,184 +1,96 @@
|
||||
/** @import { ClassBody, Expression, Identifier, Literal, MethodDefinition, PrivateIdentifier, PropertyDefinition } from 'estree' */
|
||||
/** @import { Context, StateField } from '../types' */
|
||||
/** @import { CallExpression, ClassBody, MethodDefinition, PropertyDefinition, StaticBlock } from 'estree' */
|
||||
/** @import { StateField } from '#compiler' */
|
||||
/** @import { Context } from '../types' */
|
||||
import * as b from '#compiler/builders';
|
||||
import { regex_invalid_identifier_chars } from '../../../patterns.js';
|
||||
import { get_rune } from '../../../scope.js';
|
||||
import { should_proxy } from '../utils.js';
|
||||
import { get_name } from '../../../nodes.js';
|
||||
|
||||
/**
|
||||
* @param {ClassBody} node
|
||||
* @param {Context} context
|
||||
*/
|
||||
export function ClassBody(node, context) {
|
||||
if (!context.state.analysis.runes) {
|
||||
const state_fields = context.state.analysis.classes.get(node);
|
||||
|
||||
if (!state_fields) {
|
||||
// in legacy mode, do nothing
|
||||
context.next();
|
||||
return;
|
||||
}
|
||||
|
||||
/** @type {Map<string, StateField>} */
|
||||
const public_state = new Map();
|
||||
/** @type {Array<MethodDefinition | PropertyDefinition | StaticBlock>} */
|
||||
const body = [];
|
||||
|
||||
/** @type {Map<string, StateField>} */
|
||||
const private_state = new Map();
|
||||
const child_state = { ...context.state, state_fields };
|
||||
|
||||
/** @type {Map<(MethodDefinition|PropertyDefinition)["key"], string>} */
|
||||
const definition_names = new Map();
|
||||
for (const [name, field] of state_fields) {
|
||||
if (name[0] === '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
/** @type {string[]} */
|
||||
const private_ids = [];
|
||||
// insert backing fields for stuff declared in the constructor
|
||||
if (field.node.type === 'AssignmentExpression') {
|
||||
const member = b.member(b.this, field.key);
|
||||
|
||||
for (const definition of node.body) {
|
||||
if (
|
||||
(definition.type === 'PropertyDefinition' || definition.type === 'MethodDefinition') &&
|
||||
(definition.key.type === 'Identifier' ||
|
||||
definition.key.type === 'PrivateIdentifier' ||
|
||||
definition.key.type === 'Literal')
|
||||
) {
|
||||
const type = definition.key.type;
|
||||
const name = get_name(definition.key, public_state);
|
||||
if (!name) continue;
|
||||
|
||||
// we store the deconflicted name in the map so that we can access it later
|
||||
definition_names.set(definition.key, name);
|
||||
|
||||
const is_private = type === 'PrivateIdentifier';
|
||||
if (is_private) private_ids.push(name);
|
||||
|
||||
if (definition.value?.type === 'CallExpression') {
|
||||
const rune = get_rune(definition.value, context.state.scope);
|
||||
if (
|
||||
rune === '$state' ||
|
||||
rune === '$state.raw' ||
|
||||
rune === '$derived' ||
|
||||
rune === '$derived.by'
|
||||
) {
|
||||
/** @type {StateField} */
|
||||
const field = {
|
||||
kind:
|
||||
rune === '$state'
|
||||
? 'state'
|
||||
: rune === '$state.raw'
|
||||
? 'raw_state'
|
||||
: rune === '$derived.by'
|
||||
? 'derived_by'
|
||||
: 'derived',
|
||||
// @ts-expect-error this is set in the next pass
|
||||
id: is_private ? definition.key : null
|
||||
};
|
||||
|
||||
if (is_private) {
|
||||
private_state.set(name, field);
|
||||
} else {
|
||||
public_state.set(name, field);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const should_proxy = field.type === '$state' && true; // TODO
|
||||
|
||||
// each `foo = $state()` needs a backing `#foo` field
|
||||
for (const [name, field] of public_state) {
|
||||
let deconflicted = name;
|
||||
while (private_ids.includes(deconflicted)) {
|
||||
deconflicted = '_' + deconflicted;
|
||||
}
|
||||
const key = b.key(name);
|
||||
|
||||
private_ids.push(deconflicted);
|
||||
field.id = b.private_id(deconflicted);
|
||||
}
|
||||
body.push(
|
||||
b.prop_def(field.key, null),
|
||||
|
||||
/** @type {Array<MethodDefinition | PropertyDefinition>} */
|
||||
const body = [];
|
||||
b.method('get', key, [], [b.return(b.call('$.get', member))]),
|
||||
|
||||
const child_state = { ...context.state, public_state, private_state };
|
||||
b.method(
|
||||
'set',
|
||||
key,
|
||||
[b.id('value')],
|
||||
[b.stmt(b.call('$.set', member, b.id('value'), should_proxy && b.true))]
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Replace parts of the class body
|
||||
for (const definition of node.body) {
|
||||
if (
|
||||
definition.type === 'PropertyDefinition' &&
|
||||
(definition.key.type === 'Identifier' ||
|
||||
definition.key.type === 'PrivateIdentifier' ||
|
||||
definition.key.type === 'Literal')
|
||||
) {
|
||||
const name = definition_names.get(definition.key);
|
||||
if (!name) continue;
|
||||
|
||||
const is_private = definition.key.type === 'PrivateIdentifier';
|
||||
const field = (is_private ? private_state : public_state).get(name);
|
||||
|
||||
if (definition.value?.type === 'CallExpression' && field !== undefined) {
|
||||
let value = null;
|
||||
|
||||
if (definition.value.arguments.length > 0) {
|
||||
const init = /** @type {Expression} **/ (
|
||||
context.visit(definition.value.arguments[0], child_state)
|
||||
);
|
||||
|
||||
value =
|
||||
field.kind === 'state'
|
||||
? b.call(
|
||||
'$.state',
|
||||
should_proxy(init, context.state.scope) ? b.call('$.proxy', init) : init
|
||||
)
|
||||
: field.kind === 'raw_state'
|
||||
? b.call('$.state', init)
|
||||
: field.kind === 'derived_by'
|
||||
? b.call('$.derived', init)
|
||||
: b.call('$.derived', b.thunk(init));
|
||||
} else {
|
||||
// if no arguments, we know it's state as `$derived()` is a compile error
|
||||
value = b.call('$.state');
|
||||
}
|
||||
|
||||
if (is_private) {
|
||||
body.push(b.prop_def(field.id, value));
|
||||
} else {
|
||||
// #foo;
|
||||
const member = b.member(b.this, field.id);
|
||||
body.push(b.prop_def(field.id, value));
|
||||
|
||||
// get foo() { return this.#foo; }
|
||||
body.push(b.method('get', definition.key, [], [b.return(b.call('$.get', member))]));
|
||||
|
||||
// set foo(value) { this.#foo = value; }
|
||||
const val = b.id('value');
|
||||
|
||||
body.push(
|
||||
b.method(
|
||||
'set',
|
||||
definition.key,
|
||||
[val],
|
||||
[b.stmt(b.call('$.set', member, val, field.kind === 'state' && b.true))]
|
||||
)
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (definition.type !== 'PropertyDefinition') {
|
||||
body.push(
|
||||
/** @type {MethodDefinition | StaticBlock} */ (context.visit(definition, child_state))
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
body.push(/** @type {MethodDefinition} **/ (context.visit(definition, child_state)));
|
||||
}
|
||||
const name = get_name(definition.key);
|
||||
const field = name && /** @type {StateField} */ (state_fields.get(name));
|
||||
|
||||
return { ...node, body };
|
||||
}
|
||||
if (!field) {
|
||||
body.push(/** @type {PropertyDefinition} */ (context.visit(definition, child_state)));
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Identifier | PrivateIdentifier | Literal} node
|
||||
* @param {Map<string, StateField>} public_state
|
||||
*/
|
||||
function get_name(node, public_state) {
|
||||
if (node.type === 'Literal') {
|
||||
let name = node.value?.toString().replace(regex_invalid_identifier_chars, '_');
|
||||
|
||||
// the above could generate conflicts because it has to generate a valid identifier
|
||||
// so stuff like `0` and `1` or `state%` and `state^` will result in the same string
|
||||
// so we have to de-conflict. We can only check `public_state` because private state
|
||||
// can't have literal keys
|
||||
while (name && public_state.has(name)) {
|
||||
name = '_' + name;
|
||||
if (name[0] === '#') {
|
||||
body.push(/** @type {PropertyDefinition} */ (context.visit(definition, child_state)));
|
||||
} else if (field.node === definition) {
|
||||
const member = b.member(b.this, field.key);
|
||||
|
||||
const should_proxy = field.type === '$state' && true; // TODO
|
||||
|
||||
body.push(
|
||||
b.prop_def(
|
||||
field.key,
|
||||
/** @type {CallExpression} */ (context.visit(field.value, child_state))
|
||||
),
|
||||
|
||||
b.method('get', definition.key, [], [b.return(b.call('$.get', member))]),
|
||||
|
||||
b.method(
|
||||
'set',
|
||||
definition.key,
|
||||
[b.id('value')],
|
||||
[b.stmt(b.call('$.set', member, b.id('value'), should_proxy && b.true))]
|
||||
)
|
||||
);
|
||||
}
|
||||
return name;
|
||||
} else {
|
||||
return node.name;
|
||||
}
|
||||
|
||||
return { ...node, body };
|
||||
}
|
||||
|
@ -1,23 +0,0 @@
|
||||
/** @import { MemberExpression } from 'estree' */
|
||||
/** @import { Context } from '../types.js' */
|
||||
import * as b from '#compiler/builders';
|
||||
|
||||
/**
|
||||
* @param {MemberExpression} node
|
||||
* @param {Context} context
|
||||
*/
|
||||
export function MemberExpression(node, context) {
|
||||
if (
|
||||
context.state.analysis.runes &&
|
||||
node.object.type === 'ThisExpression' &&
|
||||
node.property.type === 'PrivateIdentifier'
|
||||
) {
|
||||
const field = context.state.private_derived.get(node.property.name);
|
||||
|
||||
if (field) {
|
||||
return b.call(node);
|
||||
}
|
||||
}
|
||||
|
||||
context.next();
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
import { flushSync } from 'svelte';
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({
|
||||
html: `<button>10</button>`,
|
||||
ssrHtml: `<button>0</button>`,
|
||||
|
||||
async test({ assert, target }) {
|
||||
flushSync();
|
||||
|
||||
assert.htmlEqual(target.innerHTML, `<button>10</button>`);
|
||||
}
|
||||
});
|
@ -0,0 +1,13 @@
|
||||
<script>
|
||||
class Counter {
|
||||
constructor() {
|
||||
this.count = $state(0);
|
||||
$effect(() => {
|
||||
this.count = 10;
|
||||
});
|
||||
}
|
||||
}
|
||||
const counter = new Counter();
|
||||
</script>
|
||||
|
||||
<button on:click={() => counter.count++}>{counter.count}</button>
|
@ -0,0 +1,13 @@
|
||||
import { flushSync } from 'svelte';
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({
|
||||
html: `<button>10</button>`,
|
||||
ssrHtml: `<button>0</button>`,
|
||||
|
||||
async test({ assert, target }) {
|
||||
flushSync();
|
||||
|
||||
assert.htmlEqual(target.innerHTML, `<button>10</button>`);
|
||||
}
|
||||
});
|
@ -0,0 +1,12 @@
|
||||
<script>
|
||||
const counter = new class Counter {
|
||||
constructor() {
|
||||
this.count = $state(0);
|
||||
$effect(() => {
|
||||
this.count = 10;
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<button on:click={() => counter.count++}>{counter.count}</button>
|
@ -0,0 +1,3 @@
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({});
|
@ -0,0 +1,9 @@
|
||||
<script>
|
||||
class Test {
|
||||
0 = $state();
|
||||
|
||||
constructor() {
|
||||
this[1] = $state();
|
||||
}
|
||||
}
|
||||
</script>
|
@ -0,0 +1,45 @@
|
||||
import { flushSync } from 'svelte';
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({
|
||||
// The component context class instance gets shared between tests, strangely, causing hydration to fail?
|
||||
mode: ['client', 'server'],
|
||||
|
||||
async test({ assert, target, logs }) {
|
||||
const btn = target.querySelector('button');
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
|
||||
assert.deepEqual(logs, [0, 'class trigger false', 'local trigger false', 1]);
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
|
||||
assert.deepEqual(logs, [0, 'class trigger false', 'local trigger false', 1, 2]);
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
|
||||
assert.deepEqual(logs, [0, 'class trigger false', 'local trigger false', 1, 2, 3]);
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
|
||||
assert.deepEqual(logs, [
|
||||
0,
|
||||
'class trigger false',
|
||||
'local trigger false',
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
'class trigger true',
|
||||
'local trigger true'
|
||||
]);
|
||||
}
|
||||
});
|
@ -0,0 +1,37 @@
|
||||
<script module>
|
||||
class SomeLogic {
|
||||
trigger() {
|
||||
this.someValue++;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.someValue = $state(0);
|
||||
this.isAboveThree = $derived(this.someValue > 3);
|
||||
}
|
||||
}
|
||||
|
||||
const someLogic = new SomeLogic();
|
||||
</script>
|
||||
|
||||
<script>
|
||||
function increment() {
|
||||
someLogic.trigger();
|
||||
}
|
||||
|
||||
let localDerived = $derived(someLogic.someValue > 3);
|
||||
|
||||
$effect(() => {
|
||||
console.log(someLogic.someValue);
|
||||
});
|
||||
$effect(() => {
|
||||
console.log('class trigger ' + someLogic.isAboveThree)
|
||||
});
|
||||
$effect(() => {
|
||||
console.log('local trigger ' + localDerived)
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<button on:click={increment}>
|
||||
clicks: {someLogic.someValue}
|
||||
</button>
|
@ -0,0 +1,20 @@
|
||||
import { flushSync } from 'svelte';
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({
|
||||
html: `<button>0</button>`,
|
||||
|
||||
test({ assert, target }) {
|
||||
const btn = target.querySelector('button');
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
assert.htmlEqual(target.innerHTML, `<button>1</button>`);
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
assert.htmlEqual(target.innerHTML, `<button>2</button>`);
|
||||
}
|
||||
});
|
@ -0,0 +1,12 @@
|
||||
<script>
|
||||
class Counter {
|
||||
count;
|
||||
|
||||
constructor(count) {
|
||||
this.count = $state(count);
|
||||
}
|
||||
}
|
||||
const counter = new Counter(0);
|
||||
</script>
|
||||
|
||||
<button onclick={() => counter.count++}>{counter.count}</button>
|
@ -0,0 +1,20 @@
|
||||
import { flushSync } from 'svelte';
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({
|
||||
html: `<button>10: 20</button>`,
|
||||
|
||||
test({ assert, target }) {
|
||||
const btn = target.querySelector('button');
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
assert.htmlEqual(target.innerHTML, `<button>11: 22</button>`);
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
assert.htmlEqual(target.innerHTML, `<button>12: 24</button>`);
|
||||
}
|
||||
});
|
@ -0,0 +1,22 @@
|
||||
<script>
|
||||
class Counter {
|
||||
constructor(initial) {
|
||||
this.count = $state(initial);
|
||||
}
|
||||
|
||||
increment = () => {
|
||||
this.count++;
|
||||
}
|
||||
}
|
||||
|
||||
class PluggableCounter extends Counter {
|
||||
constructor(initial, plugin) {
|
||||
super(initial)
|
||||
this.custom = $derived(plugin(this.count));
|
||||
}
|
||||
}
|
||||
|
||||
const counter = new PluggableCounter(10, (count) => count * 2);
|
||||
</script>
|
||||
|
||||
<button onclick={counter.increment}>{counter.count}: {counter.custom}</button>
|
@ -0,0 +1,20 @@
|
||||
import { flushSync } from 'svelte';
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({
|
||||
html: `<button>20</button>`,
|
||||
|
||||
test({ assert, target }) {
|
||||
const btn = target.querySelector('button');
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
assert.htmlEqual(target.innerHTML, `<button>22</button>`);
|
||||
|
||||
flushSync(() => {
|
||||
btn?.click();
|
||||
});
|
||||
assert.htmlEqual(target.innerHTML, `<button>24</button>`);
|
||||
}
|
||||
});
|
@ -0,0 +1,18 @@
|
||||
<script>
|
||||
class Counter {
|
||||
/** @type {number} */
|
||||
#count;
|
||||
|
||||
constructor(initial) {
|
||||
this.#count = $state(initial);
|
||||
this.doubled = $derived(this.#count * 2);
|
||||
}
|
||||
|
||||
increment = () => {
|
||||
this.#count++;
|
||||
}
|
||||
}
|
||||
const counter = new Counter(10);
|
||||
</script>
|
||||
|
||||
<button onclick={counter.increment}>{counter.doubled}</button>
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_duplicate",
|
||||
"message": "`count` has already been declared on this class",
|
||||
"start": {
|
||||
"line": 5,
|
||||
"column": 2
|
||||
},
|
||||
"end": {
|
||||
"line": 5,
|
||||
"column": 24
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,7 @@
|
||||
export class Counter {
|
||||
count = $state(0);
|
||||
|
||||
constructor() {
|
||||
this.count = $state(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_invalid_assignment",
|
||||
"message": "Cannot assign to a state field before its declaration",
|
||||
"start": {
|
||||
"line": 4,
|
||||
"column": 3
|
||||
},
|
||||
"end": {
|
||||
"line": 4,
|
||||
"column": 18
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,9 @@
|
||||
export class Counter {
|
||||
constructor() {
|
||||
if (true) {
|
||||
this.count = -1;
|
||||
}
|
||||
|
||||
this.count = $state(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_duplicate",
|
||||
"message": "`count` has already been declared on this class",
|
||||
"start": {
|
||||
"line": 5,
|
||||
"column": 2
|
||||
},
|
||||
"end": {
|
||||
"line": 5,
|
||||
"column": 24
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,7 @@
|
||||
export class Counter {
|
||||
constructor() {
|
||||
this.count = $state(0);
|
||||
this.count = 1;
|
||||
this.count = $state(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_duplicate",
|
||||
"message": "`count` has already been declared on this class",
|
||||
"start": {
|
||||
"line": 5,
|
||||
"column": 2
|
||||
},
|
||||
"end": {
|
||||
"line": 5,
|
||||
"column": 28
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,7 @@
|
||||
export class Counter {
|
||||
constructor() {
|
||||
this.count = $state(0);
|
||||
this.count = 1;
|
||||
this.count = $state.raw(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_invalid_placement",
|
||||
"message": "`$state(...)` can only be used as a variable declaration initializer, a class field declaration, or the first assignment to a class field at the top level of the constructor.",
|
||||
"start": {
|
||||
"line": 4,
|
||||
"column": 16
|
||||
},
|
||||
"end": {
|
||||
"line": 4,
|
||||
"column": 25
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,7 @@
|
||||
export class Counter {
|
||||
constructor() {
|
||||
if (true) {
|
||||
this.count = $state(0);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_duplicate",
|
||||
"message": "`count` has already been declared on this class",
|
||||
"start": {
|
||||
"line": 5,
|
||||
"column": 2
|
||||
},
|
||||
"end": {
|
||||
"line": 5,
|
||||
"column": 27
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,7 @@
|
||||
export class Counter {
|
||||
// prettier-ignore
|
||||
'count' = $state(0);
|
||||
constructor() {
|
||||
this['count'] = $state(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_duplicate",
|
||||
"message": "`count` has already been declared on this class",
|
||||
"start": {
|
||||
"line": 4,
|
||||
"column": 2
|
||||
},
|
||||
"end": {
|
||||
"line": 4,
|
||||
"column": 27
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,6 @@
|
||||
export class Counter {
|
||||
count = $state(0);
|
||||
constructor() {
|
||||
this['count'] = $state(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_invalid_placement",
|
||||
"message": "`$state(...)` can only be used as a variable declaration initializer, a class field declaration, or the first assignment to a class field at the top level of the constructor.",
|
||||
"start": {
|
||||
"line": 5,
|
||||
"column": 16
|
||||
},
|
||||
"end": {
|
||||
"line": 5,
|
||||
"column": 25
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,7 @@
|
||||
const count = 'count';
|
||||
|
||||
export class Counter {
|
||||
constructor() {
|
||||
this[count] = $state(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_invalid_assignment",
|
||||
"message": "Cannot assign to a state field before its declaration",
|
||||
"start": {
|
||||
"line": 3,
|
||||
"column": 2
|
||||
},
|
||||
"end": {
|
||||
"line": 3,
|
||||
"column": 17
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,6 @@
|
||||
export class Counter {
|
||||
constructor() {
|
||||
this.count = -1;
|
||||
this.count = $state(0);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"code": "state_field_invalid_assignment",
|
||||
"message": "Cannot assign to a state field before its declaration",
|
||||
"start": {
|
||||
"line": 2,
|
||||
"column": 1
|
||||
},
|
||||
"end": {
|
||||
"line": 2,
|
||||
"column": 12
|
||||
}
|
||||
}
|
||||
]
|
@ -0,0 +1,7 @@
|
||||
export class Counter {
|
||||
count = -1;
|
||||
|
||||
constructor() {
|
||||
this.count = $state(0);
|
||||
}
|
||||
}
|
Loading…
Reference in new issue