This commit is contained in:
2026-11-02 12:42:04 +00:00
commit e4e28174bf
5498 changed files with 1735888 additions and 0 deletions

21
node_modules/svelte-eslint-parser/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Yosuke Ota
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

356
node_modules/svelte-eslint-parser/README.md generated vendored Normal file
View File

@@ -0,0 +1,356 @@
[![NPM license](https://img.shields.io/npm/l/svelte-eslint-parser.svg)](https://www.npmjs.com/package/svelte-eslint-parser)
[![NPM version](https://img.shields.io/npm/v/svelte-eslint-parser.svg)](https://www.npmjs.com/package/svelte-eslint-parser)
[![NPM downloads](https://img.shields.io/badge/dynamic/json.svg?label=downloads&colorB=green&suffix=/day&query=$.downloads&uri=https://api.npmjs.org//downloads/point/last-day/svelte-eslint-parser&maxAge=3600)](http://www.npmtrends.com/svelte-eslint-parser)
[![NPM downloads](https://img.shields.io/npm/dw/svelte-eslint-parser.svg)](http://www.npmtrends.com/svelte-eslint-parser)
[![NPM downloads](https://img.shields.io/npm/dm/svelte-eslint-parser.svg)](http://www.npmtrends.com/svelte-eslint-parser)
[![NPM downloads](https://img.shields.io/npm/dy/svelte-eslint-parser.svg)](http://www.npmtrends.com/svelte-eslint-parser)
[![NPM downloads](https://img.shields.io/npm/dt/svelte-eslint-parser.svg)](http://www.npmtrends.com/svelte-eslint-parser)
[![Build Status](https://github.com/sveltejs/svelte-eslint-parser/workflows/CI/badge.svg?branch=main)](https://github.com/sveltejs/svelte-eslint-parser/actions?query=workflow%3ACI)
[![Coverage Status](https://coveralls.io/repos/github/sveltejs/svelte-eslint-parser/badge.svg?branch=main)](https://coveralls.io/github/sveltejs/svelte-eslint-parser?branch=main)
<div align="center">
# svelte-eslint-parser
## [Svelte](https://svelte.dev/) parser for [ESLint](https://eslint.org/)
[Live DEMO](https://sveltejs.github.io/svelte-eslint-parser/playground) •
[Discord](https://svelte.dev/chat)
</div>
## Motivation
The `svelte-eslint-parser` aims to make it easy to create your own ESLint rules for [Svelte](https://svelte.dev/).
[eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte) is an ESLint plugin built upon this parser, and it already [implements some rules](https://sveltejs.github.io/eslint-plugin-svelte/rules/).
### ESLint Plugins Using svelte-eslint-parser
#### [eslint-plugin-svelte](https://sveltejs.github.io/eslint-plugin-svelte/)
ESLint plugin for Svelte.
Provides a variety of template-based checks using the Svelte AST.
#### [@intlify/eslint-plugin-svelte](https://github.com/intlify/eslint-plugin-svelte)
ESLint plugin for internationalization (i18n) in Svelte applications, offering helpful i18n-related rules.
---
## Installation
```bash
npm install --save-dev eslint svelte-eslint-parser
```
---
## Usage
### ESLint Config (`eslint.config.js`)
```js
import js from "@eslint/js";
import svelteParser from "svelte-eslint-parser";
export default [
js.configs.recommended,
{
files: [
"**/*.svelte",
"*.svelte",
// Need to specify the file extension for Svelte 5 with rune symbols
"**/*.svelte.js",
"*.svelte.js",
"**/*.svelte.ts",
"*.svelte.ts",
],
languageOptions: {
parser: svelteParser,
},
},
];
```
### CLI
```bash
eslint "src/**/*.{js,svelte}"
```
---
## Options
The [parserOptions](https://eslint.org/docs/latest/use/configure/parser#configure-parser-options) for this parser generally match what [espree](https://github.com/eslint/espree#usage)—ESLint's default parser—supports.
For example:
```js
import svelteParser from "svelte-eslint-parser";
export default [
// ...
{
files: [
// Set .svelte/.js/.ts files. See above for more details.
],
languageOptions: {
parser: svelteParser,
parserOptions: {
sourceType: "module",
ecmaVersion: 2024,
ecmaFeatures: {
globalReturn: false,
impliedStrict: false,
jsx: false,
},
},
},
},
];
```
### parserOptions.parser
Use the `parserOptions.parser` property to define a custom parser for `<script>` tags. Any additional parser options (besides the parser itself) are passed along to the specified parser.
```js
import ts from "typescript-eslint";
export default [
{
files: [
// Set .svelte/.js/.ts files. See above for more details.
],
languageOptions: {
parser: svelteParser,
parserOptions: {
parser: ts.parser,
},
},
},
];
```
#### Using TypeScript in `<script>`
If you use the parser from [typescript-eslint](https://typescript-eslint.io/) (`ts.parser`, a re-export of `@typescript-eslint/parser`) for TypeScript within `<script>` of `.svelte` files, additional configuration is needed. For example:
```js
import ts from "typescript-eslint";
export default [
// Other config for non-Svelte files
{
languageOptions: {
parser: ts.parser,
parserOptions: {
project: "path/to/your/tsconfig.json",
extraFileExtensions: [".svelte"],
},
},
},
// Svelte config
{
files: [
// Set .svelte/.js/.ts files. See above for more details.
],
languageOptions: {
parser: svelteParser,
// Parse the `<script>` in `.svelte` as TypeScript by adding the following configuration.
parserOptions: {
parser: ts.parser,
},
},
},
];
```
#### Using JSDoc types in JavaScript
The configuration above also supports JSDoc type annotations in JavaScript
`<script>` blocks (with no `lang`, `lang="js"`, or `lang="javascript"`) and
`.svelte.js` files. Configure `parserOptions.project` or
`parserOptions.projectService` to enable type-aware lint rules.
```svelte
<script>
/** @param {number} value */
function increment(value) {
return value + 1;
}
</script>
{increment(1)}
```
When using multiple parsers, assign `ts.parser` to the `js`
entry as well as `ts` to enable JSDoc type information in ordinary `<script>`
blocks. JavaScript configured to use Espree continues to use Espree.
#### Multiple parsers
To switch parsers for each language, provide an object:
```js
import ts from "typescript-eslint";
import espree from "espree";
export default [
{
files: [
// Set .svelte/.js/.ts files. See above for more details.
],
languageOptions: {
parser: svelteParser,
parserOptions: {
parser: {
ts: ts.parser,
js: espree,
typescript: ts.parser,
},
},
},
},
];
```
### parserOptions.svelteConfig
If you use `eslint.config.js`, you can specify a `svelte.config.js` file via `parserOptions.svelteConfig`.
```js
import svelteConfig from "./svelte.config.js";
export default [
{
files: [
// Set .svelte/.js/.ts files. See above for more details.
],
languageOptions: {
parser: svelteParser,
parserOptions: {
svelteConfig,
},
},
},
];
```
If `parserOptions.svelteConfig` is not set, the parser attempts to statically read some config from `svelte.config.js`.
### parserOptions.svelteFeatures
You can configure how Svelte-specific features are parsed via `parserOptions.svelteFeatures`.
For example:
```js
export default [
{
files: [
// Set .svelte/.js/.ts files. See above for more details.
],
languageOptions: {
parser: svelteParser,
parserOptions: {
svelteFeatures: {
// This is for Svelte 5. The default is true.
// If false, ESLint won't recognize rune symbols.
// If not specified, the parser tries to read compilerOptions.runes from `svelte.config.js`.
// If `parserOptions.svelteConfig` is not given and static analysis fails, it defaults to true.
runes: true,
},
},
},
},
];
```
---
## Experimental
### `ts.sys.readFile` hook for type-aware Svelte lint
> ⚠️ **Experimental.** Opt-in only; behavior may change or be removed.
Speeds up type-aware lint of `.svelte` files. Your ESLint config must
already list `.svelte` via `parserOptions.extraFileExtensions`.
```sh
SVELTE_ESLINT_PARSER_EXPERIMENTAL_TS_SYS_HOOK=1 \
eslint --no-cache --concurrency auto .
```
When enabled, the hook also resolves `.svelte` import specifiers to the
imported component's virtual module, so type-aware rules see a component's
real prop, event, and slot types across files. `import Foo from "./Foo.svelte"`
is resolved through a virtual `Foo.svelte.ts` companion that the hook serves
from the same translation — no `tsconfig` changes are required. If a real
`Foo.svelte.ts` (a Svelte runes module) exists on disk, it always takes
precedence and the hook leaves it untouched. In that case component prop types
are not available for that component, because plain TypeScript resolution picks
the module instead of the component. To avoid this name collision, enable the
`svelte/no-conflicting-module-names` rule from `eslint-plugin-svelte` (v3.22.0
or later), which reports a `Foo.svelte` and `Foo.svelte.ts` pair.
Component typing currently requires a TypeScript `<script>` and supports
Svelte 3, 4, and 5. Props come from `$props()` annotations or destructuring
in runes mode, and from `$$Props` or exported `let` bindings in legacy mode.
Defaulted props are optional. Explicit `$$Events` and `$$Slots` declarations
supply event and slot types; otherwise those types remain permissive.
Instance exports (`export const`, `export function`, `export class`, and
`export { … }` in the instance script) are part of the component instance type,
so a `bind:this` target typed as the component sees them.
This is not a full replacement for Svelte's generated component declarations.
Unannotated props without defaults use `any`, rest props keep the prop type
open, and generic parameters are represented by their constraints rather than
preserving a generic component signature. Slot types inferred from template
markup are not synthesized. JavaScript-only components do not receive this
TypeScript translation.
Caveat: rules that read raw TypeScript diagnostics
(`program.getSemanticDiagnostics()` and friends) report positions inside
the parser's virtual shim — a pre-existing property of type-aware Svelte
lint, not specific to the hook.
---
## Editor Integrations
### Visual Studio Code
Use the [dbaeumer.vscode-eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) extension provided by Microsoft.
By default, it only targets `*.js` and `*.jsx`, so you need to configure `.svelte` file support. For example, in **.vscode/settings.json**:
```json
{
"eslint.validate": ["javascript", "javascriptreact", "svelte"]
}
```
---
## Usage for Custom Rules / Plugins
- See [AST.md](./docs/AST.md) for the AST specification. You can explore it on the [Live DEMO](https://sveltejs.github.io/svelte-eslint-parser/).
- This parser generates its own [ScopeManager](https://eslint.org/docs/developer-guide/scope-manager-interface). Check the [Live DEMO](https://sveltejs.github.io/svelte-eslint-parser/scope).
- Several rules are [already implemented] in [`eslint-plugin-svelte`], and their source code can be a helpful reference.
---
## Contributing
Contributions are welcome! Please open an issue or submit a PR on GitHub.
For internal details, see [internal-mechanism.md](./docs/internal-mechanism.md).
---
## License
See [LICENSE](LICENSE) (MIT) for rights and limitations.

4
node_modules/svelte-eslint-parser/lib/ast/base.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
import type { Locations } from "./common.js";
export interface BaseNode extends Locations {
type: string;
}

1
node_modules/svelte-eslint-parser/lib/ast/base.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

24
node_modules/svelte-eslint-parser/lib/ast/common.d.ts generated vendored Normal file
View File

@@ -0,0 +1,24 @@
import type { BaseNode } from "./base.js";
export interface Position {
/** >= 1 */
line: number;
/** >= 0 */
column: number;
}
export type Range = [number, number];
export interface SourceLocation {
start: Position;
end: Position;
}
export interface Locations {
loc: SourceLocation;
range: Range;
}
export interface Token extends BaseNode {
type: "Boolean" | "Null" | "Identifier" | "Keyword" | "Punctuator" | "JSXIdentifier" | "JSXText" | "Numeric" | "String" | "RegularExpression" | "Template" | "HTMLText" | "HTMLIdentifier" | "MustacheKeyword" | "HTMLComment";
value: string;
}
export interface Comment extends BaseNode {
type: "Line" | "Block";
value: string;
}

1
node_modules/svelte-eslint-parser/lib/ast/common.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

428
node_modules/svelte-eslint-parser/lib/ast/html.d.ts generated vendored Normal file
View File

@@ -0,0 +1,428 @@
import type ESTree from "estree";
import type { TSESTree } from "@typescript-eslint/types";
import type { BaseNode } from "./base.js";
import type { Token, Comment } from "./common.js";
import type { SvelteFunctionBindingsExpression } from "./script.js";
export type SvelteHTMLNode = SvelteProgram | SvelteScriptElement | SvelteStyleElement | SvelteElement | SvelteStartTag | SvelteEndTag | SvelteName | SvelteMemberExpressionName | SvelteText | SvelteLiteral | SvelteMustacheTag | SvelteDebugTag | SvelteConstTag | SvelteDeclarationTag | SvelteRenderTag | SvelteIfBlock | SvelteElseBlock | SvelteEachBlock | SvelteAwaitBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock | SvelteAttribute | SvelteShorthandAttribute | SvelteSpreadAttribute | SvelteAttachTag | SvelteDirective | SvelteStyleDirective | SvelteSpecialDirective | SvelteGenericsDirective | SvelteDirectiveKey | SvelteSpecialDirectiveKey | SvelteHTMLComment;
/** Node of Svelte program root */
export interface SvelteProgram extends BaseNode {
type: "Program";
body: (SvelteScriptElement | SvelteStyleElement | Child)[];
sourceType: "script" | "module";
comments: Comment[];
tokens: Token[];
parent: null;
}
/** Node of elements like HTML element. */
export type SvelteElement = SvelteHTMLElement | SvelteComponentElement | SvelteSpecialElement;
type BaseSvelteElement = BaseNode;
/** Node of `<script>` element. */
export interface SvelteScriptElement extends BaseSvelteElement {
type: "SvelteScriptElement";
name: SvelteName;
startTag: SvelteStartTag;
body: ESTree.Program["body"];
endTag: SvelteEndTag | null;
parent: SvelteProgram;
}
/** Node of `<style>` element. */
export interface SvelteStyleElement extends BaseSvelteElement {
type: "SvelteStyleElement";
name: SvelteName;
startTag: SvelteStartTag;
children: [SvelteText];
endTag: SvelteEndTag | null;
parent: SvelteProgram;
}
/** Node of HTML element. */
export interface SvelteHTMLElement extends BaseSvelteElement {
type: "SvelteElement";
kind: "html";
name: SvelteName;
startTag: SvelteStartTag;
children: Child[];
endTag: SvelteEndTag | null;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of Svelte component element. */
export interface SvelteComponentElement extends BaseSvelteElement {
type: "SvelteElement";
kind: "component";
name: ESTree.Identifier | SvelteMemberExpressionName;
startTag: SvelteStartTag;
children: Child[];
endTag: SvelteEndTag | null;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of Svelte special component element. e.g. `<svelte:window>` */
export interface SvelteSpecialElement extends BaseSvelteElement {
type: "SvelteElement";
kind: "special";
name: SvelteName;
startTag: SvelteStartTag;
children: Child[];
endTag: SvelteEndTag | null;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of start tag. */
export interface SvelteStartTag extends BaseNode {
type: "SvelteStartTag";
attributes: (SvelteAttribute | SvelteShorthandAttribute | SvelteSpreadAttribute | SvelteAttachTag | SvelteDirective | SvelteStyleDirective | SvelteSpecialDirective | SvelteGenericsDirective)[];
selfClosing: boolean;
parent: SvelteElement | SvelteScriptElement | SvelteStyleElement;
}
/** Node of end tag. */
export interface SvelteEndTag extends BaseNode {
type: "SvelteEndTag";
parent: SvelteElement | SvelteScriptElement | SvelteStyleElement;
}
/** Node of names. It is used for element names other than components and normal attribute names. */
export interface SvelteName extends BaseNode {
type: "SvelteName";
name: string;
parent: SvelteElement | SvelteScriptElement | SvelteStyleElement | SvelteAttribute | SvelteMemberExpressionName | SvelteDirectiveKey;
}
/** Nodes that may be used in component names. The component names separated by dots. */
export interface SvelteMemberExpressionName extends BaseNode {
type: "SvelteMemberExpressionName";
object: SvelteMemberExpressionName | ESTree.Identifier;
property: SvelteName;
parent: SvelteComponentElement;
}
type Child = SvelteElement | SvelteText | SvelteMustacheTag | SvelteDebugTag | SvelteConstTag | SvelteDeclarationTag | SvelteRenderTag | SvelteIfBlockAlone | SvelteEachBlock | SvelteAwaitBlock | SvelteKeyBlock | SvelteSnippetBlock | SvelteHTMLComment;
/** Node of text. like HTML text. */
export interface SvelteText extends BaseNode {
type: "SvelteText";
value: string;
parent: SvelteProgram | SvelteElement | SvelteStyleElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of literal. */
export interface SvelteLiteral extends BaseNode {
type: "SvelteLiteral";
value: string;
parent: SvelteAttribute | SvelteStyleDirective;
}
/** Node of mustache tag. e.g. `{...}`, `{@html ...}`. Like JSXExpressionContainer */
export type SvelteMustacheTag = SvelteMustacheTagText | SvelteMustacheTagRaw;
interface BaseSvelteMustacheTag extends BaseNode {
type: "SvelteMustacheTag";
kind: "text" | "raw";
expression: ESTree.Expression;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock | SvelteAttribute | SvelteStyleDirective;
}
/** Node of mustache tag. e.g. `{...}``. Like JSXExpressionContainer */
export interface SvelteMustacheTagText extends BaseSvelteMustacheTag {
kind: "text";
}
/** Node of mustache tag. e.g. `{@html ...}`. Like JSXExpressionContainer */
export interface SvelteMustacheTagRaw extends BaseSvelteMustacheTag {
kind: "raw";
parent: Exclude<BaseSvelteMustacheTag["parent"], SvelteAttribute | SvelteStyleDirective>;
}
/** Node of debug mustache tag. e.g. `{@debug}` */
export interface SvelteDebugTag extends BaseNode {
type: "SvelteDebugTag";
identifiers: ESTree.Identifier[];
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of const tag. e.g. `{@const}` */
export interface SvelteConstTag extends BaseNode {
type: "SvelteConstTag";
/**
* @deprecated Use `declarations` instead.
*/
declaration: ESTree.VariableDeclarator;
declarations: [ESTree.VariableDeclarator];
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of declaration tag. e.g. `{let foo = bar}` */
export interface SvelteDeclarationTag extends BaseNode {
type: "SvelteDeclarationTag";
declaration: ESTree.VariableDeclaration & {
kind: "let" | "const";
};
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of render tag. e.g. `{@render}` */
export interface SvelteRenderTag extends BaseNode {
type: "SvelteRenderTag";
expression: ESTree.SimpleCallExpression | (ESTree.ChainExpression & {
expression: ESTree.SimpleCallExpression;
});
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of if block. e.g. `{#if}` */
export type SvelteIfBlock = SvelteIfBlockAlone | SvelteIfBlockElseIf;
interface BaseSvelteIfBlock extends BaseNode {
type: "SvelteIfBlock";
elseif: boolean;
expression: ESTree.Expression;
children: Child[];
else: SvelteElseBlock | null;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlock | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of if block. e.g. `{#if}` */
export interface SvelteIfBlockAlone extends BaseSvelteIfBlock {
elseif: false;
parent: Exclude<BaseSvelteIfBlock["parent"], SvelteElseBlockElseIf>;
}
/** Node of if block. e.g. `{:else if}` */
export interface SvelteIfBlockElseIf extends BaseSvelteIfBlock {
elseif: true;
parent: SvelteElseBlockElseIf;
}
/** Node of else block. e.g. `{:else}` */
export type SvelteElseBlock = SvelteElseBlockAlone | SvelteElseBlockElseIf;
interface BaseSvelteElseBlock extends BaseNode {
type: "SvelteElseBlock";
elseif: boolean;
children: (Child | SvelteIfBlockElseIf)[];
parent: SvelteIfBlock | SvelteEachBlock;
}
/** Node of else block. e.g. `{:else}` */
export interface SvelteElseBlockAlone extends BaseSvelteElseBlock {
elseif: false;
children: Child[];
}
/** Node of else block. e.g. `{:else if ...}` */
export interface SvelteElseBlockElseIf extends BaseSvelteElseBlock {
elseif: true;
children: [SvelteIfBlockElseIf];
}
/** Node of each block. e.g. `{#each}` */
export interface SvelteEachBlock extends BaseNode {
type: "SvelteEachBlock";
expression: ESTree.Expression;
context: ESTree.Pattern | null;
index: ESTree.Identifier | null;
key: ESTree.Expression | null;
children: Child[];
else: SvelteElseBlockAlone | null;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of await block. e.g. `{#await}`, `{#await ... then ... }`, `{#await ... catch ... }` */
export type SvelteAwaitBlock = SvelteAwaitBlockAwaitPending | SvelteAwaitBlockAwaitThen | SvelteAwaitBlockAwaitCatch;
interface BaseSvelteAwaitBlock extends BaseNode {
type: "SvelteAwaitBlock";
expression: ESTree.Expression;
kind: "await" | "await-then" | "await-catch";
pending: SvelteAwaitPendingBlock | null;
then: SvelteAwaitThenBlock | null;
catch: SvelteAwaitCatchBlock | null;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of await block. e.g. `{#await}` */
export interface SvelteAwaitBlockAwaitPending extends BaseSvelteAwaitBlock {
kind: "await";
pending: SvelteAwaitPendingBlock;
then: SvelteAwaitThenBlockAlone | null;
catch: SvelteAwaitCatchBlockAlone | null;
}
/** Node of await block. e.g. `{#await ... then ... }` */
export interface SvelteAwaitBlockAwaitThen extends BaseSvelteAwaitBlock {
kind: "await-then";
pending: null;
then: SvelteAwaitThenBlockAwaitThen;
catch: SvelteAwaitCatchBlockAlone | null;
}
/** Node of await block. e.g. `{#await ... catch ... }` */
export interface SvelteAwaitBlockAwaitCatch extends BaseSvelteAwaitBlock {
kind: "await-catch";
pending: null;
then: null;
catch: SvelteAwaitCatchBlockAwaitCatch;
}
/** Node of await pending block. e.g. `{#await expr} ... {:then}` */
export interface SvelteAwaitPendingBlock extends BaseNode {
type: "SvelteAwaitPendingBlock";
children: Child[];
parent: SvelteAwaitBlock;
}
/** Node of await then block. e.g. `{:then}`, `{#await ... then ...}` */
export type SvelteAwaitThenBlock = SvelteAwaitThenBlockAlone | SvelteAwaitThenBlockAwaitThen;
interface BaseSvelteAwaitThenBlock extends BaseNode {
type: "SvelteAwaitThenBlock";
awaitThen: boolean;
value: ESTree.Pattern | null;
children: Child[];
parent: SvelteAwaitBlock;
}
/** Node of await then block. e.g. `{:then}` */
export interface SvelteAwaitThenBlockAlone extends BaseSvelteAwaitThenBlock {
awaitThen: false;
parent: SvelteAwaitBlockAwaitPending;
}
/** Node of await then block. e.g. `{#await ... then ...}` */
export interface SvelteAwaitThenBlockAwaitThen extends BaseSvelteAwaitThenBlock {
awaitThen: true;
parent: SvelteAwaitBlockAwaitThen;
}
/** Node of await catch block. e.g. `{:catch}`, `{#await ... catch ... }` */
export type SvelteAwaitCatchBlock = SvelteAwaitCatchBlockAlone | SvelteAwaitCatchBlockAwaitCatch;
interface BaseSvelteAwaitCatchBlock extends BaseNode {
type: "SvelteAwaitCatchBlock";
awaitCatch: boolean;
error: ESTree.Pattern | null;
children: Child[];
parent: SvelteAwaitBlock;
}
/** Node of await catch block. e.g. `{:catch}` */
export interface SvelteAwaitCatchBlockAlone extends BaseSvelteAwaitCatchBlock {
awaitCatch: false;
parent: SvelteAwaitBlockAwaitPending | SvelteAwaitBlockAwaitThen;
}
/** Node of await catch block. e.g. `{#await ... catch ... }` */
export interface SvelteAwaitCatchBlockAwaitCatch extends BaseSvelteAwaitCatchBlock {
awaitCatch: true;
error: ESTree.Pattern | null;
children: Child[];
parent: SvelteAwaitBlockAwaitCatch;
}
/** Node of key block. e.g. `{#key}` */
export interface SvelteKeyBlock extends BaseNode {
type: "SvelteKeyBlock";
expression: ESTree.Expression;
children: Child[];
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of snippet block. e.g. `{#snippet}` */
export interface SvelteSnippetBlock extends BaseNode {
type: "SvelteSnippetBlock";
id: ESTree.Identifier;
params: ESTree.Pattern[];
children: Child[];
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of HTML comment. */
export interface SvelteHTMLComment extends BaseNode {
type: "SvelteHTMLComment";
value: string;
parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock;
}
/** Node of HTML attribute. */
export interface SvelteAttribute extends BaseNode {
type: "SvelteAttribute";
key: SvelteName;
boolean: boolean;
value: (SvelteLiteral | SvelteMustacheTagText)[];
parent: SvelteStartTag;
}
/** Node of shorthand attribute. e.g. `<img {src}>` */
export interface SvelteShorthandAttribute extends BaseNode {
type: "SvelteShorthandAttribute";
key: ESTree.Identifier;
value: ESTree.Identifier;
parent: SvelteStartTag;
}
/** Node of spread attribute. e.g. `<Info {...pkg}/>`. Like JSXSpreadAttribute */
export interface SvelteSpreadAttribute extends BaseNode {
type: "SvelteSpreadAttribute";
argument: ESTree.Expression;
parent: SvelteStartTag;
}
export interface SvelteAttachTag extends BaseNode {
type: "SvelteAttachTag";
expression: ESTree.Expression;
parent: SvelteStartTag;
}
/** Node of directive. e.g. `<input bind:value />` */
export type SvelteDirective = SvelteActionDirective | SvelteAnimationDirective | SvelteBindingDirective | SvelteClassDirective | SvelteEventHandlerDirective | SvelteLetDirective | SvelteRefDirective | SvelteTransitionDirective;
export type SvelteDirectiveKey = SvelteDirectiveKeyTextName | SvelteDirectiveKeyFunctionName | SvelteDirectiveKeyForEventHandler | SvelteDirectiveKeyForAction | SvelteDirectiveKeyForStyleShorthand;
interface BaseSvelteDirectiveKey<N extends ESTree.Expression | SvelteName> extends BaseNode {
type: "SvelteDirectiveKey";
name: N;
modifiers: string[];
parent: SvelteDirective | SvelteStyleDirective;
}
export type SvelteDirectiveKeyTextName = BaseSvelteDirectiveKey<SvelteName>;
export type SvelteDirectiveKeyFunctionName = BaseSvelteDirectiveKey<ESTree.Identifier>;
export type SvelteDirectiveKeyForEventHandler = BaseSvelteDirectiveKey<SvelteName>;
export type SvelteDirectiveKeyForAction = BaseSvelteDirectiveKey<ESTree.Identifier | ESTree.MemberExpression | SvelteName>;
export type SvelteDirectiveKeyForStyleShorthand = BaseSvelteDirectiveKey<ESTree.Identifier>;
interface BaseSvelteDirective extends BaseNode {
type: "SvelteDirective";
key: SvelteDirectiveKey;
parent: SvelteStartTag;
}
export interface SvelteActionDirective extends BaseSvelteDirective {
kind: "Action";
key: SvelteDirectiveKeyForAction;
expression: null | ESTree.Expression;
}
export interface SvelteAnimationDirective extends BaseSvelteDirective {
kind: "Animation";
key: SvelteDirectiveKeyFunctionName;
expression: null | ESTree.Expression;
}
export interface SvelteBindingDirective extends BaseSvelteDirective {
kind: "Binding";
key: SvelteDirectiveKeyTextName;
shorthand: boolean;
expression: null | ESTree.Expression | SvelteFunctionBindingsExpression;
}
export interface SvelteClassDirective extends BaseSvelteDirective {
kind: "Class";
key: SvelteDirectiveKeyTextName;
shorthand: boolean;
expression: null | ESTree.Expression;
}
export interface SvelteEventHandlerDirective extends BaseSvelteDirective {
kind: "EventHandler";
key: SvelteDirectiveKeyForEventHandler;
expression: null | ESTree.Expression;
}
export interface SvelteLetDirective extends BaseSvelteDirective {
kind: "Let";
key: SvelteDirectiveKeyTextName;
expression: null | ESTree.Pattern;
}
export interface SvelteRefDirective extends BaseSvelteDirective {
kind: "Ref";
key: SvelteDirectiveKeyTextName;
expression: null | ESTree.Expression;
}
export interface SvelteTransitionDirective extends BaseSvelteDirective {
kind: "Transition";
key: SvelteDirectiveKeyFunctionName;
intro: boolean;
outro: boolean;
expression: null | ESTree.Expression;
}
/** Node of style directive. e.g. `<input style:color />` */
export type SvelteStyleDirective = SvelteStyleDirectiveShorthand | SvelteStyleDirectiveLongform;
interface BaseSvelteStyleDirective extends BaseNode {
type: "SvelteStyleDirective";
key: SvelteDirectiveKeyTextName | SvelteDirectiveKeyForStyleShorthand;
value: (SvelteLiteral | SvelteMustacheTagText)[];
parent: SvelteStartTag;
}
export interface SvelteStyleDirectiveShorthand extends BaseSvelteStyleDirective {
key: SvelteDirectiveKeyForStyleShorthand;
shorthand: true;
value: [];
}
export interface SvelteStyleDirectiveLongform extends BaseSvelteStyleDirective {
key: SvelteDirectiveKeyTextName;
shorthand: false;
value: (SvelteLiteral | SvelteMustacheTagText)[];
}
export interface SvelteSpecialDirectiveKey extends BaseNode {
type: "SvelteSpecialDirectiveKey";
parent: SvelteSpecialDirective;
}
export interface SvelteSpecialDirective extends BaseNode {
type: "SvelteSpecialDirective";
kind: "this";
key: SvelteSpecialDirectiveKey;
expression: ESTree.Expression;
parent: SvelteStartTag;
}
export interface SvelteGenericsDirective extends BaseNode {
type: "SvelteGenericsDirective";
key: SvelteName & {
name: "generics";
};
params: TSESTree.TSTypeParameterDeclaration["params"];
parent: SvelteStartTag;
}
export {};

1
node_modules/svelte-eslint-parser/lib/ast/html.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

6
node_modules/svelte-eslint-parser/lib/ast/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import type { SvelteHTMLNode } from "./html.js";
import type { SvelteScriptNode } from "./script.js";
export * from "./common.js";
export * from "./html.js";
export * from "./script.js";
export type SvelteNode = SvelteHTMLNode | SvelteScriptNode;

3
node_modules/svelte-eslint-parser/lib/ast/index.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export * from "./common.js";
export * from "./html.js";
export * from "./script.js";

24
node_modules/svelte-eslint-parser/lib/ast/script.d.ts generated vendored Normal file
View File

@@ -0,0 +1,24 @@
import type ESTree from "estree";
import type { BaseNode } from "./base.js";
import type { SvelteBindingDirective } from "./html.js";
export type SvelteScriptNode = SvelteReactiveStatement | SvelteFunctionBindingsExpression;
/** Node of `$` statement. */
export interface SvelteReactiveStatement extends BaseNode {
type: "SvelteReactiveStatement";
label: ESTree.Identifier & {
name: "$";
};
body: ESTree.Statement;
parent: ESTree.Node;
}
/** Node of `bind:name={get, set}` expression. */
export interface SvelteFunctionBindingsExpression extends BaseNode {
type: "SvelteFunctionBindingsExpression";
expressions: [
/** Getter */
ESTree.Expression,
/** Setter */
ESTree.Expression
];
parent: SvelteBindingDirective;
}

1
node_modules/svelte-eslint-parser/lib/ast/script.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,7 @@
import type * as ESTree from "estree";
import type { Comment, Token } from "../ast/index.js";
import type { Context } from "./index.js";
/** Fix locations */
export declare function fixLocations(node: ESTree.Node, tokens: Token[], comments: Comment[], offset: number, visitorKeys: {
[type: string]: string[];
} | undefined, ctx: Context): void;

View File

@@ -0,0 +1,62 @@
import { traverseNodes } from "../traverse.js";
/** Fix locations */
export function fixLocations(node, tokens, comments, offset, visitorKeys, ctx) {
if (offset === 0) {
return;
}
const traversed = new Set();
traverseNodes(node, {
visitorKeys,
enterNode: (n) => {
if (traversed.has(n)) {
return;
}
traversed.add(n);
if (traversed.has(n.range)) {
if (!traversed.has(n.loc)) {
// However, `Node#loc` may not be shared.
const locs = ctx.getConvertLocation({
start: n.range[0],
end: n.range[1],
});
applyLocs(n, locs);
traversed.add(n.loc);
}
}
else {
const start = n.range[0] + offset;
const end = n.range[1] + offset;
const locs = ctx.getConvertLocation({ start, end });
applyLocs(n, locs);
traversed.add(n.range);
traversed.add(n.loc);
}
},
leaveNode: Function.prototype,
});
for (const t of tokens) {
const start = t.range[0] + offset;
const end = t.range[1] + offset;
const locs = ctx.getConvertLocation({ start, end });
applyLocs(t, locs);
}
for (const t of comments) {
const start = t.range[0] + offset;
const end = t.range[1] + offset;
const locs = ctx.getConvertLocation({ start, end });
applyLocs(t, locs);
}
}
/**
* applyLocs
*/
function applyLocs(target, locs) {
target.loc = locs.loc;
target.range = locs.range;
if (typeof target.start === "number") {
delete target.start;
}
if (typeof target.end === "number") {
delete target.end;
}
}

View File

@@ -0,0 +1,116 @@
import type { Comment, Locations, SvelteElement, SvelteHTMLElement, SvelteScriptElement, SvelteSnippetBlock, SvelteStyleElement, Token } from "../ast/index.js";
import type ESTree from "estree";
import type * as SvAST from "../parser/svelte-ast-types.js";
import type * as Compiler from "../parser/svelte-ast-types-for-v5.js";
import { ScriptLetContext } from "./script-let.js";
import { LetDirectiveCollections } from "./let-directive-collection.js";
import { type NormalizedParserOptions } from "../parser/parser-options.js";
export declare class ScriptsSourceCode {
private raw;
private trimmedRaw;
readonly attrs: Record<string, string | undefined>;
private _appendScriptLets;
separateIndexes: number[];
constructor(script: string, attrs: Record<string, string | undefined>);
getCurrentVirtualCode(): string;
getCurrentVirtualCodeInfo(): {
script: string;
render: string;
rootScope: string;
};
getCurrentVirtualCodeLength(): number;
addLet(letCode: string, kind: "generics" | "snippet" | "render"): {
start: number;
end: number;
};
stripCode(start: number, end: number): void;
}
export type ContextSourceCode = {
template: string;
scripts: ScriptsSourceCode;
};
export declare class Context {
readonly code: string;
readonly parserOptions: NormalizedParserOptions;
readonly sourceCode: ContextSourceCode;
readonly tokens: Token[];
readonly comments: Comment[];
private readonly locs;
private readonly locsMap;
readonly scriptLet: ScriptLetContext;
readonly letDirCollections: LetDirectiveCollections;
readonly slots: Set<SvelteHTMLElement>;
readonly elements: Map<SvelteElement, SvAST.Element | SvAST.InlineComponent | SvAST.Window | SvAST.Document | SvAST.Body | SvAST.Head | SvAST.Title | SvAST.Options | SvAST.SlotTemplate | SvAST.Slot | Compiler.ElementLike>;
readonly snippets: SvelteSnippetBlock[];
private readonly state;
private readonly blocks;
constructor(code: string, parserOptions: NormalizedParserOptions);
getLocFromIndex(index: number): {
line: number;
column: number;
};
getIndexFromLoc(loc: {
line: number;
column: number;
}): number;
/**
* Get the location information of the given node.
* @param node The node.
*/
getConvertLocation(node: {
start: number;
end: number;
} | ESTree.Node): Locations;
addComment(comment: Comment): void;
/**
* Add token to tokens
*/
addToken(type: Token["type"], range: {
start: number;
end: number;
}): Token;
/**
* get text
*/
getText(range: {
start: number;
end: number;
} | ESTree.Node): string;
isTypeScript(): boolean;
stripScriptCode(start: number, end: number): void;
findBlock(element: SvelteScriptElement | SvelteStyleElement | SvelteElement): Block | undefined;
findSelfClosingBlock(element: SvelteElement): SelfClosingBlock | undefined;
}
type Block = {
tag: "script" | "style" | "template";
originalTag: string;
attrs: Compiler.Attribute[];
selfClosing?: false;
contentRange: [number, number];
startTagRange: [number, number];
endTagRange: [number, number];
} | SelfClosingBlock;
type SelfClosingBlock = {
tag: "script" | "style" | "template";
originalTag: string;
attrs: Compiler.Attribute[];
selfClosing: true;
startTagRange: [number, number];
};
export declare class LinesAndColumns {
private readonly lineStartIndices;
constructor(code: string);
getLocFromIndex(index: number): {
line: number;
column: number;
};
getIndexFromLoc(loc: {
line: number;
column: number;
}): number;
/**
* Get the location information of the given indexes.
*/
getLocations(start: number, end: number): Locations;
}
export {};

340
node_modules/svelte-eslint-parser/lib/context/index.js generated vendored Normal file
View File

@@ -0,0 +1,340 @@
import { ScriptLetContext } from "./script-let.js";
import { LetDirectiveCollections } from "./let-directive-collection.js";
import { parseAttributes } from "../parser/html.js";
import { sortedLastIndex } from "../utils/index.js";
import { isTypeScript, } from "../parser/parser-options.js";
export class ScriptsSourceCode {
constructor(script, attrs) {
this._appendScriptLets = null;
this.separateIndexes = [];
this.raw = script;
this.trimmedRaw = script.trimEnd();
this.attrs = attrs;
this.separateIndexes = [script.length];
}
getCurrentVirtualCode() {
if (this._appendScriptLets == null) {
return this.raw;
}
return (this.trimmedRaw +
this._appendScriptLets.separate +
this._appendScriptLets.beforeSpaces +
this._appendScriptLets.render +
this._appendScriptLets.snippet +
this._appendScriptLets.generics);
}
getCurrentVirtualCodeInfo() {
if (this._appendScriptLets == null) {
return { script: this.raw, render: "", rootScope: "" };
}
return {
script: this.trimmedRaw + this._appendScriptLets.separate,
render: this._appendScriptLets.beforeSpaces + this._appendScriptLets.render,
rootScope: this._appendScriptLets.snippet + this._appendScriptLets.generics,
};
}
getCurrentVirtualCodeLength() {
if (this._appendScriptLets == null) {
return this.raw.length;
}
return (this.trimmedRaw.length +
this._appendScriptLets.separate.length +
this._appendScriptLets.beforeSpaces.length +
this._appendScriptLets.render.length +
this._appendScriptLets.snippet.length +
this._appendScriptLets.generics.length);
}
addLet(letCode, kind) {
if (this._appendScriptLets == null) {
const currentLength = this.trimmedRaw.length;
this.separateIndexes = [currentLength, currentLength + 1];
const after = this.raw.slice(currentLength + 2);
this._appendScriptLets = {
separate: "\n;",
beforeSpaces: after,
render: "",
snippet: "",
generics: "",
};
}
const start = this.getCurrentVirtualCodeLength();
this._appendScriptLets[kind] += letCode;
return {
start,
end: this.getCurrentVirtualCodeLength(),
};
}
stripCode(start, end) {
this.raw =
this.raw.slice(0, start) +
this.raw.slice(start, end).replace(/[^\n\r ]/g, " ") +
this.raw.slice(end);
this.trimmedRaw =
this.trimmedRaw.slice(0, start) +
this.trimmedRaw.slice(start, end).replace(/[^\n\r ]/g, " ") +
this.trimmedRaw.slice(end);
}
}
export class Context {
constructor(code, parserOptions) {
this.tokens = [];
this.comments = [];
this.locsMap = new Map();
this.letDirCollections = new LetDirectiveCollections();
this.slots = new Set();
this.elements = new Map();
this.snippets = [];
// ----- States ------
this.state = {};
this.blocks = [];
this.code = code;
this.parserOptions = parserOptions;
this.locs = new LinesAndColumns(code);
const spaces = code.replace(/[^\n\r ]/g, " ");
let templateCode = "";
let scriptCode = "";
const scriptAttrs = {};
let start = 0;
for (const block of extractBlocks(code)) {
if (block.tag === "template") {
if (block.selfClosing) {
continue;
}
const lang = block.attrs.find((attr) => attr.name === "lang");
if (!lang || !Array.isArray(lang.value)) {
continue;
}
const langValue = lang.value[0];
if (!langValue ||
langValue.type !== "Text" ||
langValue.data === "html") {
continue;
}
}
this.blocks.push(block);
if (block.selfClosing) {
// Self-closing blocks are temporarily replaced with `<s---->` or `<t---->` tag
// because the svelte compiler cannot parse self-closing block(script, style) tags.
// It will be restored later in `convertHTMLElement()` processing.
templateCode += `${code.slice(start, block.startTagRange[0] + 2 /* `<` and first letter */)}${"-".repeat(block.tag.length - 1 /* skip first letter */)}${code.slice(block.startTagRange[0] + 1 /* skip `<` */ + block.tag.length, block.startTagRange[1])}`;
scriptCode += spaces.slice(start, block.startTagRange[1]);
start = block.startTagRange[1];
}
else {
templateCode +=
code.slice(start, block.contentRange[0]) +
spaces.slice(block.contentRange[0], block.contentRange[1]);
if (block.tag === "script") {
scriptCode +=
spaces.slice(start, block.contentRange[0]) +
code.slice(...block.contentRange);
for (const attr of block.attrs) {
if (Array.isArray(attr.value)) {
const attrValue = attr.value[0];
scriptAttrs[attr.name] =
attrValue && attrValue.type === "Text"
? attrValue.data
: undefined;
}
}
}
else {
scriptCode += spaces.slice(start, block.contentRange[1]);
}
start = block.contentRange[1];
}
}
templateCode += code.slice(start);
scriptCode += spaces.slice(start);
this.sourceCode = {
template: templateCode,
scripts: new ScriptsSourceCode(scriptCode, scriptAttrs),
};
this.scriptLet = new ScriptLetContext(this);
}
getLocFromIndex(index) {
let loc = this.locsMap.get(index);
if (!loc) {
loc = this.locs.getLocFromIndex(index);
this.locsMap.set(index, loc);
}
return {
line: loc.line,
column: loc.column,
};
}
getIndexFromLoc(loc) {
return this.locs.getIndexFromLoc(loc);
}
/**
* Get the location information of the given node.
* @param node The node.
*/
getConvertLocation(node) {
const { start, end } = node;
return {
range: [start, end],
loc: {
start: this.getLocFromIndex(start),
end: this.getLocFromIndex(end),
},
};
}
addComment(comment) {
this.comments.push(comment);
}
/**
* Add token to tokens
*/
addToken(type, range) {
const token = {
type,
value: this.getText(range),
...this.getConvertLocation(range),
};
this.tokens.push(token);
return token;
}
/**
* get text
*/
getText(range) {
return this.code.slice(range.start, range.end);
}
isTypeScript() {
if (this.state.isTypeScript != null) {
return this.state.isTypeScript;
}
const lang = this.sourceCode.scripts.attrs.lang;
return (this.state.isTypeScript = isTypeScript(this.parserOptions, lang));
}
stripScriptCode(start, end) {
this.sourceCode.scripts.stripCode(start, end);
}
findBlock(element) {
const tag = element.type === "SvelteScriptElement"
? "script"
: element.type === "SvelteStyleElement"
? "style"
: element.name.name.toLowerCase();
return this.blocks.find((block) => block.tag === tag &&
!block.selfClosing &&
element.range[0] <= block.contentRange[0] &&
block.contentRange[1] <= element.range[1]);
}
findSelfClosingBlock(element) {
return this.blocks.find((block) => Boolean(block.selfClosing &&
element.startTag.range[0] <= block.startTagRange[0] &&
block.startTagRange[1] <= element.startTag.range[1]));
}
}
function isValidStartTagOpenIndex(code, startTagOpenIndex) {
const prev = code.slice(0, startTagOpenIndex);
return />\s*$|^\s*$/m.test(prev);
}
/** Extract <script> blocks */
function* extractBlocks(code) {
const startTagOpenRe = /<!--[\s\S]*?-->|<(script|style|template)([\s>])/giu;
const endScriptTagRe = /<\/script>/giu;
const endStyleTagRe = /<\/style>/giu;
const endTemplateTagRe = /<\/template>/giu;
let startTagOpenMatch;
while ((startTagOpenMatch = startTagOpenRe.exec(code))) {
const [, tag, nextChar] = startTagOpenMatch;
if (!tag) {
continue;
}
const startTagStart = startTagOpenMatch.index;
if (!isValidStartTagOpenIndex(code, startTagStart)) {
continue;
}
let startTagEnd = startTagOpenRe.lastIndex;
const lowerTag = tag.toLowerCase();
let attrs = [];
if (!nextChar.trim()) {
const attrsData = parseAttributes(code, startTagOpenRe.lastIndex);
attrs = attrsData.attributes;
startTagEnd = attrsData.index;
if (code[startTagEnd] === "/" && code[startTagEnd + 1] === ">") {
yield {
tag: lowerTag,
originalTag: tag,
attrs,
selfClosing: true,
startTagRange: [startTagStart, startTagEnd + 2],
};
continue;
}
if (code[startTagEnd] === ">") {
startTagEnd++;
}
else {
continue;
}
}
const endTagRe = lowerTag === "script"
? endScriptTagRe
: lowerTag === "style"
? endStyleTagRe
: endTemplateTagRe;
endTagRe.lastIndex = startTagEnd;
const endTagMatch = endTagRe.exec(code);
if (endTagMatch) {
const endTagStart = endTagMatch.index;
const endTagEnd = endTagRe.lastIndex;
yield {
tag: lowerTag,
originalTag: tag,
attrs,
startTagRange: [startTagStart, startTagEnd],
contentRange: [startTagEnd, endTagStart],
endTagRange: [endTagStart, endTagEnd],
};
startTagOpenRe.lastIndex = endTagEnd;
}
}
}
export class LinesAndColumns {
constructor(code) {
const len = code.length;
const lineStartIndices = [0];
for (let index = 0; index < len; index++) {
const c = code[index];
if (c === "\r") {
const next = code[index + 1] || "";
if (next === "\n") {
index++;
}
lineStartIndices.push(index + 1);
}
else if (c === "\n") {
lineStartIndices.push(index + 1);
}
}
this.lineStartIndices = lineStartIndices;
}
getLocFromIndex(index) {
const lineNumber = sortedLastIndex(this.lineStartIndices, (target) => target - index);
return {
line: lineNumber,
column: index - this.lineStartIndices[lineNumber - 1],
};
}
getIndexFromLoc(loc) {
const lineStartIndex = this.lineStartIndices[loc.line - 1];
const positionIndex = lineStartIndex + loc.column;
return positionIndex;
}
/**
* Get the location information of the given indexes.
*/
getLocations(start, end) {
return {
range: [start, end],
loc: {
start: this.getLocFromIndex(start),
end: this.getLocFromIndex(end),
},
};
}
}

View File

@@ -0,0 +1,15 @@
import type { SvelteLetDirective, SvelteName } from "../ast/index.js";
import type * as ESTree from "estree";
import type { ScriptLetBlockParam, ScriptLetCallback } from "./script-let.js";
/** A class that collects pattern nodes for Let directives. */
export declare class LetDirectiveCollection {
private readonly list;
getLetParams(): ScriptLetBlockParam[];
addPattern(pattern: ESTree.Pattern | SvelteName, directive: SvelteLetDirective, typing: string, ...callbacks: ScriptLetCallback<ESTree.Pattern>[]): ScriptLetCallback<ESTree.Pattern>[];
}
export declare class LetDirectiveCollections {
private readonly stack;
beginExtract(): void;
getCollection(): LetDirectiveCollection;
extract(): LetDirectiveCollection;
}

View File

@@ -0,0 +1,36 @@
/** A class that collects pattern nodes for Let directives. */
export class LetDirectiveCollection {
constructor() {
this.list = [];
}
getLetParams() {
return this.list;
}
addPattern(pattern, directive, typing, ...callbacks) {
this.list.push({
node: pattern,
parent: directive,
typing,
callback(node, options) {
for (const callback of callbacks) {
callback(node, options);
}
},
});
return callbacks;
}
}
export class LetDirectiveCollections {
constructor() {
this.stack = [];
}
beginExtract() {
this.stack.push(new LetDirectiveCollection());
}
getCollection() {
return this.stack[this.stack.length - 1];
}
extract() {
return this.stack.pop();
}
}

View File

@@ -0,0 +1,102 @@
import type * as eslint from "eslint";
import type * as ESTree from "estree";
import type { TSESTree } from "@typescript-eslint/types";
import type { Context } from "./index.js";
import type { Comment, SvelteEachBlock, SvelteIfBlock, SvelteName, SvelteNode, SvelteSnippetBlock, Token } from "../ast/index.js";
import type { ESLintExtendedProgram } from "../parser/index.js";
export type ScriptLetCallback<E extends ESTree.Node> = (es: E, options: ScriptLetCallbackOption) => void;
export type ScriptLetCallbackOption = {
getScope: (node: ESTree.Node) => eslint.Scope.Scope;
registerNodeToScope: (node: any, scope: eslint.Scope.Scope) => void;
scopeManager: eslint.Scope.ScopeManager;
visitorKeys?: {
[type: string]: string[];
};
};
export type ScriptLetRestoreCallback = (node: ESTree.Node, tokens: Token[], comments: Comment[], options: ScriptLetRestoreCallbackOption) => void;
type ScriptLetRestoreCallbackOption = {
getScope: (node: ESTree.Node) => eslint.Scope.Scope;
registerNodeToScope: (node: any, scope: eslint.Scope.Scope) => void;
scopeManager: eslint.Scope.ScopeManager;
visitorKeys?: {
[type: string]: string[];
};
addPostProcess: (callback: () => void) => void;
};
type StatementNodeType = `${TSESTree.Statement["type"]}`;
type TypeGenHelper = {
generateUniqueId: (base: string) => string;
};
type ObjectShorthandProperty = ESTree.Property & {
key: ESTree.Identifier;
value: ESTree.Identifier;
};
export type ScriptLetBlockParam = {
node: ESTree.Pattern | SvelteName;
parent: SvelteNode;
typing: string;
callback: (node: ESTree.Pattern, options: ScriptLetCallbackOption) => void;
};
/**
* A class that handles script fragments.
* The script fragment AST node remaps and connects to the original directive AST node.
*/
export declare class ScriptLetContext {
private readonly script;
private readonly ctx;
private readonly restoreCallbacks;
private readonly programRestoreCallbacks;
private readonly closeScopeCallbacks;
private readonly unique;
private currentScriptScopeKind;
constructor(ctx: Context);
addExpression<E extends ESTree.Expression>(expression: E | SvelteName, parent: SvelteNode, typing?: string | null, ...callbacks: ScriptLetCallback<E>[]): ScriptLetCallback<E>[];
addExpressionFromRange<E extends ESTree.Expression>(range: [number, number], parent: SvelteNode, typing?: string | null, ...callbacks: ScriptLetCallback<E>[]): ScriptLetCallback<E>[];
addObjectShorthandProperty(identifier: SvelteName, parent: SvelteNode, ...callbacks: ScriptLetCallback<ObjectShorthandProperty>[]): void;
addVariableDeclarator(declarator: ESTree.VariableDeclarator | ESTree.AssignmentExpression, parent: SvelteNode, ...callbacks: ScriptLetCallback<ESTree.VariableDeclarator>[]): ScriptLetCallback<ESTree.VariableDeclarator>[];
addDeclaration<D extends ESTree.VariableDeclaration>(declaration: D, parent: SvelteNode, ...callbacks: ScriptLetCallback<D>[]): ScriptLetCallback<D>[];
addGenericTypeAliasDeclaration(param: TSESTree.TSTypeParameter, callbackId: (id: TSESTree.Identifier, type: TSESTree.TypeNode) => void, callbackDefault: (type: TSESTree.TypeNode) => void): void;
nestIfBlock(expression: ESTree.Expression, ifBlock: SvelteIfBlock, callback: ScriptLetCallback<ESTree.Expression>): {
beginElse: () => void;
};
nestEachBlock(expression: ESTree.Expression, context: ESTree.Pattern | null, indexRange: {
start: number;
end: number;
} | null, eachBlock: SvelteEachBlock, callback: (expr: ESTree.Expression, ctx: ESTree.Pattern | null, index: ESTree.Identifier | null) => void): void;
nestSnippetBlock(id: ESTree.Identifier, closeParentIndex: number, snippetBlock: SvelteSnippetBlock, kind: "snippet" | null, paramTypes: {
param: ESTree.Pattern;
type: string;
}[] | null, callback: (id: ESTree.Identifier, params: ESTree.Pattern[]) => void): void;
/**
* Strip the annotations spliced in by `nestSnippetBlock` and shift everything
* after each one back to its original source location.
*/
private removeSnippetParamTypes;
nestBlock(block: SvelteNode, params?: ScriptLetBlockParam[] | ((helper: TypeGenHelper | null) => {
param: ScriptLetBlockParam;
preparationScript?: {
script: string;
nodeType: StatementNodeType;
}[];
})): void;
closeScope(): void;
addProgramRestore(callback: ScriptLetRestoreCallback): void;
private appendScript;
private appendScriptWithoutOffset;
private pushScope;
/**
* Restore AST nodes
*/
restore(result: ESLintExtendedProgram): void;
/**
* Restore AST nodes
*/
private restoreNodes;
/**
* Restore program node
*/
private restoreProgram;
private remapNodes;
private generateUniqueId;
}
export {};

View File

@@ -0,0 +1,987 @@
import { getWithLoc } from "../parser/converts/common.js";
import { getScopeFromNode, removeAllScopeAndVariableAndReference, removeIdentifierVariable, removeReference, removeScope, } from "../scope/index.js";
import { getKeys, traverseNodes, getNodes } from "../traverse.js";
import { UniqueIdGenerator } from "./unique.js";
import { fixLocations } from "./fix-locations.js";
/**
* Get node range
*/
function getNodeRange(node, code) {
const loc = "range" in node
? { start: node.range[0], end: node.range[1] }
: getWithLoc(node);
let start = loc.start;
let end = loc.end;
let openingParenCount = 0;
let closingParenCount = 0;
if (node.leadingComments) {
const commentStart = getWithLoc(node.leadingComments[0]).start;
if (commentStart < start) {
start = commentStart;
// Extract the number of parentheses before the node.
let leadingEnd = loc.start;
for (let index = node.leadingComments.length - 1; index >= 0; index--) {
const comment = node.leadingComments[index];
const loc = getWithLoc(comment);
for (const c of code.slice(loc.end, leadingEnd).trim()) {
if (c === "(")
openingParenCount++;
}
leadingEnd = loc.start;
}
}
}
if (node.trailingComments) {
const commentEnd = getWithLoc(node.trailingComments[node.trailingComments.length - 1]).end;
if (end < commentEnd) {
end = commentEnd;
// Extract the number of parentheses after the node.
let trailingStart = loc.end;
for (const comment of node.trailingComments) {
const loc = getWithLoc(comment);
for (const c of code.slice(trailingStart, loc.start).trim()) {
if (c === ")")
closingParenCount++;
}
trailingStart = loc.end;
}
}
}
// Adjust the range so that the parentheses match up.
if (openingParenCount < closingParenCount) {
for (; openingParenCount < closingParenCount && start >= 0; start--) {
const c = code[start].trim();
if (c)
continue;
if (c !== "(")
break;
openingParenCount++;
}
}
else if (openingParenCount > closingParenCount) {
for (; openingParenCount > closingParenCount && end < code.length; end++) {
const c = code[end].trim();
if (c)
continue;
if (c !== ")")
break;
closingParenCount++;
}
}
return [start, end];
}
/**
* A class that handles script fragments.
* The script fragment AST node remaps and connects to the original directive AST node.
*/
export class ScriptLetContext {
constructor(ctx) {
this.restoreCallbacks = [];
this.programRestoreCallbacks = [];
this.closeScopeCallbacks = [];
this.unique = new UniqueIdGenerator();
this.currentScriptScopeKind = "render";
this.script = ctx.sourceCode.scripts;
this.ctx = ctx;
}
addExpression(expression, parent, typing, ...callbacks) {
const range = getNodeRange(expression, this.ctx.code);
return this.addExpressionFromRange(range, parent, typing, ...callbacks);
}
addExpressionFromRange(range, parent, typing, ...callbacks) {
const part = this.ctx.code.slice(...range);
const isTS = typing && this.ctx.isTypeScript();
this.appendScript(`(${part})${isTS ? `as (${typing})` : ""};`, range[0] - 1, this.currentScriptScopeKind, "ExpressionStatement", (st, tokens, comments, result) => {
const exprSt = st;
const tsAs = isTS
? exprSt.expression
: null;
const node = tsAs?.expression || exprSt.expression;
// Process for nodes
for (const callback of callbacks) {
callback(node, result);
}
tokens.shift(); // (
tokens.pop(); // )
tokens.pop(); // ;
if (isTS) {
for (const scope of extractTypeNodeScopes(tsAs.typeAnnotation, result)) {
removeScope(result.scopeManager, scope);
}
this.remapNodes([
{
offset: range[0] - 1,
range,
newNode: node,
},
], tokens, comments, result.visitorKeys);
}
node.parent = parent;
// Disconnect the tree structure.
exprSt.expression = null;
});
return callbacks;
}
addObjectShorthandProperty(identifier, parent, ...callbacks) {
const range = getNodeRange(identifier, this.ctx.code);
const part = this.ctx.code.slice(...range);
this.appendScript(`({${part}});`, range[0] - 2, this.currentScriptScopeKind, "ExpressionStatement", (st, tokens, _comments, result) => {
const exprSt = st;
const objectExpression = exprSt.expression;
const node = objectExpression.properties[0];
// Process for nodes
for (const callback of callbacks) {
callback(node, result);
}
node.key.parent = parent;
node.value.parent = parent;
tokens.shift(); // (
tokens.shift(); // {
tokens.pop(); // }
tokens.pop(); // )
tokens.pop(); // ;
// Disconnect the tree structure.
exprSt.expression = null;
});
}
addVariableDeclarator(declarator, parent, ...callbacks) {
const range = declarator.type === "VariableDeclarator"
? // As of Svelte v5-next.65, VariableDeclarator nodes do not have location information.
[
getNodeRange(declarator.id, this.ctx.code)[0],
getNodeRange(declarator.init, this.ctx.code)[1],
]
: getNodeRange(declarator, this.ctx.code);
const part = this.ctx.code.slice(...range);
this.appendScript(`const ${part};`, range[0] - 6, this.currentScriptScopeKind, "VariableDeclaration", (st, tokens, _comments, result) => {
const decl = st;
const node = decl.declarations[0];
// Process for nodes
for (const callback of callbacks) {
callback(node, result);
}
const scope = result.getScope(decl);
for (const variable of scope.variables) {
for (const def of variable.defs) {
if (def.parent === decl) {
def.parent = parent;
}
}
}
node.parent = parent;
tokens.shift(); // const
tokens.pop(); // ;
// Disconnect the tree structure.
decl.declarations = [];
});
return callbacks;
}
addDeclaration(declaration, parent, ...callbacks) {
const range = getNodeRange(declaration, this.ctx.code);
const part = this.ctx.code.slice(...range);
this.appendScript(`${part};`, range[0], this.currentScriptScopeKind, "VariableDeclaration", (st, tokens, _comments, result) => {
const node = st;
for (const callback of callbacks) {
callback(node, result);
}
node.parent = parent;
result.addPostProcess(() => {
fixLocations(node, [], [], range[0] - node.range[0], result.visitorKeys, this.ctx);
const locs = this.ctx.getConvertLocation({
start: range[0],
end: range[1],
});
node.range = locs.range;
node.loc = locs.loc;
});
tokens.pop(); // ;
});
return callbacks;
}
addGenericTypeAliasDeclaration(param, callbackId, callbackDefault) {
const ranges = getTypeParameterRanges(this.ctx.code, param);
let scriptLet = `type ${this.ctx.code.slice(...ranges.idRange)}`;
if (ranges.constraintRange) {
scriptLet += ` = ${this.ctx.code.slice(...ranges.constraintRange)};`;
// |extends|
}
else {
scriptLet += " = unknown;";
}
this.appendScript(scriptLet, ranges.idRange[0] - 5, "generics", "TSTypeAliasDeclaration", (st, tokens, _comments, result) => {
const decl = st;
const id = decl.id;
const typeAnnotation = decl.typeAnnotation;
// Process for nodes
callbackId(id, typeAnnotation);
const scope = result.getScope(decl);
for (const variable of scope.variables) {
for (const def of variable.defs) {
if (def.node === decl) {
def.node = param;
}
}
}
id.parent = param;
typeAnnotation.parent = param;
tokens.shift(); // type
if (ranges.constraintRange) {
const eqToken = tokens[1];
eqToken.type = "Keyword";
eqToken.value = "extends";
eqToken.range[0] = eqToken.range[0] - 1;
eqToken.range[1] = eqToken.range[0] + 7;
tokens.pop(); // ;
}
else {
tokens.pop(); // ;
tokens.pop(); // unknown
tokens.pop(); // =
}
// Disconnect the tree structure.
delete decl.id;
delete decl.typeAnnotation;
delete decl.typeParameters;
});
if (ranges.defaultRange) {
const eqDefaultType = this.ctx.code.slice(ranges.constraintRange?.[1] ?? ranges.idRange[1], ranges.defaultRange[1]);
const id = this.generateUniqueId(eqDefaultType);
const scriptLet = `type ${id}${eqDefaultType};`;
this.appendScript(scriptLet, ranges.defaultRange[0] - 5 - id.length - 1, "generics", "TSTypeAliasDeclaration", (st, tokens, _comments, result) => {
const decl = st;
const typeAnnotation = decl.typeAnnotation;
// Process for nodes
callbackDefault(typeAnnotation);
const scope = result.getScope(decl);
removeIdentifierVariable(decl.id, scope);
typeAnnotation.parent = param;
tokens.shift(); // type
tokens.shift(); // ${id}
tokens.pop(); // ;
// Disconnect the tree structure.
delete decl.id;
delete decl.typeAnnotation;
delete decl.typeParameters;
});
}
}
nestIfBlock(expression, ifBlock, callback) {
const range = getNodeRange(expression, this.ctx.code);
const part = this.ctx.code.slice(...range);
const restore = this.appendScript(`if(${part}){`, range[0] - 3, this.currentScriptScopeKind, "IfStatement", (st, tokens, _comments, result) => {
const ifSt = st;
const node = ifSt.test;
const scope = result.getScope(ifSt.consequent);
// Process for nodes
callback(node, result);
node.parent = ifBlock;
// Process for scope
result.registerNodeToScope(ifBlock, scope);
tokens.shift(); // if
tokens.shift(); // (
if (ifSt.alternate) {
tokens.pop(); // else
}
tokens.pop(); // }
tokens.pop(); // {
tokens.pop(); // )
// Disconnect the tree structure.
ifSt.test = null;
ifSt.consequent = null;
ifSt.alternate = null;
});
this.pushScope(restore, "}", this.currentScriptScopeKind);
return {
beginElse: () => {
this.closeScope();
this.script.addLet("else ", this.currentScriptScopeKind);
// Keep the IfStatement's restore range open until its alternate ends.
this.pushScope(restore, "", this.currentScriptScopeKind);
},
};
}
nestEachBlock(expression, context, indexRange, eachBlock, callback) {
const exprRange = getNodeRange(expression, this.ctx.code);
const ctxRange = context && getNodeRange(context, this.ctx.code);
let source = "Array.from(";
const exprOffset = source.length;
source += `${this.ctx.code.slice(...exprRange)}).forEach((`;
const ctxOffset = source.length;
if (ctxRange) {
source += this.ctx.code.slice(...ctxRange);
}
else {
source += "__$ctx__";
}
let idxOffset = null;
if (indexRange) {
source += ",";
idxOffset = source.length;
source += this.ctx.code.slice(indexRange.start, indexRange.end);
}
source += ")=>{";
const restore = this.appendScript(source, exprRange[0] - exprOffset, this.currentScriptScopeKind, "ExpressionStatement", (st, tokens, comments, result) => {
const expSt = st;
const call = expSt.expression;
const fn = call.arguments[0];
const callArrayFrom = call.callee
.object;
const expr = callArrayFrom.arguments[0];
const ctx = fn.params[0];
const idx = (fn.params[1] ?? null);
const scope = result.getScope(fn.body);
// Process for nodes
callback(expr, context ? ctx : null, idx);
// Process for scope
result.registerNodeToScope(eachBlock, scope);
for (const v of scope.variables) {
for (const def of v.defs) {
if (def.node === fn) {
def.node = eachBlock;
}
}
}
if (!context) {
// remove `__$ctx__` variable
removeIdentifierVariable(ctx, scope);
}
// remove Array reference
const arrayId = callArrayFrom.callee
.object;
const ref = scope.upper.references.find((r) => r.identifier === arrayId);
if (ref) {
removeReference(ref, scope.upper);
}
expr.parent = eachBlock;
ctx.parent = eachBlock;
if (idx) {
idx.parent = eachBlock;
}
tokens.shift(); // Array
tokens.shift(); // .
tokens.shift(); // from
tokens.shift(); // (
tokens.pop(); // )
tokens.pop(); // =>
tokens.pop(); // {
tokens.pop(); // }
tokens.pop(); // )
tokens.pop(); // ;
const map = [
{
offset: exprOffset,
range: exprRange,
newNode: expr,
},
];
if (ctxRange) {
map.push({
offset: ctxOffset,
range: ctxRange,
newNode: ctx,
});
}
if (indexRange) {
map.push({
offset: idxOffset,
range: [indexRange.start, indexRange.end],
newNode: idx,
});
}
this.remapNodes(map, tokens, comments, result.visitorKeys);
// Disconnect the tree structure.
expSt.expression = null;
});
this.pushScope(restore, "});", this.currentScriptScopeKind);
}
nestSnippetBlock(id, closeParentIndex, snippetBlock,
// If set to null, `currentScriptScopeKind` will be used.
kind, paramTypes, callback) {
const scopeKind = kind || this.currentScriptScopeKind;
const idRange = getNodeRange(id, this.ctx.code);
// Type annotations are spliced in after the parameters they type. Each one
// shifts what follows it, so record where it lands in the virtual code.
const insertions = [];
let part = "";
let cursor = idRange[0];
for (const { param, type } of paramTypes ?? []) {
const paramEnd = getWithLoc(param).end;
part += this.ctx.code.slice(cursor, paramEnd);
const annotation = `: (${type})`;
const start = paramEnd + (part.length - (paramEnd - idRange[0]));
insertions.push({ start, end: start + annotation.length });
part += annotation;
cursor = paramEnd;
}
part += this.ctx.code.slice(cursor, closeParentIndex + 1);
// Type snippet calls as svelte2tsx does, not as `void`. Call a `Snippet`
// instead of using `ReturnType`, which a user type can shadow.
const isTypeScript = this.ctx.isTypeScript();
const closeToken = isTypeScript
? "return (null as unknown as import('svelte').Snippet)();}"
: "}";
const restore = this.appendScript(`function ${part}{`, idRange[0] - 9, scopeKind, "FunctionDeclaration", (st, tokens, comments, result) => {
const fnDecl = st;
const idNode = fnDecl.id;
const params = [...fnDecl.params];
const scope = result.getScope(fnDecl);
// This must run before `removeSnippetParamTypes` shifts the tokens.
if (isTypeScript) {
const returnStatement = fnDecl.body.body.pop();
removeAllScopeAndVariableAndReference(returnStatement, result);
const start = tokens.findIndex((t) => returnStatement.range[0] <= t.range[0]);
const end = tokens.findIndex((t) => returnStatement.range[1] <= t.range[0]);
tokens.splice(start, end - start);
}
if (insertions.length) {
this.removeSnippetParamTypes(params, insertions, tokens, comments, result);
}
// Process for nodes
callback(idNode, params);
idNode.parent = snippetBlock;
for (const param of params) {
param.parent = snippetBlock;
}
// Process for scope
result.registerNodeToScope(snippetBlock, scope);
tokens.shift(); // function
tokens.pop(); // {
tokens.pop(); // }
// Disconnect the tree structure.
fnDecl.id = null;
fnDecl.params = [];
});
this.pushScope(restore, closeToken, scopeKind);
}
/**
* Strip the annotations spliced in by `nestSnippetBlock` and shift everything
* after each one back to its original source location.
*/
removeSnippetParamTypes(params, insertions, tokens, comments, result) {
function shiftAt(position) {
let shift = 0;
for (const insertion of insertions) {
if (insertion.end <= position) {
shift += insertion.end - insertion.start;
}
}
return shift;
}
for (const param of params) {
const typeAnnotation = param
.typeAnnotation;
if (typeAnnotation &&
insertions.some(({ start }) => start === typeAnnotation.range[0])) {
delete param.typeAnnotation;
param.range[1] = typeAnnotation.range[0];
param.loc = this.ctx.getConvertLocation({
start: param.range[0],
end: param.range[1],
}).loc;
removeAllScopeAndVariableAndReference(typeAnnotation, result);
}
fixLocations(param, [], [], -shiftAt(param.range[0]), result.visitorKeys, this.ctx);
}
const ctx = this.ctx;
function relocate(target) {
const shift = shiftAt(target.range[0]);
const locs = ctx.getConvertLocation({
start: target.range[0] - shift,
end: target.range[1] - shift,
});
target.range = locs.range;
target.loc = locs.loc;
}
for (let index = tokens.length - 1; index >= 0; index--) {
const token = tokens[index];
if (insertions.some(({ start, end }) => start <= token.range[0] && token.range[1] <= end)) {
tokens.splice(index, 1);
}
else {
relocate(token);
}
}
comments.forEach(relocate);
}
nestBlock(block, params) {
let resolvedParams;
if (typeof params === "function") {
if (this.ctx.isTypeScript()) {
const generatedTypes = params({
generateUniqueId: (base) => this.generateUniqueId(base),
});
resolvedParams = [generatedTypes.param];
if (generatedTypes.preparationScript) {
for (const preparationScript of generatedTypes.preparationScript) {
this.appendScriptWithoutOffset(preparationScript.script, this.currentScriptScopeKind, preparationScript.nodeType, (node, tokens, comments, result) => {
tokens.length = 0;
comments.length = 0;
removeAllScopeAndVariableAndReference(node, result);
});
}
}
}
else {
const generatedTypes = params(null);
resolvedParams = [generatedTypes.param];
}
}
else {
resolvedParams = params;
}
if (!resolvedParams || resolvedParams.length === 0) {
const restore = this.appendScript(`{`, block.range[0], this.currentScriptScopeKind, "BlockStatement", (st, tokens, _comments, result) => {
const blockSt = st;
// Process for scope
const scope = result.getScope(blockSt);
result.registerNodeToScope(block, scope);
tokens.length = 0; // clear tokens
// Disconnect the tree structure.
blockSt.body = null;
});
this.pushScope(restore, "}", this.currentScriptScopeKind);
}
else {
const sortedParams = [...resolvedParams]
.map((d) => {
return {
...d,
range: getNodeRange(d.node, this.ctx.code),
};
})
.sort((a, b) => {
const [pA] = a.range;
const [pB] = b.range;
return pA - pB;
});
const maps = [];
let source = "";
for (let index = 0; index < sortedParams.length; index++) {
const param = sortedParams[index];
const range = param.range;
if (source) {
source += ",";
}
const offset = source.length + 1; /* ( */
source += this.ctx.code.slice(...range);
maps.push({
index: maps.length,
offset,
range,
});
if (this.ctx.isTypeScript()) {
source += `: (${param.typing})`;
}
}
const restore = this.appendScript(`(${source})=>{`, maps[0].range[0] - 1, this.currentScriptScopeKind, "ExpressionStatement", (st, tokens, comments, result) => {
const exprSt = st;
const fn = exprSt.expression;
const scope = result.getScope(fn.body);
// Process for nodes
for (let index = 0; index < fn.params.length; index++) {
const p = fn.params[index];
sortedParams[index].callback(p, result);
if (this.ctx.isTypeScript()) {
const typeAnnotation = p.typeAnnotation;
delete p.typeAnnotation;
p.range[1] = typeAnnotation.range[0];
p.loc.end = {
line: typeAnnotation.loc.start.line,
column: typeAnnotation.loc.start.column,
};
removeAllScopeAndVariableAndReference(typeAnnotation, result);
}
p.parent = sortedParams[index].parent;
}
// Process for scope
result.registerNodeToScope(block, scope);
for (const v of scope.variables) {
for (const def of v.defs) {
if (def.node === fn) {
def.node = block;
}
}
}
tokens.shift(); // (
tokens.pop(); // )
tokens.pop(); // =>
tokens.pop(); // {
tokens.pop(); // }
tokens.pop(); // ;
this.remapNodes(maps.map((m) => {
return {
offset: m.offset,
range: m.range,
newNode: fn.params[m.index],
};
}), tokens, comments, result.visitorKeys);
// Disconnect the tree structure.
exprSt.expression = null;
});
this.pushScope(restore, "};", this.currentScriptScopeKind);
}
}
closeScope() {
this.closeScopeCallbacks.pop()();
}
addProgramRestore(callback) {
this.programRestoreCallbacks.push(callback);
}
appendScript(text, offset, kind, nodeType, callback) {
const resultCallback = this.appendScriptWithoutOffset(text, kind, nodeType, (node, tokens, comments, result) => {
fixLocations(node, tokens, comments, offset - resultCallback.start, result.visitorKeys, this.ctx);
callback(node, tokens, comments, result);
});
return resultCallback;
}
appendScriptWithoutOffset(text, kind, nodeType, callback) {
const { start: startOffset, end: endOffset } = this.script.addLet(text, kind);
const restoreCallback = {
start: startOffset,
end: endOffset,
nodeType,
callback,
};
this.restoreCallbacks.push(restoreCallback);
return restoreCallback;
}
pushScope(restoreCallback, closeToken, kind) {
const upper = this.currentScriptScopeKind;
this.currentScriptScopeKind = kind;
this.closeScopeCallbacks.push(() => {
this.script.addLet(closeToken, kind);
this.currentScriptScopeKind = upper;
restoreCallback.end = this.script.getCurrentVirtualCodeLength();
});
}
/**
* Restore AST nodes
*/
restore(result) {
const nodeToScope = getNodeToScope(result.scopeManager);
const postprocessList = [];
const callbackOption = {
getScope,
registerNodeToScope,
scopeManager: result.scopeManager,
visitorKeys: result.visitorKeys,
addPostProcess: (cb) => postprocessList.push(cb),
};
this.restoreNodes(result, callbackOption);
this.restoreProgram(result, callbackOption);
postprocessList.forEach((p) => p());
// Helpers
/** Get scope */
function getScope(node) {
return getScopeFromNode(result.scopeManager, node);
}
/** Register node to scope */
function registerNodeToScope(node, scope) {
// If we replace the `scope.block` at this time,
// the scope restore calculation will not work, so we will replace the `scope.block` later.
postprocessList.push(() => {
const beforeBlock = scope.block;
scope.block = node;
for (const variable of [
...scope.variables,
...(scope.upper?.variables ?? []),
]) {
for (const def of variable.defs) {
if (def.node === beforeBlock) {
def.node = node;
}
}
}
});
const scopes = nodeToScope.get(node);
if (scopes) {
scopes.push(scope);
}
else {
nodeToScope.set(node, [scope]);
}
}
}
/**
* Restore AST nodes
*/
restoreNodes(result, callbackOption) {
let orderedRestoreCallback = this.restoreCallbacks.shift();
if (!orderedRestoreCallback) {
return;
}
const separateIndexes = this.script.separateIndexes;
const tokens = result.ast.tokens;
const processedTokens = [];
const comments = result.ast.comments;
const processedComments = [];
let tok;
while ((tok = tokens.shift())) {
if (separateIndexes.includes(tok.range[0]) && tok.value === ";") {
break;
}
if (orderedRestoreCallback.start <= tok.range[0]) {
tokens.unshift(tok);
break;
}
processedTokens.push(tok);
}
while ((tok = comments.shift())) {
if (orderedRestoreCallback.start <= tok.range[0]) {
comments.unshift(tok);
break;
}
processedComments.push(tok);
}
const targetNodes = new Map();
const removeStatements = [];
traverseNodes(result.ast, {
visitorKeys: result.visitorKeys,
enterNode: (node) => {
while (node.range && separateIndexes.includes(node.range[1] - 1)) {
node.range[1]--;
node.loc.end.column--;
}
if (node.loc.end.column < 0) {
node.loc.end = this.ctx.getLocFromIndex(node.range[1]);
}
if (node.parent === result.ast &&
separateIndexes[0] <= node.range[0]) {
removeStatements.push(node);
}
if (!orderedRestoreCallback) {
return;
}
if (orderedRestoreCallback.nodeType === node.type &&
orderedRestoreCallback.start <= node.range[0] &&
node.range[1] <= orderedRestoreCallback.end) {
targetNodes.set(node, orderedRestoreCallback);
orderedRestoreCallback = this.restoreCallbacks.shift();
}
//
},
leaveNode(node) {
const restoreCallback = targetNodes.get(node);
if (!restoreCallback) {
return;
}
const startIndex = {
token: tokens.findIndex((t) => restoreCallback.start <= t.range[0]),
comment: comments.findIndex((t) => restoreCallback.start <= t.range[0]),
};
if (startIndex.comment === -1) {
startIndex.comment = comments.length;
}
const endIndex = {
token: tokens.findIndex((t) => restoreCallback.end < t.range[1], startIndex.token),
comment: comments.findIndex((t) => restoreCallback.end < t.range[1], startIndex.comment),
};
if (endIndex.token === -1) {
endIndex.token = tokens.length;
}
if (endIndex.comment === -1) {
endIndex.comment = comments.length;
}
const targetTokens = tokens.splice(startIndex.token, endIndex.token - startIndex.token);
const targetComments = comments.splice(startIndex.comment, endIndex.comment - startIndex.comment);
restoreCallback.callback(node, targetTokens, targetComments, callbackOption);
processedTokens.push(...targetTokens);
processedComments.push(...targetComments);
},
});
for (const st of removeStatements) {
const index = result.ast.body.indexOf(st);
result.ast.body.splice(index, 1);
}
result.ast.tokens = processedTokens;
result.ast.comments = processedComments;
}
/**
* Restore program node
*/
restoreProgram(result, callbackOption) {
for (const callback of this.programRestoreCallbacks) {
callback(result.ast, result.ast.tokens, result.ast.comments, callbackOption);
}
}
remapNodes(maps, tokens, comments, visitorKeys) {
const targetMaps = [...maps];
const first = targetMaps.shift();
let tokenIndex = 0;
for (; tokenIndex < tokens.length; tokenIndex++) {
const token = tokens[tokenIndex];
if (first.range[1] <= token.range[0]) {
break;
}
}
for (const map of targetMaps) {
const startOffset = map.offset - first.offset + first.range[0];
const endOffset = startOffset + (map.range[1] - map.range[0]);
let removeCount = 0;
let target = tokens[tokenIndex];
while (target && target.range[1] <= startOffset) {
removeCount++;
target = tokens[tokenIndex + removeCount];
}
if (removeCount) {
tokens.splice(tokenIndex, removeCount);
}
const bufferTokens = [];
for (; tokenIndex < tokens.length; tokenIndex++) {
const token = tokens[tokenIndex];
if (endOffset <= token.range[0]) {
break;
}
bufferTokens.push(token);
}
fixLocations(map.newNode, bufferTokens, comments.filter((t) => startOffset <= t.range[0] && t.range[1] <= endOffset), map.range[0] - startOffset, visitorKeys, this.ctx);
}
tokens.splice(tokenIndex);
}
generateUniqueId(base) {
return this.unique.generate(base, this.ctx.code, this.script.getCurrentVirtualCode());
}
}
function getTypeParameterRanges(code, param) {
const idRange = [
param.range[0],
param.constraint || param.default ? param.name.range[1] : param.range[1],
];
let constraintRange = null;
let defaultRange = null;
if (param.constraint) {
constraintRange = [
param.constraint.range[0],
param.default ? param.constraint.range[1] : param.range[1],
];
const index = getTokenIndex(code, (code, index) => code.startsWith("extends", index), idRange[1], param.constraint.range[0]);
if (index != null) {
idRange[1] = index;
constraintRange[0] = index + 7;
}
}
if (param.default) {
defaultRange = [param.default.range[0], param.range[1]];
const index = getTokenIndex(code, (code, index) => code[index] === "=", constraintRange?.[1] ?? idRange[1], param.default.range[0]);
if (index != null) {
(constraintRange ?? idRange)[1] = index;
defaultRange[0] = index + 1;
}
}
return { idRange, constraintRange, defaultRange };
}
function getTokenIndex(code, targetToken, start, end) {
let index = start;
while (index < end) {
if (targetToken(code, index)) {
return index;
}
if (code.startsWith("//", index)) {
const lfIndex = code.indexOf("\n", index);
if (lfIndex >= 0) {
index = lfIndex + 1;
continue;
}
return null;
}
if (code.startsWith("/*", index)) {
const endIndex = code.indexOf("*/", index);
if (endIndex >= 0) {
index = endIndex + 2;
continue;
}
return null;
}
index++;
}
return null;
}
/** Get the node to scope map from given scope manager */
function getNodeToScope(scopeManager) {
if ("__nodeToScope" in scopeManager) {
return scopeManager.__nodeToScope;
}
// transform scopeManager
const nodeToScope = new WeakMap();
for (const scope of scopeManager.scopes) {
const scopes = nodeToScope.get(scope.block);
if (scopes) {
scopes.push(scope);
}
else {
nodeToScope.set(scope.block, [scope]);
}
}
scopeManager.acquire = function (node, inner) {
/**
* predicate
*/
function predicate(testScope) {
if (testScope.type === "function" && testScope.functionExpressionScope) {
return false;
}
return true;
}
const scopes = nodeToScope.get(node);
if (!scopes || scopes.length === 0) {
return null;
}
// Heuristic selection from all scopes.
// If you would like to get all scopes, please use ScopeManager#acquireAll.
if (scopes.length === 1) {
return scopes[0];
}
if (inner) {
for (let i = scopes.length - 1; i >= 0; --i) {
const scope = scopes[i];
if (predicate(scope)) {
return scope;
}
}
}
else {
for (let i = 0, iz = scopes.length; i < iz; ++i) {
const scope = scopes[i];
if (predicate(scope)) {
return scope;
}
}
}
return null;
};
return nodeToScope;
}
/** Extract the type scope of the given node. */
function extractTypeNodeScopes(node, result) {
const scopes = new Set();
for (const scope of iterateTypeNodeScopes(node)) {
scopes.add(scope);
}
return scopes;
/** Iterate the type scope of the given node. */
function* iterateTypeNodeScopes(node) {
if (node.type === "TSParenthesizedType") {
// Skip TSParenthesizedType.
yield* iterateTypeNodeScopes(node.typeAnnotation);
}
else if (node.type === "TSConditionalType") {
yield result.getScope(node);
// `falseType` of `TSConditionalType` is sibling scope.
const falseType = node.falseType;
yield* iterateTypeNodeScopes(falseType);
}
else if (node.type === "TSFunctionType" ||
node.type === "TSMappedType" ||
node.type === "TSConstructorType") {
yield result.getScope(node);
}
else {
const typeNode = node;
for (const key of getKeys(typeNode, result.visitorKeys)) {
for (const child of getNodes(typeNode, key)) {
yield* iterateTypeNodeScopes(child);
}
}
}
}
}

View File

@@ -0,0 +1,5 @@
export declare class UniqueIdGenerator {
private uniqueIdSeq;
private readonly usedUniqueIds;
generate(base: string, ...texts: string[]): string;
}

View File

@@ -0,0 +1,15 @@
export class UniqueIdGenerator {
constructor() {
this.uniqueIdSeq = 1;
this.usedUniqueIds = new Set();
}
generate(base, ...texts) {
const hasId = (id) => this.usedUniqueIds.has(id) || texts.some((t) => t.includes(id));
let candidate = `$_${base.replace(/\W/g, "_")}${this.uniqueIdSeq++}`;
while (hasId(candidate)) {
candidate = `$_${base.replace(/\W/g, "_")}${this.uniqueIdSeq++}`;
}
this.usedUniqueIds.add(candidate);
return candidate;
}
}

13
node_modules/svelte-eslint-parser/lib/errors.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import type { Context } from "./context/index.js";
/**
* Svelte parse errors.
*/
export declare class ParseError extends SyntaxError {
index: number;
lineNumber: number;
column: number;
/**
* Initialize this ParseError instance.
*/
constructor(message: string, offset: number, ctx: Context);
}

15
node_modules/svelte-eslint-parser/lib/errors.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
/**
* Svelte parse errors.
*/
export class ParseError extends SyntaxError {
/**
* Initialize this ParseError instance.
*/
constructor(message, offset, ctx) {
super(message);
this.index = offset;
const loc = ctx.getLocFromIndex(offset);
this.lineNumber = loc.line;
this.column = loc.column;
}
}

2
node_modules/svelte-eslint-parser/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export * from "./main.js";
export * as default from "./main.js";

2
node_modules/svelte-eslint-parser/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export * from "./main.js";
export * as default from "./main.js";

13
node_modules/svelte-eslint-parser/lib/main.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import * as AST from "./ast/index.js";
import { traverseNodes } from "./traverse.js";
import { ParseError } from "./errors.js";
export { parseForESLint, type StyleContext, type StyleContextNoStyleElement, type StyleContextParseError, type StyleContextSuccess, type StyleContextUnknownLang, } from "./parser/index.js";
export { name } from "./meta.js";
export declare const meta: {
name: "svelte-eslint-parser";
version: "1.10.0";
};
export type { SvelteConfig } from "./svelte-config/index.js";
export { AST, ParseError };
export declare const VisitorKeys: import("eslint").SourceCode.VisitorKeys;
export { traverseNodes };

21
node_modules/svelte-eslint-parser/lib/main.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import * as AST from "./ast/index.js";
import { traverseNodes } from "./traverse.js";
import { KEYS } from "./visitor-keys.js";
import { ParseError } from "./errors.js";
export { parseForESLint, } from "./parser/index.js";
export { name } from "./meta.js";
// If we use `export * as meta from "./meta.js"`,
// the structuredClone performed by eslint-plugin-prettier will fail,
// so we will need to re-export it as a plain object.
// https://github.com/prettier/eslint-plugin-prettier/blob/b307125faeb58b6dbfd5d8812b2dffcfdc8358df/eslint-plugin-prettier.js#L199
import * as metaModule from "./meta.js";
export const meta = { ...metaModule };
export { AST, ParseError };
// Keys
// eslint-disable-next-line @typescript-eslint/naming-convention -- ignore
export const VisitorKeys = KEYS;
// tools
export { traverseNodes };
// Opt-in `ts.sys.readFile` hook. See `ts-sys-hook.ts`.
import { installTsSysHook } from "./ts-sys-hook.js";
installTsSysHook();

2
node_modules/svelte-eslint-parser/lib/meta.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export declare const name: "svelte-eslint-parser";
export declare const version: "1.10.0";

5
node_modules/svelte-eslint-parser/lib/meta.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
// IMPORTANT!
// This file has been automatically generated,
// in order to update its content execute "pnpm run build:meta"
export const name = "svelte-eslint-parser";
export const version = "1.10.0";

View File

@@ -0,0 +1,19 @@
import type ESTree from "estree";
import type * as eslint from "eslint";
import type { SvelteScriptElement, SvelteSnippetBlock } from "../ast/index.js";
import type { NormalizedParserOptions } from "./parser-options.js";
import type { SvelteParseContext } from "./svelte-parse-context.js";
/**
* Analyze scope
*/
export declare function analyzeScope(node: ESTree.Node, parserOptions: NormalizedParserOptions): eslint.Scope.ScopeManager;
/** Analyze reactive scope */
export declare function analyzeReactiveScope(scopeManager: eslint.Scope.ScopeManager): void;
/**
* Analyze store scope. e.g. $count
*/
export declare function analyzeStoreScope(scopeManager: eslint.Scope.ScopeManager, svelteParseContext: SvelteParseContext): void;
/** Transform props exports */
export declare function analyzePropsScope(body: SvelteScriptElement, scopeManager: eslint.Scope.ScopeManager, svelteParseContext: SvelteParseContext): void;
/** Analyze snippets in component scope */
export declare function analyzeSnippetsScope(snippets: SvelteSnippetBlock[], scopeManager: eslint.Scope.ScopeManager): void;

View File

@@ -0,0 +1,308 @@
import { getFallbackKeys } from "../traverse.js";
import { addReference, addVariable, getScopeFromNode, removeIdentifierVariable, } from "../scope/index.js";
import { addElementToSortedArray } from "../utils/index.js";
import { getGlobalsForSvelte } from "./globals.js";
import { getESLintScope } from "./eslint-scope.js";
/**
* Analyze scope
*/
export function analyzeScope(node, parserOptions) {
const ecmaVersion = parserOptions.ecmaVersion || 2020;
const ecmaFeatures = parserOptions.ecmaFeatures || {};
const sourceType = parserOptions.sourceType || "module";
const root = node.type === "Program"
? node
: {
type: "Program",
body: [node],
sourceType,
};
const { analyze } = getESLintScope();
return analyze(root, {
ignoreEval: true,
nodejsScope: false,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 2022,
sourceType,
fallback: getFallbackKeys,
});
}
/** Analyze reactive scope */
export function analyzeReactiveScope(scopeManager) {
for (const reference of [...scopeManager.globalScope.through]) {
const parent = reference.writeExpr && getParent(reference.writeExpr);
if (parent?.type === "AssignmentExpression") {
const pp = getParent(parent);
if (pp?.type === "ExpressionStatement") {
const ppp = getParent(pp);
if (ppp?.type === "SvelteReactiveStatement" && ppp.label.name === "$") {
const referenceScope = reference.from;
if (referenceScope.type === "module") {
// It is computed
transformComputedVariable(parent, ppp, reference);
continue;
}
}
}
}
}
/** Transform ref to ComputedVariable */
function transformComputedVariable(node, parent, reference) {
const referenceScope = reference.from;
const name = reference.identifier.name;
let variable = referenceScope.set.get(name);
if (!variable) {
// eslint-disable-next-line @typescript-eslint/naming-convention -- class name
const { Variable } = getESLintScope();
variable = new Variable(name, referenceScope);
variable.scope = referenceScope;
variable.name = name;
addElementToSortedArray(variable.defs, {
type: "ComputedVariable",
node: node,
parent: parent,
name: reference.identifier,
}, (a, b) => a.node.range[0] - b.node.range[0]);
addVariable(referenceScope.variables, variable);
referenceScope.set.set(name, variable);
}
addElementToSortedArray(variable.identifiers, reference.identifier, (a, b) => a.range[0] - b.range[0]);
reference.resolved = variable;
removeReferenceFromThrough(reference, referenceScope);
}
}
/**
* Analyze store scope. e.g. $count
*/
export function analyzeStoreScope(scopeManager, svelteParseContext) {
const moduleScope = scopeManager.scopes.find((scope) => scope.type === "module");
if (!moduleScope) {
return;
}
const toBeMarkAsUsedReferences = [];
const globals = getGlobalsForSvelte(svelteParseContext);
for (const reference of [...scopeManager.globalScope.through]) {
if (reference.identifier.name.startsWith("$") &&
!globals.includes(reference.identifier.name)) {
const realName = reference.identifier.name.slice(1);
const variable = moduleScope.set.get(realName);
if (variable) {
if (reference.isWriteOnly()) {
// Need mark as used
toBeMarkAsUsedReferences.push(reference);
}
// It does not write directly to the original variable.
// Therefore, this variable is always a reference.
reference.isWrite = () => false;
reference.isWriteOnly = () => false;
reference.isReadWrite = () => false;
reference.isReadOnly = () => true;
reference.isRead = () => true;
addReference(variable.references, reference);
reference.resolved = variable;
removeReferenceFromThrough(reference, moduleScope);
}
}
}
for (const variable of new Set(toBeMarkAsUsedReferences.map((ref) => ref.resolved))) {
if (variable.references.some((ref) => !toBeMarkAsUsedReferences.includes(ref) &&
ref.identifier !== variable.identifiers[0])) {
// It is already used.
continue;
}
// Add the virtual reference for reading.
addVirtualReference(variable.identifiers[0], variable, moduleScope, {
read: true,
}).svelteMarkAsUsed = true;
}
}
/** Transform props exports */
export function analyzePropsScope(body, scopeManager, svelteParseContext) {
const moduleScope = scopeManager.scopes.find((scope) => scope.type === "module");
if (!moduleScope) {
return;
}
for (const node of body.body) {
if (node.type === "ExportNamedDeclaration") {
// Process for Svelte v4 style props. e.g. `export let x`;
if (node.declaration) {
if (node.declaration.type === "VariableDeclaration") {
for (const decl of node.declaration.declarations) {
for (const pattern of extractPattern(decl.id)) {
if (pattern.type === "Identifier") {
addPropReference(pattern, moduleScope);
}
}
}
}
}
else {
for (const spec of node.specifiers) {
if (spec.local.type !== "Literal") {
addPropReference(spec.local, moduleScope);
}
}
}
}
else if (node.type === "VariableDeclaration") {
// Process if not confirmed as non-Runes mode.
if (svelteParseContext.runes !== false) {
// Process for Svelte v5 Runes props. e.g. `let { x = $bindable() } = $props()`;
for (const decl of node.declarations) {
if (decl.init?.type === "CallExpression" &&
decl.init.callee.type === "Identifier" &&
decl.init.callee.name === "$props" &&
decl.id.type === "ObjectPattern") {
for (const pattern of extractPattern(decl.id)) {
if (pattern.type === "AssignmentPattern" &&
pattern.left.type === "Identifier" &&
pattern.right.type === "CallExpression" &&
pattern.right.callee.type === "Identifier" &&
pattern.right.callee.name === "$bindable") {
addPropReference(pattern.left, moduleScope);
}
}
}
}
}
}
}
function* extractPattern(node) {
yield node;
if (node.type === "Identifier") {
return;
}
if (node.type === "ObjectPattern") {
for (const prop of node.properties) {
if (prop.type === "Property") {
yield* extractPattern(prop.value);
}
else {
yield* extractPattern(prop);
}
}
return;
}
if (node.type === "ArrayPattern") {
for (const elem of node.elements) {
if (elem) {
yield* extractPattern(elem);
}
}
return;
}
if (node.type === "AssignmentPattern") {
yield* extractPattern(node.left);
return;
}
if (node.type === "RestElement") {
yield* extractPattern(node.argument);
}
}
/** Add virtual prop reference */
function addPropReference(node, scope) {
for (const variable of scope.variables) {
if (variable.name !== node.name) {
continue;
}
if (variable.references.some((ref) => ref.sveltePropReference)) {
continue;
}
// Add the virtual reference for writing.
const reference = addVirtualReference({
...node,
// @ts-expect-error -- ignore
parent: body,
loc: {
start: { ...node.loc.start },
end: { ...node.loc.end },
},
range: [...node.range],
}, variable, scope, {
write: true,
read: true,
});
reference.sveltePropReference = true;
}
}
}
/** Analyze snippets in component scope */
export function analyzeSnippetsScope(snippets, scopeManager) {
for (const snippet of snippets) {
const parent = snippet.parent;
if (parent.type === "SvelteElement" &&
(parent.kind === "component" ||
(parent.kind === "special" &&
(parent.name.name === "svelte:component" ||
parent.name.name === "svelte:boundary")))) {
const scope = getScopeFromNode(scopeManager, snippet.id);
const upperScope = scope.upper;
if (!upperScope)
continue;
const variable = upperScope.set.get(snippet.id.name);
if (!variable)
continue;
const defIds = variable.defs.map((d) => d.name);
const refs = variable.references.filter((id) => !defIds.includes(id.identifier));
if (refs.length <= 0) {
// If the snippet is not referenced,
// remove the a variable from the upperScope.
removeIdentifierVariable(snippet.id, upperScope);
}
else {
// Add the virtual reference for reading.
const reference = addVirtualReference(snippet.id, variable, upperScope, {
read: true,
});
reference.svelteSnippetReference = true;
}
}
}
}
/** Remove reference from through */
function removeReferenceFromThrough(reference, baseScope) {
const variable = reference.resolved;
const name = reference.identifier.name;
let scope = baseScope;
while (scope) {
scope.through = scope.through.filter((ref) => {
if (reference === ref) {
return false;
}
else if (ref.identifier.name === name) {
ref.resolved = variable;
if (!variable.references.includes(ref)) {
addReference(variable.references, ref);
}
return false;
}
return true;
});
scope = scope.upper;
}
}
/**
* Add the virtual reference.
*/
function addVirtualReference(node, variable, scope, readWrite) {
// eslint-disable-next-line @typescript-eslint/naming-convention -- class name
const { Reference } = getESLintScope();
const reference = new Reference(node, scope, (readWrite.write ? 0x1 : 0) | (readWrite.read ? 0x2 : 0), null, false, false,
// for backwards compatibility
null);
reference.svelteVirtualReference = true;
reference.from = scope;
reference.identifier = node;
reference.isWrite = () => Boolean(readWrite.write);
reference.isWriteOnly = () => Boolean(readWrite.write) && !readWrite.read;
reference.isRead = () => Boolean(readWrite.read);
reference.isReadOnly = () => Boolean(readWrite.read) && !readWrite.write;
reference.isReadWrite = () => Boolean(readWrite.read && readWrite.write);
addReference(variable.references, reference);
reference.resolved = variable;
return reference;
}
/** Get parent node */
function getParent(node) {
return node.parent;
}

View File

@@ -0,0 +1,42 @@
/** Compatibility for Svelte v4 <-> v5 */
import type ESTree from "estree";
import type * as SvAST from "./svelte-ast-types.js";
import type * as Compiler from "./svelte-ast-types-for-v5.js";
export type Child = Compiler.AttachTag | Compiler.Text | Compiler.Tag | Compiler.ElementLike | Compiler.Block | Compiler.Comment;
type HasChildren = {
children?: SvAST.TemplateNode[];
};
export declare function getFragmentFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): SvAST.Fragment | Compiler.Fragment | undefined;
export declare function getInstanceFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): SvAST.Script | Compiler.Script | null | undefined;
export declare function getModuleFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): SvAST.Script | Compiler.Script | null | undefined;
/**
* Source range of the instance `<script>` content, in original-source
* coordinates. Used to tell instance-script statements apart from module-script
* ones, which the virtual code concatenates.
*/
export declare function getInstanceScriptRange(svelteAst: Compiler.Root | SvAST.AstLegacy): [number, number] | null;
export declare function getOptionsFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): Compiler.SvelteOptionsRaw | null;
export declare function getChildren(fragment: Required<HasChildren> | {
nodes: (Child | SvAST.TemplateNode)[];
}): (SvAST.TemplateNode | Child)[];
export declare function getChildren(fragment: HasChildren | {
nodes: (Child | SvAST.TemplateNode)[];
}): (SvAST.TemplateNode | Child)[] | undefined;
export declare function trimChildren(children: (SvAST.TemplateNode | Child)[]): (SvAST.TemplateNode | Child)[];
export declare function getFragment(element: {
fragment: Compiler.Fragment;
} | Required<HasChildren>): Compiler.Fragment | Required<HasChildren>;
export declare function getFragment(element: {
fragment: Compiler.Fragment;
} | HasChildren): Compiler.Fragment | HasChildren;
export declare function getModifiers(node: SvAST.Directive | SvAST.StyleDirective | Compiler.Directive): string[];
export declare function getTestFromIfBlock(block: SvAST.IfBlock | Compiler.IfBlock): ESTree.Expression;
export declare function getConsequentFromIfBlock(block: SvAST.IfBlock | Compiler.IfBlock): Compiler.Fragment | SvAST.IfBlock;
export declare function getAlternateFromIfBlock(block: SvAST.IfBlock | Compiler.IfBlock): Compiler.Fragment | SvAST.ElseBlock | null;
export declare function getBodyFromEachBlock(block: SvAST.EachBlock | Compiler.EachBlock): Compiler.Fragment | SvAST.EachBlock;
export declare function getFallbackFromEachBlock(block: SvAST.EachBlock | Compiler.EachBlock): Compiler.Fragment | SvAST.ElseBlock | null;
export declare function getPendingFromAwaitBlock(block: SvAST.AwaitBlock | Compiler.AwaitBlock): Compiler.Fragment | SvAST.PendingBlock | null;
export declare function getThenFromAwaitBlock(block: SvAST.AwaitBlock | Compiler.AwaitBlock): Compiler.Fragment | SvAST.ThenBlock | null;
export declare function getCatchFromAwaitBlock(block: SvAST.AwaitBlock | Compiler.AwaitBlock): Compiler.Fragment | SvAST.CatchBlock | null;
export declare function getDeclaratorFromConstTag(node: SvAST.ConstTag | Compiler.ConstTag): ESTree.AssignmentExpression | Compiler.ConstTag["declaration"]["declarations"][0];
export {};

163
node_modules/svelte-eslint-parser/lib/parser/compat.js generated vendored Normal file
View File

@@ -0,0 +1,163 @@
// Root
export function getFragmentFromRoot(svelteAst) {
return (svelteAst.fragment ?? svelteAst.html);
}
export function getInstanceFromRoot(svelteAst) {
return svelteAst.instance;
}
export function getModuleFromRoot(svelteAst) {
return svelteAst.module;
}
/**
* Source range of the instance `<script>` content, in original-source
* coordinates. Used to tell instance-script statements apart from module-script
* ones, which the virtual code concatenates.
*/
export function getInstanceScriptRange(svelteAst) {
const instance = getInstanceFromRoot(svelteAst);
if (!instance) {
return null;
}
const content = instance
.content;
if (content &&
typeof content.start === "number" &&
typeof content.end === "number") {
return [content.start, content.end];
}
return [instance.start, instance.end];
}
export function getOptionsFromRoot(svelteAst) {
const root = svelteAst;
if (root.options) {
return {
type: "SvelteOptions",
name: "svelte:options",
// @ts-expect-error - name_loc is required in Svelte since 5.45.3 but we can not set it.
name_loc: null,
attributes: root.options.attributes,
fragment: {
type: "Fragment",
nodes: [],
},
start: root.options.start,
end: root.options.end,
};
}
return null;
}
export function getChildren(fragment) {
return (fragment.nodes ??
fragment.children);
}
export function trimChildren(children) {
if (!startsWithWhitespace(children[0]) &&
!endsWithWhitespace(children[children.length - 1])) {
return children;
}
const nodes = [...children];
while (isWhitespace(nodes[0])) {
nodes.shift();
}
const first = nodes[0];
if (startsWithWhitespace(first)) {
nodes[0] = { ...first, data: first.data.trimStart() };
}
while (isWhitespace(nodes[nodes.length - 1])) {
nodes.pop();
}
const last = nodes[nodes.length - 1];
if (endsWithWhitespace(last)) {
nodes[nodes.length - 1] = { ...last, data: last.data.trimEnd() };
}
return nodes;
function startsWithWhitespace(child) {
if (!child) {
return false;
}
return child.type === "Text" && child.data.trimStart() !== child.data;
}
function endsWithWhitespace(child) {
if (!child) {
return false;
}
return child.type === "Text" && child.data.trimEnd() !== child.data;
}
function isWhitespace(child) {
if (!child) {
return false;
}
return child.type === "Text" && child.data.trim() === "";
}
}
export function getFragment(element) {
if (element.fragment) {
return element.fragment;
}
return element;
}
export function getModifiers(node) {
return node.modifiers ?? [];
}
// IfBlock
export function getTestFromIfBlock(block) {
return (block.expression ?? block.test);
}
export function getConsequentFromIfBlock(block) {
return block.consequent ?? block;
}
export function getAlternateFromIfBlock(block) {
if (block.alternate) {
return block.alternate;
}
return block.else ?? null;
}
// EachBlock
export function getBodyFromEachBlock(block) {
if (block.body) {
return block.body;
}
return block;
}
export function getFallbackFromEachBlock(block) {
if (block.fallback) {
return block.fallback;
}
return block.else ?? null;
}
// AwaitBlock
export function getPendingFromAwaitBlock(block) {
const pending = block.pending;
if (!pending) {
return null;
}
if (pending.type === "Fragment") {
return pending;
}
return pending.skip ? null : pending;
}
export function getThenFromAwaitBlock(block) {
const then = block.then;
if (!then) {
return null;
}
if (then.type === "Fragment") {
return then;
}
return then.skip ? null : then;
}
export function getCatchFromAwaitBlock(block) {
const catchFragment = block.catch;
if (!catchFragment) {
return null;
}
if (catchFragment.type === "Fragment") {
return catchFragment;
}
return catchFragment.skip ? null : catchFragment;
}
// ConstTag
export function getDeclaratorFromConstTag(node) {
return (node.declaration?.declarations?.[0] ??
node.expression);
}

View File

@@ -0,0 +1,6 @@
import type { SvelteAttribute, SvelteShorthandAttribute, SvelteAttachTag, SvelteDirective, SvelteSpreadAttribute, SvelteStartTag, SvelteStyleDirective } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
import type * as SvAST from "../svelte-ast-types.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
/** Convert for Attributes */
export declare function convertAttributes(attributes: (SvAST.AttributeOrDirective | Compiler.Attribute | Compiler.SpreadAttribute | Compiler.AttachTag | Compiler.Directive)[], parent: SvelteStartTag, ctx: Context): IterableIterator<SvelteAttribute | SvelteShorthandAttribute | SvelteSpreadAttribute | SvelteAttachTag | SvelteDirective | SvelteStyleDirective>;

View File

@@ -0,0 +1,697 @@
import { getWithLoc, indexOf } from "./common.js";
import { convertMustacheTag } from "./mustache.js";
import { convertTextToLiteral } from "./text.js";
import { ParseError } from "../../errors.js";
import { svelteVersion } from "../svelte-version.js";
import { hasTypeInfo } from "../../utils/index.js";
import { getModifiers } from "../compat.js";
/** Convert for Attributes */
export function* convertAttributes(attributes, parent, ctx) {
for (const attr of attributes) {
if (attr.type === "Attribute") {
yield convertAttribute(attr, parent, ctx);
continue;
}
if (attr.type === "SpreadAttribute" || attr.type === "Spread") {
yield convertSpreadAttribute(attr, parent, ctx);
continue;
}
if (attr.type === "AttachTag") {
yield convertAttachTag(attr, parent, ctx);
continue;
}
if (attr.type === "BindDirective" || attr.type === "Binding") {
yield convertBindingDirective(attr, parent, ctx);
continue;
}
if (attr.type === "OnDirective" || attr.type === "EventHandler") {
yield convertEventHandlerDirective(attr, parent, ctx);
continue;
}
if (attr.type === "ClassDirective" || attr.type === "Class") {
yield convertClassDirective(attr, parent, ctx);
continue;
}
if (attr.type === "StyleDirective") {
yield convertStyleDirective(attr, parent, ctx);
continue;
}
if (attr.type === "TransitionDirective" || attr.type === "Transition") {
yield convertTransitionDirective(attr, parent, ctx);
continue;
}
if (attr.type === "AnimateDirective" || attr.type === "Animation") {
yield convertAnimationDirective(attr, parent, ctx);
continue;
}
if (attr.type === "UseDirective" || attr.type === "Action") {
yield convertActionDirective(attr, parent, ctx);
continue;
}
if (attr.type === "LetDirective") {
yield convertLetDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Let") {
yield convertLetDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Ref") {
throw new ParseError("Ref are not supported.", attr.start, ctx);
}
if (attr.type === "Style") {
throw new ParseError(`Svelte v3.46.0 is no longer supported. Please use Svelte>=v3.46.1.`, attr.start, ctx);
}
throw new ParseError(`Unknown directive or attribute (${attr.type}) are not supported.`, attr.start, ctx);
}
}
/** Convert for Attribute */
function convertAttribute(node, parent, ctx) {
const attribute = {
type: "SvelteAttribute",
boolean: false,
key: null,
value: [],
parent,
...ctx.getConvertLocation(node),
};
const keyStart = ctx.code.indexOf(node.name, node.start);
const keyRange = { start: keyStart, end: keyStart + node.name.length };
attribute.key = {
type: "SvelteName",
name: node.name,
parent: attribute,
...ctx.getConvertLocation(keyRange),
};
if (node.value === true) {
// Boolean attribute
attribute.boolean = true;
ctx.addToken("HTMLIdentifier", keyRange);
return attribute;
}
const value = node.value;
const shorthand = isAttributeShorthandForSvelteV4(value) ||
isAttributeShorthandForSvelteV5(value);
if (shorthand) {
const key = {
...attribute.key,
type: "Identifier",
};
const sAttr = {
type: "SvelteShorthandAttribute",
key,
value: key,
parent,
loc: attribute.loc,
range: attribute.range,
};
key.parent = sAttr;
ctx.scriptLet.addObjectShorthandProperty(attribute.key, sAttr, (es) => {
if (
// FIXME: Older parsers may use the same node. In that case, do not replace.
// We will drop support for ESLint v7 in the next major version and remove this branch.
es.key !== es.value) {
sAttr.key = es.key;
}
sAttr.value = es.value;
});
return sAttr;
}
// Not required for shorthands. Therefore, register the token here.
ctx.addToken("HTMLIdentifier", keyRange);
processAttributeValue(value, attribute, parent, ctx);
return attribute;
function isAttributeShorthandForSvelteV4(value) {
return Array.isArray(value) && value[0]?.type === "AttributeShorthand";
}
function isAttributeShorthandForSvelteV5(value) {
return (!Array.isArray(value) &&
value.type === "ExpressionTag" &&
ctx.code[node.start] === "{" &&
ctx.code[node.end - 1] === "}");
}
}
/** Common process attribute value */
function processAttributeValue(nodeValue, attribute, attributeParent, ctx) {
const nodes = (Array.isArray(nodeValue) ? nodeValue : [nodeValue])
.filter((v) => v.type !== "Text" ||
// ignore empty
// https://github.com/sveltejs/svelte/pull/6539
v.start < v.end)
.map((v, index, array) => {
if (v.type === "Text") {
const next = array[index + 1];
if (next && next.start < v.end) {
// Maybe bug in Svelte can cause the completion index to shift.
return {
...v,
end: next.start,
};
}
}
return v;
});
if (nodes.length === 1 &&
(nodes[0].type === "ExpressionTag" || nodes[0].type === "MustacheTag") &&
attribute.type === "SvelteAttribute") {
const typing = buildAttributeType(attributeParent.parent, attribute.key.name, ctx);
const mustache = convertMustacheTag(nodes[0], attribute, typing, ctx);
attribute.value.push(mustache);
return;
}
for (const v of nodes) {
if (v.type === "Text") {
attribute.value.push(convertTextToLiteral(v, attribute, ctx));
continue;
}
if (v.type === "ExpressionTag" || v.type === "MustacheTag") {
const mustache = convertMustacheTag(v, attribute, null, ctx);
attribute.value.push(mustache);
continue;
}
const u = v;
throw new ParseError(`Unknown attribute value (${u.type}) are not supported.`, u.start, ctx);
}
}
/** Build attribute type */
function buildAttributeType(element, attrName, ctx) {
if (svelteVersion.gte(5) &&
attrName.startsWith("on") &&
(element.type !== "SvelteElement" || element.kind === "html")) {
return buildEventHandlerType(element, attrName.slice(2), ctx);
}
if (element.type !== "SvelteElement" || element.kind !== "component") {
return null;
}
const elementName = ctx.elements.get(element).name;
// Svelte 3/4 ComponentProps takes an instance, while Svelte 5 also accepts
// the component function. Extract the legacy constructor instance without
// relying on a locally shadowable utility type such as InstanceType.
const componentPropsType = svelteVersion.gte(5)
? `import('svelte').ComponentProps<typeof ${elementName}>`
: `(typeof ${elementName} extends new (...args: any[]) => (infer C extends import('svelte').SvelteComponent) ? import('svelte').ComponentProps<C> : never)`;
return conditional({
check: `'${attrName}'`,
extends: `infer PROP`,
true: conditional({
check: `PROP`,
extends: `keyof ${componentPropsType}`,
true: `${componentPropsType}[PROP]`,
false: `never`,
}),
false: `never`,
});
/** Generate `C extends E ? T : F` type. */
function conditional(types) {
return `${types.check} extends ${types.extends}?(${types.true}):(${types.false})`;
}
}
/** Convert for Spread */
function convertSpreadAttribute(node, parent, ctx) {
const attribute = {
type: "SvelteSpreadAttribute",
argument: null,
parent,
...ctx.getConvertLocation(node),
};
const spreadStart = ctx.code.indexOf("...", node.start);
ctx.addToken("Punctuator", {
start: spreadStart,
end: spreadStart + 3,
});
ctx.scriptLet.addExpression(node.expression, attribute, null, (es) => {
attribute.argument = es;
});
return attribute;
}
function convertAttachTag(node, parent, ctx) {
const attachTag = {
type: "SvelteAttachTag",
expression: node.expression,
parent,
...ctx.getConvertLocation(node),
};
ctx.scriptLet.addExpression(node.expression, attachTag, null, (es) => {
attachTag.expression = es;
});
const atAttachStart = ctx.code.indexOf("@attach", attachTag.range[0]);
ctx.addToken("MustacheKeyword", {
start: atAttachStart,
end: atAttachStart + 7,
});
return attachTag;
}
/** Convert for Binding Directive */
function convertBindingDirective(node, parent, ctx) {
const directive = {
type: "SvelteDirective",
kind: "Binding",
key: null,
shorthand: false,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
processDirective(node, directive, ctx, {
processExpression(expression, shorthand) {
directive.shorthand = shorthand;
return ctx.scriptLet.addExpression(expression, directive, buildFunctionBindingsType(node, parent.parent, expression, ctx), (es, { getScope }) => {
directive.expression = es;
if (isFunctionBindings(ctx, es)) {
directive.expression.type = "SvelteFunctionBindingsExpression";
return;
}
const scope = getScope(es);
const reference = scope.references.find((ref) => ref.identifier === es);
if (reference) {
// The bind directive does read and write.
reference.isWrite = () => true;
reference.isWriteOnly = () => false;
reference.isReadWrite = () => true;
reference.isReadOnly = () => false;
reference.isRead = () => true;
}
});
},
});
return directive;
}
/**
* Function bindings on a component are typed as a setter of the bound prop. The
* assertion applies to the whole `getter, setter` sequence, so it contextually
* types only the setter, whose parameter receives the prop value.
*/
function buildFunctionBindingsType(node, element, expression, ctx) {
if (element.type !== "SvelteElement" ||
element.kind !== "component" ||
expression.type !== "SequenceExpression" ||
!isFunctionBindings(ctx, {
...expression,
range: [getWithLoc(expression).start, getWithLoc(expression).end],
})) {
return null;
}
const propType = buildAttributeType(element, node.name, ctx);
// An undeclared prop resolves to `never`, which would poison the parameter.
return (propType &&
`(value: [${propType}] extends [never] ? any : (${propType})) => void`);
}
/**
* Checks whether the given expression is Function bindings (added in Svelte 5.9.0) or not.
* See https://svelte.dev/docs/svelte/bind#Function-bindings
*/
function isFunctionBindings(ctx, expression) {
// Svelte 3/4 does not support Function bindings.
if (!svelteVersion.gte(5)) {
return false;
}
if (expression.type !== "SequenceExpression" ||
expression.expressions.length !== 2) {
return false;
}
const bindValueOpenIndex = ctx.code.lastIndexOf("{", expression.range[0]);
if (bindValueOpenIndex < 0)
return false;
const betweenText = ctx.code
.slice(bindValueOpenIndex + 1, expression.range[0])
// Strip comments
.replace(/\/\/[^\n]*\n|\/\*[\s\S]*?\*\//g, "")
.trim();
return !betweenText;
}
/** Convert for EventHandler Directive */
function convertEventHandlerDirective(node, parent, ctx) {
const directive = {
type: "SvelteDirective",
kind: "EventHandler",
key: null,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
const typing = buildEventHandlerType(parent.parent, node.name, ctx);
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, typing),
});
return directive;
}
/** Build event handler type */
function buildEventHandlerType(element, eventName, ctx) {
const nativeEventHandlerType = `(e:${conditional({
check: `'${eventName}'`,
extends: `infer EVT`,
true: conditional({
check: `EVT`,
extends: `keyof HTMLElementEventMap`,
true: `HTMLElementEventMap[EVT]`,
false: `CustomEvent<any>`,
}),
false: `never`,
})})=>void`;
if (element.type !== "SvelteElement") {
return nativeEventHandlerType;
}
const elementName = ctx.elements.get(element).name;
if (element.kind === "component") {
const componentEventsType = `import('svelte').ComponentEvents<${elementName}>`;
return `(e:${conditional({
check: `0`,
extends: `(1 & ${componentEventsType})`,
// `componentEventsType` is `any`
// `@typescript-eslint/parser` currently cannot parse `*.svelte` import types correctly.
// So if we try to do a correct type parsing, it's argument type will be `any`.
// A workaround is to inject the type directly, as `CustomEvent<any>` is better than `any`.
true: `CustomEvent<any>`,
// `componentEventsType` has an exact type.
false: conditional({
check: `'${eventName}'`,
extends: `infer EVT`,
true: conditional({
check: `EVT`,
extends: `keyof ${componentEventsType}`,
true: `${componentEventsType}[EVT]`,
false: `CustomEvent<any>`,
}),
false: `never`,
}),
})})=>void`;
}
if (element.kind === "special") {
if (elementName === "svelte:component")
return `(e:CustomEvent<any>)=>void`;
return nativeEventHandlerType;
}
const attrName = `on:${eventName}`;
const svelteHTMLElementsType = "import('svelte/elements').SvelteHTMLElements";
return conditional({
check: `'${elementName}'`,
extends: "infer EL",
true: conditional({
check: `EL`,
extends: `keyof ${svelteHTMLElementsType}`,
true: conditional({
check: `'${attrName}'`,
extends: "infer ATTR",
true: conditional({
check: `ATTR`,
extends: `keyof ${svelteHTMLElementsType}[EL]`,
true: `${svelteHTMLElementsType}[EL][ATTR]`,
false: nativeEventHandlerType,
}),
false: `never`,
}),
false: nativeEventHandlerType,
}),
false: `never`,
});
/** Generate `C extends E ? T : F` type. */
function conditional(types) {
return `${types.check} extends ${types.extends}?(${types.true}):(${types.false})`;
}
}
/** Convert for Class Directive */
function convertClassDirective(node, parent, ctx) {
const directive = {
type: "SvelteDirective",
kind: "Class",
key: null,
shorthand: false,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
processDirective(node, directive, ctx, {
processExpression(expression, shorthand) {
directive.shorthand = shorthand;
return ctx.scriptLet.addExpression(expression, directive);
},
});
return directive;
}
/** Convert for Style Directive */
function convertStyleDirective(node, parent, ctx) {
const directive = {
type: "SvelteStyleDirective",
key: null,
shorthand: false,
value: [],
parent,
...ctx.getConvertLocation(node),
};
processDirectiveKey(node, directive, ctx);
const keyName = directive.key.name;
if (node.value === true) {
const shorthandDirective = directive;
shorthandDirective.shorthand = true;
ctx.scriptLet.addExpression(keyName, shorthandDirective.key, null, (expression) => {
if (expression.type !== "Identifier") {
throw new ParseError(`Expected JS identifier or attribute value.`, expression.range[0], ctx);
}
shorthandDirective.key.name = expression;
});
return shorthandDirective;
}
ctx.addToken("HTMLIdentifier", {
start: keyName.range[0],
end: keyName.range[1],
});
processAttributeValue(node.value, directive, parent, ctx);
return directive;
}
/** Convert for Transition Directive */
function convertTransitionDirective(node, parent, ctx) {
const directive = {
type: "SvelteDirective",
kind: "Transition",
intro: node.intro,
outro: node.outro,
key: null,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, null),
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier"], ctx)),
});
return directive;
}
/** Convert for Animation Directive */
function convertAnimationDirective(node, parent, ctx) {
const directive = {
type: "SvelteDirective",
kind: "Animation",
key: null,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, null),
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier"], ctx)),
});
return directive;
}
/** Convert for Action Directive */
function convertActionDirective(node, parent, ctx) {
const directive = {
type: "SvelteDirective",
kind: "Action",
key: null,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, `Parameters<typeof ${node.name}>[1]`),
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier", "MemberExpression"], ctx)),
});
return directive;
}
/** Convert for Let Directive */
function convertLetDirective(node, parent, ctx) {
const directive = {
type: "SvelteDirective",
kind: "Let",
key: null,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
processDirective(node, directive, ctx, {
processPattern(pattern) {
return ctx.letDirCollections
.getCollection()
.addPattern(pattern, directive, buildLetDirectiveType(parent.parent, node.name, ctx));
},
processName: node.expression
? undefined
: (name) => {
// shorthand
ctx.letDirCollections
.getCollection()
.addPattern(name, directive, buildLetDirectiveType(parent.parent, node.name, ctx), (es) => {
directive.expression = es;
});
return [];
},
});
return directive;
}
/** Build let directive param type */
function buildLetDirectiveType(element, letName, ctx) {
if (element.type !== "SvelteElement") {
return "any";
}
let slotName = "default";
let componentName;
const svelteNode = ctx.elements.get(element);
const slotAttr = svelteNode.attributes.find((attr) => {
return attr.type === "Attribute" && attr.name === "slot";
});
if (slotAttr) {
if (Array.isArray(slotAttr.value) &&
slotAttr.value.length === 1 &&
slotAttr.value[0].type === "Text") {
slotName = slotAttr.value[0].data;
}
else {
return "any";
}
const parent = findParentComponent(element);
if (parent == null)
return "any";
componentName = ctx.elements.get(parent).name;
}
else {
if (element.kind === "component") {
componentName = svelteNode.name;
}
else {
const parent = findParentComponent(element);
if (parent == null)
return "any";
componentName = ctx.elements.get(parent).name;
}
}
return `${String(componentName)}['$$slot_def'][${JSON.stringify(slotName)}][${JSON.stringify(letName)}]`;
/** Find parent component element */
function findParentComponent(node) {
let parent = node.parent;
while (parent && parent.type !== "SvelteElement") {
parent = parent.parent;
}
if (!parent || parent.kind !== "component") {
return null;
}
return parent;
}
}
/** Common process for directive */
function processDirective(node, directive, ctx, processors) {
processDirectiveKey(node, directive, ctx);
processDirectiveExpression(node, directive, ctx, processors);
}
/** Common process for directive key */
function processDirectiveKey(node, directive, ctx) {
const colonIndex = ctx.code.indexOf(":", directive.range[0]);
ctx.addToken("HTMLIdentifier", {
start: directive.range[0],
end: colonIndex,
});
const nameIndex = ctx.code.indexOf(node.name, colonIndex + 1);
const nameRange = {
start: nameIndex,
end: nameIndex + node.name.length,
};
let keyEndIndex = nameRange.end;
// modifiers
if (ctx.code[nameRange.end] === "|") {
let nextStart = nameRange.end + 1;
let nextEnd = indexOf(ctx.code, (c) => c === "=" || c === ">" || c === "/" || c === "|" || !c.trim(), nextStart);
ctx.addToken("HTMLIdentifier", { start: nextStart, end: nextEnd });
while (ctx.code[nextEnd] === "|") {
nextStart = nextEnd + 1;
nextEnd = indexOf(ctx.code, (c) => c === "=" || c === ">" || c === "/" || c === "|" || !c.trim(), nextStart);
ctx.addToken("HTMLIdentifier", { start: nextStart, end: nextEnd });
}
keyEndIndex = nextEnd;
}
const key = (directive.key = {
type: "SvelteDirectiveKey",
name: null,
modifiers: getModifiers(node),
parent: directive,
...ctx.getConvertLocation({ start: node.start, end: keyEndIndex }),
});
// put name
key.name = {
type: "SvelteName",
name: node.name,
parent: key,
...ctx.getConvertLocation(nameRange),
};
}
/** Common process for directive expression */
function processDirectiveExpression(node, directive, ctx, processors) {
const key = directive.key;
const keyName = key.name;
let shorthand = false;
if (node.expression) {
shorthand =
node.expression.type === "Identifier" &&
node.expression.name === node.name &&
getWithLoc(node.expression).start === keyName.range[0];
if (shorthand && getWithLoc(node.expression).end !== keyName.range[1]) {
// The identifier location may be incorrect in some edge cases.
// e.g. bind:value=""
getWithLoc(node.expression).end = keyName.range[1];
}
if (processors.processExpression) {
processors.processExpression(node.expression, shorthand).push((es) => {
if (node.expression &&
(es.type === "SvelteFunctionBindingsExpression"
? "SequenceExpression"
: es.type) !== node.expression.type) {
throw new ParseError(`Expected ${node.expression.type}, but ${es.type} found.`, es.range[0], ctx);
}
directive.expression = es;
});
}
else {
processors.processPattern(node.expression, shorthand).push((es) => {
directive.expression = es;
});
}
}
if (!shorthand) {
if (processors.processName) {
processors.processName(keyName).push((es) => {
key.name = es;
});
}
else {
ctx.addToken("HTMLIdentifier", {
start: keyName.range[0],
end: keyName.range[1],
});
}
}
}
/** Build processExpression for Expression */
function buildProcessExpressionForExpression(directive, ctx, typing) {
return (expression) => {
if (hasTypeInfo(expression)) {
return ctx.scriptLet.addExpression(expression, directive, null);
}
return ctx.scriptLet.addExpression(expression, directive, typing);
};
}
/** Build expression type checker to script let callbacks */
function buildExpressionTypeChecker(expected, ctx) {
return (node) => {
if (!expected.includes(node.type)) {
throw new ParseError(`Expected JS ${expected.join(", or ")}, but ${node.type} found.`, node.range[0], ctx);
}
};
}

View File

@@ -0,0 +1,16 @@
import type * as SvAST from "../svelte-ast-types.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
import type { SvelteAwaitBlock, SvelteEachBlock, SvelteIfBlock, SvelteIfBlockAlone, SvelteIfBlockElseIf, SvelteKeyBlock, SvelteSnippetBlock } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
export declare function convertIfBlock(node: SvAST.IfBlock | Compiler.IfBlock, parent: SvelteIfBlock["parent"], ctx: Context): SvelteIfBlockAlone;
export declare function convertIfBlock(node: SvAST.IfBlock | Compiler.IfBlock, parent: SvelteIfBlock["parent"], ctx: Context, elseifContext?: {
start: number;
}): SvelteIfBlockElseIf;
/** Convert for EachBlock */
export declare function convertEachBlock(node: SvAST.EachBlock | Compiler.EachBlock, parent: SvelteEachBlock["parent"], ctx: Context): SvelteEachBlock;
/** Convert for AwaitBlock */
export declare function convertAwaitBlock(node: SvAST.AwaitBlock | Compiler.AwaitBlock, parent: SvelteAwaitBlock["parent"], ctx: Context): SvelteAwaitBlock;
/** Convert for KeyBlock */
export declare function convertKeyBlock(node: SvAST.KeyBlock | Compiler.KeyBlock, parent: SvelteKeyBlock["parent"], ctx: Context): SvelteKeyBlock;
/** Convert for SnippetBlock */
export declare function convertSnippetBlock(node: Compiler.SnippetBlock, parent: SvelteSnippetBlock["parent"], ctx: Context): SvelteSnippetBlock;

View File

@@ -0,0 +1,555 @@
import { convertChildren } from "./element.js";
import { getWithLoc, indexOf, lastIndexOf } from "./common.js";
import { svelteVersion } from "../svelte-version.js";
import { getAlternateFromIfBlock, getBodyFromEachBlock, getCatchFromAwaitBlock, getChildren, getConsequentFromIfBlock, getFallbackFromEachBlock, getFragment, getPendingFromAwaitBlock, getTestFromIfBlock, getThenFromAwaitBlock, trimChildren, } from "../compat.js";
/** Get start index of block */
function startBlockIndex(code, endIndex, block) {
return lastIndexOf(code, (c, index) => {
if (c !== "{") {
return false;
}
for (let next = index + 1; next < code.length; next++) {
const nextC = code[next];
if (!nextC.trim()) {
continue;
}
return code.startsWith(block, next);
}
return false;
}, endIndex);
}
function startIndexFromFragment(fragment, getBeforeEndIndex) {
if (fragment.start != null) {
return fragment.start;
}
const children = getChildren(fragment);
return children.length ? children[0].start : getBeforeEndIndex();
}
function endIndexFromFragment(fragment, getBeforeEndIndex) {
if (fragment.end != null) {
return fragment.end;
}
const children = getChildren(fragment);
return children.length
? children[children.length - 1].end
: getBeforeEndIndex();
}
function endIndexFromBlock(fragment, lastExpression, ctx) {
return endIndexFromFragment(fragment, () => {
return ctx.code.indexOf("}", getWithLoc(lastExpression).end) + 1;
});
}
/** Convert for IfBlock */
export function convertIfBlock(node, parent, ctx, elseifContext) {
// {#if expr} {:else} {/if}
// {:else if expr} {/if}
const elseif = Boolean(elseifContext);
const nodeStart = startBlockIndex(ctx.code, elseifContext?.start ?? node.start, elseif ? ":else" : "#if");
const ifBlock = {
type: "SvelteIfBlock",
elseif: Boolean(elseif),
expression: null,
children: [],
else: null,
parent,
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
};
const test = getTestFromIfBlock(node);
const { beginElse } = ctx.scriptLet.nestIfBlock(test, ifBlock, (es) => {
ifBlock.expression = es;
});
const consequent = getConsequentFromIfBlock(node);
for (const child of convertChildren({
nodes:
// Adjust for Svelte v5
trimChildren(getChildren(consequent)),
}, ifBlock, ctx)) {
ifBlock.children.push(child);
}
if (elseif) {
const index = ctx.code.indexOf("if", nodeStart);
ctx.addToken("MustacheKeyword", { start: index, end: index + 2 });
}
extractMustacheBlockTokens(ifBlock, ctx, { startOnly: elseif });
const elseFragment = getAlternateFromIfBlock(node);
if (!elseFragment) {
ctx.scriptLet.closeScope();
return ifBlock;
}
beginElse();
const elseStart = startBlockIndexForElse(elseFragment, consequent, test, ctx);
const elseChildren = getChildren(elseFragment);
if (elseChildren.length === 1) {
const c = elseChildren[0];
if (c.type === "IfBlock" && c.elseif) {
const elseBlock = {
type: "SvelteElseBlock",
elseif: true,
children: [],
parent: ifBlock,
...ctx.getConvertLocation({
start: elseStart,
end: c.end,
}),
};
ifBlock.else = elseBlock;
const elseIfBlock = convertIfBlock(c, elseBlock, ctx, {
start: elseStart,
});
// adjust loc
elseBlock.range[1] = elseIfBlock.range[1];
elseBlock.loc.end = {
line: elseIfBlock.loc.end.line,
column: elseIfBlock.loc.end.column,
};
elseBlock.children = [elseIfBlock];
ctx.scriptLet.closeScope();
return ifBlock;
}
}
const elseBlock = {
type: "SvelteElseBlock",
elseif: false,
children: [],
parent: ifBlock,
...ctx.getConvertLocation({
start: elseStart,
end: endIndexFromFragment(elseFragment, () => ctx.code.indexOf("}", elseStart + 5) + 1),
}),
};
ifBlock.else = elseBlock;
ctx.scriptLet.nestBlock(elseBlock);
for (const child of convertChildren({
nodes:
// Adjust for Svelte v5
trimChildren(elseChildren),
}, elseBlock, ctx)) {
elseBlock.children.push(child);
}
ctx.scriptLet.closeScope(); // else block
ctx.scriptLet.closeScope(); // if statement
extractMustacheBlockTokens(elseBlock, ctx, { startOnly: true });
return ifBlock;
}
function startBlockIndexForElse(elseFragment, beforeFragment, lastExpression, ctx) {
const elseChildren = getChildren(elseFragment);
if (elseChildren.length > 0) {
const c = elseChildren[0];
if (c.type === "IfBlock" && c.elseif) {
const contentStart = getWithLoc(getTestFromIfBlock(c)).start;
if (contentStart <= c.start) {
return startBlockIndex(ctx.code, contentStart - 1, ":else");
}
}
return startBlockIndex(ctx.code, c.start, ":else");
}
const beforeEnd = endIndexFromFragment(beforeFragment, () => {
return ctx.code.indexOf("}", getWithLoc(lastExpression).end) + 1;
});
return startBlockIndex(ctx.code, beforeEnd, ":else");
}
/** Convert for EachBlock */
export function convertEachBlock(node, parent, ctx) {
// {#each expr as item, index (key)} {/each}
const nodeStart = startBlockIndex(ctx.code, node.start, "#each");
const eachBlock = {
type: "SvelteEachBlock",
expression: null,
context: null,
index: null,
key: null,
children: [],
else: null,
parent,
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
};
let indexRange = null;
if (node.index) {
const start = ctx.code.indexOf(node.index, getWithLoc(node.context ?? node.expression).end);
indexRange = {
start,
end: start + node.index.length,
};
}
ctx.scriptLet.nestEachBlock(node.expression, node.context, indexRange, eachBlock, (expression, context, index) => {
eachBlock.expression = expression;
eachBlock.context = context;
eachBlock.index = index;
});
if (node.context) {
const asStart = ctx.code.indexOf("as", getWithLoc(node.expression).end);
ctx.addToken("Keyword", {
start: asStart,
end: asStart + 2,
});
}
if (node.key) {
ctx.scriptLet.addExpression(node.key, eachBlock, null, (key) => {
eachBlock.key = key;
});
}
const body = getBodyFromEachBlock(node);
eachBlock.children.push(...convertChildren({
nodes:
// Adjust for Svelte v5
trimChildren(getChildren(body)),
}, eachBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(eachBlock, ctx);
const fallbackFragment = getFallbackFromEachBlock(node);
if (!fallbackFragment) {
return eachBlock;
}
const elseStart = startBlockIndexForElse(fallbackFragment, body, node.key || indexRange || node.context || node.expression, ctx);
const elseBlock = {
type: "SvelteElseBlock",
elseif: false,
children: [],
parent: eachBlock,
...ctx.getConvertLocation({
start: elseStart,
end: endIndexFromFragment(fallbackFragment, () => elseStart),
}),
};
eachBlock.else = elseBlock;
ctx.scriptLet.nestBlock(elseBlock);
elseBlock.children.push(...convertChildren({
nodes:
// Adjust for Svelte v5
trimChildren(getChildren(fallbackFragment)),
}, elseBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(elseBlock, ctx, { startOnly: true });
return eachBlock;
}
/** Convert for AwaitBlock */
export function convertAwaitBlock(node, parent, ctx) {
const nodeStart = startBlockIndex(ctx.code, node.start, "#await");
const awaitBlock = {
type: "SvelteAwaitBlock",
expression: null,
kind: "await",
pending: null,
then: null,
catch: null,
parent,
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
};
ctx.scriptLet.addExpression(node.expression, awaitBlock, null, (expression) => {
awaitBlock.expression = expression;
});
const pending = getPendingFromAwaitBlock(node);
if (pending) {
const pendingBlock = {
type: "SvelteAwaitPendingBlock",
children: [],
parent: awaitBlock,
...ctx.getConvertLocation({
start: awaitBlock.range[0],
end: endIndexFromBlock(pending, node.expression, ctx),
}),
};
ctx.scriptLet.nestBlock(pendingBlock);
pendingBlock.children.push(...convertChildren(pending, pendingBlock, ctx));
awaitBlock.pending = pendingBlock;
ctx.scriptLet.closeScope();
}
const then = getThenFromAwaitBlock(node);
if (then) {
const awaitThen = !pending;
if (awaitThen) {
awaitBlock.kind = "await-then";
}
const thenStart = awaitBlock.pending
? startBlockIndex(ctx.code, node.value
? getWithLoc(node.value).start
: startIndexFromFragment(then, () => {
return awaitBlock.pending.range[1];
}), ":then")
: nodeStart;
const thenBlock = {
type: "SvelteAwaitThenBlock",
awaitThen,
value: null,
children: [],
parent: awaitBlock,
...ctx.getConvertLocation({
start: thenStart,
end: endIndexFromFragment(then, () => {
return (ctx.code.indexOf("}", node.value ? getWithLoc(node.value).end : thenStart + 5) + 1);
}),
}),
};
if (node.value) {
const baseParam = {
node: node.value,
parent: thenBlock,
callback(value) {
thenBlock.value = value;
},
typing: "any",
};
ctx.scriptLet.nestBlock(thenBlock, (typeCtx) => {
if (!typeCtx) {
return {
param: baseParam,
};
}
const expression = ctx.getText(node.expression);
if (node.expression.type === "Literal") {
return {
param: {
...baseParam,
typing: expression,
},
};
}
const idAwaitThenValue = typeCtx.generateUniqueId("AwaitThenValue");
if (node.expression.type === "Identifier" &&
// We cannot use type annotations like `(x: Foo<x>)` if they have the same identifier name.
!hasIdentifierFor(node.expression.name, baseParam.node)) {
return {
preparationScript: [generateAwaitThenValueType(idAwaitThenValue)],
param: {
...baseParam,
typing: `${idAwaitThenValue}<(typeof ${expression})>`,
},
};
}
const id = typeCtx.generateUniqueId(expression);
return {
preparationScript: [
{
script: `const ${id} = ${expression};`,
nodeType: "VariableDeclaration",
},
generateAwaitThenValueType(idAwaitThenValue),
],
param: {
...baseParam,
typing: `${idAwaitThenValue}<(typeof ${id})>`,
},
};
});
}
else {
ctx.scriptLet.nestBlock(thenBlock);
}
thenBlock.children.push(...convertChildren(then, thenBlock, ctx));
if (awaitBlock.pending) {
extractMustacheBlockTokens(thenBlock, ctx, { startOnly: true });
}
else {
const thenIndex = ctx.code.indexOf("then", getWithLoc(node.expression).end);
ctx.addToken("MustacheKeyword", {
start: thenIndex,
end: thenIndex + 4,
});
}
awaitBlock.then = thenBlock;
ctx.scriptLet.closeScope();
}
const catchFragment = getCatchFromAwaitBlock(node);
if (catchFragment) {
const awaitCatch = !pending && !then;
if (awaitCatch) {
awaitBlock.kind = "await-catch";
}
const catchStart = awaitBlock.then || awaitBlock.pending
? startBlockIndex(ctx.code, node.error
? getWithLoc(node.error).start
: startIndexFromFragment(catchFragment, () => {
return (awaitBlock.then || awaitBlock.pending).range[1];
}), ":catch")
: nodeStart;
const catchBlock = {
type: "SvelteAwaitCatchBlock",
awaitCatch,
error: null,
children: [],
parent: awaitBlock,
...ctx.getConvertLocation({
start: catchStart,
end: endIndexFromFragment(catchFragment, () => {
return (ctx.code.indexOf("}", node.error ? getWithLoc(node.error).end : catchStart + 6) + 1);
}),
}),
};
if (node.error) {
ctx.scriptLet.nestBlock(catchBlock, [
{
node: node.error,
parent: catchBlock,
typing: "Error",
callback: (error) => {
catchBlock.error = error;
},
},
]);
}
else {
ctx.scriptLet.nestBlock(catchBlock);
}
catchBlock.children.push(...convertChildren(catchFragment, catchBlock, ctx));
if (awaitBlock.pending || awaitBlock.then) {
extractMustacheBlockTokens(catchBlock, ctx, { startOnly: true });
}
else {
const catchIndex = ctx.code.indexOf("catch", getWithLoc(node.expression).end);
ctx.addToken("MustacheKeyword", {
start: catchIndex,
end: catchIndex + 5,
});
}
awaitBlock.catch = catchBlock;
ctx.scriptLet.closeScope();
}
extractMustacheBlockTokens(awaitBlock, ctx);
return awaitBlock;
}
/** Convert for KeyBlock */
export function convertKeyBlock(node, parent, ctx) {
const nodeStart = startBlockIndex(ctx.code, node.start, "#key");
const keyBlock = {
type: "SvelteKeyBlock",
expression: null,
children: [],
parent,
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
};
ctx.scriptLet.addExpression(node.expression, keyBlock, null, (expression) => {
keyBlock.expression = expression;
});
ctx.scriptLet.nestBlock(keyBlock);
keyBlock.children.push(...convertChildren({
nodes:
// Adjust for Svelte v5
trimChildren(getChildren(getFragment(node))),
}, keyBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(keyBlock, ctx);
return keyBlock;
}
/** Convert for SnippetBlock */
export function convertSnippetBlock(node, parent, ctx) {
// {#snippet x(args)}...{/snippet}
const nodeStart = startBlockIndex(ctx.code, node.start, "#snippet");
const snippetBlock = {
type: "SvelteSnippetBlock",
id: null,
params: [],
children: [],
parent,
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
};
let beforeClosingParen;
if (node.parameters.length > 0) {
const lastParam = node.parameters[node.parameters.length - 1];
beforeClosingParen = lastParam.typeAnnotation ?? lastParam;
}
else {
beforeClosingParen = node.expression;
}
const closeParenIndex = ctx.code.indexOf(")", getWithLoc(beforeClosingParen).end);
const scopeKind = parent.type === "Program"
? "snippet"
: // use currentScriptScopeKind
null;
ctx.scriptLet.nestSnippetBlock(node.expression, closeParenIndex, snippetBlock, scopeKind, buildSnippetParamTypes(node, parent, ctx), (id, params) => {
snippetBlock.id = id;
snippetBlock.params = params;
});
snippetBlock.children.push(...convertChildren({
nodes:
// Adjust for Svelte v5
trimChildren(node.body.nodes),
}, snippetBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(snippetBlock, ctx);
ctx.snippets.push(snippetBlock);
return snippetBlock;
}
/**
* A snippet written as a child of a component is passed to it as the prop of
* the same name, so its unannotated parameters take their types from that prop.
*/
function buildSnippetParamTypes(node, parent, ctx) {
if (!ctx.isTypeScript() ||
!svelteVersion.gte(5) ||
parent.type !== "SvelteElement" ||
parent.kind !== "component") {
return null;
}
const elementName = ctx.elements.get(parent).name;
const componentPropsType = `import('svelte').ComponentProps<typeof ${elementName}>`;
const snippetName = node.expression.name;
// Fall back to `any` for a prop the component does not declare, rather than
// letting `never` poison every use of the parameter.
const snippetType = `('${snippetName}' extends infer KEY?KEY extends keyof ${componentPropsType}?NonNullable<${componentPropsType}[KEY]>:any:any)`;
const types = [];
node.parameters.forEach((param, index) => {
// A default value or rest element cannot take a positional annotation.
if (param.typeAnnotation ||
param.type === "AssignmentPattern" ||
param.type === "RestElement") {
return;
}
types.push({
param,
type: `${snippetType} extends (...args: infer A) => any ? A[${index}] : any`,
});
});
return types.length ? types : null;
}
/** Extract mustache block tokens */
function extractMustacheBlockTokens(node, ctx, option) {
const startSectionNameStart = indexOf(ctx.code, (c) => Boolean(c.trim()), node.range[0] + 1);
const startSectionNameEnd = indexOf(ctx.code, (c) => c === "}" || !c.trim(), startSectionNameStart + 1);
ctx.addToken("MustacheKeyword", {
start: startSectionNameStart,
end: startSectionNameEnd,
});
if (option?.startOnly) {
return;
}
const endSectionNameEnd = lastIndexOf(ctx.code, (c) => Boolean(c.trim()), node.range[1] - 2) + 1;
const endSectionNameStart = lastIndexOf(ctx.code, (c) => c === "{" || c === "/" || !c.trim(), endSectionNameEnd - 1);
ctx.addToken("MustacheKeyword", {
start: endSectionNameStart,
end: endSectionNameEnd,
});
}
/** Generate Awaited like type code */
function generateAwaitThenValueType(id) {
return {
script: `type ${id}<T> = T extends null | undefined
? T
: T extends { then(value: infer F): any }
? F extends (value: infer V, ...args: any) => any
? ${id}<V>
: never
: T;`,
nodeType: "TSTypeAliasDeclaration",
};
}
/** Checks whether the given name identifier is exists or not. */
function hasIdentifierFor(name, node) {
if (node.type === "Identifier") {
return node.name === name;
}
if (node.type === "ObjectPattern") {
return node.properties.some((property) => property.type === "Property"
? hasIdentifierFor(name, property.value)
: hasIdentifierFor(name, property));
}
if (node.type === "ArrayPattern") {
return node.elements.some((element) => element && hasIdentifierFor(name, element));
}
if (node.type === "RestElement") {
return hasIdentifierFor(name, node.argument);
}
if (node.type === "AssignmentPattern") {
return hasIdentifierFor(name, node.left);
}
return false;
}

View File

@@ -0,0 +1,23 @@
import type ESTree from "estree";
/** indexOf */
export declare function indexOf(str: string, search: (c: string, index: number) => boolean, start: number, end?: number): number;
/** lastIndexOf */
export declare function lastIndexOf(str: string, search: (c: string, index: number) => boolean, end: number): number;
export declare function getWithLoc<N extends ESTree.Comment>(node: N): N & {
start: number;
end: number;
};
export declare function getWithLoc<N extends ESTree.Node | {
start: number;
end: number;
}>(node: N): N & {
start: number;
end: number;
};
export declare function getWithLoc<N extends ESTree.Node | {
start: number;
end: number;
}>(node: N | null | undefined): (N & {
start: number;
end: number;
}) | null | undefined;

View File

@@ -0,0 +1,25 @@
/** indexOf */
export function indexOf(str, search, start, end) {
const endIndex = end ?? str.length;
for (let index = start; index < endIndex; index++) {
const c = str[index];
if (search(c, index)) {
return index;
}
}
return -1;
}
/** lastIndexOf */
export function lastIndexOf(str, search, end) {
for (let index = end; index >= 0; index--) {
const c = str[index];
if (search(c, index)) {
return index;
}
}
return -1;
}
/** Get node with location */
export function getWithLoc(node) {
return node;
}

View File

@@ -0,0 +1,6 @@
import type { SvelteConstTag } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
import type * as SvAST from "../svelte-ast-types.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
/** Convert for ConstTag */
export declare function convertConstTag(node: SvAST.ConstTag | Compiler.ConstTag, parent: SvelteConstTag["parent"], ctx: Context): SvelteConstTag;

View File

@@ -0,0 +1,31 @@
import { getDeclaratorFromConstTag } from "../compat.js";
/** Convert for ConstTag */
export function convertConstTag(node, parent, ctx) {
const mustache = {
type: "SvelteConstTag",
declaration: null,
declarations: [],
parent,
...ctx.getConvertLocation(node),
};
// Link declaration and declarations for backward compatibility.
// TODO Remove in v2 and later.
Object.defineProperty(mustache, "declaration", {
get() {
return mustache.declarations[0];
},
set(value) {
mustache.declarations = [value];
},
enumerable: false,
});
ctx.scriptLet.addVariableDeclarator(getDeclaratorFromConstTag(node), mustache, (declaration) => {
mustache.declarations = [declaration];
});
const atConstStart = ctx.code.indexOf("@const", mustache.range[0]);
ctx.addToken("MustacheKeyword", {
start: atConstStart,
end: atConstStart + 6,
});
return mustache;
}

View File

@@ -0,0 +1,5 @@
import type { SvelteDeclarationTag, SvelteElement, SvelteElseBlockAlone, SvelteAwaitCatchBlock, SvelteAwaitPendingBlock, SvelteAwaitThenBlock, SvelteEachBlock, SvelteIfBlock, SvelteKeyBlock, SvelteProgram, SvelteSnippetBlock } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
/** Convert for DeclarationTag */
export declare function convertDeclarationTag(node: Compiler.DeclarationTag, parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock, ctx: Context): SvelteDeclarationTag;

View File

@@ -0,0 +1,13 @@
/** Convert for DeclarationTag */
export function convertDeclarationTag(node, parent, ctx) {
const declarationTag = {
type: "SvelteDeclarationTag",
declaration: null,
parent,
...ctx.getConvertLocation(node),
};
ctx.scriptLet.addDeclaration(node.declaration, declarationTag, (declaration) => {
declarationTag.declaration = declaration;
});
return declarationTag;
}

View File

@@ -0,0 +1,19 @@
import type { SvelteAwaitBlock, SvelteAwaitCatchBlock, SvelteAwaitPendingBlock, SvelteAwaitThenBlock, SvelteConstTag, SvelteDeclarationTag, SvelteDebugTag, SvelteEachBlock, SvelteElement, SvelteElseBlockAlone, SvelteHTMLComment, SvelteIfBlock, SvelteIfBlockAlone, SvelteKeyBlock, SvelteMustacheTag, SvelteProgram, SvelteRenderTag, SvelteScriptElement, SvelteSnippetBlock, SvelteStyleElement, SvelteText } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
import type * as SvAST from "../svelte-ast-types.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
import type { Child } from "../compat.js";
/** Convert for Fragment or Element or ... */
export declare function convertChildren(fragment: {
children?: SvAST.TemplateNode[];
} | Compiler.Fragment | {
nodes: (Child | SvAST.TemplateNode)[];
}, parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock, ctx: Context): IterableIterator<SvelteText | SvelteElement | SvelteMustacheTag | SvelteDebugTag | SvelteConstTag | SvelteDeclarationTag | SvelteRenderTag | SvelteIfBlockAlone | SvelteEachBlock | SvelteAwaitBlock | SvelteKeyBlock | SvelteSnippetBlock | SvelteHTMLComment>;
/** Extract element tag and tokens */
export declare function extractElementTags<E extends SvelteScriptElement | SvelteElement | SvelteStyleElement>(element: E, ctx: Context, options: {
buildNameNode: (openTokenRange: {
start: number;
end: number;
}) => E["name"];
extractAttribute?: boolean;
}): void;

View File

@@ -0,0 +1,671 @@
import { convertAwaitBlock, convertEachBlock, convertIfBlock, convertKeyBlock, convertSnippetBlock, } from "./block.js";
import { getWithLoc, indexOf } from "./common.js";
import { convertMustacheTag, convertDebugTag, convertRawMustacheTag, } from "./mustache.js";
import { convertText } from "./text.js";
import { convertAttributes } from "./attr.js";
import { convertConstTag } from "./const.js";
import { convertDeclarationTag } from "./declaration.js";
import { sortNodes } from "../sort.js";
import { ParseError } from "../../index.js";
import { convertRenderTag } from "./render.js";
import { getChildren, getFragment } from "../compat.js";
/** Convert for Fragment or Element or ... */
export function* convertChildren(fragment, parent, ctx) {
const children = getChildren(fragment);
if (!children)
return;
for (const child of children) {
if (child.type === "Comment") {
yield convertComment(child, parent, ctx);
continue;
}
if (child.type === "Text") {
if (!child.data && child.start === child.end) {
continue;
}
yield convertText(child, parent, ctx);
continue;
}
if (child.type === "RegularElement") {
yield convertHTMLElement(child, parent, ctx);
continue;
}
if (child.type === "Element") {
if (child.name.includes(":")) {
yield convertSpecialElement(child, parent, ctx);
}
else {
yield convertHTMLElement(child, parent, ctx);
}
continue;
}
if (child.type === "Component") {
yield convertComponentElement(child, parent, ctx);
continue;
}
if (child.type === "InlineComponent") {
if (child.name.includes(":")) {
yield convertSpecialElement(child, parent, ctx);
}
else {
yield convertComponentElement(child, parent, ctx);
}
continue;
}
if (child.type === "SvelteComponent" ||
child.type === "SvelteElement" ||
child.type === "SvelteSelf") {
yield convertSpecialElement(child, parent, ctx);
continue;
}
if (child.type === "SlotElement" || child.type === "Slot") {
yield convertSlotElement(child, parent, ctx);
continue;
}
if (child.type === "ExpressionTag" || child.type === "MustacheTag") {
yield convertMustacheTag(child, parent, null, ctx);
continue;
}
if (child.type === "HtmlTag" || child.type === "RawMustacheTag") {
yield convertRawMustacheTag(child, parent, ctx);
continue;
}
if (child.type === "IfBlock") {
// {#if expr} {/if}
yield convertIfBlock(child, parent, ctx);
continue;
}
if (child.type === "EachBlock") {
// {#each expr as item, index (key)} {/each}
yield convertEachBlock(child, parent, ctx);
continue;
}
if (child.type === "AwaitBlock") {
// {#await promise} {:then number} {:catch error} {/await}
yield convertAwaitBlock(child, parent, ctx);
continue;
}
if (child.type === "KeyBlock") {
// {#key expression}...{/key}
yield convertKeyBlock(child, parent, ctx);
continue;
}
if (child.type === "SnippetBlock") {
// {#snippet x(args)}...{/snippet}
yield convertSnippetBlock(child, parent, ctx);
continue;
}
if (child.type === "SvelteWindow" || child.type === "Window") {
yield convertWindowElement(child, parent, ctx);
continue;
}
if (child.type === "SvelteBody" || child.type === "Body") {
yield convertBodyElement(child, parent, ctx);
continue;
}
if (child.type === "SvelteHead" || child.type === "Head") {
yield convertHeadElement(child, parent, ctx);
continue;
}
if (child.type === "TitleElement" || child.type === "Title") {
yield convertTitleElement(child, parent, ctx);
continue;
}
if (child.type === "SvelteOptions" || child.type === "Options") {
yield convertOptionsElement(child, parent, ctx);
continue;
}
if (child.type === "SvelteFragment" || child.type === "SlotTemplate") {
yield convertSlotTemplateElement(child, parent, ctx);
continue;
}
if (child.type === "DebugTag") {
yield convertDebugTag(child, parent, ctx);
continue;
}
if (child.type === "ConstTag") {
yield convertConstTag(child, parent, ctx);
continue;
}
if (child.type === "DeclarationTag") {
yield convertDeclarationTag(child, parent, ctx);
continue;
}
if (child.type === "RenderTag") {
yield convertRenderTag(child, parent, ctx);
continue;
}
if (child.type === "SvelteDocument" || child.type === "Document") {
yield convertDocumentElement(child, parent, ctx);
continue;
}
if (child.type === "SvelteBoundary") {
yield convertSvelteBoundaryElement(child, parent, ctx);
continue;
}
throw new Error(`Unknown type:${child.type}`);
}
}
/** Extract `let:` directives. */
function extractLetDirectives(fragment) {
const letDirectives = [];
const attributes = [];
for (const attr of fragment.attributes) {
if (attr.type === "LetDirective" || attr.type === "Let") {
letDirectives.push(attr);
}
else {
attributes.push(attr);
}
}
return { letDirectives, attributes };
}
/** Check if children needs a scope. */
function needScopeByChildren(fragment) {
const children = getChildren(fragment);
if (!children)
return false;
for (const child of children) {
if (child.type === "ConstTag") {
return true;
}
if (child.type === "DeclarationTag") {
return true;
}
if (child.type === "SnippetBlock") {
return true;
}
}
return false;
}
/** Convert for HTML Comment */
function convertComment(node, parent, ctx) {
const comment = {
type: "SvelteHTMLComment",
value: node.data,
parent,
...ctx.getConvertLocation(node),
};
ctx.addToken("HTMLComment", node);
return comment;
}
/** Convert for HTMLElement */
function convertHTMLElement(node, parent, ctx) {
const locs = ctx.getConvertLocation(node);
const element = {
type: "SvelteElement",
kind: "html",
name: null,
startTag: {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: null,
range: [locs.range[0], null],
loc: {
start: {
line: locs.loc.start.line,
column: locs.loc.start.column,
},
end: null,
},
},
children: [],
endTag: null,
parent,
...locs,
};
ctx.elements.set(element, node);
element.startTag.parent = element;
const elementName = node.name;
const { letDirectives, attributes } = extractLetDirectives(node);
const letParams = [];
if (letDirectives.length) {
ctx.letDirCollections.beginExtract();
element.startTag.attributes.push(...convertAttributes(letDirectives, element.startTag, ctx));
letParams.push(...ctx.letDirCollections.extract().getLetParams());
}
const fragment = getFragment(node);
if (!letParams.length && !needScopeByChildren(fragment)) {
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
element.children.push(...convertChildren(fragment, element, ctx));
}
else {
ctx.scriptLet.nestBlock(element, letParams);
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
sortNodes(element.startTag.attributes);
element.children.push(...convertChildren(fragment, element, ctx));
ctx.scriptLet.closeScope();
}
extractElementTags(element, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = {
type: "SvelteName",
name: elementName,
parent: element,
...ctx.getConvertLocation(openTokenRange),
};
return name;
},
});
if (element.name.name === "script" ||
element.name.name === "style" ||
(element.name.name === "template" && ctx.findBlock(element))) {
// Restore the block-like element.
for (const child of element.children) {
if (child.type === "SvelteText") {
child.value = ctx.code.slice(...child.range);
}
}
if (element.name.name === "script") {
ctx.stripScriptCode(element.startTag.range[1], element.endTag?.range[0] ?? element.range[1]);
}
}
if (element.startTag.selfClosing && element.name.name.endsWith("-")) {
// Restore the self-closing block.
const selfClosingBlock = /^[a-z]-+$/iu.test(element.name.name) &&
ctx.findSelfClosingBlock(element);
if (selfClosingBlock) {
element.name.name = selfClosingBlock.originalTag;
}
}
return element;
}
/** Convert for Special element. e.g. <svelte:self> */
function convertSpecialElement(node, parent, ctx) {
const locs = ctx.getConvertLocation(node);
const element = {
type: "SvelteElement",
kind: "special",
name: null,
startTag: {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: null,
range: [locs.range[0], null],
loc: {
start: {
line: locs.loc.start.line,
column: locs.loc.start.column,
},
end: null,
},
},
children: [],
endTag: null,
parent,
...locs,
};
ctx.elements.set(element, node);
element.startTag.parent = element;
const elementName = node.name;
const { letDirectives, attributes } = extractLetDirectives(node);
const letParams = [];
if (letDirectives.length) {
ctx.letDirCollections.beginExtract();
element.startTag.attributes.push(...convertAttributes(letDirectives, element.startTag, ctx));
letParams.push(...ctx.letDirCollections.extract().getLetParams());
}
const fragment = getFragment(node);
if (!letParams.length && !needScopeByChildren(fragment)) {
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
element.children.push(...convertChildren(fragment, element, ctx));
}
else {
ctx.scriptLet.nestBlock(element, letParams);
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
sortNodes(element.startTag.attributes);
element.children.push(...convertChildren(fragment, element, ctx));
ctx.scriptLet.closeScope();
}
const thisExpression = (node.type === "SvelteComponent" && node.expression) ||
(node.type === "SvelteElement" && node.tag) ||
(node.type === "InlineComponent" &&
elementName === "svelte:component" &&
node.expression) ||
(node.type === "Element" && elementName === "svelte:element" && node.tag);
if (thisExpression) {
processThisAttribute(node, thisExpression, element, ctx);
}
extractElementTags(element, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = {
type: "SvelteName",
name: elementName,
parent: element,
...ctx.getConvertLocation(openTokenRange),
};
return name;
},
});
return element;
}
/** process `this=` */
function processThisAttribute(node, thisValue, element, ctx) {
const startIndex = findStartIndexOfThis(node, ctx);
const eqIndex = ctx.code.indexOf("=", startIndex + 4 /* t,h,i,s */);
let thisNode;
if (typeof thisValue === "string") {
// Svelte v4
// this="..."
thisNode = createSvelteAttribute(startIndex, eqIndex, thisValue);
}
else {
// this={...}
const valueStartIndex = indexOf(ctx.code, (c) => Boolean(c.trim()), eqIndex + 1);
if (thisValue.type === "Literal" &&
typeof thisValue.value === "string" &&
ctx.code[valueStartIndex] !== "{") {
thisNode = createSvelteAttribute(startIndex, eqIndex, thisValue.value);
}
else {
thisNode = createSvelteSpecialDirective(startIndex, eqIndex, thisValue);
}
}
const targetIndex = element.startTag.attributes.findIndex((attr) => thisNode.range[1] <= attr.range[0]);
if (targetIndex === -1) {
element.startTag.attributes.push(thisNode);
}
else {
element.startTag.attributes.splice(targetIndex, 0, thisNode);
}
/** Create SvelteAttribute */
function createSvelteAttribute(startIndex, eqIndex, thisValue) {
const valueStartIndex = indexOf(ctx.code, (c) => Boolean(c.trim()), eqIndex + 1);
const quote = ctx.code.startsWith(thisValue, valueStartIndex)
? null
: ctx.code[valueStartIndex];
const literalStartIndex = quote
? valueStartIndex + quote.length
: valueStartIndex;
const literalEndIndex = literalStartIndex + thisValue.length;
const endIndex = quote ? literalEndIndex + quote.length : literalEndIndex;
const thisAttr = {
type: "SvelteAttribute",
key: null,
boolean: false,
value: [],
parent: element.startTag,
...ctx.getConvertLocation({ start: startIndex, end: endIndex }),
};
thisAttr.key = {
type: "SvelteName",
name: "this",
parent: thisAttr,
...ctx.getConvertLocation({ start: startIndex, end: eqIndex }),
};
thisAttr.value.push({
type: "SvelteLiteral",
value: thisValue,
parent: thisAttr,
...ctx.getConvertLocation({
start: literalStartIndex,
end: literalEndIndex,
}),
});
// this
ctx.addToken("HTMLIdentifier", {
start: startIndex,
end: startIndex + 4,
});
// =
ctx.addToken("Punctuator", {
start: eqIndex,
end: eqIndex + 1,
});
if (quote) {
// "
ctx.addToken("Punctuator", {
start: valueStartIndex,
end: literalStartIndex,
});
}
ctx.addToken("HTMLText", {
start: literalStartIndex,
end: literalEndIndex,
});
if (quote) {
// "
ctx.addToken("Punctuator", {
start: literalEndIndex,
end: endIndex,
});
}
return thisAttr;
}
/** Create SvelteSpecialDirective */
function createSvelteSpecialDirective(startIndex, eqIndex, expression) {
const closeIndex = ctx.code.indexOf("}", getWithLoc(expression).end);
const endIndex = indexOf(ctx.code, (c) => c === ">" || !c.trim(), closeIndex);
const thisDir = {
type: "SvelteSpecialDirective",
kind: "this",
key: null,
expression: null,
parent: element.startTag,
...ctx.getConvertLocation({ start: startIndex, end: endIndex }),
};
thisDir.key = {
type: "SvelteSpecialDirectiveKey",
parent: thisDir,
...ctx.getConvertLocation({ start: startIndex, end: eqIndex }),
};
// this
ctx.addToken("HTMLIdentifier", {
start: startIndex,
end: startIndex + 4,
});
// =
ctx.addToken("Punctuator", {
start: eqIndex,
end: eqIndex + 1,
});
ctx.scriptLet.addExpression(expression, thisDir, null, (es) => {
thisDir.expression = es;
});
return thisDir;
}
}
/** Find the start index of `this` */
function findStartIndexOfThis(node, ctx) {
// Get the end index of `svelte:element`
const startIndex = ctx.code.indexOf(node.name, node.start) + node.name.length;
const sortedAttrs = [...node.attributes].sort((a, b) => a.start - b.start);
// Find the start index of `this` from the end index of `svelte:element`.
// However, it only seeks to the start index of the first attribute (or the end index of element node).
let thisIndex = indexOf(ctx.code, (_c, index) => ctx.code.startsWith("this", index), startIndex, sortedAttrs[0]?.start ?? node.end);
while (thisIndex < 0) {
if (sortedAttrs.length === 0)
throw new ParseError("Cannot resolved `this` attribute.", thisIndex, ctx);
// Step3: Find the start index of `this` from the end index of attribute.
// However, it only seeks to the start index of the first attribute (or the end index of element node).
const nextStartIndex = sortedAttrs.shift().end;
thisIndex = indexOf(ctx.code, (_c, index) => ctx.code.startsWith("this", index), nextStartIndex, sortedAttrs[0]?.start ?? node.end);
}
return thisIndex;
}
/** Convert for ComponentElement */
function convertComponentElement(node, parent, ctx) {
const locs = ctx.getConvertLocation(node);
const element = {
type: "SvelteElement",
kind: "component",
name: null,
startTag: {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: null,
range: [locs.range[0], null],
loc: {
start: {
line: locs.loc.start.line,
column: locs.loc.start.column,
},
end: null,
},
},
children: [],
endTag: null,
parent,
...locs,
};
ctx.elements.set(element, node);
element.startTag.parent = element;
const elementName = node.name;
const { letDirectives, attributes } = extractLetDirectives(node);
const letParams = [];
if (letDirectives.length) {
ctx.letDirCollections.beginExtract();
element.startTag.attributes.push(...convertAttributes(letDirectives, element.startTag, ctx));
letParams.push(...ctx.letDirCollections.extract().getLetParams());
}
const fragment = getFragment(node);
if (!letParams.length && !needScopeByChildren(fragment)) {
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
element.children.push(...convertChildren(fragment, element, ctx));
}
else {
ctx.scriptLet.nestBlock(element, letParams);
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
sortNodes(element.startTag.attributes);
element.children.push(...convertChildren(fragment, element, ctx));
ctx.scriptLet.closeScope();
}
extractElementTags(element, ctx, {
buildNameNode: (openTokenRange) => {
const chains = elementName.split(".");
const id = chains.shift();
const idRange = {
start: openTokenRange.start,
end: openTokenRange.start + id.length,
};
// ctx.addToken("Identifier", idRange)
const identifier = {
type: "Identifier",
name: id,
// @ts-expect-error -- ignore
parent: element,
...ctx.getConvertLocation(idRange),
};
let object = identifier;
// eslint-disable-next-line func-style -- var
let esCallback = (es) => {
element.name = es;
};
let start = idRange.end + 1;
for (const name of chains) {
const range = { start, end: start + name.length };
ctx.addToken("HTMLIdentifier", range);
const mem = {
type: "SvelteMemberExpressionName",
object,
property: {
type: "SvelteName",
name,
parent: null,
...ctx.getConvertLocation(range),
},
parent: element,
...ctx.getConvertLocation({
start: openTokenRange.start,
end: range.end,
}),
};
mem.property.parent = mem;
object.parent = mem;
object = mem;
start = range.end + 1;
if (mem.object === identifier) {
esCallback = (es) => {
mem.object = es;
};
}
}
ctx.scriptLet.addExpression(identifier, identifier.parent, null, esCallback);
return object;
},
});
return element;
}
/** Convert for Slot */
function convertSlotElement(node, parent, ctx) {
// Slot translates to SvelteHTMLElement.
const element = convertHTMLElement(node, parent, ctx);
ctx.slots.add(element);
return element;
}
/** Convert for window element. e.g. <svelte:window> */
function convertWindowElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for document element. e.g. <svelte:document> */
function convertDocumentElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for body element. e.g. <svelte:body> */
function convertBodyElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for head element. e.g. <svelte:head> */
function convertHeadElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for title element. e.g. <title> */
function convertTitleElement(node, parent, ctx) {
return convertHTMLElement(node, parent, ctx);
}
/** Convert for options element. e.g. <svelte:options> */
function convertOptionsElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for <svelte:fragment> element. */
function convertSlotTemplateElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for <svelte:boundary> element. */
function convertSvelteBoundaryElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Extract element tag and tokens */
export function extractElementTags(element, ctx, options) {
const startTagNameEnd = indexOf(ctx.code, (c) => c === "/" || c === ">" || !c.trim(), element.range[0] + 1);
const openTokenRange = {
start: element.range[0] + 1,
end: startTagNameEnd,
};
element.name = options.buildNameNode(openTokenRange);
const startTagEnd = ctx.code.indexOf(">", element.startTag.attributes[element.startTag.attributes.length - 1]
?.range[1] ?? openTokenRange.end) + 1;
element.startTag.range[1] = startTagEnd;
element.startTag.loc.end = ctx.getLocFromIndex(startTagEnd);
if (ctx.code[element.range[1] - 1] !== ">") {
// Have not end tag
return;
}
if (ctx.code[element.range[1] - 2] === "/") {
// self close
element.startTag.selfClosing = true;
return;
}
const endTagOpen = ctx.code.lastIndexOf("<", element.range[1] - 1);
if (endTagOpen <= startTagEnd - 1) {
// void element
return;
}
const endTagNameStart = endTagOpen + 2;
const endTagNameEnd = indexOf(ctx.code, (c) => c === ">" || !c.trim(), endTagNameStart);
const endTagClose = ctx.code.indexOf(">", endTagNameEnd);
element.endTag = {
type: "SvelteEndTag",
parent: element,
...ctx.getConvertLocation({ start: endTagOpen, end: endTagClose + 1 }),
};
ctx.addToken("HTMLIdentifier", {
start: endTagNameStart,
end: endTagNameEnd,
});
}

View File

@@ -0,0 +1 @@
export { convertSvelteRoot } from "./root.js";

View File

@@ -0,0 +1 @@
export { convertSvelteRoot } from "./root.js";

View File

@@ -0,0 +1,10 @@
import type { SvelteDebugTag, SvelteMustacheTag, SvelteMustacheTagRaw, SvelteMustacheTagText } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
import type * as SvAST from "../svelte-ast-types.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
/** Convert for MustacheTag */
export declare function convertMustacheTag(node: SvAST.MustacheTag | Compiler.ExpressionTag, parent: SvelteMustacheTag["parent"], typing: string | null, ctx: Context): SvelteMustacheTagText;
/** Convert for MustacheTag */
export declare function convertRawMustacheTag(node: SvAST.RawMustacheTag | Compiler.HtmlTag, parent: SvelteMustacheTagRaw["parent"], ctx: Context): SvelteMustacheTagRaw;
/** Convert for DebugTag */
export declare function convertDebugTag(node: SvAST.DebugTag, parent: SvelteDebugTag["parent"], ctx: Context): SvelteDebugTag;

View File

@@ -0,0 +1,49 @@
import { hasTypeInfo } from "../../utils/index.js";
/** Convert for MustacheTag */
export function convertMustacheTag(node, parent, typing, ctx) {
return convertMustacheTag0(node, "text", parent, typing, ctx);
}
/** Convert for MustacheTag */
export function convertRawMustacheTag(node, parent, ctx) {
const mustache = convertMustacheTag0(node, "raw", parent, null, ctx);
const atHtmlStart = ctx.code.indexOf("@html", mustache.range[0]);
ctx.addToken("MustacheKeyword", {
start: atHtmlStart,
end: atHtmlStart + 5,
});
return mustache;
}
/** Convert for DebugTag */
export function convertDebugTag(node, parent, ctx) {
const mustache = {
type: "SvelteDebugTag",
identifiers: [],
parent,
...ctx.getConvertLocation(node),
};
for (const id of node.identifiers) {
ctx.scriptLet.addExpression(id, mustache, null, (es) => {
mustache.identifiers.push(es);
});
}
const atDebugStart = ctx.code.indexOf("@debug", mustache.range[0]);
ctx.addToken("MustacheKeyword", {
start: atDebugStart,
end: atDebugStart + 6,
});
return mustache;
}
/** Convert to MustacheTag */
function convertMustacheTag0(node, kind, parent, typing, ctx) {
const mustache = {
type: "SvelteMustacheTag",
kind,
expression: null,
parent,
...ctx.getConvertLocation(node),
};
ctx.scriptLet.addExpression(node.expression, mustache, hasTypeInfo(node.expression) ? null : typing, (es) => {
mustache.expression = es;
});
return mustache;
}

View File

@@ -0,0 +1,5 @@
import type { SvelteRenderTag } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
/** Convert for RenderTag */
export declare function convertRenderTag(node: Compiler.RenderTag, parent: SvelteRenderTag["parent"], ctx: Context): SvelteRenderTag;

View File

@@ -0,0 +1,21 @@
import { getWithLoc } from "./common.js";
/** Convert for RenderTag */
export function convertRenderTag(node, parent, ctx) {
const mustache = {
type: "SvelteRenderTag",
expression: null,
parent,
...ctx.getConvertLocation(node),
};
const callRange = getWithLoc(node.expression);
ctx.scriptLet.addExpressionFromRange([callRange.start, callRange.end], mustache, null, (expression) => {
mustache.expression = expression;
mustache.expression.parent = mustache;
});
const atRenderStart = ctx.code.indexOf("@render", mustache.range[0]);
ctx.addToken("MustacheKeyword", {
start: atRenderStart,
end: atRenderStart + 7,
});
return mustache;
}

View File

@@ -0,0 +1,8 @@
import type * as SvAST from "../svelte-ast-types.js";
import type * as Compiler from "../svelte-ast-types-for-v5.js";
import type { SvelteProgram } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
/**
* Convert root
*/
export declare function convertSvelteRoot(svelteAst: Compiler.Root | SvAST.AstLegacy, ctx: Context): SvelteProgram;

View File

@@ -0,0 +1,302 @@
import { convertChildren, extractElementTags } from "./element.js";
import { convertAttributes } from "./attr.js";
import { parseScriptWithoutAnalyzeScope } from "../script.js";
import { fixLocations } from "../../context/fix-locations.js";
import { getChildren, getFragmentFromRoot, getInstanceFromRoot, getModuleFromRoot, getOptionsFromRoot, } from "../compat.js";
import { sortNodes } from "../sort.js";
import { withoutProjectParserOptions } from "../parser-options.js";
import { ParseError } from "../../main.js";
/**
* Convert root
*/
export function convertSvelteRoot(svelteAst, ctx) {
const ast = {
type: "Program",
body: [],
comments: ctx.comments,
sourceType: "module",
tokens: ctx.tokens,
parent: null,
...ctx.getConvertLocation({ start: 0, end: ctx.code.length }),
};
const body = ast.body;
const snippetChildren = [];
const fragment = getFragmentFromRoot(svelteAst);
if (fragment) {
let children = getChildren(fragment);
const options = getOptionsFromRoot(svelteAst);
if (options) {
children = [...children];
if (!children.some((node, idx) => {
if (options.end <= node.start) {
children.splice(idx, 0, options);
return true;
}
return false;
})) {
children.push(options);
}
}
const nonSnippetChildren = [];
for (const child of children) {
if (child.type === "SnippetBlock") {
snippetChildren.push(child);
}
else {
nonSnippetChildren.push(child);
}
}
body.push(...convertChildren({ nodes: nonSnippetChildren }, ast, ctx));
}
let script = null;
const instance = getInstanceFromRoot(svelteAst);
if (instance) {
script = {
type: "SvelteScriptElement",
name: null,
startTag: null,
body: [],
endTag: null,
parent: ast,
...ctx.getConvertLocation(instance),
};
extractAttributes(script, ctx);
extractElementTags(script, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = {
type: "SvelteName",
name: "script",
parent: script,
...ctx.getConvertLocation(openTokenRange),
};
return name;
},
});
body.push(script);
}
const module = getModuleFromRoot(svelteAst);
if (module) {
const script = {
type: "SvelteScriptElement",
name: null,
startTag: null,
body: [],
endTag: null,
parent: ast,
...ctx.getConvertLocation(module),
};
extractAttributes(script, ctx);
extractElementTags(script, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = {
type: "SvelteName",
name: "script",
parent: script,
...ctx.getConvertLocation(openTokenRange),
};
return name;
},
});
body.push(script);
}
if (svelteAst.css) {
const style = {
type: "SvelteStyleElement",
name: null,
startTag: null,
children: [],
endTag: null,
parent: ast,
...ctx.getConvertLocation(svelteAst.css),
};
extractAttributes(style, ctx);
extractElementTags(style, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = {
type: "SvelteName",
name: "style",
parent: style,
...ctx.getConvertLocation(openTokenRange),
};
return name;
},
});
if (style.endTag && style.startTag.range[1] < style.endTag.range[0]) {
const contentRange = {
start: style.startTag.range[1],
end: style.endTag.range[0],
};
ctx.addToken("HTMLText", contentRange);
style.children = [
{
type: "SvelteText",
value: ctx.code.slice(contentRange.start, contentRange.end),
parent: style,
...ctx.getConvertLocation(contentRange),
},
];
}
body.push(style);
}
body.push(...convertChildren({ nodes: snippetChildren }, ast, ctx));
if (script)
convertGenericsAttribute(script, ctx);
// Process for comments in tags
const comments = svelteAst.comments;
if (comments && Array.isArray(comments) && comments.length > 0) {
const tags = [];
// Extract tags in order to check whether comments are inside tags or not.
const elementsBuffer = [
...body.filter((node) => {
return (node.type === "SvelteScriptElement" ||
node.type === "SvelteStyleElement" ||
node.type === "SvelteElement");
}),
];
let element;
while ((element = elementsBuffer.shift())) {
tags.push(element.startTag);
if (element.type === "SvelteElement") {
elementsBuffer.unshift(...element.children.filter((node) => node.type === "SvelteElement"));
}
}
// Process all comments from Svelte compiler
for (const comment of comments) {
if (comment.type !== "Block" && comment.type !== "Line") {
throw new ParseError(`Unknown comment type: ${comment.type}`, comment.start, ctx);
}
const tag = tags.find((tag) => tag.range[0] <= comment.start && comment.end <= tag.range[1]);
if (!tag) {
// If the comment is outside of all tags, it will be skipped.
continue;
}
if (tag.attributes.some((attr) => attr.range[0] <= comment.start && comment.end <= attr.range[1])) {
// If the comment is inside the attributes, it will be skipped because it is a comment inside an expression.
continue;
}
ctx.addComment({
type: comment.type === "Block" ? "Block" : "Line",
value: comment.value,
...ctx.getConvertLocation(comment),
});
}
}
// Set the scope of the Program node.
ctx.scriptLet.addProgramRestore((node, _tokens, _comments, { scopeManager, registerNodeToScope, addPostProcess }) => {
const scopes = [];
for (const scope of scopeManager.scopes) {
if (scope.block === node) {
registerNodeToScope(ast, scope);
scopes.push(scope);
}
}
addPostProcess(() => {
// Reverts the node indicated by `block` to the original Program node.
// This state is incorrect, but `eslint-utils`'s `referenceTracker.iterateEsmReferences()` tracks import statements
// from Program nodes set to `block` in global scope. This can only be handled by the original Program node.
scopeManager.globalScope.block = node;
});
});
sortNodes(body);
return ast;
}
/** Extract attrs */
function extractAttributes(element, ctx) {
element.startTag = {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: element,
range: [element.range[0], null],
loc: {
start: {
line: element.loc.start.line,
column: element.loc.start.column,
},
end: null,
},
};
const block = ctx.findBlock(element);
if (block) {
element.startTag.attributes.push(...convertAttributes(block.attrs, element.startTag, ctx));
}
}
/** Convert generics attribute */
function convertGenericsAttribute(script, ctx) {
const lang = ctx.sourceCode.scripts.attrs.lang;
if (lang !== "ts" && lang !== "typescript") {
return;
}
const genericsAttribute = script.startTag.attributes.find((attr) => {
return (attr.type === "SvelteAttribute" &&
attr.key.name === "generics" &&
attr.value.length === 1 &&
attr.value[0].type === "SvelteLiteral");
});
if (!genericsAttribute) {
return;
}
const value = genericsAttribute.value[0];
const genericValueCode = ctx.code.slice(value.range[0], value.range[1]);
const scriptLet = `void function<${genericValueCode}>(){}`;
let result;
try {
result = parseScriptWithoutAnalyzeScope(scriptLet, ctx.sourceCode.scripts.attrs, withoutProjectParserOptions(ctx.parserOptions));
}
catch {
// ignore
return;
}
delete genericsAttribute.boolean;
delete genericsAttribute.value;
// Remove value token indexes
sortNodes(ctx.tokens);
const firstTokenIndex = ctx.tokens.findIndex((token) => value.range[0] <= token.range[0] && token.range[1] <= value.range[1]);
const lastTokenCount = ctx.tokens
.slice(firstTokenIndex)
.findIndex((token) => value.range[1] <= token.range[0]);
ctx.tokens.splice(firstTokenIndex, lastTokenCount >= 0 ? lastTokenCount : Infinity);
const generics = genericsAttribute;
generics.type = "SvelteGenericsDirective";
generics.params = [];
result.ast.tokens.shift(); // void
result.ast.tokens.shift(); // function
result.ast.tokens.shift(); // <
result.ast.tokens.pop(); // }
result.ast.tokens.pop(); // {
result.ast.tokens.pop(); // )
result.ast.tokens.pop(); // (
result.ast.tokens.pop(); // >
fixLocations(result.ast, result.ast.tokens, result.ast.comments, value.range[0] - 14, result.visitorKeys, ctx);
const { ast } = result;
const statement = ast.body[0];
const rawExpression = statement.expression;
const fnDecl = rawExpression.argument;
const typeParameters = fnDecl
.typeParameters;
const params = typeParameters.params;
// Replace tokens
for (const tokensKey of ["tokens", "comments"]) {
for (const token of result.ast[tokensKey]) {
if (params.every((param) => token.range[1] <= param.range[0] ||
param.range[1] <= token.range[0])) {
ctx[tokensKey].push(token);
}
}
}
for (const param of params) {
param.parent = generics;
generics.params.push(param);
ctx.scriptLet.addGenericTypeAliasDeclaration(param, (id, typeNode) => {
param.name = id;
if (param.constraint) {
param.constraint = typeNode;
}
}, (typeNode) => {
param.default = typeNode;
});
}
}

View File

@@ -0,0 +1,7 @@
import type { SvelteLiteral, SvelteText } from "../../ast/index.js";
import type { Context } from "../../context/index.js";
import type * as SvAST from "../svelte-ast-types.js";
/** Convert for Text */
export declare function convertText(node: SvAST.Text, parent: SvelteText["parent"], ctx: Context): SvelteText;
/** Convert for Text to Literal */
export declare function convertTextToLiteral(node: SvAST.Text, parent: SvelteLiteral["parent"], ctx: Context): SvelteLiteral;

View File

@@ -0,0 +1,40 @@
/** Convert for Text */
export function convertText(node, parent, ctx) {
const text = {
type: "SvelteText",
value: node.data,
parent,
...ctx.getConvertLocation(node),
};
extractTextTokens(node, ctx);
return text;
}
/** Convert for Text to Literal */
export function convertTextToLiteral(node, parent, ctx) {
const text = {
type: "SvelteLiteral",
value: node.data,
parent,
...ctx.getConvertLocation(node),
};
extractTextTokens(node, ctx);
return text;
}
/** Extract tokens */
function extractTextTokens(node, ctx) {
const loc = node;
let start = loc.start;
let word = false;
for (let index = loc.start; index < loc.end; index++) {
if (word !== Boolean(ctx.code[index].trim())) {
if (start < index) {
ctx.addToken("HTMLText", { start, end: index });
}
word = !word;
start = index;
}
}
if (start < loc.end) {
ctx.addToken("HTMLText", { start, end: loc.end });
}
}

View File

@@ -0,0 +1,6 @@
import * as eslintScope from "eslint-scope";
/**
* Load `eslint-scope` from ESLint's dependencies, user dependencies, or this package's dependencies.
* Return the latest version among them.
*/
export declare function getESLintScope(): typeof eslintScope;

View File

@@ -0,0 +1,21 @@
import { loadNewestModule } from "../utils/cjs-module.js";
import * as eslintScope from "eslint-scope";
let eslintScopeCache = null;
/**
* Load `eslint-scope` from ESLint's dependencies, user dependencies, or this package's dependencies.
* Return the latest version among them.
*/
export function getESLintScope() {
if (!eslintScopeCache) {
try {
eslintScopeCache = loadNewestModule("eslint-scope");
}
catch {
// ignore
}
if (!eslintScopeCache) {
eslintScopeCache = eslintScope.default || eslintScope;
}
}
return eslintScopeCache;
}

View File

@@ -0,0 +1,8 @@
import type { BasicParserObject } from "./parser-object.js";
/**
* Load `espree` from ESLint's dependencies, user dependencies, or this package's dependencies.
* Return the latest version among them.
*/
export declare function getEspree(): BasicParserObject & {
latestEcmaVersion: number;
};

21
node_modules/svelte-eslint-parser/lib/parser/espree.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import { loadNewestModule } from "../utils/cjs-module.js";
import * as espree from "espree";
let espreeCache = null;
/**
* Load `espree` from ESLint's dependencies, user dependencies, or this package's dependencies.
* Return the latest version among them.
*/
export function getEspree() {
if (!espreeCache) {
try {
espreeCache = loadNewestModule("espree");
}
catch {
// ignore
}
if (!espreeCache) {
espreeCache = espree.default || espree;
}
}
return espreeCache;
}

View File

@@ -0,0 +1,7 @@
import type { SvelteParseContext } from "./svelte-parse-context.js";
declare const globalsForSvelte: readonly ["$$slots", "$$props", "$$restProps"];
export declare const globalsForRunes: readonly ["$state", "$derived", "$effect", "$props", "$bindable", "$inspect", "$host"];
type Global = (typeof globalsForSvelte)[number] | (typeof globalsForRunes)[number];
export declare function getGlobalsForSvelte(svelteParseContext: SvelteParseContext): readonly Global[];
export declare function getGlobalsForSvelteScript(svelteParseContext: SvelteParseContext): readonly Global[];
export {};

View File

@@ -0,0 +1,24 @@
const globalsForSvelte = ["$$slots", "$$props", "$$restProps"];
export const globalsForRunes = [
"$state",
"$derived",
"$effect",
"$props",
"$bindable",
"$inspect",
"$host",
];
export function getGlobalsForSvelte(svelteParseContext) {
// Process if not confirmed as non-Runes mode.
if (svelteParseContext.runes !== false) {
return [...globalsForSvelte, ...globalsForRunes];
}
return globalsForSvelte;
}
export function getGlobalsForSvelteScript(svelteParseContext) {
// Process if not confirmed as non-Runes mode.
if (svelteParseContext.runes !== false) {
return globalsForRunes;
}
return [];
}

View File

@@ -0,0 +1,6 @@
import type * as Compiler from "./svelte-ast-types-for-v5.js";
/** Parse HTML attributes */
export declare function parseAttributes(code: string, startIndex: number): {
attributes: Compiler.Attribute[];
index: number;
};

271
node_modules/svelte-eslint-parser/lib/parser/html.js generated vendored Normal file
View File

@@ -0,0 +1,271 @@
import { getEspree } from "./espree.js";
const RE_IS_SPACE = /^\s$/u;
class State {
constructor(code, index) {
this.code = code;
this.index = index;
}
getCurr() {
return this.code[this.index];
}
skipSpaces() {
while (this.currIsSpace()) {
this.advance();
if (this.eof())
break;
}
}
currIsSpace() {
return RE_IS_SPACE.test(this.getCurr() || "");
}
currIs(expect) {
return this.code.startsWith(expect, this.index);
}
eof() {
return this.index >= this.code.length;
}
eat(expect) {
if (!this.currIs(expect)) {
return null;
}
this.index += expect.length;
return expect;
}
advance() {
this.index++;
return this.getCurr();
}
}
/** Parse HTML attributes */
export function parseAttributes(code, startIndex) {
const attributes = [];
const state = new State(code, startIndex);
while (!state.eof()) {
state.skipSpaces();
if (state.currIs(">") || state.currIs("/>") || state.eof())
break;
attributes.push(parseAttribute(state));
}
return { attributes, index: state.index };
}
/** Parse HTML attribute */
function parseAttribute(state) {
const start = state.index;
// parse key
const key = parseAttributeKey(state);
const keyEnd = state.index;
state.skipSpaces();
if (!state.eat("=")) {
return {
type: "Attribute",
name: key,
name_loc: null,
value: true,
start,
end: keyEnd,
};
}
state.skipSpaces();
if (state.eof()) {
return {
type: "Attribute",
name: key,
name_loc: null,
value: true,
start,
end: keyEnd,
};
}
// parse value
const value = parseAttributeValue(state);
return {
type: "Attribute",
name: key,
name_loc: null,
value: [value],
start,
end: state.index,
};
}
/** Parse HTML attribute key */
function parseAttributeKey(state) {
const start = state.index;
while (state.advance()) {
if (state.currIs("=") ||
state.currIs(">") ||
state.currIs("/>") ||
state.currIsSpace()) {
break;
}
}
const end = state.index;
return state.code.slice(start, end);
}
/** Parse HTML attribute value */
function parseAttributeValue(state) {
const start = state.index;
const quote = state.eat('"') || state.eat("'");
const startBk = state.index;
const expression = parseAttributeMustache(state);
if (expression) {
if (!quote || state.eat(quote)) {
const end = state.index;
return {
type: "ExpressionTag",
expression,
start,
end,
};
}
}
state.index = startBk;
if (quote) {
if (state.eof()) {
return {
type: "Text",
data: quote,
raw: quote,
start,
end: state.index,
};
}
let c;
while ((c = state.getCurr())) {
state.advance();
if (c === quote) {
const end = state.index;
const data = state.code.slice(start + 1, end - 1);
return {
type: "Text",
data,
raw: data,
start: start + 1,
end: end - 1,
};
}
}
}
else {
while (state.advance()) {
if (state.currIsSpace() || state.currIs(">") || state.currIs("/>")) {
break;
}
}
}
const end = state.index;
const data = state.code.slice(start, end);
return {
type: "Text",
data,
raw: data,
start,
end,
};
}
/** Parse mustache */
function parseAttributeMustache(state) {
if (!state.eat("{")) {
return null;
}
// parse simple expression
const leadingComments = [];
const startBk = state.index;
state.skipSpaces();
let start = state.index;
while (!state.eof()) {
if (state.eat("//")) {
leadingComments.push(parseInlineComment(state.index - 2));
state.skipSpaces();
start = state.index;
continue;
}
if (state.eat("/*")) {
leadingComments.push(parseBlockComment(state.index - 2));
state.skipSpaces();
start = state.index;
continue;
}
const stringQuote = state.eat('"') || state.eat("'");
if (stringQuote) {
skipString(stringQuote);
state.skipSpaces();
continue;
}
const endCandidate = state.index;
state.skipSpaces();
if (state.eat("}")) {
const end = endCandidate;
try {
const espree = getEspree();
const expression = espree.parse(state.code.slice(start, end), {
ecmaVersion: espree.latestEcmaVersion,
}).body[0].expression;
delete expression.range;
return {
...expression,
leadingComments,
start,
end,
};
}
catch {
break;
}
}
state.advance();
}
state.index = startBk;
return null;
function parseInlineComment(tokenStart) {
const valueStart = state.index;
let valueEnd = null;
while (!state.eof()) {
if (state.eat("\n")) {
valueEnd = state.index - 1;
break;
}
state.advance();
}
if (valueEnd == null) {
valueEnd = state.index;
}
return {
type: "Line",
value: state.code.slice(valueStart, valueEnd),
start: tokenStart,
end: state.index,
};
}
function parseBlockComment(tokenStart) {
const valueStart = state.index;
let valueEnd = null;
while (!state.eof()) {
if (state.eat("*/")) {
valueEnd = state.index - 2;
break;
}
state.advance();
}
if (valueEnd == null) {
valueEnd = state.index;
}
return {
type: "Block",
value: state.code.slice(valueStart, valueEnd),
start: tokenStart,
end: state.index,
};
}
function skipString(stringQuote) {
while (!state.eof()) {
if (state.eat(stringQuote)) {
break;
}
if (state.eat("\\")) {
// escape
state.advance();
}
state.advance();
}
}
}

View File

@@ -0,0 +1,52 @@
import type { Comment, SourceLocation, SvelteProgram, Token } from "../ast/index.js";
import type { Program } from "estree";
import type * as eslint from "eslint";
import type { Rule, Node } from "postcss";
import type { Node as SelectorNode, Root as SelectorRoot } from "postcss-selector-parser";
import type * as SvAST from "./svelte-ast-types.js";
import type * as Compiler from "./svelte-ast-types-for-v5.js";
import { type StyleContext, type StyleContextNoStyleElement, type StyleContextParseError, type StyleContextSuccess, type StyleContextUnknownLang } from "./style-context.js";
import { type SvelteParseContext } from "./svelte-parse-context.js";
export { StyleContext, StyleContextNoStyleElement, StyleContextParseError, StyleContextSuccess, StyleContextUnknownLang, };
export interface ESLintProgram extends Program {
comments: Comment[];
tokens: Token[];
}
/**
* The parsing result of ESLint custom parsers.
*/
export interface ESLintExtendedProgram {
ast: ESLintProgram;
services?: Record<string, any>;
visitorKeys?: {
[type: string]: string[];
};
scopeManager?: eslint.Scope.ScopeManager;
_virtualScriptCode?: string;
}
type ParseResult = {
ast: SvelteProgram;
services: Record<string, any> & ({
isSvelte: true;
isSvelteScript: false;
getSvelteHtmlAst: () => SvAST.Fragment | Compiler.Fragment;
getStyleContext: () => StyleContext;
getStyleSelectorAST: (rule: Rule) => SelectorRoot;
styleNodeLoc: (node: Node) => Partial<SourceLocation>;
styleNodeRange: (node: Node) => [number | undefined, number | undefined];
styleSelectorNodeLoc: (node: SelectorNode) => Partial<SourceLocation>;
svelteParseContext: SvelteParseContext;
} | {
isSvelte: false;
isSvelteScript: true;
svelteParseContext: SvelteParseContext;
});
visitorKeys: {
[type: string]: string[];
};
scopeManager: eslint.Scope.ScopeManager;
};
/**
* Parse source code
*/
export declare function parseForESLint(code: string, options?: any): ParseResult;

201
node_modules/svelte-eslint-parser/lib/parser/index.js generated vendored Normal file
View File

@@ -0,0 +1,201 @@
import { KEYS } from "../visitor-keys.js";
import { Context } from "../context/index.js";
import { parseScript, parseScriptInSvelte } from "./script.js";
import { sortNodes } from "./sort.js";
import { parseTemplate } from "./template.js";
import { analyzePropsScope, analyzeReactiveScope, analyzeSnippetsScope, analyzeStoreScope, } from "./analyze-scope.js";
import { ParseError } from "../errors.js";
import { parseTypeScript, parseTypeScriptInSvelte, } from "./typescript/index.js";
import { addReference } from "../scope/index.js";
import { parseStyleContext, parseSelector, styleNodeLoc, styleNodeRange, styleSelectorNodeLoc, } from "./style-context.js";
import { getGlobalsForSvelte, getGlobalsForSvelteScript } from "./globals.js";
import { isTypeScript, normalizeParserOptions } from "./parser-options.js";
import { getFragmentFromRoot, getInstanceScriptRange } from "./compat.js";
import { hasRunesSymbol, resolveSvelteParseContextForSvelte, resolveSvelteParseContextForSvelteScript, } from "./svelte-parse-context.js";
import { resolveSvelteConfigFromOption } from "../svelte-config/index.js";
import { getESLintScope } from "./eslint-scope.js";
import { rememberParserOptions } from "../ts-sys-hook.js";
/**
* Parse source code
*/
export function parseForESLint(code, options) {
const svelteConfig = resolveSvelteConfigFromOption(options);
const parserOptions = normalizeParserOptions(options);
// Keep the `ts.sys` hook in sync with the parser/svelte config ESLint is
// currently using. The latest set wins for any in-process TS read.
rememberParserOptions(parserOptions);
if (parserOptions.filePath &&
(parserOptions.filePath.endsWith(".svelte.js") ||
parserOptions.filePath.endsWith(".svelte.ts"))) {
const svelteParseContext = resolveSvelteParseContextForSvelteScript(svelteConfig);
return parseAsScript(code, parserOptions, svelteParseContext);
}
return parseAsSvelte(code, svelteConfig, parserOptions);
}
/**
* Parse source code as svelte component
*/
function parseAsSvelte(code, svelteConfig, parserOptions) {
const ctx = new Context(code, parserOptions);
const resultTemplate = parseTemplate(ctx.sourceCode.template, ctx, parserOptions);
const svelteParseContext = resolveSvelteParseContextForSvelte(svelteConfig, parserOptions, resultTemplate.svelteAst);
const scripts = ctx.sourceCode.scripts;
const resultScript = ctx.isTypeScript()
? parseTypeScriptInSvelte(scripts.getCurrentVirtualCodeInfo(), scripts.attrs, parserOptions, {
slots: ctx.slots,
svelteParseContext,
instanceScriptRange: getInstanceScriptRange(resultTemplate.svelteAst),
})
: parseScriptInSvelte(scripts.getCurrentVirtualCode(), scripts.attrs, parserOptions);
ctx.scriptLet.restore(resultScript);
ctx.tokens.push(...resultScript.ast.tokens);
ctx.comments.push(...resultScript.ast.comments);
sortNodes(ctx.comments);
sortNodes(ctx.tokens);
extractTokens(ctx);
analyzeStoreScope(resultScript.scopeManager, svelteParseContext);
analyzeReactiveScope(resultScript.scopeManager);
analyzeStoreScope(resultScript.scopeManager, svelteParseContext); // for reactive vars
analyzeSnippetsScope(ctx.snippets, resultScript.scopeManager);
// Add $$xxx variable
addGlobalVariables(resultScript.scopeManager, getGlobalsForSvelte(svelteParseContext));
const ast = resultTemplate.ast;
const statements = [...resultScript.ast.body];
ast.sourceType = resultScript.ast.sourceType;
const scriptElements = ast.body.filter((b) => b.type === "SvelteScriptElement");
for (let index = 0; index < scriptElements.length; index++) {
const body = scriptElements[index];
let statement = statements[0];
while (statement &&
body.range[0] <= statement.range[0] &&
(statement.range[1] <= body.range[1] ||
index === scriptElements.length - 1)) {
statement.parent = body;
body.body.push(statement);
statements.shift();
statement = statements[0];
}
if (!body.startTag.attributes.some((attr) => attr.type === "SvelteAttribute" &&
attr.key.name === "context" &&
attr.value.length === 1 &&
attr.value[0].type === "SvelteLiteral" &&
attr.value[0].value === "module")) {
analyzePropsScope(body, resultScript.scopeManager, svelteParseContext);
}
}
if (statements.length) {
throw new ParseError("The script is unterminated", statements[0].range[1], ctx);
}
const styleElement = ast.body.find((b) => b.type === "SvelteStyleElement");
let styleContext = null;
const selectorASTs = new Map();
resultScript.ast = ast;
resultScript.services = Object.assign(resultScript.services || {}, {
isSvelte: true,
isSvelteScript: false,
getSvelteHtmlAst() {
return getFragmentFromRoot(resultTemplate.svelteAst);
},
getStyleContext() {
if (styleContext === null) {
styleContext = parseStyleContext(styleElement, ctx);
}
return styleContext;
},
getStyleSelectorAST(rule) {
const cached = selectorASTs.get(rule);
if (cached !== undefined) {
return cached;
}
const ast = parseSelector(rule);
selectorASTs.set(rule, ast);
return ast;
},
styleNodeLoc,
styleNodeRange,
styleSelectorNodeLoc,
svelteParseContext: {
...svelteParseContext,
// The compiler decides if runes mode is used after parsing.
runes: svelteParseContext.runes ?? hasRunesSymbol(resultScript.ast),
},
});
resultScript.visitorKeys = Object.assign({}, KEYS, resultScript.visitorKeys);
return resultScript;
}
/**
* Parse source code as script
*/
function parseAsScript(code, parserOptions, svelteParseContext) {
const lang = parserOptions.filePath?.split(".").pop();
const resultScript = isTypeScript(parserOptions, lang)
? parseTypeScript(code, { lang }, parserOptions, svelteParseContext)
: parseScript(code, { lang }, parserOptions);
// Add $$xxx variable
addGlobalVariables(resultScript.scopeManager, getGlobalsForSvelteScript(svelteParseContext));
resultScript.services = Object.assign(resultScript.services || {}, {
isSvelte: false,
isSvelteScript: true,
svelteParseContext,
});
resultScript.visitorKeys = Object.assign({}, KEYS, resultScript.visitorKeys);
return resultScript;
}
function addGlobalVariables(scopeManager, globals) {
const globalScope = scopeManager.globalScope;
for (const globalName of globals) {
if (globalScope.set.has(globalName))
continue;
// eslint-disable-next-line @typescript-eslint/naming-convention -- class name
const { Variable } = getESLintScope();
const variable = new Variable(globalName, globalScope);
variable.name = globalName;
variable.scope = globalScope;
globalScope.variables.push(variable);
globalScope.set.set(globalName, variable);
globalScope.through = globalScope.through.filter((reference) => {
if (reference.identifier.name === globalName) {
// Links the variable and the reference.
// And this reference is removed from `Scope#through`.
reference.resolved = variable;
addReference(variable.references, reference);
return false;
}
return true;
});
}
}
/** Extract tokens */
function extractTokens(ctx) {
const useRanges = sortNodes([...ctx.tokens, ...ctx.comments]).map((t) => t.range);
let range = useRanges.shift();
for (let index = 0; index < ctx.sourceCode.template.length; index++) {
while (range && range[1] <= index) {
range = useRanges.shift();
}
if (range && range[0] <= index) {
index = range[1] - 1;
continue;
}
const c = ctx.sourceCode.template[index];
if (!c.trim()) {
continue;
}
if (isPunctuator(c)) {
ctx.addToken("Punctuator", { start: index, end: index + 1 });
}
else {
// unknown
// It is may be a bug.
ctx.addToken("Identifier", { start: index, end: index + 1 });
}
}
sortNodes(ctx.comments);
sortNodes(ctx.tokens);
/**
* Checks if the given char is punctuator
*/
function isPunctuator(c) {
return /^[^\w$]$/iu.test(c);
}
}

View File

@@ -0,0 +1,34 @@
import type { ESLintExtendedProgram, ESLintProgram } from "./index.js";
import type * as tsESLintParser from "@typescript-eslint/parser";
type TSESLintParser = typeof tsESLintParser;
/**
* The type of basic ESLint custom parser.
* e.g. espree
*/
export type BasicParserObject = {
parse(code: string, options: any): ESLintProgram;
parseForESLint: undefined;
};
/**
* The type of ESLint custom parser enhanced for ESLint.
* e.g. @babel/eslint-parser, @typescript-eslint/parser
*/
export type EnhancedParserObject = {
parseForESLint(code: string, options: any): ESLintExtendedProgram;
parse: undefined;
};
/**
* The type of ESLint (custom) parsers.
*/
export type ParserObject = EnhancedParserObject | BasicParserObject;
/** Checks whether given object is ParserObject */
export declare function isParserObject(value: unknown): value is ParserObject;
/** Checks whether given object is EnhancedParserObject */
export declare function isEnhancedParserObject(value: unknown): value is EnhancedParserObject;
/** Checks whether given object is BasicParserObject */
export declare function isBasicParserObject(value: unknown): value is BasicParserObject;
/** Checks whether given object maybe "@typescript-eslint/parser" */
export declare function maybeTSESLintParserObject(value: unknown): value is TSESLintParser;
/** Checks whether given object is "@typescript-eslint/parser" */
export declare function isTSESLintParserObject(value: unknown): value is TSESLintParser;
export {};

View File

@@ -0,0 +1,35 @@
/** Checks whether given object is ParserObject */
export function isParserObject(value) {
return isEnhancedParserObject(value) || isBasicParserObject(value);
}
/** Checks whether given object is EnhancedParserObject */
export function isEnhancedParserObject(value) {
return Boolean(value && typeof value.parseForESLint === "function");
}
/** Checks whether given object is BasicParserObject */
export function isBasicParserObject(value) {
return Boolean(value && typeof value.parse === "function");
}
/** Checks whether given object maybe "@typescript-eslint/parser" */
export function maybeTSESLintParserObject(value) {
return (isEnhancedParserObject(value) &&
isBasicParserObject(value) &&
typeof value.createProgram === "function" &&
typeof value.clearCaches === "function" &&
typeof value.version === "string");
}
/** Checks whether given object is "@typescript-eslint/parser" */
export function isTSESLintParserObject(value) {
if (!isEnhancedParserObject(value))
return false;
try {
const result = value.parseForESLint("", {});
const services = result.services;
return Boolean(services &&
services.esTreeNodeToTSNodeMap &&
services.tsNodeToESTreeNodeMap);
}
catch {
return false;
}
}

View File

@@ -0,0 +1,42 @@
import type { Program } from "typescript";
import { type UserOptionParser } from "./resolve-parser.js";
export type NormalizedParserOptions = {
parser?: UserOptionParser;
project?: string | string[] | null;
programs?: Program[] | null;
disallowAutomaticSingleRunInference?: boolean;
projectService?: unknown;
EXPERIMENTAL_useProjectService?: unknown;
ecmaVersion: number | "latest";
sourceType: "module" | "script";
ecmaFeatures?: {
globalReturn?: boolean | undefined;
impliedStrict?: boolean | undefined;
jsx?: boolean | undefined;
experimentalObjectRestSpread?: boolean | undefined;
[key: string]: any;
};
svelteFeatures?: {
runes?: boolean;
};
loc: boolean;
range: boolean;
raw: boolean;
tokens: boolean;
comment: boolean;
eslintVisitorKeys: boolean;
eslintScopeManager: boolean;
filePath?: string;
};
/** Normalize parserOptions */
export declare function normalizeParserOptions(options: any): NormalizedParserOptions;
export declare function isTypeScript(parserOptions: NormalizedParserOptions, lang: string | undefined): boolean;
/**
* Remove typing-related options from parser options.
*
* Allows the typescript-eslint parser to parse a file without
* trying to collect typing information from TypeScript.
*
* See https://typescript-eslint.io/packages/parser#withoutprojectparseroptionsparseroptions
*/
export declare function withoutProjectParserOptions(options: NormalizedParserOptions): NormalizedParserOptions;

View File

@@ -0,0 +1,71 @@
import fs from "fs";
import path from "path";
import { isTSESLintParserObject, maybeTSESLintParserObject, } from "./parser-object.js";
import { getParserForLang } from "./resolve-parser.js";
/** Normalize parserOptions */
export function normalizeParserOptions(options) {
const parserOptions = {
ecmaVersion: 2024,
sourceType: "module",
loc: true,
range: true,
raw: true,
tokens: true,
comment: true,
eslintVisitorKeys: true,
eslintScopeManager: true,
...(options || {}),
};
parserOptions.sourceType = "module";
if (parserOptions.ecmaVersion <= 5 || parserOptions.ecmaVersion == null) {
parserOptions.ecmaVersion = 2015;
}
return parserOptions;
}
const TS_PARSER_NAMES = [
"@typescript-eslint/parser",
"typescript-eslint-parser-for-extra-files",
];
export function isTypeScript(parserOptions, lang) {
const parserValue = getParserForLang(lang, parserOptions?.parser);
if (typeof parserValue !== "string") {
return (maybeTSESLintParserObject(parserValue) ||
isTSESLintParserObject(parserValue));
}
const parserName = parserValue;
if (TS_PARSER_NAMES.includes(parserName)) {
return true;
}
if (TS_PARSER_NAMES.some((nm) => parserName.includes(nm))) {
let targetPath = parserName;
while (targetPath) {
const pkgPath = path.join(targetPath, "package.json");
if (fs.existsSync(pkgPath)) {
try {
return TS_PARSER_NAMES.includes(JSON.parse(fs.readFileSync(pkgPath, "utf-8"))?.name);
}
catch {
return false;
}
}
const parent = path.dirname(targetPath);
if (targetPath === parent) {
break;
}
targetPath = parent;
}
}
return false;
}
/**
* Remove typing-related options from parser options.
*
* Allows the typescript-eslint parser to parse a file without
* trying to collect typing information from TypeScript.
*
* See https://typescript-eslint.io/packages/parser#withoutprojectparseroptionsparseroptions
*/
export function withoutProjectParserOptions(options) {
const { project: _strippedProject, programs: _strippedPrograms, projectService: _strippedProjectService, EXPERIMENTAL_useProjectService: _strippedExperimentalUseProjectService, ...result } = options;
return result;
}

View File

@@ -0,0 +1,6 @@
import type { ParserObject } from "./parser-object.js";
export type UserOptionParser = string | ParserObject | Record<string, string | ParserObject | undefined> | undefined;
/** Get parser for script lang */
export declare function getParserForLang(lang: string | undefined | null, parser: UserOptionParser): string | ParserObject;
/** Get parser */
export declare function getParser(attrs: Record<string, string | undefined>, parser: UserOptionParser): ParserObject;

View File

@@ -0,0 +1,30 @@
import { getEspree } from "./espree.js";
import { isParserObject } from "./parser-object.js";
import Module from "module";
/** Get parser for script lang */
export function getParserForLang(lang, parser) {
if (parser) {
if (typeof parser === "string" || isParserObject(parser)) {
return parser;
}
if (typeof parser === "object") {
const value = parser[lang || "js"];
if (typeof value === "string" || isParserObject(value)) {
return value;
}
}
}
return "espree";
}
/** Get parser */
export function getParser(attrs, parser) {
const parserValue = getParserForLang(attrs.lang, parser);
if (isParserObject(parserValue)) {
return parserValue;
}
if (parserValue !== "espree") {
const require = Module.createRequire(import.meta.url);
return require(parserValue);
}
return getEspree();
}

View File

@@ -0,0 +1,14 @@
import type { ESLintExtendedProgram } from "./index.js";
import type { NormalizedParserOptions } from "./parser-options.js";
/**
* Parse for <script>
*/
export declare function parseScriptInSvelte(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions): ESLintExtendedProgram;
/**
* Parse for script
*/
export declare function parseScript(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions): ESLintExtendedProgram;
/**
* Parse for script without analyze scope
*/
export declare function parseScriptWithoutAnalyzeScope(code: string, attrs: Record<string, string | undefined>, options: NormalizedParserOptions): ESLintExtendedProgram;

58
node_modules/svelte-eslint-parser/lib/parser/script.js generated vendored Normal file
View File

@@ -0,0 +1,58 @@
import { analyzeScope } from "./analyze-scope.js";
import { traverseNodes } from "../traverse.js";
import { getParser } from "./resolve-parser.js";
import { isEnhancedParserObject } from "./parser-object.js";
/**
* Parse for <script>
*/
export function parseScriptInSvelte(code, attrs, parserOptions) {
const result = parseScript(code, attrs, parserOptions);
traverseNodes(result.ast, {
visitorKeys: result.visitorKeys,
enterNode(node, parent) {
node.parent = parent;
if (node.type === "LabeledStatement" && node.label.name === "$") {
if (parent?.type === "Program") {
// Transform node type
node.type = "SvelteReactiveStatement";
}
}
},
leaveNode() {
//
},
});
return result;
}
/**
* Parse for script
*/
export function parseScript(code, attrs, parserOptions) {
const result = parseScriptWithoutAnalyzeScopeFromVCode(code, attrs, parserOptions);
if (!result.scopeManager) {
const scopeManager = analyzeScope(result.ast, parserOptions);
result.scopeManager = scopeManager;
}
return result;
}
/**
* Parse for script without analyze scope
*/
export function parseScriptWithoutAnalyzeScope(code, attrs, options) {
const parser = getParser(attrs, options.parser);
const result = isEnhancedParserObject(parser)
? parser.parseForESLint(code, options)
: parser.parse(code, options);
if ("ast" in result && result.ast != null) {
return result;
}
return { ast: result };
}
/**
* Parse for script without analyze scope
*/
function parseScriptWithoutAnalyzeScopeFromVCode(code, attrs, options) {
const result = parseScriptWithoutAnalyzeScope(code, attrs, options);
result._virtualScriptCode = code;
return result;
}

View File

@@ -0,0 +1,6 @@
/**
* Sort tokens
*/
export declare function sortNodes<T extends {
range: [number, number];
}>(tokens: T[] | null | undefined): T[];

14
node_modules/svelte-eslint-parser/lib/parser/sort.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
/**
* Sort tokens
*/
export function sortNodes(tokens) {
if (!tokens) {
return [];
}
return tokens.sort((a, b) => {
if (a.range[0] !== b.range[0]) {
return a.range[0] - b.range[0];
}
return a.range[1] - b.range[1];
});
}

View File

@@ -0,0 +1,42 @@
import type { Node, Root, Rule } from "postcss";
import { type Node as SelectorNode, type Root as SelectorRoot } from "postcss-selector-parser";
import type { Context } from "../context/index.js";
import type { SourceLocation, SvelteStyleElement } from "../ast/index.js";
export type StyleContext = StyleContextNoStyleElement | StyleContextParseError | StyleContextSuccess | StyleContextUnknownLang;
export interface StyleContextNoStyleElement {
status: "no-style-element";
}
export interface StyleContextParseError {
status: "parse-error";
sourceLang: string;
error: Error;
}
export interface StyleContextSuccess {
status: "success";
sourceLang: string;
sourceAst: Root;
}
export interface StyleContextUnknownLang {
status: "unknown-lang";
sourceLang: string;
}
/**
* Extracts style source from a SvelteStyleElement and parses it into a PostCSS AST.
*/
export declare function parseStyleContext(styleElement: SvelteStyleElement | undefined, ctx: Context): StyleContext;
/**
* Parses a PostCSS Rule node's selector and returns its AST.
*/
export declare function parseSelector(rule: Rule): SelectorRoot;
/**
* Extracts a node location (like that of any ESLint node) from a parsed svelte style node.
*/
export declare function styleNodeLoc(node: Node): Partial<SourceLocation>;
/**
* Extracts a node range (like that of any ESLint node) from a parsed svelte style node.
*/
export declare function styleNodeRange(node: Node): [number | undefined, number | undefined];
/**
* Extracts a node location (like that of any ESLint node) from a parsed svelte selector node.
*/
export declare function styleSelectorNodeLoc(node: SelectorNode): Partial<SourceLocation>;

View File

@@ -0,0 +1,156 @@
import postcss from "postcss";
import { parse as SCSSparse } from "postcss-scss";
import { default as selectorParser, } from "postcss-selector-parser";
/**
* Extracts style source from a SvelteStyleElement and parses it into a PostCSS AST.
*/
export function parseStyleContext(styleElement, ctx) {
if (!styleElement || !styleElement.endTag) {
return { status: "no-style-element" };
}
let sourceLang = "css";
for (const attribute of styleElement.startTag.attributes) {
if (attribute.type === "SvelteAttribute" &&
attribute.key.name === "lang" &&
attribute.value.length > 0 &&
attribute.value[0].type === "SvelteLiteral") {
sourceLang = attribute.value[0].value;
}
}
let parseFn, sourceAst;
switch (sourceLang) {
case "css":
case "postcss":
parseFn = postcss.parse;
break;
case "scss":
parseFn = SCSSparse;
break;
default:
return { status: "unknown-lang", sourceLang };
}
const styleCode = ctx.code.slice(styleElement.startTag.range[1], styleElement.endTag.range[0]);
try {
sourceAst = parseFn(styleCode, {
from: ctx.parserOptions.filePath,
});
}
catch (error) {
return { status: "parse-error", sourceLang, error: error };
}
fixPostCSSNodeLocation(sourceAst, styleElement);
sourceAst.walk((node) => {
fixPostCSSNodeLocation(node, styleElement);
});
return { status: "success", sourceLang, sourceAst };
}
/**
* Parses a PostCSS Rule node's selector and returns its AST.
*/
export function parseSelector(rule) {
const processor = selectorParser();
const root = processor.astSync(rule.selector);
fixSelectorNodeLocation(root, rule);
root.walk((node) => {
fixSelectorNodeLocation(node, rule);
});
return root;
}
/**
* Extracts a node location (like that of any ESLint node) from a parsed svelte style node.
*/
export function styleNodeLoc(node) {
if (node.source === undefined) {
return {};
}
return {
start: node.source.start !== undefined
? {
line: node.source.start.line,
column: node.source.start.column - 1,
}
: undefined,
end: node.source.end !== undefined
? {
line: node.source.end.line,
column: node.source.end.column,
}
: undefined,
};
}
/**
* Extracts a node range (like that of any ESLint node) from a parsed svelte style node.
*/
export function styleNodeRange(node) {
if (node.source === undefined) {
return [undefined, undefined];
}
return [
node.source.start !== undefined ? node.source.start.offset : undefined,
node.source.end !== undefined ? node.source.end.offset + 1 : undefined,
];
}
/**
* Extracts a node location (like that of any ESLint node) from a parsed svelte selector node.
*/
export function styleSelectorNodeLoc(node) {
return {
start: node.source?.start !== undefined
? {
line: node.source.start.line,
column: node.source.start.column - 1,
}
: undefined,
end: node.source?.end,
};
}
/**
* Fixes PostCSS AST locations to be relative to the whole file instead of relative to the <style> element.
*/
function fixPostCSSNodeLocation(node, styleElement) {
if (node.source?.start?.offset !== undefined) {
node.source.start.offset += styleElement.startTag.range[1];
}
if (node.source?.start?.line !== undefined) {
node.source.start.line += styleElement.loc.start.line - 1;
}
if (node.source?.end?.offset !== undefined) {
node.source.end.offset += styleElement.startTag.range[1];
}
if (node.source?.end?.line !== undefined) {
node.source.end.line += styleElement.loc.start.line - 1;
}
if (node.source?.start?.line === styleElement.loc.start.line) {
node.source.start.column += styleElement.startTag.loc.end.column;
}
if (node.source?.end?.line === styleElement.loc.start.line) {
node.source.end.column += styleElement.startTag.loc.end.column;
}
}
/**
* Fixes selector AST locations to be relative to the whole file instead of relative to their parent rule.
*/
function fixSelectorNodeLocation(node, rule) {
if (node.source === undefined) {
return;
}
const ruleLoc = styleNodeLoc(rule);
if (node.source.start !== undefined && ruleLoc.start !== undefined) {
if (node.source.start.line === 1) {
node.source.start.column += ruleLoc.start.column;
}
node.source.start.line += ruleLoc.start.line - 1;
}
else {
node.source.start = undefined;
}
if (node.source.end !== undefined && ruleLoc.start !== undefined) {
if (node.source.end.line === 1) {
node.source.end.column += ruleLoc.start.column;
}
node.source.end.line += ruleLoc.start.line - 1;
}
else {
node.source.end = undefined;
}
}

View File

@@ -0,0 +1,47 @@
import type { AST } from "svelte/compiler";
export type Root = AST.Root;
export type Fragment = AST.Fragment;
export type SvelteOptions = AST.SvelteOptions;
export type Script = AST.Script;
export type Text = AST.Text;
export type ExpressionTag = AST.ExpressionTag;
export type HtmlTag = AST.HtmlTag;
export type ConstTag = AST.ConstTag;
export type DeclarationTag = AST.DeclarationTag;
export type DebugTag = AST.DebugTag;
export type RenderTag = AST.RenderTag;
export type Component = AST.Component;
export type TitleElement = AST.TitleElement;
export type SlotElement = AST.SlotElement;
export type RegularElement = AST.RegularElement;
export type SvelteBody = AST.SvelteBody;
export type SvelteComponent = AST.SvelteComponent;
export type SvelteDocument = AST.SvelteDocument;
export type SvelteElement = AST.SvelteElement;
export type SvelteFragment = AST.SvelteFragment;
export type SvelteHead = AST.SvelteHead;
export type SvelteOptionsRaw = AST.SvelteOptionsRaw;
export type SvelteSelf = AST.SvelteSelf;
export type SvelteWindow = AST.SvelteWindow;
export type SvelteBoundary = AST.SvelteBoundary;
export type IfBlock = AST.IfBlock;
export type EachBlock = AST.EachBlock;
export type AwaitBlock = AST.AwaitBlock;
export type KeyBlock = AST.KeyBlock;
export type SnippetBlock = AST.SnippetBlock;
export type Comment = AST.Comment;
export type Attribute = AST.Attribute;
export type SpreadAttribute = AST.SpreadAttribute;
export type AttachTag = AST.AttachTag;
export type AnimateDirective = AST.AnimateDirective;
export type BindDirective = AST.BindDirective;
export type ClassDirective = AST.ClassDirective;
export type LetDirective = AST.LetDirective;
export type OnDirective = AST.OnDirective;
export type StyleDirective = AST.StyleDirective;
export type TransitionDirective = AST.TransitionDirective;
export type UseDirective = AST.UseDirective;
export type Tag = ExpressionTag | HtmlTag | ConstTag | DeclarationTag | DebugTag | RenderTag;
export type ElementLike = Component | TitleElement | SlotElement | RegularElement | SvelteBody | SvelteComponent | SvelteDocument | SvelteElement | SvelteFragment | SvelteHead | SvelteOptionsRaw | SvelteSelf | SvelteWindow | SvelteBoundary;
export type Block = EachBlock | IfBlock | AwaitBlock | KeyBlock | SnippetBlock;
export type Directive = AnimateDirective | BindDirective | ClassDirective | LetDirective | OnDirective | StyleDirective | TransitionDirective | UseDirective;

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,213 @@
import type ESTree from "estree";
interface BaseNode {
start: number;
end: number;
}
export interface AstLegacy {
html?: Fragment;
css?: Style;
instance?: Script;
module?: Script;
}
export declare type TemplateNode = Text | MustacheTag | RawMustacheTag | DebugTag | ConstTag | Directive | StyleDirective | Element | InlineComponent | Window | Document | Body | Head | Title | Options | SlotTemplate | Slot | Comment | IfBlock | EachBlock | AwaitBlock | KeyBlock;
export interface Fragment extends BaseNode {
type: "Fragment";
children: TemplateNode[];
}
export interface Text extends BaseNode {
type: "Text";
data: string;
}
export interface MustacheTag extends BaseNode {
type: "MustacheTag";
expression: ESTree.Expression;
}
export interface RawMustacheTag extends BaseNode {
type: "RawMustacheTag";
expression: ESTree.Expression;
}
export interface DebugTag extends BaseNode {
type: "DebugTag";
identifiers: ESTree.Identifier[];
}
export interface ConstTag extends BaseNode {
type: "ConstTag";
expression: ESTree.AssignmentExpression;
}
export interface IfBlock extends BaseNode {
type: "IfBlock";
expression: ESTree.Expression;
children: TemplateNode[];
else: ElseBlock | undefined;
elseif: true | undefined;
}
export interface ElseBlock extends BaseNode {
type: "ElseBlock";
children: TemplateNode[] | [IfBlock & {
elseif: true;
}];
}
export interface EachBlock extends BaseNode {
type: "EachBlock";
expression: ESTree.Expression;
context: ESTree.Pattern;
index?: string;
key: ESTree.Expression | undefined;
children: TemplateNode[];
else: ElseBlock | undefined;
}
export interface AwaitBlock extends BaseNode {
type: "AwaitBlock";
expression: ESTree.Expression;
pending: PendingBlock;
value: ESTree.Pattern | null;
then: ThenBlock;
error: ESTree.Pattern | null;
catch: CatchBlock;
}
export interface PendingBlock extends BaseNode {
type: "PendingBlock";
skip: boolean;
children: TemplateNode[];
}
export interface ThenBlock extends BaseNode {
type: "ThenBlock";
skip: boolean;
children: TemplateNode[];
}
export interface CatchBlock extends BaseNode {
type: "CatchBlock";
skip: boolean;
children: TemplateNode[];
}
export interface KeyBlock extends BaseNode {
type: "KeyBlock";
expression: ESTree.Expression;
children: TemplateNode[];
}
export interface BaseElement extends BaseNode {
type: "Element";
name: string;
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface BasicElement extends BaseElement {
tag?: undefined;
}
export interface SvelteElement extends BaseElement {
name: "svelte:element";
tag: ESTree.Expression | string;
}
export type Element = BasicElement | SvelteElement;
export interface BaseInlineComponent extends BaseNode {
type: "InlineComponent";
name: string;
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Window extends BaseNode {
type: "Window";
name: "svelte:window";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Document extends BaseNode {
type: "Document";
name: "svelte:document";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Body extends BaseNode {
type: "Body";
name: "svelte:body";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Head extends BaseNode {
type: "Head";
name: "svelte:head";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Title extends BaseNode {
type: "Title";
name: "title";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Options extends BaseNode {
type: "Options";
name: "svelte:options";
children?: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface SlotTemplate extends BaseNode {
type: "SlotTemplate";
name: "svelte:fragment";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface BasicInlineComponent extends BaseInlineComponent {
expression?: undefined;
}
export interface InlineSvelteComponent extends BaseInlineComponent {
name: "svelte:component";
expression: ESTree.Expression;
}
export type InlineComponent = BasicInlineComponent | InlineSvelteComponent;
export interface Slot extends BaseNode {
type: "Slot";
name: "slot";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Comment extends BaseNode {
type: "Comment";
data: string;
}
export interface Attribute extends BaseNode {
type: "Attribute";
name: string;
value: (Text | MustacheTag)[] | [AttributeShorthand] | true;
}
export interface Spread extends BaseNode {
type: "Spread";
expression: ESTree.Expression;
}
export interface AttributeShorthand extends BaseNode {
type: "AttributeShorthand";
expression: ESTree.Identifier;
}
export type AttributeOrDirective = Attribute | Spread | Directive | StyleDirective;
interface BaseDirective extends BaseNode {
name: string;
modifiers: string[];
}
export interface DirectiveForExpression extends BaseDirective {
type: "Action" | "Animation" | "Binding" | "Class" | "EventHandler" | "Ref";
expression: null | ESTree.Expression;
}
export interface LetDirective extends BaseDirective {
type: "Let";
expression: null | ESTree.Pattern;
}
export interface TransitionDirective extends BaseDirective {
type: "Transition";
intro: boolean;
outro: boolean;
expression: null | ESTree.Expression;
}
export interface StyleDirective extends BaseDirective {
type: "StyleDirective";
value: (Text | MustacheTag)[] | true;
}
export type Directive = DirectiveForExpression | TransitionDirective | LetDirective;
export interface Script extends BaseNode {
type: "Script";
context: string;
children: TemplateNode[];
}
export interface Style extends BaseNode {
type: "Style";
}
export {};

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,26 @@
import type * as Compiler from "./svelte-ast-types-for-v5.js";
import type * as SvAST from "./svelte-ast-types.js";
import type { NormalizedParserOptions } from "./parser-options.js";
import type { SvelteConfig } from "../svelte-config/index.js";
import type { ESLintProgram } from "./index.js";
/** The context for parsing. */
export type SvelteParseContext = {
/**
* Determines if the file is in Runes mode.
*
* - Svelte 3/4 does not support Runes mode.
* - Checks if `runes` configuration exists in:
* - `parserOptions`
* - `svelte.config.js`
* - `<svelte:options>` in the Svelte file.
* - Returns `true` if the `runes` symbol is present in the Svelte file.
*/
runes?: boolean;
/** The version of "svelte/compiler". */
compilerVersion: string;
/** The result of static analysis of `svelte.config.js`. */
svelteConfig: SvelteConfig | null;
};
export declare function resolveSvelteParseContextForSvelte(svelteConfig: SvelteConfig | null, parserOptions: NormalizedParserOptions, svelteAst: Compiler.Root | SvAST.AstLegacy): SvelteParseContext;
export declare function resolveSvelteParseContextForSvelteScript(svelteConfig: SvelteConfig | null): SvelteParseContext;
export declare function hasRunesSymbol(ast: ESLintProgram): boolean;

View File

@@ -0,0 +1,66 @@
import { compilerVersion, svelteVersion } from "./svelte-version.js";
import { traverseNodes } from "../traverse.js";
const runeSymbols = [
"$state",
"$derived",
"$effect",
"$props",
"$bindable",
"$inspect",
"$host",
];
export function resolveSvelteParseContextForSvelte(svelteConfig, parserOptions, svelteAst) {
return {
runes: isRunesAsParseContext(svelteConfig, parserOptions, svelteAst),
compilerVersion,
svelteConfig,
};
}
export function resolveSvelteParseContextForSvelteScript(svelteConfig) {
return {
// .svelte.js files are always in Runes mode for Svelte 5.
runes: svelteVersion.gte(5),
compilerVersion,
svelteConfig,
};
}
function isRunesAsParseContext(svelteConfig, parserOptions, svelteAst) {
// Svelte 3/4 does not support Runes mode.
if (!svelteVersion.gte(5)) {
return false;
}
// Compiler option.
if (parserOptions.svelteFeatures?.runes != null) {
return parserOptions.svelteFeatures?.runes;
}
if (svelteConfig?.compilerOptions?.runes != null) {
return typeof svelteConfig.compilerOptions?.runes === "function"
? svelteConfig.compilerOptions.runes({
filename: parserOptions.filePath ?? "",
})
: svelteConfig.compilerOptions?.runes;
}
// `<svelte:options>`.
const svelteOptions = svelteAst.options;
if (svelteOptions?.runes != null) {
return svelteOptions?.runes;
}
return undefined;
}
export function hasRunesSymbol(ast) {
let hasRuneSymbol = false;
traverseNodes(ast, {
enterNode(node) {
if (hasRuneSymbol) {
return;
}
if (node.type === "Identifier" && runeSymbols.includes(node.name)) {
hasRuneSymbol = true;
}
},
leaveNode() {
// do nothing
},
});
return hasRuneSymbol;
}

View File

@@ -0,0 +1,6 @@
import type { NormalizedParserOptions } from "./parser-options.js";
/**
* Translate a Svelte component to the virtual TypeScript shim. Returns
* `null` if the configured script parser is not TypeScript or parsing fails.
*/
export declare function svelteToVirtualTypeScript(filePath: string, content: string, parserOptions: NormalizedParserOptions): string | null;

View File

@@ -0,0 +1,43 @@
import { Context } from "../context/index.js";
import { resolveSvelteConfigFromOption } from "../svelte-config/index.js";
import { parseTemplate } from "./template.js";
import { analyzeTypeScriptInSvelte } from "./typescript/analyze/index.js";
import { resolveSvelteParseContextForSvelte } from "./svelte-parse-context.js";
import { getInstanceScriptRange } from "./compat.js";
/**
* Translate a Svelte component to the virtual TypeScript shim. Returns
* `null` if the configured script parser is not TypeScript or parsing fails.
*/
export function svelteToVirtualTypeScript(filePath, content, parserOptions) {
try {
// Drop `project` / `projectService`: we're already inside
// `@typescript-eslint/parser`'s stack via the `ts.sys` hook, and a nested
// analyzer trying to spin up its own program would deadlock or recurse.
const inner = {
...parserOptions,
filePath,
project: null,
projectService: undefined,
EXPERIMENTAL_useProjectService: undefined,
};
const ctx = new Context(content, inner);
if (!ctx.isTypeScript())
return null;
const template = parseTemplate(ctx.sourceCode.template, ctx, inner);
const svelteConfig = resolveSvelteConfigFromOption({
...parserOptions,
filePath,
});
const svelteParseContext = resolveSvelteParseContextForSvelte(svelteConfig, inner, template.svelteAst);
const scripts = ctx.sourceCode.scripts;
const tsCtx = analyzeTypeScriptInSvelte(scripts.getCurrentVirtualCodeInfo(), scripts.attrs, inner, {
slots: ctx.slots,
svelteParseContext,
instanceScriptRange: getInstanceScriptRange(template.svelteAst),
});
return tsCtx.script;
}
catch {
return null;
}
}

View File

@@ -0,0 +1,5 @@
import { VERSION as compilerVersion } from "svelte/compiler";
export { compilerVersion };
export declare const svelteVersion: {
gte(v: number): boolean;
};

View File

@@ -0,0 +1,8 @@
import { VERSION as compilerVersion } from "svelte/compiler";
export { compilerVersion };
const verStrings = compilerVersion.split(".");
export const svelteVersion = {
gte(v) {
return Number(verStrings[0]) >= v;
},
};

View File

@@ -0,0 +1,12 @@
import type * as Compiler from "./svelte-ast-types-for-v5.js";
import type * as SvAST from "./svelte-ast-types.js";
import type { Context } from "../context/index.js";
import type { SvelteProgram } from "../ast/index.js";
import type { NormalizedParserOptions } from "./parser-options.js";
/**
* Parse for template
*/
export declare function parseTemplate(code: string, ctx: Context, parserOptions: NormalizedParserOptions): {
ast: SvelteProgram;
svelteAst: Compiler.Root | SvAST.AstLegacy;
};

View File

@@ -0,0 +1,34 @@
import { parse } from "svelte/compiler";
import { convertSvelteRoot } from "./converts/index.js";
import { ParseError } from "../errors.js";
import { svelteVersion } from "./svelte-version.js";
/**
* Parse for template
*/
export function parseTemplate(code, ctx, parserOptions) {
try {
const options = {
filename: parserOptions.filePath,
...(svelteVersion.gte(5) ? { modern: true } : {}),
};
const svelteAst = parse(code, options);
const ast = convertSvelteRoot(svelteAst, ctx);
return {
ast,
svelteAst,
};
}
catch (e) {
if (typeof e.pos === "number") {
const err = new ParseError(e.message, e.pos, ctx);
err.svelteCompilerError = e;
throw err;
}
if (Array.isArray(e.position) && typeof e.position[0] === "number") {
const err = new ParseError(e.message, e.position[0], ctx);
err.svelteCompilerError = e;
throw err;
}
throw e;
}
}

View File

@@ -0,0 +1,13 @@
import type { VirtualTypeScriptContext } from "../context.js";
import type { TSESParseForESLintResult } from "../types.js";
import type { SvelteParseContext } from "../../svelte-parse-context.js";
/**
* Append a synthetic component `export default` so importers can resolve the
* component's prop, event, and slot types.
*
* The export must carry both a value and a type meaning: `ComponentProps<typeof
* Foo>` uses the value, while `ComponentEvents<Foo>` and Svelte-4-style
* `ComponentProps<Foo>` use `Foo` as a type. A bare `export default <expr>` only
* provides the value, so emit a value/type pair re-exported as default.
*/
export declare function appendComponentDefaultExport(result: TSESParseForESLintResult, source: string, ctx: VirtualTypeScriptContext, svelteParseContext: SvelteParseContext, instanceScriptRange: [number, number] | null): void;

View File

@@ -0,0 +1,545 @@
import { removeAllScopeAndVariableAndReference } from "../../../scope/index.js";
import { setParent } from "../set-parent.js";
import { svelteVersion } from "../../svelte-version.js";
/**
* Append a synthetic component `export default` so importers can resolve the
* component's prop, event, and slot types.
*
* The export must carry both a value and a type meaning: `ComponentProps<typeof
* Foo>` uses the value, while `ComponentEvents<Foo>` and Svelte-4-style
* `ComponentProps<Foo>` use `Foo` as a type. A bare `export default <expr>` only
* provides the value, so emit a value/type pair re-exported as default.
*/
export function appendComponentDefaultExport(result, source, ctx, svelteParseContext, instanceScriptRange) {
if (hasDefaultExport(result.ast)) {
return;
}
// Legacy recovery must only look at the instance script: a module-context
// `export let` is not a prop, and `$$Props`/`$$Events`/`$$Slots` are only
// meaningful in the instance script.
const instanceStatements = getInstanceStatements(result, instanceScriptRange);
const names = [];
// Lead with a newline so a trailing line comment can't swallow the statement.
let code = "\n";
// Runes `$props()` takes precedence over legacy recovery; the last fallback
// stays permissive so `typeof Foo` still resolves.
let propsType;
const runesProps = recoverRunesProps(result, source, svelteParseContext, instanceScriptRange);
if (runesProps?.kind === "explicit") {
propsType = runesProps.type;
}
else if (runesProps != null) {
const parts = [];
if (runesProps.probe != null) {
// Let TS infer the default value types via `typeof` of a probe object.
const probeName = ctx.generateUniqueId("propsProbe");
names.push(probeName);
code += `const ${probeName} = ${runesProps.probe};`;
parts.push(`{ [K in keyof typeof ${probeName}]?: (typeof ${probeName})[K] }`);
}
if (runesProps.members != null) {
parts.push(runesProps.members);
}
if (runesProps.open) {
parts.push("{ [key: string]: any }");
}
// An empty destructuring declares no props at all, so nothing is accepted.
propsType = parts.length ? parts.join(" & ") : "{ [key: string]: never }";
}
else {
// A component reading `$$props`/`$$restProps` accepts arbitrary attributes,
// so the synthesized (closed) type is opened with an index signature to
// avoid spurious excess-property errors. `$$Props` is exempt: there the user
// owns the open/closed decision.
const dollarPropsType = getDollarDollarPropsType(instanceStatements, svelteParseContext);
if (dollarPropsType != null) {
propsType = dollarPropsType;
}
else {
const inferredBindings = new Set();
const probeName = ctx.generateUniqueId("legacyPropsProbe");
const exportLetType = getLegacyExportLetPropsType(instanceStatements, source, svelteParseContext, (name) => {
inferredBindings.add(name);
return `(typeof ${probeName} extends () => infer P ? P : never)[${JSON.stringify(name)}]`;
});
if (inferredBindings.size) {
names.push(probeName);
// A function avoids control-flow narrowing at the end of the script;
// its object return also widens inferred boolean literal values.
code += `const ${probeName} = () => ({ ${[...inferredBindings].join(", ")} });`;
}
if (exportLetType != null && referencesOpenProps(result)) {
propsType = `${exportLetType} & { [key: string]: any }`;
}
else {
propsType = exportLetType ?? "{ [key: string]: any }";
}
}
}
// Stay permissive without `$$Events`/`$$Slots` so `on:` and slots don't get
// spurious errors.
const eventsType = hasNamedTypeDeclaration(instanceStatements, "$$Events")
? "$$Events"
: "{ [key: string]: any }";
const slotsType = hasNamedTypeDeclaration(instanceStatements, "$$Slots")
? "$$Slots"
: "{ [key: string]: any }";
const name = ctx.generateUniqueId("svelteComponent");
names.push(name);
const { valueType, typeType } = componentTypeText(propsType, eventsType, slotsType, getInstanceExportsType(instanceStatements, svelteParseContext));
code += `declare const ${name}: ${valueType};type ${name} = ${typeType};export { ${name} as default };`;
ctx.appendVirtualScript(code);
// `export { <name> as default }`.
registerRemoval(ctx, (node) => node.type === "ExportNamedDeclaration" &&
node.declaration == null &&
node.specifiers.length === 1 &&
node.specifiers[0].local.type === "Identifier" &&
node.specifiers[0].local.name === name);
// `type <name> = ...`.
registerRemoval(ctx, (node) => node.type === "TSTypeAliasDeclaration" && node.id.name === name);
// The `declare const <name>` and any props probe const.
for (const nm of names) {
registerRemoval(ctx, (node) => node.type === "VariableDeclaration" &&
node.declarations[0]?.id.type === "Identifier" &&
node.declarations[0].id.name === nm);
}
}
/**
* Value-side and type-side text of the synthetic default export, chosen by the
* *installed* Svelte version rather than the component mode: Svelte 3/4 typings
* have no `Component`, and Svelte 3's `SvelteComponent` is not generic.
*/
function componentTypeText(propsType, eventsType, slotsType, exportsType) {
const typeArgs = `<${propsType}, ${eventsType}, ${slotsType}>`;
// Instance exports are what `bind:this` hands back, so the instance type
// carries them alongside the component class.
function withExports(type) {
return exportsType == null ? type : `${type} & ${exportsType}`;
}
if (svelteVersion.gte(5)) {
// The value is Svelte 5's `Component` so `typeof Foo` matches modern usage;
// the same-named legacy `SvelteComponent` type keeps `ComponentEvents<Foo>`
// resolving.
return {
valueType: exportsType == null
? `import('svelte').Component<${propsType}>`
: `import('svelte').Component<${propsType}, ${exportsType}>`,
typeType: withExports(`import('svelte').SvelteComponent${typeArgs}`),
};
}
const className = svelteVersion.gte(4)
? "SvelteComponent"
: "SvelteComponentTyped";
const instanceType = withExports(`import('svelte').${className}${typeArgs}`);
// A constructor value so `new Foo(...)` works and `typeof Foo` resolves; the
// same-named type is the instance for `ComponentProps<Foo>` /
// `ComponentEvents<Foo>`. `ComponentConstructorOptions` (present in Svelte 3
// and 4) validates `new Foo({ props: … })` instead of accepting anything.
return {
valueType: `new (options: import('svelte').ComponentConstructorOptions<${propsType}>) => ${instanceType}`,
typeType: instanceType,
};
}
/** Register a restore process that splices a matching statement and cleans scope. */
function registerRemoval(ctx, match) {
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (!match(node)) {
return false;
}
result.ast.body.splice(result.ast.body.indexOf(node), 1);
removeAllScopeAndVariableAndReference(node, {
visitorKeys: result.visitorKeys,
scopeManager: result.scopeManager,
});
return true;
});
}
function hasDefaultExport(ast) {
return ast.body.some((node) => {
if (node.type === "ExportDefaultDeclaration") {
return true;
}
// `export { x as default }` counts as a user-authored default export too.
if (node.type === "ExportNamedDeclaration") {
return (node.exportKind !== "type" &&
node.specifiers.some((specifier) => specifier.exportKind !== "type" &&
exportName(specifier.exported) === "default"));
}
return (node.type === "ExportAllDeclaration" &&
node.exportKind !== "type" &&
node.exported != null &&
exportName(node.exported) === "default");
});
}
/** Get either spelling of an ES module export name. */
function exportName(node) {
return node.type === "Identifier" ? node.name : node.value;
}
/** Top-level statements of the instance `<script>`, filtered out of the concatenated body by source range. */
function getInstanceStatements(result, instanceScriptRange) {
if (!instanceScriptRange) {
return [];
}
const [start, end] = instanceScriptRange;
return result.ast.body.filter((node) => start <= node.range[0] && node.range[1] <= end);
}
function hasNamedTypeDeclaration(statements, name) {
return statements.some((statement) => {
const node = statement.type === "ExportNamedDeclaration"
? statement.declaration
: statement;
return (node != null &&
(node.type === "TSInterfaceDeclaration" ||
node.type === "TSTypeAliasDeclaration") &&
node.id.name === name);
});
}
/**
* Svelte treats `$$Props` as the authoritative prop typing, so it takes priority
* over `export let` inference. Referenced by name, since the declaration itself
* stays in the virtual code.
*/
function getDollarDollarPropsType(instanceStatements, svelteParseContext) {
if (svelteParseContext.runes === true) {
return null;
}
return hasNamedTypeDeclaration(instanceStatements, "$$Props")
? "$$Props"
: null;
}
/**
* Synthesize a props object type from legacy prop declarations, mirroring
* svelte2tsx: a default value makes the prop optional, an explicit annotation is
* used as-is, otherwise the type is inferred via `typeof`. Renamed exports whose
* local is a top-level `let` (`export { className as class }`) are props too.
*/
function getLegacyExportLetPropsType(instanceStatements, source, svelteParseContext, inferBinding) {
// `export let` is only a prop declaration in legacy (non-runes) mode.
if (svelteParseContext.runes === true) {
return null;
}
const members = [];
function pushMember(exportedName, declarator) {
const optional = declarator.init != null;
const typeAnnotation = declarator.id.type === "Identifier"
? declarator.id.typeAnnotation
: undefined;
const localName = declarator.id.type === "Identifier" ? declarator.id.name : null;
const typeText = typeAnnotation
? source.slice(typeAnnotation.typeAnnotation.range[0], typeAnnotation.typeAnnotation.range[1])
: localName != null
? (declarator.init &&
degenerateDefaultType(stripAsConst(declarator.init))) ||
inferBinding(localName)
: "any";
members.push(`${propKey(exportedName)}${optional ? "?" : ""}: ${typeText}`);
}
// Indexed by binding name so a renamed export can resolve its local `let`.
const letDeclarators = new Map();
for (const node of instanceStatements) {
const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
if (decl?.type !== "VariableDeclaration" || decl.kind !== "let") {
continue;
}
for (const declarator of decl.declarations) {
if (declarator.id.type === "Identifier") {
letDeclarators.set(declarator.id.name, declarator);
}
}
}
for (const node of instanceStatements) {
if (node.type !== "ExportNamedDeclaration" || node.exportKind === "type") {
continue;
}
if (node.declaration?.type === "VariableDeclaration" &&
node.declaration.kind === "let") {
for (const declarator of node.declaration.declarations) {
if (declarator.id.type !== "Identifier") {
continue;
}
pushMember(declarator.id.name, declarator);
}
continue;
}
// A renamed (or same-name) export of a top-level `let` binding is a prop.
// Skip re-exports (`export … from '…'`) and `default` (handled elsewhere).
if (node.declaration == null && node.source == null) {
for (const specifier of node.specifiers) {
if (specifier.local.type !== "Identifier" ||
specifier.exportKind === "type" ||
exportName(specifier.exported) === "default") {
continue;
}
const declarator = letDeclarators.get(specifier.local.name);
if (!declarator) {
continue;
}
pushMember(exportName(specifier.exported), declarator);
}
}
}
if (!members.length) {
return null;
}
return `{ ${members.join("; ")} }`;
}
/**
* Collect the instance script's component exports (`export const`, `export
* function`, `export class`, and `export { x }`) as a type literal, mirroring
* svelte2tsx. In legacy mode an exported `let` is a prop rather than an export.
*/
function getInstanceExportsType(instanceStatements, svelteParseContext) {
const legacy = svelteParseContext.runes !== true;
const letBindings = new Set();
for (const node of instanceStatements) {
const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
if (decl?.type !== "VariableDeclaration" || decl.kind !== "let") {
continue;
}
for (const declarator of decl.declarations) {
if (declarator.id.type === "Identifier") {
letBindings.add(declarator.id.name);
}
}
}
const members = new Map();
for (const node of instanceStatements) {
if (node.type !== "ExportNamedDeclaration" || node.exportKind === "type") {
continue;
}
const decl = node.declaration;
if (decl?.type === "VariableDeclaration") {
if (legacy && decl.kind === "let") {
continue;
}
for (const declarator of decl.declarations) {
if (declarator.id.type === "Identifier") {
members.set(declarator.id.name, declarator.id.name);
}
}
}
else if ((decl?.type === "FunctionDeclaration" ||
decl?.type === "ClassDeclaration") &&
decl.id != null) {
members.set(decl.id.name, decl.id.name);
}
else if (decl == null && node.source == null) {
for (const specifier of node.specifiers) {
if (specifier.local.type !== "Identifier" ||
specifier.exportKind === "type") {
continue;
}
const exported = exportName(specifier.exported);
if (exported === "default" ||
(legacy && letBindings.has(specifier.local.name))) {
continue;
}
members.set(exported, specifier.local.name);
}
}
}
if (!members.size) {
return null;
}
return `{ ${[...members]
.map(([exported, local]) => `${propKey(exported)}: typeof ${local}`)
.join("; ")} }`;
}
/** Quote non-identifier keys so reserved-word prop names like `class` are emitted safely. */
function propKey(name) {
return /^[$A-Z_a-z][\w$]*$/u.test(name) ? name : JSON.stringify(name);
}
/** Unresolved prop globals in either the instance script or template open the props. */
function referencesOpenProps(result) {
return result.scopeManager.globalScope.through.some(({ identifier }) => identifier.name === "$$props" || identifier.name === "$$restProps");
}
/**
* Recover props from a runes `$props()` declaration. An explicit annotation,
* `as`, or `satisfies` type is used as-is; otherwise the type is inferred from
* the destructuring.
*
* Only a top-level instance-script declaration counts, since that is the only
* place Svelte accepts `$props()`; a `<script module>` call must not hijack the
* real declaration.
*/
function recoverRunesProps(result, source, svelteParseContext, instanceScriptRange) {
if (svelteParseContext.runes === false || !instanceScriptRange) {
return null;
}
const [instanceStart, instanceEnd] = instanceScriptRange;
const propsReferences = result.scopeManager.globalScope.through.filter((reference) => {
const { name, range } = reference.identifier;
return (name === "$props" &&
range != null &&
instanceStart <= range[0] &&
range[1] <= instanceEnd);
});
if (!propsReferences.length) {
return null;
}
setParent(result);
for (const reference of propsReferences) {
const id = reference.identifier;
const call = id.parent;
if (call?.type !== "CallExpression" || call.callee !== id) {
continue;
}
// Trailing `as`/`satisfies`/`!` operators sit between the call and the
// declarator and can be stacked. The outermost annotation is the effective
// type, so keep overwriting; `!` only unwraps.
let valueNode = call;
let castType = null;
for (;;) {
const parent = valueNode.parent;
if (parent?.type === "TSAsExpression" ||
parent?.type === "TSSatisfiesExpression") {
castType = parent.typeAnnotation;
valueNode = parent;
}
else if (parent?.type === "TSNonNullExpression") {
valueNode = parent;
}
else {
break;
}
}
if (valueNode.parent?.type !== "VariableDeclarator" ||
valueNode.parent.init !== valueNode ||
!isTopLevelDeclarator(valueNode.parent)) {
continue;
}
const declId = valueNode.parent.id;
// The binding annotation is the public contract, even when the initializer
// is asserted to a narrower type.
const type = declId.typeAnnotation?.typeAnnotation ?? castType;
if (type) {
return {
kind: "explicit",
type: source.slice(type.range[0], type.range[1]),
};
}
if (declId.type === "ObjectPattern") {
return inferPropsFromObjectPattern(declId, source);
}
}
return null;
}
function isTopLevelDeclarator(declarator) {
const declaration = declarator.parent;
const statement = declaration.parent?.type === "ExportNamedDeclaration"
? declaration.parent
: declaration;
return statement.parent?.type === "Program";
}
/**
* Defaults go through a probe object because only TS can type the default
* expression; a prop with no default has no type source at all, so it stays a
* required `any`, as in svelte2tsx.
*/
function inferPropsFromObjectPattern(pattern, source) {
const members = [];
const defaulted = [];
// A prop can be destructured twice (`{ a, a: b }`, `{ 1e3: p, 1_000: q }`);
// emitting the key twice would be a TS2300 duplicate identifier.
const seen = new Set();
let open = false;
for (const prop of pattern.properties) {
if (prop.type !== "Property") {
open = true;
continue;
}
// Keys are taken raw so a string key keeps its quotes. A literal key is
// resolvable even when computed (`["a"]`), unlike an identifier one (`[k]`).
// Bigint keys are excluded: `0n` is not a valid type-literal key.
let key, normalized;
if (!prop.computed && prop.key.type === "Identifier") {
key = prop.key.name;
normalized = prop.key.name;
}
else if (prop.key.type === "Literal" &&
(typeof prop.key.value === "string" || typeof prop.key.value === "number")) {
key = prop.key.raw;
// `String` matches `ToPropertyKey`, so `1e3`, `1_000` and `"1000"` agree.
normalized = String(prop.key.value);
}
else {
open = true;
continue;
}
if (seen.has(normalized)) {
continue;
}
seen.add(normalized);
if (prop.value.type === "AssignmentPattern") {
let def = stripAsConst(prop.value.right);
// $bindable is a marker, not the default's type. Unwrap its fallback so
// null/undefined/empty arrays receive the same widening as plain defaults.
if (def.type === "CallExpression" &&
def.callee.type === "Identifier" &&
def.callee.name === "$bindable" &&
!def.typeArguments) {
const fallback = def.arguments[0];
if (!fallback) {
members.push(`${key}?: any`);
continue;
}
if (fallback.type !== "SpreadElement")
def = stripAsConst(fallback);
}
const degraded = degenerateDefaultType(def);
if (degraded != null) {
members.push(`${key}?: ${degraded}`);
continue;
}
// ESTree ranges exclude wrapping parens, so a sequence expression default
// would slice to `1, 2` and make the probe object literal invalid.
defaulted.push(`${key}: (${source.slice(def.range[0], def.range[1])})`);
}
else {
members.push(`${key}: any`);
}
}
return {
kind: "inferred",
members: members.length ? `{ ${members.join("; ")} }` : null,
probe: defaulted.length ? `{ ${defaulted.join(", ")} }` : null,
open,
};
}
/**
* Unwrap `X as const`, whose `const` parses as a type reference rather than a
* keyword. The frozen literal type it produces would reject every other value an
* importer passes; an author who wants that narrowing writes an explicit
* annotation, which takes precedence anyway.
*/
function stripAsConst(node) {
if (node.type === "TSAsExpression" &&
node.typeAnnotation.type === "TSTypeReference" &&
node.typeAnnotation.typeName.type === "Identifier" &&
node.typeAnnotation.typeName.name === "const") {
return node.expression;
}
return node;
}
/**
* Defaults that TS can only infer as an uninhabitable type (`never[]`, `null`,
* `undefined`), which would reject every value an importer can pass. svelte2tsx
* degrades them to `any` for the same reason.
*/
function degenerateDefaultType(node) {
if (node.type === "ArrayExpression" && node.elements.length === 0) {
return "any[]";
}
// `raw` distinguishes the null literal from a regex literal, whose `value` is
// also null when the environment cannot build the `RegExp`.
if (node.type === "Literal" && node.raw === "null") {
return "any";
}
if (node.type === "Identifier" && node.name === "undefined") {
return "any";
}
if (node.type === "UnaryExpression" && node.operator === "void") {
return "any";
}
return null;
}

View File

@@ -0,0 +1,56 @@
import { VirtualTypeScriptContext } from "../context.js";
import type { SvelteHTMLElement } from "../../../ast/index.js";
import type { NormalizedParserOptions } from "../../parser-options.js";
import type { SvelteParseContext } from "../../svelte-parse-context.js";
export type AnalyzeTypeScriptContext = {
slots: Set<SvelteHTMLElement>;
svelteParseContext: SvelteParseContext;
/** Source range of the instance `<script>` content; the virtual code concatenates both scripts. */
instanceScriptRange?: [number, number] | null;
};
type SvelteTypeScriptCode = {
/**
* User-authored <script> content.
*
* Example:
* <script lang="ts">
* const x = $derived(0);
* </script>
*/
script: string;
/**
* Template code that is wrapped in the synthetic render function, where
* template scopes are modeled.
*
* Example:
* {#if ok}
* {const x = $derived(0)}
* {/if}
*/
render: string;
/**
* Template-generated code that must stay outside the render wrapper, such as
* top-level snippets.
*
* Example:
* {#snippet s()}
* {const x = $derived(0)}
* {/snippet}
*/
rootScope: string;
};
/**
* Analyze TypeScript source code in Svelte.
* Generate virtual code to provide correct type information for Svelte store reference names, scopes, and runes.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export declare function analyzeTypeScriptInSvelte(
/** Split virtual code generated from the Svelte component. */
code: SvelteTypeScriptCode, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, context: AnalyzeTypeScriptContext): VirtualTypeScriptContext;
/**
* Analyze TypeScript source code.
* Generate virtual code to provide correct type information for Svelte runes.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export declare function analyzeTypeScript(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, svelteParseContext: SvelteParseContext): VirtualTypeScriptContext;
export {};

View File

@@ -0,0 +1,840 @@
import { addAllReferences, addVariable, getAllReferences, getProgramScope, removeAllScopeAndVariableAndReference, removeIdentifierReference, removeIdentifierVariable, replaceScope, } from "../../../scope/index.js";
import { addElementsToSortedArray, sortedLastIndex, } from "../../../utils/index.js";
import { parseScriptWithoutAnalyzeScope } from "../../script.js";
import { VirtualTypeScriptContext } from "../context.js";
import { setParent } from "../set-parent.js";
import { getGlobalsForSvelte, globalsForRunes } from "../../globals.js";
import { withoutProjectParserOptions } from "../../parser-options.js";
import { appendComponentDefaultExport } from "./component.js";
/**
* Analyze TypeScript source code in Svelte.
* Generate virtual code to provide correct type information for Svelte store reference names, scopes, and runes.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export function analyzeTypeScriptInSvelte(
/** Split virtual code generated from the Svelte component. */
code, attrs, parserOptions, context) {
const ctx = new VirtualTypeScriptContext(code.script + code.render + code.rootScope);
ctx.appendOriginal(/^\s*/u.exec(code.script)[0].length);
const result = parseScriptWithoutAnalyzeScope(code.script + code.render + code.rootScope, attrs, withoutProjectParserOptions(parserOptions));
ctx._beforeResult = result;
analyzeStoreReferenceNames(result, context.svelteParseContext, ctx);
analyzeDollarDollarVariables(result, ctx, context.svelteParseContext, context.slots);
analyzeRuneVariables(result, ctx, context.svelteParseContext);
if (!attrs.lang || attrs.lang === "js" || attrs.lang === "javascript") {
// Keep leading JSDoc attached to the user's declaration, not to the last
// synthetic declaration inserted above it.
ctx.appendVirtualScript("\n");
}
const scriptTransformers = [
...analyzeReactiveScopes(result),
];
const renderTransformers = [];
const rootScopeTransformers = [];
const renderStart = code.script.length;
const rootScopeStart = code.script.length + code.render.length;
for (const transform of analyzeDollarDerivedScopes(result, context.svelteParseContext)) {
if (transform.node.range[0] < renderStart) {
scriptTransformers.push(transform);
}
else if (transform.node.range[0] < rootScopeStart) {
renderTransformers.push(transform);
}
else {
rootScopeTransformers.push(transform);
}
}
applyTransforms(scriptTransformers, ctx);
analyzeRenderScopes(code, ctx, () => applyTransforms(renderTransformers, ctx));
// Type checking non-module TypeScript code can report
// `Cannot redeclare block-scoped variable 'xxx'`, so add a dummy export.
// Keep it before consuming `rootScope` so it remains a standalone statement
// at the render/rootScope boundary instead of splitting transformed rootScope
// expressions such as `{#snippet s()}{const x = $derived(0)}{/snippet}`.
// See https://github.com/sveltejs/svelte-eslint-parser/issues/557
if (!hasExportDeclaration(result.ast)) {
appendDummyExport(ctx);
}
// This starts consuming `rootScope`. Keep it after `analyzeRenderScopes()` so
// top-level snippet code is emitted outside the synthetic render function:
// {#snippet s()}
// {const x = $derived(0)}
// {/snippet}
// Keep it after the dummy export above so the export can stay at the
// render/rootScope boundary.
applyTransforms(rootScopeTransformers, ctx);
ctx.appendOriginalToEnd();
// Emitted last so it lands as a standalone top-level statement.
appendComponentDefaultExport(result, code.script + code.render + code.rootScope, ctx, context.svelteParseContext, context.instanceScriptRange ?? null);
return ctx;
}
/**
* Analyze TypeScript source code.
* Generate virtual code to provide correct type information for Svelte runes.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export function analyzeTypeScript(code, attrs, parserOptions, svelteParseContext) {
const ctx = new VirtualTypeScriptContext(code);
ctx.appendOriginal(/^\s*/u.exec(code)[0].length);
const result = parseScriptWithoutAnalyzeScope(code, attrs, withoutProjectParserOptions(parserOptions));
ctx._beforeResult = result;
analyzeRuneVariables(result, ctx, svelteParseContext);
if (!attrs.lang || attrs.lang === "js" || attrs.lang === "javascript") {
ctx.appendVirtualScript("\n");
}
applyTransforms([...analyzeDollarDerivedScopes(result, svelteParseContext)], ctx);
ctx.appendOriginalToEnd();
return ctx;
}
function hasExportDeclaration(ast) {
for (const node of ast.body) {
if (node.type === "ExportNamedDeclaration" ||
node.type === "ExportDefaultDeclaration") {
return true;
}
}
return false;
}
/**
* Analyze the store reference names.
* Insert type definitions code to provide correct type information for variables that begin with `$`.
*/
function analyzeStoreReferenceNames(result, svelteParseContext, ctx) {
const globals = getGlobalsForSvelte(svelteParseContext);
const scopeManager = result.scopeManager;
const programScope = getProgramScope(scopeManager);
const maybeStoreRefNames = new Set();
for (const reference of scopeManager.globalScope.through) {
if (
// Begin with `$`.
reference.identifier.name.startsWith("$") &&
// Ignore globals
!globals.includes(reference.identifier.name) &&
// Ignore if it is already defined.
!programScope.set.has(reference.identifier.name)) {
maybeStoreRefNames.add(reference.identifier.name);
}
}
if (maybeStoreRefNames.size) {
const storeValueTypeName = ctx.generateUniqueId("StoreValueType");
ctx.appendVirtualScript(`type ${storeValueTypeName}<T> = T extends null | undefined
? T
: T extends object & { subscribe(run: infer F, ...args: any): any }
? F extends (value: infer V, ...args: any) => any
? V
: never
: T;`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "TSTypeAliasDeclaration" ||
node.id.name !== storeValueTypeName) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `type` scope
removeAllScopeAndVariableAndReference(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
for (const nm of maybeStoreRefNames) {
const realName = nm.slice(1);
ctx.appendVirtualScript(`declare let ${nm}: ${storeValueTypeName}<typeof ${realName}>;`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "VariableDeclaration" ||
!node.declare ||
node.declarations.length !== 1 ||
node.declarations[0].id.type !== "Identifier" ||
node.declarations[0].id.name !== nm) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `declare` variable
removeAllScopeAndVariableAndReference(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
}
}
}
/**
* Analyze `$$slots`, `$$props`, and `$$restProps` .
* Insert type definitions code to provide correct type information for `$$slots`, `$$props`, and `$$restProps`.
*/
function analyzeDollarDollarVariables(result, ctx, svelteParseContext, slots) {
const globals = getGlobalsForSvelte(svelteParseContext);
const scopeManager = result.scopeManager;
for (const globalName of globals) {
if (!scopeManager.globalScope.through.some((reference) => reference.identifier.name === globalName)) {
continue;
}
switch (globalName) {
case "$$props":
appendDeclareVirtualScript(globalName, `{ [index: string]: any }`);
break;
case "$$restProps":
appendDeclareVirtualScript(globalName, `{ [index: string]: any }`);
break;
case "$$slots": {
const nameTypes = new Set();
for (const slot of slots) {
const nameAttr = slot.startTag.attributes.find((attr) => attr.type === "SvelteAttribute" && attr.key.name === "name");
if (!nameAttr || nameAttr.value.length === 0) {
nameTypes.add('"default"');
continue;
}
if (nameAttr.value.length === 1) {
const value = nameAttr.value[0];
if (value.type === "SvelteLiteral") {
nameTypes.add(JSON.stringify(value.value));
}
else {
nameTypes.add("string");
}
continue;
}
nameTypes.add(`\`${nameAttr.value
.map((value) => value.type === "SvelteLiteral"
? value.value.replace(/([$`])/gu, "\\$1")
: "${string}")
.join("")}\``);
}
appendDeclareVirtualScript(globalName, `Record<${nameTypes.size > 0 ? [...nameTypes].join(" | ") : "any"}, boolean>`);
break;
}
case "$state":
case "$derived":
case "$effect":
case "$props":
case "$bindable":
case "$inspect":
case "$host":
// Processed by `analyzeRuneVariables`.
break;
default: {
const _ = globalName;
throw Error(`Unknown global: ${_}`);
}
}
}
/** Append declare virtual script */
function appendDeclareVirtualScript(name, type) {
ctx.appendVirtualScript(`declare let ${name}: ${type};`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "VariableDeclaration" ||
!node.declare ||
node.declarations.length !== 1 ||
node.declarations[0].id.type !== "Identifier" ||
node.declarations[0].id.name !== name) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `declare` variable
removeAllScopeAndVariableAndReference(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
}
}
/** Append dummy export */
function appendDummyExport(ctx) {
ctx.appendVirtualScript(`export namespace SvelteEslintParserModuleMarker {}`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "ExportNamedDeclaration" ||
node.declaration?.type !== "TSModuleDeclaration" ||
node.declaration.kind !== "namespace" ||
node.declaration.id.type !== "Identifier" ||
node.declaration.id.name !== "SvelteEslintParserModuleMarker") {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `declare` variable
removeAllScopeAndVariableAndReference(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
}
/**
* Analyze Runes.
* Insert type definitions code to provide correct type information for Runes.
*/
function analyzeRuneVariables(result, ctx, svelteParseContext) {
// No processing is needed if the user is determined not to be in Runes mode.
if (svelteParseContext.runes === false) {
return;
}
const scopeManager = result.scopeManager;
for (const globalName of globalsForRunes) {
if (!scopeManager.globalScope.through.some((reference) => reference.identifier.name === globalName)) {
continue;
}
switch (globalName) {
// See https://github.com/sveltejs/svelte/blob/bd2d3db6d0d7a931c2e84c38a5c537e30dda1dbe/packages/svelte/types/index.d.ts#L3124
case "$state": {
appendDeclareFunctionVirtualScripts(globalName, [
"<T>(initial: T): T",
"<T>(): T | undefined",
]);
appendDeclareNamespaceVirtualScripts(globalName, [
"export function eager<T>(value: T): T",
]);
appendDeclareNamespaceVirtualScripts(globalName, [
"export function raw<T>(initial: T): T;",
"export function raw<T>(): T | undefined;",
]);
appendDeclareNamespaceVirtualScripts(globalName, [
"export function snapshot<T>(state: T): T;",
]);
break;
}
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3247
case "$derived": {
appendDeclareFunctionVirtualScripts(globalName, [
"<T>(expression: T): T",
]);
appendDeclareNamespaceVirtualScripts(globalName, [
"export function by<T>(fn: () => T): T;",
]);
break;
}
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3307
case "$effect": {
appendDeclareFunctionVirtualScripts(globalName, [
"(fn: () => void | (() => void)): void",
]);
appendDeclareNamespaceVirtualScripts(globalName, [
"export function pre(fn: () => void | (() => void)): void;",
"export function pending(): number;",
"export function tracking(): boolean;",
"export function root(fn: () => void | (() => void)): () => void;",
]);
break;
}
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3416
case "$props": {
// NOTE: In the Svelte repository's `index.d.ts`, the return type is any, but that triggers `@typescript-eslint/no-unsafe-assignment`. To avoid this, use generics here.
appendDeclareFunctionVirtualScripts(globalName, ["<T>(): T"]);
appendDeclareNamespaceVirtualScripts(globalName, [
"export function id(): string;",
]);
break;
}
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3459
case "$bindable": {
appendDeclareFunctionVirtualScripts(globalName, [
"<T>(fallback?: T): T",
]);
break;
}
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3502
case "$inspect": {
appendDeclareFunctionVirtualScripts(globalName, [
`<T extends any[]>(...values: T): { with: (fn: (type: 'init' | 'update', ...values: T) => void) => void }`,
]);
appendDeclareNamespaceVirtualScripts(globalName, [
"export function trace(name?: string): void;",
]);
break;
}
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3565
case "$host": {
appendDeclareFunctionVirtualScripts(globalName, [
`<El extends HTMLElement = HTMLElement>(): El`,
]);
break;
}
default: {
const _ = globalName;
throw Error(`Unknown global: ${_}`);
}
}
}
/** Append declare virtual script */
function appendDeclareFunctionVirtualScripts(name, types) {
for (const type of types) {
ctx.appendVirtualScript(`declare function ${name}${type};`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "TSDeclareFunction" ||
!node.declare ||
node.id?.type !== "Identifier" ||
node.id.name !== name) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `declare` variable
removeAllScopeAndVariableAndReference(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
}
}
function appendDeclareNamespaceVirtualScripts(name, scripts) {
for (const script of scripts) {
ctx.appendVirtualScript(`declare namespace ${name} { ${script} }`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "TSModuleDeclaration" ||
!node.declare ||
node.id?.type !== "Identifier" ||
node.id.name !== name) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `declare` variable
removeAllScopeAndVariableAndReference(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
}
}
}
/**
* Analyze the reactive scopes.
* Transform source code to provide the correct type information in the `$:` statements.
*/
function* analyzeReactiveScopes(result) {
const scopeManager = result.scopeManager;
const throughIds = scopeManager.globalScope.through.map((reference) => reference.identifier);
for (const statement of result.ast.body) {
if (statement.type === "LabeledStatement" && statement.label.name === "$") {
if (statement.body.type === "ExpressionStatement" &&
statement.body.expression.type === "AssignmentExpression" &&
statement.body.expression.operator === "=" &&
// Must be a pattern that can be used in the LHS of variable declarations.
// https://github.com/sveltejs/svelte-eslint-parser/issues/213
(statement.body.expression.left.type === "Identifier" ||
statement.body.expression.left.type === "ArrayPattern" ||
statement.body.expression.left.type === "ObjectPattern")) {
const left = statement.body.expression.left;
if (throughIds.some((id) => left.range[0] <= id.range[0] && id.range[1] <= left.range[1])) {
const node = statement;
const expression = statement.body.expression;
yield {
node,
transform: (ctx) => transformForDeclareReactiveVar(node, left, expression, result.ast.tokens, ctx),
};
continue;
}
}
yield {
node: statement,
transform: (ctx) => transformForReactiveStatement(statement, ctx),
};
}
}
}
/**
* Analyze the $derived scopes.
* Transform source code to provide the correct type information in the `$derived(...)` expression.
*/
function* analyzeDollarDerivedScopes(result, svelteParseContext) {
// No processing is needed if the user is determined not to be in Runes mode.
if (svelteParseContext.runes === false)
return;
const scopeManager = result.scopeManager;
const derivedReferences = scopeManager.globalScope.through.filter((reference) => reference.identifier.name === "$derived");
if (!derivedReferences.length) {
return;
}
setParent(result);
for (const ref of derivedReferences) {
const derived = ref.identifier;
if (derived.parent.type === "CallExpression" &&
derived.parent.callee === derived &&
derived.parent.arguments[0]?.type !== "SpreadElement") {
const node = derived.parent;
yield {
node,
transform: (ctx) => transformForDollarDerived(node, ctx),
};
}
}
}
/**
* Analyze the render scopes.
* Transform source code to provide the correct type information in the HTML templates.
*/
function analyzeRenderScopes(code, ctx, analyzeInTemplate) {
ctx.appendOriginal(code.script.length);
const renderFunctionName = ctx.generateUniqueId("render");
ctx.appendVirtualScript(`export function ${renderFunctionName}(){`);
analyzeInTemplate();
ctx.appendOriginal(code.script.length + code.render.length);
ctx.appendVirtualScript(`}`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "ExportNamedDeclaration" ||
node.declaration?.type !== "FunctionDeclaration" ||
node.declaration?.id?.name !== renderFunctionName) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1, ...node.declaration.body.body);
for (const body of node.declaration.body.body) {
body.parent = program;
}
const scopeManager = result.scopeManager;
removeFunctionScope(node.declaration, scopeManager);
return true;
});
}
/**
* Applies the given transforms.
* Note that intersecting transformations are not applied.
*/
function applyTransforms(transforms, ctx) {
transforms.sort((a, b) => a.node.range[0] - b.node.range[0]);
let offset = 0;
for (const transform of transforms) {
const range = transform.node.range;
if (offset <= range[0]) {
transform.transform(ctx);
}
offset = range[1];
}
}
/**
* Transform for `$: id = ...` to `$: let id = ...`
*/
function transformForDeclareReactiveVar(statement, id, expression, tokens, ctx) {
// e.g.
// From:
// $: id = x + y;
//
// To:
// $: let id = fn()
// function fn () { let tmp; return (tmp = x + y); }
//
//
// From:
// $: ({id} = foo);
//
// To:
// $: let {id} = fn()
// function fn () { let tmp; return (tmp = foo); }
/**
* The opening paren tokens for
* `$: ({id} = foo);`
* ^
*/
const openParens = [];
/**
* The equal token for
* `$: ({id} = foo);`
* ^
*/
let eq = null;
/**
* The closing paren tokens for
* `$: ({id} = foo);`
* ^
*/
const closeParens = [];
/**
* The closing paren token for
* `$: id = (foo);`
* ^
*/
let expressionCloseParen = null;
const startIndex = sortedLastIndex(tokens, (target) => target.range[0] - statement.range[0]);
for (let index = startIndex; index < tokens.length; index++) {
const token = tokens[index];
if (statement.range[1] <= token.range[0]) {
break;
}
if (token.range[1] <= statement.range[0]) {
continue;
}
if (token.value === "(" && token.range[1] <= expression.range[0]) {
openParens.push(token);
}
if (token.value === "=" &&
expression.left.range[1] <= token.range[0] &&
token.range[1] <= expression.right.range[0]) {
eq = token;
}
if (token.value === ")") {
if (expression.range[1] <= token.range[0]) {
closeParens.push(token);
}
else if (expression.right.range[1] <= token.range[0]) {
expressionCloseParen = token;
}
}
}
const functionId = ctx.generateUniqueId("reactiveVariableScopeFunction");
const tmpVarId = ctx.generateUniqueId("tmpVar");
for (const token of openParens) {
ctx.appendOriginal(token.range[0]);
ctx.skipOriginalOffset(token.range[1] - token.range[0]);
}
ctx.appendOriginal(expression.range[0]);
ctx.skipUntilOriginalOffset(id.range[0]);
ctx.appendVirtualScript("let ");
ctx.appendOriginal(eq ? eq.range[1] : expression.right.range[0]);
ctx.appendVirtualScript(`${functionId}();\nfunction ${functionId}(){let ${tmpVarId};return (${tmpVarId} = `);
ctx.appendOriginal(expression.right.range[1]);
ctx.appendVirtualScript(`)`);
for (const token of closeParens) {
ctx.appendOriginal(token.range[0]);
ctx.skipOriginalOffset(token.range[1] - token.range[0]);
}
ctx.appendOriginal(statement.range[1]);
ctx.appendVirtualScript(`}`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "SvelteReactiveStatement") {
return false;
}
const reactiveStatement = node;
if (reactiveStatement.body.type !== "VariableDeclaration" ||
reactiveStatement.body.kind !== "let" ||
reactiveStatement.body.declarations.length !== 1) {
return false;
}
const [idDecl] = reactiveStatement.body.declarations;
if (idDecl.type !== "VariableDeclarator" ||
idDecl.id.type !== id.type ||
idDecl.init?.type !== "CallExpression" ||
idDecl.init.callee.type !== "Identifier" ||
idDecl.init.callee.name !== functionId) {
return false;
}
const program = result.ast;
const nextIndex = program.body.indexOf(reactiveStatement) + 1;
const fnDecl = program.body[nextIndex];
if (!fnDecl ||
fnDecl.type !== "FunctionDeclaration" ||
fnDecl.id.name !== functionId ||
fnDecl.body.body.length !== 2 ||
fnDecl.body.body[0].type !== "VariableDeclaration" ||
fnDecl.body.body[1].type !== "ReturnStatement") {
return false;
}
const tmpVarDeclaration = fnDecl.body.body[0];
if (tmpVarDeclaration.declarations.length !== 1 ||
tmpVarDeclaration.declarations[0].type !== "VariableDeclarator") {
return false;
}
const tempVarDeclId = tmpVarDeclaration.declarations[0].id;
if (tempVarDeclId.type !== "Identifier" ||
tempVarDeclId.name !== tmpVarId) {
return false;
}
const returnStatement = fnDecl.body.body[1];
const assignment = returnStatement.argument;
if (assignment?.type !== "AssignmentExpression" ||
assignment.left.type !== "Identifier" ||
assignment.right.type !== expression.right.type) {
return false;
}
const tempLeft = assignment.left;
// Remove function declaration
program.body.splice(nextIndex, 1);
// Restore expression statement
assignment.left = idDecl.id;
assignment.loc = {
start: idDecl.id.loc.start,
end: expressionCloseParen
? expressionCloseParen.loc.end
: assignment.right.loc.end,
};
assignment.range = [
idDecl.id.range[0],
expressionCloseParen
? expressionCloseParen.range[1]
: assignment.right.range[1],
];
idDecl.id.parent = assignment;
const newBody = {
type: "ExpressionStatement",
expression: assignment,
directive: undefined,
loc: statement.body.loc,
range: statement.body.range,
parent: reactiveStatement,
};
assignment.parent = newBody;
reactiveStatement.body = newBody;
// Restore statement end location
reactiveStatement.range[1] = returnStatement.range[1];
reactiveStatement.loc.end.line = returnStatement.loc.end.line;
reactiveStatement.loc.end.column = returnStatement.loc.end.column;
// Restore tokens
addElementsToSortedArray(program.tokens, [...openParens, ...closeParens], (a, b) => a.range[0] - b.range[0]);
const scopeManager = result.scopeManager;
removeAllScopeAndVariableAndReference(tmpVarDeclaration, {
visitorKeys: result.visitorKeys,
scopeManager,
});
removeFunctionScope(fnDecl, scopeManager);
const scope = getProgramScope(scopeManager);
for (const reference of getAllReferences(idDecl.id, scope)) {
reference.writeExpr = assignment.right;
}
removeIdentifierReference(tempLeft, scope);
removeIdentifierVariable(tempVarDeclId, scope);
removeIdentifierReference(idDecl.init.callee, scope);
removeIdentifierVariable(idDecl.id, scope);
return true;
});
}
/**
* Transform for `$: ...` to `$: function foo(){...}`
*/
function transformForReactiveStatement(statement, ctx) {
const functionId = ctx.generateUniqueId("reactiveStatementScopeFunction");
const originalBody = statement.body;
ctx.appendOriginal(originalBody.range[0]);
ctx.appendVirtualScript(`export function ${functionId}(){`);
ctx.appendOriginal(originalBody.range[1]);
ctx.appendVirtualScript(`}`);
ctx.appendOriginal(statement.range[1]);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "SvelteReactiveStatement") {
return false;
}
const reactiveStatement = node;
const body = reactiveStatement.body;
if (body.type !== "ExportNamedDeclaration" ||
body.declaration?.type !== "FunctionDeclaration" ||
body.declaration?.id?.name !== functionId) {
return false;
}
reactiveStatement.body = body.declaration.body.body[0];
reactiveStatement.body.parent = reactiveStatement;
const scopeManager = result.scopeManager;
removeFunctionScope(body.declaration, scopeManager);
return true;
});
}
/**
* Transform for `$derived(expr)` to `$derived((()=>{ type This = typeof this; return fn(); function fn (this: This) { return expr } })())`
*/
function transformForDollarDerived(derivedCall, ctx) {
const functionId = ctx.generateUniqueId("$derivedArgument");
const thisTypeId = ctx.generateUniqueId("$This");
const expression = derivedCall.arguments[0];
ctx.appendOriginal(expression.range[0]);
ctx.appendVirtualScript(`(()=>{type ${thisTypeId} = typeof this; return ${functionId}();function ${functionId}(this: ${thisTypeId}){return `);
ctx.appendOriginal(expression.range[1]);
ctx.appendVirtualScript(`}})()`);
ctx.restoreContext.addRestoreExpressionProcess({
target: "CallExpression",
restore: (node, result) => {
if (node.callee.type !== "Identifier" ||
node.callee.name !== "$derived") {
return false;
}
const arg = node.arguments[0];
if (!arg ||
arg.type !== "CallExpression" ||
arg.arguments.length !== 0 ||
arg.callee.type !== "ArrowFunctionExpression" ||
arg.callee.body.type !== "BlockStatement" ||
arg.callee.body.body.length !== 3) {
return false;
}
const thisTypeNode = arg.callee.body.body[0];
if (thisTypeNode.type !== "TSTypeAliasDeclaration" ||
thisTypeNode.id.name !== thisTypeId) {
return false;
}
const returnNode = arg.callee.body.body[1];
if (returnNode.type !== "ReturnStatement" ||
returnNode.argument?.type !== "CallExpression" ||
returnNode.argument.callee.type !== "Identifier" ||
returnNode.argument.callee.name !== functionId) {
return false;
}
const fnNode = arg.callee.body.body[2];
if (fnNode.type !== "FunctionDeclaration" ||
fnNode.id.name !== functionId ||
fnNode.body.body.length !== 1 ||
fnNode.body.body[0].type !== "ReturnStatement" ||
!fnNode.body.body[0].argument ||
fnNode.params[0]?.type !== "Identifier" ||
!fnNode.params[0].typeAnnotation ||
fnNode.params[0].typeAnnotation.typeAnnotation.type !==
"TSTypeReference" ||
fnNode.params[0].typeAnnotation.typeAnnotation.typeName.type !==
"Identifier") {
return false;
}
const expr = fnNode.body.body[0].argument;
node.arguments[0] = expr;
expr.parent = node;
const scopeManager = result.scopeManager;
const fnScope = scopeManager.acquire(fnNode);
removeIdentifierVariable(fnNode.params[0], fnScope);
removeIdentifierReference(fnNode.params[0].typeAnnotation.typeAnnotation.typeName, fnScope);
removeFunctionScope(fnNode, scopeManager);
const scope = scopeManager.acquire(arg.callee);
removeIdentifierVariable(thisTypeNode.id, scope);
removeIdentifierReference(returnNode.argument.callee, scope);
removeFunctionScope(arg.callee, scopeManager);
return true;
},
});
}
/** Remove function scope and marge child scopes to upper scope */
function removeFunctionScope(node, scopeManager) {
const scope = scopeManager.acquire(node);
const upper = scope.upper;
// Remove render function variable
if (node.id) {
removeIdentifierVariable(node.id, upper);
removeIdentifierReference(node.id, upper);
}
replaceScope(scopeManager, scope, scope.childScopes);
// Marge scope
// * marge variables
for (const variable of scope.variables) {
if (variable.name === "arguments" && variable.defs.length === 0) {
continue;
}
const upperVariable = upper.set.get(variable.name);
if (upperVariable) {
addElementsToSortedArray(upperVariable.identifiers, variable.identifiers, (a, b) => a.range[0] - b.range[0]);
addElementsToSortedArray(upperVariable.defs, variable.defs, (a, b) => a.node.range[0] - b.node.range[0]);
addAllReferences(upperVariable.references, variable.references);
}
else {
upper.set.set(variable.name, variable);
addVariable(upper.variables, variable);
variable.scope = upper;
}
for (const reference of variable.references) {
if (reference.from === scope) {
reference.from = upper;
}
reference.resolved = upperVariable || variable;
}
}
// * marge references
addAllReferences(upper.references, scope.references);
for (const reference of scope.references) {
if (reference.from === scope) {
reference.from = upper;
}
}
}

View File

@@ -0,0 +1,21 @@
import { RestoreContext } from "./restore.js";
import type { TSESParseForESLintResult } from "./types.js";
/**
* Context for virtual TypeScript code.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export declare class VirtualTypeScriptContext {
private readonly originalCode;
readonly restoreContext: RestoreContext;
script: string;
private consumedIndex;
private readonly unique;
_beforeResult: TSESParseForESLintResult | null;
constructor(code: string);
skipOriginalOffset(offset: number): void;
skipUntilOriginalOffset(offset: number): void;
appendOriginalToEnd(): void;
appendOriginal(index: number): void;
appendVirtualScript(virtualFragment: string): void;
generateUniqueId(base: string): string;
}

View File

@@ -0,0 +1,44 @@
import { UniqueIdGenerator } from "../../context/unique.js";
import { RestoreContext } from "./restore.js";
/**
* Context for virtual TypeScript code.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export class VirtualTypeScriptContext {
constructor(code) {
this.script = "";
this.consumedIndex = 0;
this.unique = new UniqueIdGenerator();
this._beforeResult = null;
this.originalCode = code;
this.restoreContext = new RestoreContext(code);
}
skipOriginalOffset(offset) {
this.consumedIndex += offset;
}
skipUntilOriginalOffset(offset) {
this.consumedIndex = Math.max(offset, this.consumedIndex);
}
appendOriginalToEnd() {
this.appendOriginal(this.originalCode.length);
}
appendOriginal(index) {
if (this.consumedIndex >= index) {
return;
}
this.restoreContext.addOffset({
original: this.consumedIndex,
dist: this.script.length,
});
this.script += this.originalCode.slice(this.consumedIndex, index);
this.consumedIndex = index;
}
appendVirtualScript(virtualFragment) {
const start = this.script.length;
this.script += virtualFragment;
this.restoreContext.addVirtualFragmentRange(start, this.script.length);
}
generateUniqueId(base) {
return this.unique.generate(base, this.originalCode, this.script);
}
}

View File

@@ -0,0 +1,16 @@
import type { ESLintExtendedProgram } from "../index.js";
import type { NormalizedParserOptions } from "../parser-options.js";
import type { SvelteParseContext } from "../svelte-parse-context.js";
import type { AnalyzeTypeScriptContext } from "./analyze/index.js";
/**
* Parse for TypeScript in <script>
*/
export declare function parseTypeScriptInSvelte(code: {
script: string;
render: string;
rootScope: string;
}, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, context: AnalyzeTypeScriptContext): ESLintExtendedProgram;
/**
* Parse for TypeScript
*/
export declare function parseTypeScript(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, svelteParseContext: SvelteParseContext): ESLintExtendedProgram;

View File

@@ -0,0 +1,79 @@
import { parseScript, parseScriptInSvelte, parseScriptWithoutAnalyzeScope, } from "../script.js";
import { analyzeTypeScript, analyzeTypeScriptInSvelte, } from "./analyze/index.js";
import { setParent } from "./set-parent.js";
import { getCompanionToRefresh, primeTranslationCache, reloadCompanionInProjectServices, } from "../../ts-sys-hook.js";
import { getJavaScriptParserOptions } from "./javascript.js";
/**
* Parse for TypeScript in <script>
*/
export function parseTypeScriptInSvelte(code, attrs, parserOptions, context) {
const tsCtx = analyzeTypeScriptInSvelte(code, attrs, parserOptions, context);
// Share the shim with the ts.sys hook so projectService reads hit a cache.
if (parserOptions.filePath) {
primeTranslationCache(parserOptions.filePath, tsCtx.script);
// Before the component's own parse, so when the program already holds the
// companion, the component's rules see it current too, as in a component
// that imports itself.
refreshCompanion(parserOptions.filePath, parserOptions);
}
// Virtual scripts can be parsed repeatedly for the same file. In single-run
// mode, typescript-eslint falls back to an isolated program on later calls,
// losing project imports and compiler options.
let result = parseScriptInSvelte(tsCtx.script, attrs, {
...parserOptions,
disallowAutomaticSingleRunInference: true,
});
const jsOptions = getJavaScriptParserOptions(result, attrs, parserOptions);
if (jsOptions) {
result = parseScriptInSvelte(tsCtx.script, attrs, jsOptions);
}
tsCtx.restoreContext.restore(result);
return result;
}
/**
* Let the type-aware parser pick up the new content of the `X.svelte.ts`
* companion that importers see. See `getCompanionToRefresh`.
*/
function refreshCompanion(filePath, parserOptions) {
if (parserOptions.projectService != null ||
parserOptions.EXPERIMENTAL_useProjectService != null) {
const companion = getCompanionToRefresh(filePath);
if (companion)
reloadCompanionInProjectServices(companion.filePath);
return;
}
if (parserOptions.project == null)
return;
const companion = getCompanionToRefresh(filePath);
if (!companion)
return;
// Parsing the companion path makes typescript-eslint fire the companion's
// file watcher, as it does for a linted file.
try {
parseScriptWithoutAnalyzeScope(companion.code, { lang: "ts" }, {
...parserOptions,
filePath: companion.filePath,
disallowAutomaticSingleRunInference: true,
});
}
catch {
// The refresh is best effort. Linting the component itself has succeeded.
}
}
/**
* Parse for TypeScript
*/
export function parseTypeScript(code, attrs, parserOptions, svelteParseContext) {
const tsCtx = analyzeTypeScript(code, attrs, parserOptions, svelteParseContext);
let result = parseScript(tsCtx.script, attrs, {
...parserOptions,
disallowAutomaticSingleRunInference: true,
});
const jsOptions = getJavaScriptParserOptions(result, attrs, parserOptions);
if (jsOptions) {
result = parseScript(tsCtx.script, attrs, jsOptions);
}
setParent(result);
tsCtx.restoreContext.restore(result);
return result;
}

View File

@@ -0,0 +1,9 @@
import type { ESLintExtendedProgram } from "../index.js";
import type { NormalizedParserOptions } from "../parser-options.js";
/**
* TypeScript treats unknown extensions as TS, where JSDoc type annotations
* are ignored. Use a JS source file for the virtual component instead.
* Keep the original project intact: its source files and checker can be
* shared by other lint calls, including calls using projectService.
*/
export declare function getJavaScriptParserOptions(result: ESLintExtendedProgram, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions): NormalizedParserOptions | null;

View File

@@ -0,0 +1,48 @@
import { withoutProjectParserOptions } from "../parser-options.js";
import { loadNewestModule } from "../../utils/cjs-module.js";
/**
* TypeScript treats unknown extensions as TS, where JSDoc type annotations
* are ignored. Use a JS source file for the virtual component instead.
* Keep the original project intact: its source files and checker can be
* shared by other lint calls, including calls using projectService.
*/
export function getJavaScriptParserOptions(result, attrs, parserOptions) {
if (attrs.lang && attrs.lang !== "js" && attrs.lang !== "javascript") {
return null;
}
const originalProgram = result.services?.program;
if (!originalProgram || !parserOptions.filePath)
return null;
const originalSource = originalProgram.getSourceFile(parserOptions.filePath);
if (!originalSource)
return null;
const ts = loadNewestModule("typescript");
if (originalSource.flags & ts.NodeFlags.JavaScriptFile)
return null;
const source = ts.createSourceFile(originalSource.fileName, originalSource.text, originalSource.languageVersion, true, ts.ScriptKind.JS);
source.impliedNodeFormat = originalSource.impliedNodeFormat;
const options = {
...originalProgram.getCompilerOptions(),
allowJs: true,
allowNonTsExtensions: true,
};
const host = ts.createCompilerHost(options, true);
const getSourceFile = host.getSourceFile.bind(host);
host.getCurrentDirectory = () => originalProgram.getCurrentDirectory();
host.getSourceFile = (fileName, ...args) => {
const existing = originalProgram.getSourceFile(fileName);
if (existing === originalSource)
return source;
return existing ?? getSourceFile(fileName, ...args);
};
const program = ts.createProgram({
rootNames: originalProgram.getRootFileNames(),
options,
host,
projectReferences: originalProgram.getProjectReferences(),
});
return {
...withoutProjectParserOptions(parserOptions),
programs: [program],
};
}

Some files were not shown because too many files have changed in this diff Show More