svelte-ast 0.0.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +47 -1
  2. package/README.md +561 -2
  3. package/a11y.d.ts +1636 -0
  4. package/a11y.js +36 -0
  5. package/core.d.ts +1800 -0
  6. package/core.js +1 -0
  7. package/entities.d.ts +10 -0
  8. package/entities.js +1 -0
  9. package/index.d.ts +2844 -0
  10. package/index.js +1 -0
  11. package/is-valid-type.js +1 -0
  12. package/lexer.d.ts +224 -0
  13. package/lexer.js +3 -0
  14. package/module.d.ts +1243 -0
  15. package/module.js +1 -0
  16. package/package.json +72 -3
  17. package/parse-imports-exports.js +1 -0
  18. package/parse-module.js +1 -0
  19. package/parse-sections.js +1 -0
  20. package/parse.js +1 -0
  21. package/runes.js +1 -0
  22. package/scope.d.ts +1831 -0
  23. package/scope.js +1 -0
  24. package/shared-2yyqqbp5.js +2 -0
  25. package/shared-3654hw2t.js +2 -0
  26. package/shared-45k6qp45.js +2 -0
  27. package/shared-5tpb3h6x.js +2 -0
  28. package/shared-8598bnrd.js +2 -0
  29. package/shared-8gdz1w3m.js +2 -0
  30. package/shared-97v1a9gx.js +2 -0
  31. package/shared-a23q4q40.js +3 -0
  32. package/shared-bzqbnvee.js +2 -0
  33. package/shared-csw62q5w.js +2 -0
  34. package/shared-dgdrqgdn.js +2 -0
  35. package/shared-drb44hb9.js +2 -0
  36. package/shared-e4gbs4rb.js +3 -0
  37. package/shared-j53a13yb.js +3 -0
  38. package/shared-jqc2xr03.js +2 -0
  39. package/shared-jre53ftf.js +2 -0
  40. package/shared-m0dcdh24.js +5 -0
  41. package/shared-m3dr31c3.js +2 -0
  42. package/shared-n05mksm5.js +2 -0
  43. package/shared-np2e2ssk.js +2 -0
  44. package/shared-s46wfvhw.js +10 -0
  45. package/shared-tqkk8zh6.js +2 -0
  46. package/shared-w9n1rzqm.js +10 -0
  47. package/typescript.d.ts +10 -0
  48. package/typescript.js +1 -0
  49. package/walk.d.ts +2210 -0
  50. package/walk.js +1 -0
  51. package/warnings.d.ts +1680 -0
  52. package/warnings.js +6 -0
  53. package/index.ts +0 -1
package/README.md CHANGED
@@ -1,5 +1,564 @@
1
1
  # svelte-ast
2
2
 
3
- Placeholder package reserving the "svelte-ast" name.
3
+ > svelte/compiler's AST, 2.4× faster, with zero dependencies.
4
4
 
5
- This package name is currently reserved and not yet implemented.
5
+ | | svelte-ast | svelte/compiler |
6
+ |:---|:---|:---|
7
+ | Parse 400 components, 1.5 MB | **64.7 ms** | 155 ms |
8
+ | Import in a fresh process | **5.3 ms** | 44.7 ms |
9
+ | `parse` for the browser, gzipped | **58.5 kB** | 126.7 kB |
10
+ | Memory retained by ten parses kept alive | **147 MB** | 294 MB |
11
+
12
+ Apple M2; see [Parity and performance](#parity-and-performance) for how they're measured.
13
+
14
+ ```sh
15
+ bun i svelte-ast
16
+ ```
17
+
18
+ ```ts
19
+ import { parse } from "svelte-ast";
20
+
21
+ const ast = parse(`<script>let name = "world";</script>\n<h1>Hello {name}!</h1>`);
22
+
23
+ ast.instance?.content.body; // [VariableDeclaration]
24
+ ast.fragment.nodes; // [Text, RegularElement]
25
+ ```
26
+
27
+ Parse `.svelte` components, including `<script lang="ts">`, into the same AST, and the same errors, as `svelte/compiler`'s `parse(source, { modern: true })`. svelte-ast has no dependencies and uses no Node APIs, so it runs in the browser as well as in Node, Bun and Deno.
28
+
29
+ It's for tools that analyze components statically, such as documentation and type generators that read a component's props, events and slots. They need only the AST, but parse every component in a library, often on every change. [sveld](https://github.com/carbon-design-system/sveld), which generates TypeScript definitions and documentation for Svelte components, uses it.
30
+
31
+ | Function | For | Import from |
32
+ |:---|:---|:---|
33
+ | [`parse`](#parsesource-options--astroot) | A component's AST, the same as svelte's | `svelte-ast` |
34
+ | [`parseSections`](#parsesectionssource-options--astroot) | A component's AST without the markup: its `<script>`s, `<style>` and `<svelte:options>` | `svelte-ast` |
35
+ | [`parseModule`](#parsemodulesource-options--program) | A `.js` or `.ts` module's AST, the same as a component's `<script>` | `svelte-ast` |
36
+ | [`parseImportsExports`](#parseimportsexportssource-options--moduledeclaration) | A module's `import` and `export` statements, without parsing the rest | `svelte-ast` |
37
+ | [`lexImportsExports`](#leximportsexportssource-options--lexedstatement) | Their offsets, sources and names, without loading a parser | `svelte-ast/lexer` |
38
+ | [`lexDynamicImports`](#lexdynamicimportssource--lexeddynamicimport) | A module's `import(…)`, `require(…)` and `import.meta.glob(…)`, with their offsets and sources, without loading a parser | `svelte-ast/lexer` |
39
+ | [`lexComponent`](#lexcomponentsource--lexedcomponent) | A component's `<script>`s, `<style>` and `<svelte:options>`, with their attributes and offsets, without loading a parser | `svelte-ast/lexer` |
40
+ | [`lexStrings`](#lexstringssource--lexedstring) | A module's string and template literals, with their offsets and values, without loading a parser | `svelte-ast/lexer` |
41
+ | [`createParser`, `createSectionsParser`, `createModuleParser`](#smaller-bundles-svelte-astcore-and-svelte-astmodule) | The parsers without TypeScript, named HTML entities or the template parser, for a smaller bundle | `svelte-ast/core`, `svelte-ast/module` |
42
+ | [`isValidType`](#isvalidtypetext-options--boolean) | Whether a JSDoc type is safe to copy into a `.d.ts` | `svelte-ast` |
43
+ | [`isRunesMode`](#isrunesmodesource--boolean) | Whether svelte compiles a component in runes mode, mostly without parsing it | `svelte-ast` |
44
+ | [`walk`, `visitorKeys`, `markupVisitorKeys`, `valueVisitorKeys`, `skipTypeWrappers`](#walknode-visitor-keys--void) | Visit, skip, stop at or replace nodes, in the whole AST, only the markup, or everything but TypeScript's types | `svelte-ast`, `svelte-ast/walk` |
45
+ | [`children`, `forEachChild`](#childrennode-keys--node-and-foreachchildnode-callback-keys--void) | A node's children, cached or without allocating | `svelte-ast`, `svelte-ast/walk` |
46
+ | [`isReference`](#isreferencenode-parent--boolean), [`extractIdentifiers`](#extractidentifierspattern--identifier) | Which identifiers are references, and which ones a pattern declares | `svelte-ast`, `svelte-ast/walk` |
47
+ | [`analyzeScopes`](#analyzescopesast-options--scopes) | Which declaration each name refers to, and every read and write of it | `svelte-ast`, `svelte-ast/scope` |
48
+ | [`a11yWarnings`](#a11ywarningsast-options--a11ywarning) | svelte's accessibility warnings, without compiling | `svelte-ast/a11y` |
49
+ | [`compilerWarnings`](#compilerwarningsast-options--compilerwarning) | svelte's other warnings, without compiling: unused CSS selectors, empty blocks, attribute and naming mistakes, bidirectional text, nested classes, state read outside a closure, unused props, and runes-mode deprecations | `svelte-ast/warnings` |
50
+ | [`createLocator`, `locate`](#createlocatorsource--offset--position) | Lines and columns for the nodes you report, without parsing with `loc` | `svelte-ast`, `svelte-ast/walk` |
51
+
52
+ ## Migrating from svelte/compiler
53
+
54
+ svelte-ast is a drop-in for `parse` in most tools: change the import, and pass `loc: true` if you read line and column numbers.
55
+
56
+ ```diff
57
+ - import { type AST, parse } from "svelte/compiler";
58
+ + import { type AST, parse } from "svelte-ast";
59
+
60
+ - const ast = parse(source, { modern: true });
61
+ + const ast = parse(source, { loc: true });
62
+ ```
63
+
64
+ | | svelte/compiler | svelte-ast |
65
+ |:---|:---|:---|
66
+ | `loc`, `name_loc` | Always | With `loc: true`; otherwise only `start`/`end` offsets, for a faster parse and a smaller AST |
67
+ | Errors | `CompileError` | `ParseError`: same `code`, `message`, `position`, `start`, `end` and `frame`; no `filename`; `reason`, the message without its link |
68
+ | AST formats | Modern, legacy (`modern: false`), error-tolerant (`loose`) | Modern |
69
+ | Non-ASCII identifiers | Its own Unicode 17 tables | The JavaScript engine's Unicode data, which is smaller to ship: the same in Node 24 and Bun; an engine on another Unicode version differs on the letters added in between |
70
+ | TypeScript-only errors | Reported, e.g. modifier order or initializers in ambient contexts | Not reported: code that only TypeScript's own checks reject still parses |
71
+ | Invalid regular expressions | Reported as `js_parse_error`, e.g. `/a/gg` or `/(/` | Not reported: the literal parses, which keeps acorn's regular expression validator out of the bundle |
72
+
73
+ ## Examples
74
+
75
+ **List the components a file renders**, e.g. to build a dependency graph:
76
+
77
+ ```ts
78
+ import { parse, walk } from "svelte-ast";
79
+
80
+ function componentsUsed(source: string): string[] {
81
+ const names = new Set<string>();
82
+ walk(parse(source, { css: false }).fragment, {
83
+ enter(node) {
84
+ if (node.type === "Component") names.add(node.name);
85
+ },
86
+ });
87
+ return [...names]; // ["Button", "Modal.Root"]
88
+ }
89
+ ```
90
+
91
+ **Report syntax errors**, e.g. in a pre-commit check, with svelte's own messages:
92
+
93
+ ```ts
94
+ import { ParseError, parse } from "svelte-ast";
95
+
96
+ try {
97
+ parse(source, { css: false });
98
+ } catch (error) {
99
+ if (!(error instanceof ParseError)) throw error;
100
+ console.error(`${file}:${error.start?.line}:${error.start?.column} ${error.code}\n${error.frame}`);
101
+ }
102
+ ```
103
+
104
+ [`examples/`](examples) has runnable versions of these and more, each a CLI you can point at your own components: a module graph, unused imports and variables, unused CSS classes, runes-or-legacy detection, `$props()` and their defaults, `.d.ts` props from JSDoc, and styles without parsing them.
105
+
106
+ ## Parity and performance
107
+
108
+ - **svelte/compiler parity.** Tested on over 12,000 components: carbon-components-svelte, svelte's own test suite, bits-ui, shadcn-svelte, skeleton, flowbite-svelte, svelte.dev, immich, SvelteKit, melt-ui, layerchart and paneforge. Every one either parses to svelte's AST, `loc` included, or throws svelte's error with the same code, message, position and frame. A differential fuzzer compares the two parsers on mutated components.
109
+ - **TypeScript.** `<script lang="ts">` and `.ts` modules parse to svelte's AST, key order and `loc` included, on 6,604 real-world modules and on all but 2 of the 9,586 TypeScript conformance tests svelte parses.
110
+
111
+ Apple M2, medians of warm calls. The corpus is `tests/corpus`: all of carbon-components-svelte plus svelte's and sveld's test inputs.
112
+
113
+ | Input | svelte-ast | svelte-ast, `loc: true` | svelte/compiler |
114
+ |:---|:---|:---|:---|
115
+ | Corpus, 400 components, 1.5 MB | **64.7 ms** | 84.0 ms | 155 ms (2.4×) |
116
+ | Carbon's 5 largest components, 318 kB | **13.8 ms** | | 31.3 ms (2.3×) |
117
+ | `lang="ts"` components, 22 files | **0.79 ms** | | 2.40 ms (3.0×) |
118
+
119
+ | `parse` alone, minified for the browser | Gzipped |
120
+ |:---|:---|
121
+ | svelte/compiler | 126.7 kB |
122
+ | svelte-ast | **58.5 kB** |
123
+ | `svelte-ast/core`'s `createParser()`, without TypeScript and named HTML entities | **41.0 kB** |
124
+
125
+ In a fresh process, importing the parser takes 5.3 ms with svelte-ast and 44.7 ms with `svelte/compiler`, and a first parse of the whole corpus takes 65 ms against 161 ms. Keeping ten parses of the corpus alive retains 147 MB with svelte-ast, 260 MB with `loc: true`, and 294 MB with `svelte/compiler`.
126
+
127
+ ## API
128
+
129
+ ### `parse(source, options?) => AST.Root`
130
+
131
+ | Option | Default | Description |
132
+ |:---|:---|:---|
133
+ | `loc` | `false` | Add `loc` (line and column) to script and expression nodes, and `name_loc` to elements, attributes and directives, as svelte does. They cost time and memory, and most tools only need `start`/`end`. |
134
+ | `css` | `true` | Parse `<style>` into rules and selectors. With `false`, `css` keeps its `start`, `end` and `content`, but `children` and `comments` are empty and CSS syntax errors aren't reported. It also keeps `<style lang="scss">` from failing to parse as CSS. |
135
+ | `script` | `true` | Parse each `<script>`. With `false`, `instance` and `module` keep their attributes, `start` and `end`, and `content` is a `Program` with an empty `body`; their comments aren't collected and their syntax errors aren't reported. Expressions in the markup are still parsed. For a pass that only reads the markup; 3.4× faster on the benchmark corpus. |
136
+ | `comments` | `true` | Collect JavaScript comments, in scripts, expressions and tags. With `false`, `comments` is empty and no node has `leadingComments` or `trailingComments`, including the HTML comment before a `<script>` that svelte copies into its `content.leadingComments`. HTML and CSS comments are kept. 3 to 6% faster, and 8% less memory. |
137
+
138
+ With `loc: true`, the result equals svelte's. With the defaults, it's svelte's without `loc` and `name_loc`.
139
+
140
+ A syntax error throws a `ParseError` with svelte's `code` (e.g. `"block_unclosed"`), `message`, `position` (`[start, end]` offsets), `start`/`end` (`{ line, column, character }`) and `frame` (the source around the error). `message` is always the reason, a line break, then the link to the error's docs, `https://svelte.dev/e/${code}`; `reason` is the reason on its own, e.g. `"Unexpected token"`.
141
+
142
+ ### `parseSections(source, options?) => AST.Root`
143
+
144
+ `parse` for a pass that only reads a component's scripts, such as its props or its module script's exports: the top-level `<script>`s, `<style>` and `<svelte:options>` are parsed as `parse` parses them, and the markup between them is skipped as [`lexComponent`](#lexcomponentsource--lexedcomponent) skips it. `fragment.nodes` is empty, `comments` has only the scripts' comments, and the markup's syntax errors aren't reported; the rest is `parse`'s, offsets and the HTML comment before a `<script>` included. It takes `parse`'s options, and on the benchmark corpus it's 1.5× faster, where most of what's left is the scripts. It's a function of its own so that a bundle with only `parse` doesn't carry the lexer; `createParser` doesn't return it, and `createSectionsParser` does, without the parts you leave out.
145
+
146
+ ```ts
147
+ import { parseSections } from "svelte-ast";
148
+
149
+ const { instance, module } = parseSections(source, { css: false });
150
+ module?.content.body; // the module script's statements, with parse's offsets
151
+ ```
152
+
153
+ ### `parseModule(source, options?) => Program`
154
+
155
+ Parses a JavaScript or TypeScript module, such as a `.ts` file a component imports, into the same AST a component's `<script>` gets, with comments attached as `leadingComments`/`trailingComments`. Options: `typescript` and `loc`, default `false`, and `comments`, default `true`.
156
+
157
+ ### `parseImportsExports(source, options?) => ModuleDeclaration[]`
158
+
159
+ A module's top-level `import` and `export` statements, without parsing the rest, e.g. to rewrite a component's imports or follow a module graph. Each node is the one `parseModule(source, { comments: false })` has for that statement: `ImportDeclaration`, `ExportNamedDeclaration`, `ExportDefaultDeclaration` and `ExportAllDeclaration`, and, in TypeScript, `TSImportEqualsDeclaration`, `TSExportAssignment` and `TSNamespaceExportDeclaration`. `import(...)` and `import.meta` are expressions, so they aren't returned; [`lexDynamicImports`](#lexdynamicimportssource--lexeddynamicimport) finds them. Unlike a regex, it never matches an `import` in a comment, a string, a template or a nested block such as `declare module "a" { ... }`.
160
+
161
+ It stops after the last `import` or `export` that could start a statement, so the code after a component's imports is never read: on Carbon's component scripts, it takes a third of `parseModule`'s time, and about a seventh with `localExports: false`. A syntax error in a statement it returns throws a `ParseError`, including a name exported twice; errors elsewhere aren't reported.
162
+
163
+ | Option | Default | Description |
164
+ |:---|:---|:---|
165
+ | `typescript` | `false` | Parse TypeScript: `import type`, `export type`, `import a = require("a")`. |
166
+ | `localExports` | `true` | Return the exports of the module's own bindings, such as `export let a`, `export function b() {}`, `export { c }` and `export default d`, parsed in full. With `false`, only imports and the exports that have a `from` (`export * from "e"`, `export { f } from "f"`, `export import`) are returned. |
167
+
168
+ ```ts
169
+ import { parseImportsExports } from "svelte-ast";
170
+
171
+ function dependencies(source: string, typescript = false): string[] {
172
+ return parseImportsExports(source, { typescript, localExports: false }).flatMap(
173
+ (node) => ("source" in node && node.source ? [node.source.value] : []),
174
+ );
175
+ }
176
+ ```
177
+
178
+ ### `lexImportsExports(source, options?) => LexedStatement[]`
179
+
180
+ From `svelte-ast/lexer`, and also `svelte-ast`. A module's top-level `import` statements and `export … from` re-exports, read by hand instead of parsed, for a tool on a hot or eagerly loaded path, such as a preprocessor that rewrites a component's imports, that needs each statement's offsets, source and names, but not the AST. `svelte-ast/lexer` loads no parser, so a fresh process imports it in 1.4 ms, and on Carbon's component scripts it takes 40% of the time `parseImportsExports` takes with `localExports: false`.
181
+
182
+ It finds the statements `parseImportsExports` returns with `localExports: false`, with the same offsets, sources and names. It doesn't check syntax and never throws: a statement it can't read, such as `import { a from "a"` or `import a = require("a")`, has `source: null` and no specifiers, and ends where it stopped reading. `import type` and `type` before a name are always read.
183
+
184
+ With `exportLists: true`, it also returns each top-level `export { a, b as c }` without `from`, e.g. to follow a binding through an `index.js` that imports it and exports it again: `source` is `null`, and each specifier has kind `local`, with `local` the binding in this module. Those are the `ExportNamedDeclaration`s without a declaration that `parseImportsExports` returns with `localExports: true`; `export const a`, `export function b` and `export default` still aren't returned. A module that ends with an export list is read to its end.
185
+
186
+ ```ts
187
+ import { lexImportsExports } from "svelte-ast/lexer";
188
+
189
+ for (const statement of lexImportsExports(source)) {
190
+ statement.kind; // "import" | "export"
191
+ statement.start; // offset of `import` or `export`
192
+ statement.end; // after the `;`, or the last token without one
193
+ statement.source; // { value: "carbon-components-svelte", start, end } (quotes included), or null
194
+ statement.typeOnly; // `import type …` or `export type …`
195
+ statement.specifiers;
196
+ // import: { kind: "default" | "namespace" | "named", imported, local, typeOnly, start, end }
197
+ // export: { kind: "all" | "namespace" | "named" | "local", local, exported, typeOnly, start, end }
198
+ }
199
+ ```
200
+
201
+ | Specifier | `import` | `export … from` |
202
+ |:---|:---|:---|
203
+ | `a` in `import a` | `default`, `imported: "default"`, `local: "a"` | |
204
+ | `* as a` | `namespace`, `imported: "*"`, `local: "a"` | `namespace`, `local: "*"`, `exported: "a"` |
205
+ | `*` | | `all`, `local: "*"`, `exported: null` |
206
+ | `b as c`, `"b-c" as d` | `named`, `imported: "b"`, `local: "c"` | `named`, `local: "b"`, `exported: "c"` |
207
+ | `b as c` in `export { … }`, with `exportLists` | | `local`, `local: "b"`, `exported: "c"` |
208
+
209
+ Names are as the module sees them: escapes decoded, and a string name without its quotes. A specifier's `typeOnly` is also `true` in an `import type` or `export type`. Its `start` is that of `type` before the name, if any, and `end` is after the last name; for `export *`, after the `*`.
210
+
211
+ ### `lexDynamicImports(source) => LexedDynamicImport[]`
212
+
213
+ From `svelte-ast/lexer`, and also `svelte-ast`. A module's `import(…)` and `require(…)` calls and Vite's `import.meta.glob(…)`, at any depth, in source order, read without parsing, e.g. to follow the lazily loaded part of a module graph. Unlike a regular expression, it never matches in a comment, a string, a template or a regular expression, and it tells a literal argument from a computed one. `lexImportsExports` finds the static imports; together they're a module's dependencies.
214
+
215
+ ```ts
216
+ import { lexDynamicImports } from "svelte-ast/lexer";
217
+
218
+ for (const call of lexDynamicImports(source)) {
219
+ call.kind; // "import" | "require" | "glob"
220
+ call.start; // offset of `import` or `require`
221
+ call.end; // after the `)`
222
+ call.source; // { value: "./Chart.svelte", start, end } (quotes or backticks included), or null
223
+ }
224
+ ```
225
+
226
+ `source` is the first argument if it's a string or a template without `${…}` and it's followed by `)` or `,`, as in `import("a", { with: { type: "json" } })`; it's `null` for a computed argument such as `` import(`./${name}.js`) `` or `import.meta.glob(["a", "b"])`, and for a call without arguments. Type arguments are skipped, as in `import.meta.glob<Module>("./*.ts")`.
227
+
228
+ Where `parseModule` accepts the module, the calls are its `ImportExpression`s, its calls of an identifier `require`, `new require(…)` included, and of `import.meta.glob`, and in TypeScript also its `import("a")` types, as in `typeof import("a")`, and the `require("a")` of `import a = require("a")`. A method named `import` or `require`, such as `{ import() {} }`, isn't a call, and neither are `a.require(…)`, `require?.(…)` or `(require)(…)`. It doesn't check syntax and never throws. It matched `parseModule` on all 33,001 modules and component scripts it accepts from the projects under [Parity and performance](#parity-and-performance), svelte's tests and TypeScript's conformance tests.
229
+
230
+ ### `lexComponent(source) => LexedComponent`
231
+
232
+ From `svelte-ast/lexer`, and also `svelte-ast`. A component's top-level `<script>`, `<script module>`, `<style>` and `<svelte:options>`, with their attributes and the offsets of their tags and content, found without parsing: e.g. to read a component's scripts and their imports, its language or its options, or to rewrite a script, on a path that can't afford a parser. On the benchmark corpus it's about 50× faster than `parse`.
233
+
234
+ It skips the markup by tracking only tags, attribute values, blocks, and the brackets, strings, comments and templates of each `{…}` expression, so a `<script>` in `<svelte:head>`, a block, an attribute, an expression or an HTML comment isn't one, and it stops after the last `<script`, `<style` or `<svelte:options`. Where `parse` accepts the component, the sections are its `instance`, `module`, `css` and `options`, with the same offsets, into the source without a leading byte order mark. It doesn't check syntax and never throws.
235
+
236
+ ```ts
237
+ import { lexComponent } from "svelte-ast/lexer";
238
+
239
+ const { typescript, instance, module, css, options } = lexComponent(source);
240
+ typescript; // whether `parse` reads it as TypeScript, decided by the first <script> with a lang
241
+ instance?.content; // { start, end }: source.slice(start, end) is the script
242
+ instance?.attributes; // [{ name: "lang", value: "ts", start, end }]
243
+ module?.context; // "module"
244
+ options?.attributes; // [{ name: "runes", value: "{true}", start, end }]
245
+ ```
246
+
247
+ An attribute's `value` is as written, without its quotes: character references aren't decoded, an expression keeps its braces, and an attribute without a value has `true`.
248
+
249
+ `typescript` is what `createParser` needs to know to load the TypeScript parser only for the components that use it:
250
+
251
+ ```ts
252
+ import { createParser } from "svelte-ast/core";
253
+ import { lexComponent } from "svelte-ast/lexer";
254
+
255
+ let parser = createParser();
256
+ let loaded = false;
257
+
258
+ async function parseComponent(source: string) {
259
+ if (!loaded && lexComponent(source).typescript) {
260
+ const { typescript } = await import("svelte-ast/typescript");
261
+ parser = createParser({ typescript });
262
+ loaded = true;
263
+ }
264
+ return parser.parse(source);
265
+ }
266
+ ```
267
+
268
+ ### `lexStrings(source) => LexedString[]`
269
+
270
+ From `svelte-ast/lexer`, and also `svelte-ast`. A module's string literals and the text of its template literals, in source order, read without parsing, for a tool that only needs a script's strings, such as one that collects the class names a component's script can produce. With `parse(source, { script: false })` for the markup, it reads a component's scripts in a fraction of the time: on Carbon's 258 components, `parse` with `comments: false` takes 19.5 ms, and `script: false` plus `lexStrings` on each script 9.6 ms, of which `lexStrings` is 1.55 ms, 15% of what `parseModule` takes on the same scripts.
271
+
272
+ Where `parseModule` accepts the module, the strings are its `Literal`s with a string value and its `TemplateElement`s, types, imports and directives included, with the same offsets and values. Comments and regular expressions are skipped, and it never throws. It tells a regular expression from a division by the token before it, as acorn's tokenizer does, but acorn's parser can overrule that guess and `lexStrings` can't: a statement that starts with a regular expression after a line break without a `;`, following `let a`, an `import`, a type alias ending in `}`, or a block after `case …:` or a label, reads as a division, as does `/` after a variable named `of`, and a quote in that regular expression starts a string. It matched `parseModule` on all 21,443 modules and component scripts it accepts from the projects under [Parity and performance](#parity-and-performance), and on all 9,647 of TypeScript's conformance tests that `parseModule` accepts.
273
+
274
+ ```ts
275
+ import { lexStrings } from "svelte-ast/lexer";
276
+
277
+ for (const string of lexStrings(source)) {
278
+ string.kind; // "string", a Literal: start and end include the quotes
279
+ // "template", a TemplateElement: the text between the backtick, `${` or `}` around it
280
+ string.value; // escapes decoded, as Literal's value or TemplateElement's value.cooked
281
+ }
282
+ ```
283
+
284
+ `value` is `null` for an escape acorn rejects in a module, such as `"\1"`, or one that leaves a tagged template's `cooked` `null`. A template's line breaks read as `\n` in `value`; its raw text is `source.slice(start, end)`, with `\r\n` and `\r` as `\n`.
285
+
286
+ ### Smaller bundles: `svelte-ast/core` and `svelte-ast/module`
287
+
288
+ `createParser(support?)` from `svelte-ast/core` returns `parse`, `parseModule` and `parseImportsExports` without the TypeScript parser and the table of HTML's named character references, which most tools can do without. `createSectionsParser(support?)`, from the same entry, returns `parseSections` the same way; it's separate so that a bundle with only `createParser` doesn't carry the lexer. `createModuleParser(support?)` from `svelte-ast/module` returns `parseModule` and `parseImportsExports` without the template parser either, for tools that read `.js` and `.ts` files but never components, such as a bundler plugin following a module graph. Pass back the parts you need; with them, the parsers are the same as `svelte-ast`'s.
289
+
290
+ ```ts
291
+ import { createParser, createSectionsParser } from "svelte-ast/core";
292
+ import { typescript } from "svelte-ast/typescript";
293
+
294
+ const { parse, parseModule, parseImportsExports } = createParser({ typescript });
295
+ const { parseSections } = createSectionsParser({ typescript });
296
+ ```
297
+
298
+ | Support | Without it |
299
+ |:---|:---|
300
+ | `typescript` from `svelte-ast/typescript` | A component with `<script lang="ts">`, or `typescript: true`, throws an `Error`, not a `ParseError`: a missing import, not a syntax error, and never a JavaScript AST of TypeScript |
301
+ | `entities` from `svelte-ast/entities` (`createParser` and `createSectionsParser` only) | Numeric references, such as `&#169;`, and `&amp;`, `&apos;`, `&gt;`, `&lt;` and `&quot;` are decoded, but other names, such as `&copy;`, are left as written, so `Text.data` differs from svelte's where the source uses them |
302
+
303
+ Both also export `ParseError`, the same class as `svelte-ast`'s, and the node types.
304
+
305
+ ### `isValidType(text, options?) => boolean`
306
+
307
+ Whether `text` is exactly one TypeScript type, such as a JSDoc `{"sm" | "lg"}` a tool is about to copy into a `.d.ts`. The text is parsed as a type on its own, not wrapped in a statement, so a `;`, a line break or a `}` in it can't end the type and smuggle in a statement: `string; let x = 1` and `{ a: string } }` are `false`. Whitespace and comments around the type are allowed. Results aren't cached.
308
+
309
+ A `//` comment runs to the end of the line, so `string // the size` is a valid type but breaks `CustomEvent<${text}>`. Pass `inline: true` when the text goes before more code on the same line: it's then also `false` unless every `//` comment in it ends with a line break.
310
+
311
+ ### `isRunesMode(source) => boolean`
312
+
313
+ Whether svelte compiles the component in runes mode, as `compile(source).metadata.runes` says: by `<svelte:options runes>` if it has one, otherwise by whether it uses a rune, such as `$state` or `$props`, or `await` outside a function in its instance script or markup. A `$state` that subscribes to a store named `state`, or that a function declares, isn't a rune, as in svelte. E.g. to track a migration to Svelte 5, or to pick the rules a linter applies.
314
+
315
+ Most components are decided without parsing: `<svelte:options>` is read with `lexComponent`, a component without a rune's name or `await` isn't in runes mode, and one whose scripts call a rune in a way that can't be a declaration, a method, a type or a store is. The rest is parsed, without the markup unless a rune's name or `await` is in it, and a syntax error there throws a `ParseError`. On 12,808 components from other Svelte projects, it takes a twelfth of the time parsing them does.
316
+
317
+ ### `walk(node, visitor, keys?) => void`
318
+
319
+ Visits `node` and every node under it, depth-first and in source order, calling `visitor.enter(node, parent, key, index)` before a node's children and `visitor.leave(node, parent, key, index)` after them. `parent[key]` is the node, or `parent[key][index]` when the field is an array; all three are `null` for the node you pass. Checking `node.type` narrows `node`.
320
+
321
+ What `enter` and `leave` return controls the walk:
322
+
323
+ - **`SKIP`** from `enter` skips the node's children. `leave` is still called, so a stack you push in `enter` and pop in `leave` stays balanced.
324
+ - **`STOP`** from `enter` or `leave` ends the walk there, without `leave` on the node's ancestors, e.g. to find the first use of a rune.
325
+ - **A node** from `enter` replaces this one: `walk` writes it to `parent[key]` (or `parent[key][index]`), then enters it and visits its children instead, and `leave` gets the replacement. `return node.expression` on each `TSAsExpression` strips `a as B as C` down to `a`. The node you pass to `walk` can't be replaced.
326
+ - **Anything else**, `false` included, is ignored, so `enter: (node) => node.type === "Component" && names.add(node.name)` still visits every node.
327
+
328
+ It works on any node the parsers return: a `Root`, a `Fragment`, an expression, a `Program`, a `<style>`'s rules. It never descends into `loc`, comments or strings, and throws on a node type it doesn't know. A component's sections are visited in scope order, `module`, `instance`, `fragment`, then `css`, and a template literal's `quasis` before its `expressions`. `<svelte:options>`'s attributes aren't visited; read them from `ast.options?.attributes`. In `import { a }` and `export { a }`, one `Identifier` is both names, so it's visited twice.
329
+
330
+ `visitorKeys` is the table `walk` reads: the fields of each node type that hold child nodes, in source order, e.g. `visitorKeys.IfBlock` is `["test", "consequent", "alternate"]`. Pass another table as `keys` to visit other fields; a node whose type it has no entry for throws. `markupVisitorKeys` visits only the markup: `Root`'s `fragment`, elements' attributes and fragments, attribute values and blocks' fragments, but no script, style or expression. For a query about the markup, such as the components a file renders or the classes it uses, it's 4.8× faster on the benchmark corpus than walking everything:
331
+
332
+ ```ts
333
+ import { markupVisitorKeys, walk } from "svelte-ast";
334
+
335
+ walk(
336
+ ast,
337
+ {
338
+ enter(node) {
339
+ if (node.type === "Component") names.add(node.name);
340
+ },
341
+ },
342
+ markupVisitorKeys,
343
+ );
344
+ ```
345
+
346
+ `valueVisitorKeys` leaves out TypeScript's types: no type annotation, type parameter or type argument, no `implements`, and no type in `as` or `satisfies`. It reaches every value and binding, so an `Identifier` it reaches is never a type's name, and a tool that rewrites values can't fold `size` in `type S = typeof size` or `let a: typeof size`. It still enters a declaration that holds only types, such as `type`, `interface` or an index signature, but not its children, and of `declare function f(): void` it visits only the name. The TypeScript nodes whose children it visits hold values: `as`, `satisfies`, `<T>a`, `a!` and `a<T>` their expression, an enum its members, a namespace its body, `import a = b` and `export =` their value, and a parameter property its parameter. Walking with it takes about as long as walking everything.
347
+
348
+ `skipTypeWrappers(node)` gives the value inside those wrappers: `a` for `a as T`, `a satisfies T`, `<T>a`, `a!`, `a<T>` and any nesting of them, and `node` itself for anything else, for code that reads values, such as an evaluator deciding whether `size as Size` is a constant.
349
+
350
+ `svelte-ast/walk` exports `walk`, `SKIP`, `STOP`, `visitorKeys`, `markupVisitorKeys`, `valueVisitorKeys`, `skipTypeWrappers`, `children`, `forEachChild`, `isReference`, `extractIdentifiers`, `createLocator`, `locate` and the types without loading a parser, for code that walks ASTs from elsewhere, such as a cache.
351
+
352
+ ### `children(node, keys?) => Node[]` and `forEachChild(node, callback, keys?) => void`
353
+
354
+ The child nodes `walk` would visit next, in source order, for a traversal of your own, such as one that evaluates expressions and decides per node what to visit. `forEachChild(node, (child, key, index) => ...)` calls back with each child, the field that holds it, and its index when the field is an array, and allocates nothing. `children(node)` returns an array that it makes on the first call for each node and returns again after, so a tool that walks the same tree many times lists each node's children once. ASTs don't change after `parse`, so the cache stays right unless you change one, for instance by replacing a node with `walk`; don't change the array. Both take `keys` as `walk` does and throw on a node type it has no entry for.
355
+
356
+ ```ts
357
+ import { forEachChild, valueVisitorKeys } from "svelte-ast/walk";
358
+
359
+ function visit(node) {
360
+ if (node.type === "ConditionalExpression") return evaluateBranches(node);
361
+ forEachChild(node, visit, valueVisitorKeys);
362
+ }
363
+ ```
364
+
365
+ ### `isReference(node, parent) => boolean`
366
+
367
+ Whether `node` is an `Identifier` that names a variable, function, class, import or other binding, where it's declared or where it's used, given the `parent` `walk` passes. It's the check svelte's analyzer makes, from [`is-reference`](https://github.com/Rich-Harris/is-reference): `false` for a property or method name (`b` in `a.b`, `{ b: a }` and `class { b() {} }`, unless computed), the renamed side of an import or export (`b` in `import { b as a }` and `export { a as b }`), and labels. Unlike `is-reference`, it's also `false` for `import.meta` and `new.target`, an import attribute's key, and `b` in `export * as b from`.
368
+
369
+ In TypeScript, a name in a type isn't a reference (`B` in `let a: B`, interface and type alias names), but a value is: the expression of `as`, `satisfies`, `<T>a`, `a!`, `a<T>` and `export =`, an enum's name and member initializers, a parameter property (`a` in `constructor(private a)`), and both sides of `import a = b`. Names of namespaces and of functions without a body (overloads, `declare function`) aren't references.
370
+
371
+ ```ts
372
+ import { isReference, parseModule, walk } from "svelte-ast";
373
+
374
+ const used = new Set<string>();
375
+ walk(parseModule("const a = b.c({ d: e });"), {
376
+ enter(node, parent) {
377
+ if (node.type === "Identifier" && isReference(node, parent)) used.add(node.name);
378
+ },
379
+ });
380
+ used; // Set { "a", "b", "e" }
381
+ ```
382
+
383
+ ### `extractIdentifiers(pattern) => Identifier[]`
384
+
385
+ The `Identifier` nodes a pattern binds, in source order, as svelte's `extract_identifiers` returns them: `a`, `c`, `d`, `e` and `f` in `let { a, b: [c, ...d], e = 1, ...f } = x`. Property keys, defaults and type annotations aren't included, and a member expression binds nothing, so `[a.b, c] = x` yields only `c`. It takes any binding or assignment target: a declarator's `id`, a function's params, including a parameter property, a catch clause's `param`, an each block's `context`, a snippet's `parameters`, or an assignment's `left`, where `a!`, `a as T`, `a satisfies T` and `<T>a` yield `a`.
386
+
387
+ ```ts
388
+ import { extractIdentifiers, parseModule } from "svelte-ast";
389
+
390
+ const [declaration] = parseModule("let { a, b: [c] } = x;").body;
391
+ if (declaration.type === "VariableDeclaration") {
392
+ declaration.declarations.flatMap((d) => extractIdentifiers(d.id)).map((node) => node.name); // ["a", "c"]
393
+ }
394
+ ```
395
+
396
+ ### `analyzeScopes(ast, options?) => Scopes`
397
+
398
+ Finds the scopes of a component, its scripts and markup together, or of a module: which declaration each name refers to, and where each binding is read, written or subscribed to. It resolves names as svelte's analyzer does, which `tests/scope.test.ts` checks on the corpus: on 12,548 components from the corpus, svelte's tests and the Svelte projects listed under parity, they agree on all 208,797 names they both resolve, but for a class expression's name inside its body, a snippet's own name and a `var` declared twice, where svelte-ast follows JavaScript.
399
+
400
+ ```ts
401
+ import { parse } from "svelte-ast";
402
+ import { analyzeScopes } from "svelte-ast/scope";
403
+
404
+ const ast = parse(`<script>
405
+ let { size = "md" } = $props();
406
+ function label(size) { return size; }
407
+ </script>
408
+ <Tooltip let:direction={actual}>{actual} {size}</Tooltip>`);
409
+ const scopes = analyzeScopes(ast);
410
+
411
+ const size = scopes.instance.get("size");
412
+ size?.prop; // "size"
413
+ size?.rune; // "$props"
414
+ size?.initial; // the Literal "md"
415
+ size?.references.length; // 1: the parameter in `label` is another binding
416
+ size?.references.some((reference) => reference.writes || reference.mutates); // false
417
+ ```
418
+
419
+ It returns:
420
+
421
+ - **`module`** and **`instance`**, the scopes of `<script module>` and `<script>` (one scope, for a module). A `Scope` has the `node` that makes it, its `parent`, its `declarations` by name, and `get(name)`, the binding a name refers to there, or `null` for a global. With `types: true`, its `types` holds its `type`, `interface` and type parameter bindings, and `getType(name)` is the binding a name refers to in a type.
422
+ - **`scopeOf(node)`**, the scope a node is in; `null` in a type, the `<style>` or another AST. The first call walks the AST again to record every node's scope, so a tool that only resolves names doesn't keep a map of every node.
423
+ - **`bindingOf(identifier)`**, the binding an `Identifier` declares or refers to; `null` for a global, a property key or a name in a type.
424
+ - **`referenceOf(identifier)`**, the `Reference` an `Identifier` is, to tell a read from a write or a store subscription; `null` for one that declares a binding or isn't a reference.
425
+ - **`declaredIn(node)`**, the bindings of the scope a node makes: a function's parameters (its body's declarations are its body's), a block's or an each block's declarations, a snippet's parameters, or an element's `let:` names.
426
+
427
+ A `Binding` has its `name`, its `kind`, the `Identifier` that declares it as `node` (`null` for an each block's index and for `let:x` without a value), the `declaration` that holds it, its `scope` and its `references`. `initial` is what it starts as, as svelte's analyzer has it: an initializer, or for a prop destructured from `$props()`, its default without `$bindable`. `rune` is the rune its initializer calls, such as `"$state"`, `"$derived"` or `"$props"`, unless a binding or a store shadows it, and `prop` the name a parent passes a prop as: `"class"` for `klass` in `let { class: klass } = $props()` or `export { klass as class }`, `"size"` for `export let size`.
428
+
429
+ A `Reference` has its `Identifier` as `node`, its `parent`, its `scope` and its `binding`, and says whether it `reads` the value (all but a plain `=`'s target), `writes` it (`=`, `+=`, `++`, `bind:`, `for (a of b)`), or `mutates` it (`a` in `a.b = c` and `bind:value={a.b}`), and whether it's a `store` subscription. Names the markup holds as strings, such as `Foo` in `<Foo.Bar>`, `a` in `use:a`, `transition:a` and `animate:a`, and `color` in `style:color`, get a new `Identifier` with the name's `start` and `end`.
430
+
431
+ The markup's scopes are svelte's:
432
+
433
+ - `{#each items as item, i (key)}` declares `item` and `i` for the key and the body, but not for `{:else}`.
434
+ - A snippet's name is declared where the snippet is, and its parameters inside it. A top-level snippet is in the markup's scope, so a `<script>` that uses one refers to a global, as in svelte's analyzer.
435
+ - `{@const}` declares a name for its whole block or element, `{:then value}` and `{:catch error}` for their branch.
436
+ - `let:` declares a name for the element's attributes and children, or for a component's default slot; children with a `slot` attribute get their own scope. `let:a={b}` declares `b`, `let:a` declares `a`.
437
+ - `$count`, without a declaration of `$count`, is a subscription to `count`, unless it's a rune: `$state` refers to a store `state` only if `state` isn't itself made by a rune.
438
+ - `$: a = b` declares `a` if nothing else does, and writes it: the assignment is one of its references.
439
+
440
+ Names in TypeScript's types aren't references, and `type` and `interface` declare nothing; it skips them with `valueVisitorKeys`. Enums, enum members and namespaces are declared. It doesn't change the AST, and takes less than half as long as parsing it.
441
+
442
+ | Option | Default | Description |
443
+ |:---|:---|:---|
444
+ | `types` | `false` | Resolve the names in types too, for a tool that asks which declarations some code uses, such as one that copies a statement with the imports it needs. |
445
+
446
+ With `types: true`, `type` and `interface` declare bindings of those kinds, and a type parameter or `infer U` one of kind `"type-param"`, in a scope's `types`, apart from its values, so `type A` and `const A` are two bindings. A name in a type is a `Reference` with `type: true` that neither reads, writes nor mutates: `A` in `let a: A`, `a` in `typeof a`, `I` in `implements I` and `extends I`, `N` in `N.T`, and the local name in `export type { A }`. A name in a type refers to a type, an import, a class or an enum; `typeof a` to a value; `N` in `N.T` to a namespace, an enum or an import, so `import type { A }` and `import { type A }` get the references. Property and method names in type literals and interfaces aren't references, but for a computed key's value. Type parameters are in scope for their function, class, method, type alias, interface or function type, `infer U` for its conditional type's true branch, and the parameters of a function type or signature are bindings of kind `"param"`, for `typeof x` and `x is T`. `<script generics="...">`'s names aren't declared. The value references are those it finds without `types`.
447
+
448
+ ```ts
449
+ const ast = parse(`<script lang="ts">
450
+ import type { DataTableHeader } from "carbon-components-svelte";
451
+ let headers: DataTableHeader[] = [];
452
+ </script>`);
453
+ const { instance } = analyzeScopes(ast, { types: true });
454
+ instance.get("DataTableHeader")?.references[0]?.type; // true
455
+ ```
456
+
457
+ ### `a11yWarnings(ast, options?) => A11yWarning[]`
458
+
459
+ From `svelte-ast/a11y`. The `a11y_…` warnings svelte's compiler gives for a component, with the same `code`, `message` and offsets, and without the ones a `<!-- svelte-ignore -->` comment before an element, or one of its ancestors, silences. For a linter that already has the AST: on Carbon's 2,202 components it takes 60 ms, against 735 ms for `compile(source, { generate: false })`. It loads neither acorn nor the parser.
460
+
461
+ | Option | Default | Description |
462
+ |:---|:---|:---|
463
+ | `runes` | `false` | Whether the component compiles in runes mode, as [`isRunesMode`](#isrunesmodesource--boolean) says. In runes mode, `svelte-ignore` takes only svelte 5's codes, separated by commas; in legacy mode, svelte 4's `a11y-…` codes too, as svelte does. |
464
+
465
+ ```ts
466
+ import { isRunesMode, parse } from "svelte-ast";
467
+ import { a11yWarnings } from "svelte-ast/a11y";
468
+
469
+ for (const warning of a11yWarnings(parse(source), { runes: isRunesMode(source) })) {
470
+ warning.code; // "a11y_missing_attribute"
471
+ warning.message; // "`<img>` element should have an alt attribute\nhttps://svelte.dev/e/a11y_missing_attribute"
472
+ warning.start; // offsets of the element or attribute
473
+ }
474
+ ```
475
+
476
+ The ARIA tables come from svelte's, which read aria-query and axobject-query, generated into the package, so it has no dependencies. On svelte's tests, carbon-components-svelte, bits-ui, shadcn-svelte, skeleton, flowbite-svelte, svelte.dev, immich and SvelteKit, it gives the warnings `compile` gives for all 13,276 components both accept, 899 warnings, and for 13,163 with their `svelte-ignore` comments and common a11y attributes removed, 2,185 warnings.
477
+
478
+ ### `compilerWarnings(ast, options) => CompilerWarning[]`
479
+
480
+ From `svelte-ast/warnings`. The warnings svelte's compiler gives for a component besides the `a11y_…` ones, with the same `code`, `message` and offsets, and without the ones a `svelte-ignore` comment silences. It loads neither acorn nor the parser. It gives:
481
+
482
+ | Code | When |
483
+ | --- | --- |
484
+ | `css_unused_selector` | A selector in the `<style>` matches no element in the markup |
485
+ | `block_empty` | A block's branch holds only whitespace, such as `{#if a} {/if}` |
486
+ | `element_invalid_self_closing_tag` | An HTML element that isn't void is written `<div/>` |
487
+ | `component_name_lowercase` | A lowercase element's name is an imported value, such as `<foo />` after `import foo from "./Foo.svelte"` |
488
+ | `attribute_global_event_reference` | `onclick={onclick}` or `{onclick}` on an element, where nothing in scope is named `onclick` |
489
+ | `attribute_avoid_is`, `attribute_invalid_property_name`, `attribute_illegal_colon` | The `is` attribute, React's `className` and `htmlFor`, and a colon in an attribute name that isn't `xmlns:` or `xlink:` |
490
+ | `bind_invalid_each_rest` | `bind:` to a name from the rest of an `{#each}` pattern, such as `...rest` |
491
+ | `attribute_quoted` | In runes mode, `prop="{value}"` on a component or custom element |
492
+ | `event_directive_deprecated`, `slot_element_deprecated`, `svelte_component_deprecated`, `svelte_self_deprecated` | In runes mode, `on:`, `<slot>`, `<svelte:component>` and `<svelte:self>` |
493
+ | `node_invalid_placement_ssr` | An element the browser would move out of its parent, such as a `<div>` in a `<p>`, with a block between them. Without the block, svelte fails the build |
494
+ | `element_implicitly_closed` | A tag closes an open element, such as the second `<li>` in `<li>a<li>b` |
495
+ | `svelte_element_invalid_this` | `<svelte:element this="div">`, with a string for `this` |
496
+ | `script_unknown_attribute` | A `<script>` attribute other than `context`, `generics`, `lang` and `module` |
497
+ | `script_context_deprecated` | In runes mode, `<script context="module">` |
498
+ | `options_deprecated_accessors`, `options_deprecated_immutable` | In runes mode, `accessors` and `immutable` in `<svelte:options>` |
499
+ | `options_missing_custom_element` | `customElement` in `<svelte:options>` without the `customElement` option |
500
+ | `bidirectional_control_characters` | A string, template or text holds a character that changes the direction of the text, such as U+202E |
501
+ | `perf_avoid_inline_class`, `perf_avoid_nested_class` | `new class {}` outside the module script's top level, and a class declared in a function, a `$:` statement or the markup |
502
+ | `legacy_code`, `unknown_code` | In runes mode, a `svelte-ignore` comment names a svelte 4 code, such as `a11y-autofocus`, or a code svelte doesn't have |
503
+ | `state_referenced_locally` | In runes mode, a script reads a `$state`, `$derived` or `$props` binding in the function that declares it, so it gets only the first value. `$state` warns only if it's reassigned or holds a value svelte doesn't proxy, such as a number |
504
+ | `non_reactive_update` | In runes mode, the markup reads a script's binding outside a function, and something reassigns it, but no rune declares it. `bind:this` counts only inside a block |
505
+ | `store_rune_conflict` | `$state(...)` or another rune's call where a local `state` makes it a store subscription |
506
+ | `custom_element_props_identifier` | In runes mode, a custom element without `customElement.props` takes `let props = $props()` or `...rest` |
507
+ | `export_let_unused` | In legacy mode, nothing reads an `export let` |
508
+ | `reactive_declaration_invalid_placement` | In legacy mode, a `$:` statement outside the instance script's top level |
509
+ | `reactive_declaration_module_script_dependency` | In legacy mode, a `$:` statement reads a module script's binding that something reassigns |
510
+ | `legacy_component_creation` | `new App({ target })`, where `App` is the default import of a `.svelte` file |
511
+
512
+ Its options:
513
+
514
+ - `source` (required): the source passed to `parse`. svelte reads it to tell `<div/>` from `<div></div>`, which the AST doesn't.
515
+ - `filename`: svelte's `filename` option. `svelte_self_deprecated` names the self-import after it, or `Self` without one.
516
+ - `customElement`: svelte's `customElement` option. `<svelte:options customElement>` counts without it, except for `options_missing_custom_element`. A custom element gets no `slot_element_deprecated`.
517
+ - `runes`: as for [`a11yWarnings`](#a11ywarningsast-options--a11ywarning).
518
+
519
+ ```ts
520
+ import { isRunesMode, parse } from "svelte-ast";
521
+ import { compilerWarnings } from "svelte-ast/warnings";
522
+
523
+ const ast = parse(source);
524
+ for (const warning of compilerWarnings(ast, { source, filename, runes: isRunesMode(source) })) {
525
+ warning.code; // "css_unused_selector"
526
+ warning.message; // 'Unused CSS selector ".a"\nhttps://svelte.dev/e/css_unused_selector'
527
+ warning.start; // offsets of the selector
528
+ }
529
+ ```
530
+
531
+ svelte gives some warnings as it parses: `element_implicitly_closed` and `svelte_element_invalid_this`. `parse` records them with the AST it returns, so pass that AST: a copy, or an AST from svelte's `parse`, gets neither. svelte gives these and the `script_…`, `options_…` and `store_rune_conflict` warnings outside its walk of the markup, so a `svelte-ignore` comment silences none of them. For `non_reactive_update` and `export_let_unused`, only a comment before the declaration counts.
532
+
533
+ svelte checks every string for `bidirectional_control_characters` with one regular expression with the `g` flag. After a match, its next check starts part way into the next string, so svelte can miss one, and the miss carries over to the next component it compiles. svelte-ast follows this within a component, but starts each component afresh, as svelte does for the first one it compiles. svelte throws on an `unknown_code` or `legacy_code` in a comment before a `<script>`; svelte-ast gives no warning for it.
534
+
535
+ It's a port of svelte 5's analysis, so it gives what svelte 5 gives. It builds scopes only for a component that needs them, and shares them between checks: a check of the scripts' syntax and the markup's text first rules out most components. On the 8,834 components of the projects below that have the AST, it takes 193 ms, against 60 ms without the scope warnings. `compile(source, { generate: false })` takes 2,693 ms on the 8,735 of them it accepts. For all the warnings, on the same projects, svelte's tests and the corpus, it gives the warnings `compile` gives for all 13,097 components both accept, 1,344 warnings. For the warnings besides `css_unused_selector`, on the same projects, svelte's tests, carbon-components-svelte and the corpus, it gives the warnings `compile` gives for all 15,090 components both accept with their `svelte-ignore` comments removed, 602 warnings, and for all 12,119 that compile with `<svelte:options runes>` added, 1,295 warnings. On svelte's tests, carbon-components-svelte, bits-ui, shadcn-svelte, skeleton, flowbite-svelte, svelte.dev, immich, SvelteKit, melt-ui, layerchart and paneforge, it gives the warnings `compile` gives for all 14,208 components both accept, 1,516 warnings with the static `class` and `id` attributes removed from the markup. A differential fuzzer (`scripts/fuzz-css.ts`) found no difference on 166,000 more components.
536
+
537
+ ### `createLocator(source) => (offset) => Position`
538
+
539
+ A function from an offset to its `{ line, column }`, line from 1 and column from 0, as `loc: true` gives them: for a tool that parses without `loc`, which is faster, and needs lines only for what it reports. Lines are found on the first call, and each lookup starts its search at the line found last, so lookups in source order are fastest. Lines end at `\n`, as in the markup's `loc` and `ParseError`; acorn's `loc` in scripts and modules also ends them at a lone `\r`, U+2028 and U+2029. `parse` drops a leading byte order mark, so pass the source without one.
540
+
541
+ ```ts
542
+ import { createLocator, parse, walk } from "svelte-ast";
543
+
544
+ const locate = createLocator(source);
545
+ walk(parse(source), {
546
+ enter(node) {
547
+ if (node.type === "Component") console.log(node.name, locate(node.start).line);
548
+ },
549
+ });
550
+ ```
551
+
552
+ `locate(source, offset)` gives the same `{ line, column }` without keeping a locator: it keeps the lines of the last 64 sources it was called with, so a tool that reports nodes from many files, in any order, looks lines up once per file rather than scanning each from the start.
553
+
554
+ ```ts
555
+ import { locate } from "svelte-ast";
556
+
557
+ `${file}:${locate(source, node.start).line}`;
558
+ ```
559
+
560
+ ### Types
561
+
562
+ `AST` is svelte's `AST` namespace (`AST.Root`, `AST.RegularElement`, `AST.CSS.Rule`, ...), corrected to match what the parser returns: `name_loc` and a comment's `loc` are optional, `Root.instance`/`module` are absent rather than `null` when there's no such `<script>`, `Root.js` is declared, and every directive has `modifiers`. Each function's options and results are exported too, e.g. `ParseOptions` and `LexedStatement`.
563
+
564
+ The script's node types are exported as well (`Program`, `Node`, `Statement`, `Expression`, `Identifier`, ...), so you don't need a separate types package. They include `start`/`end` on every node, and the TypeScript nodes (`TSInterfaceDeclaration`, `TSTypeAnnotation`, ...; `TSNode` is their union) and fields (`typeAnnotation`, `typeParameters`, `returnType`, `importKind`, ...). The TypeScript nodes are in the `Statement`, `Declaration` and `Expression` unions, so checking `node.type` narrows to them. Where the grammar only allows a string, such as an import's `source`, the type is `StringLiteral`, a `Literal` whose `value` is a `string`.