diff --git a/tools/ui/node_modules/svelte-ast-print/LICENSE.md b/tools/ui/node_modules/svelte-ast-print/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..a05c7e1a8a0bc10b79daf63e7cd1cad159174365 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/LICENSE.md @@ -0,0 +1,19 @@ +# MIT License + +Copyright (c) 2024-present [these people](https://github.com/xeho91/svelte-ast-print/graphs/contributors) + +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. diff --git a/tools/ui/node_modules/svelte-ast-print/README.md b/tools/ui/node_modules/svelte-ast-print/README.md new file mode 100644 index 0000000000000000000000000000000000000000..55bed9c1673de83d4749bfd6ad4722c35071347f --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/README.md @@ -0,0 +1,248 @@ +# `svelte-ast-print` + +![NPM Version](https://img.shields.io/npm/v/svelte-ast-print?style=for-the-badge&logo=npm) + +Print **Svelte [AST]** nodes as a string.\ +A.k.a. [`parse`] in reverse. + +This is what you need to create [codemods] - e.g. for migration between Svelte versions syntaxes. + +## Documentation + + + +## Acknowledgements + +This package depends on: + +1. [`esrap`] for printing [ESTree] specification-compliant [AST] nodes +1. [`zimmerframe`] for walking on the [AST] nodes + +## Limitations + +> [!WARNING] +> **TypeScript isn't supported**, yet.\ +> See & subscribe to progress on [issue #86 - Add support for TypeScript](https://github.com/xeho91/svelte-ast-print/issues/86). + +--- + +> [!IMPORTANT] +> **It ignores any previous formatting**.\ +> The current focus is to be able to write codemods as soon as possible - because right now, there are no alternatives. +> +> If you need to format modified and stringified Svelte AST, use available formatters for Svelte: +> +> - [Biome](https://github.com/biomejs/biome) - _⚠️ has partial support_ +> - [Prettier](https://github.com/prettier/prettier) with [`prettier-plugin-svelte`](https://github.com/sveltejs/prettier-plugin-svelte) +> +> See [Formatting](#formatting) section for examples. + +--- + +> [!NOTE] +> **This package is in beta stage.**\ +> See [Roadmap](https://github.com/xeho91/svelte-ast-print/discussions/2) + +## Getting started + +1. Use the package manager of your choice to install this package: + +
+ npm + + ```sh + npm install svelte-ast-print + ``` + +
+ +
+ yarn + + ```sh + yarn add svelte-ast-print + ``` + +
+ +
+ pnpm + + ```sh + pnpm add svelte-ast-print + ``` + +
+ +
+ bun + + ```sh + bun add svelte-ast-print + ``` + +
+ +1. Incorporate it into your project, for example using Node.js and with the Svelte [`parse`] method: + + ```ts + import fs from "node:fs"; + + import { print } from "svelte-ast-print"; + import { parse } from "svelte/compiler"; + + const originalSvelteCode = fs.readFileSync("src/App.svelte", "utf-8"); + let svelteAST = parse(originalSvelteCode, { modern: true }); + // 👆 For now, only modern is supported. + // By default is 'false'. + // Is it planned to be 'true' from Svelte v6+ + + // ... + // Do some modifications on this AST... + // e.g. transform `` to `{@render children()}` + // ... + + const output = print(svelteAST); // AST is now a stringified code output! 🎉 + + fs.writeFileSync("src/App.svelte", output, { encoding: " utf-8" }); + ``` + +> [!IMPORTANT] +> When using [`parse`] from `svelte`, please remember about passing `modern: true` to options _(second argument)_. +> This option is only available starting `svelte@5`\ +> Example: +> +> ```js +> import { parse } from "svelte/compiler"; +> +> parse(code, { modern: true }); +> // 👆 Don't forget about this +> ``` +> +> You can omit it from Svelte `v6` - [source](https://github.com/sveltejs/svelte/blob/5a05f6371a994286626a44168cb2c02f8a2ad567/packages/svelte/src/compiler/index.js#L99-L100). + +--- + +## Formatting + +Until the package will support formatting feature option... below are the current and **simplified** workaround examples +on how to get printed output formatted to your needs. + +### Prettier + +Two dependencies are required: + +1. [`prettier`](https://github.com/prettier/prettier) +1. [`prettier-plugin-svelte`](https://github.com/sveltejs/prettier-plugin-svelte) + +Follow `prettier-plugin-svelte` [Setup guide](https://github.com/sveltejs/prettier-plugin-svelte?tab=readme-ov-file#setup) +on how to configure Prettier for Svelte. + +#### Using Prettier API + +```js +import { format } from "prettier"; +import { parse } from "svelte/compiler"; +import { print } from "svelte-ast-print"; + +let code = "..." // 👈 Raw Svelte code +let ast = parse(code, { modern: true }); +// 👆 Don't forget about this, you can omit in Svelte v6 + +// .. work with AST - transformations, etc. ... + +const output = print(ast); +const formatted = await format(output { + // Two ways to provide options: + + // 1. provide file path to prettier config + filepath: "path/to/your/prettier/config/file", + + // or.. + + // 2. See `prettier-plugin-svelte` Setup guide for more info + parser: "svelte", + plugins: ["svelte-plugin-prettier"] +}); +``` + +#### Using Prettier CLI + +... and Node.js API. + +```js +import fs from "node:fs"; +import childProcess from "node:child_process"; + +import { parse } from "svelte/compiler"; +import { print } from "svelte-ast-print"; + +const code = fs.readFileSync("./Button.svelte", "utf-8"); +let ast = parse(code, { modern: true }); +// 👆 Don't forget about this, you can omit in Svelte v6 + +// .. work with AST - transformations, etc. ... + +const output = print(ast); + +fs.writeFileSync("./Button.svelte", output, "utf-8"); +childProcess.spawnSync("prettier", ["./Button.svelte", "--write"], { + stdio: "inherit", + encoding: "utf-8", +}); +``` + +### Biome + +> [!WARNING] +> This sub-section is incomplete. Feel free to contribute! + +--- + +## Contributing + +Take a look at [contributing guide](./.github/CONTRIBUTING.md). + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. +**Contributions of any kind are welcome!** + +💌 to these people: + + + + + + + + + + +

Mateusz Kadlubowski

💻 🚧 📖 🚇 ⚠️

Manuel

📖

Jeppe Reinhold

💻
+ + + + + + +## Support + +If you don't have time, but you need this project to work, or resolve an existing issue, consider sponsorship. + +## Author + +Mateusz "[xeho91](https://github.com/xeho91)" Kadlubowski + +## License + +![Project License](https://img.shields.io/github/license/xeho91/svelte-ast-print?style=for-the-badge) + +This project is licensed under the [MIT License](./LICENSE.md). + + + +[`esrap`]: https://github.com/rich-harris/esrap +[`zimmerframe`]: https://github.com/rich-harris/zimmerframe +[ESTree]: https://github.com/estree/estree +[codemods]: https://codemod.com/blog/what-are-codemods#ill-find-replace-whats-the-issue-hint-a-lot +[`parse`]: https://svelte.dev/docs/svelte-compiler#parse +[AST]: https://en.wikipedia.org/wiki/Abstract_syntax_tree diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/LICENSE b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8c45e1bcded321a25e02eae65d8ece2e257c37d0 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2023 [these people](https://github.com/Rich-Harris/esrap/graphs/contributors) + +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. diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/README.md b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a9b1f6a976c55122f256b4c76f202b7ffc2d2d95 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/README.md @@ -0,0 +1,57 @@ +# esrap + +Parse in reverse. AST goes in, code comes out. + +## Usage + +```js +import { print } from 'esrap'; + +const { code, map } = print({ + type: 'Program', + body: [ + { + type: 'ExpressionStatement', + expression: { + callee: { + type: 'Identifier', + name: 'alert' + }, + arguments: [ + { + type: 'Literal', + value: 'hello world!' + } + ] + } + } + ] +}); + +console.log(code); // alert('hello world!'); +``` + +If the nodes of the input AST have `loc` properties (e.g. the AST was generated with [`acorn`](https://github.com/acornjs/acorn/tree/master/acorn/#interface) with the `locations` option set), sourcemap mappings will be created. + +## Options + +You can pass information that will be added to the resulting sourcemap (note that the AST is assumed to come from a single file): + +```js +const { code, map } = print(ast, { + sourceMapSource: 'input.js', + sourceMapContent: fs.readFileSync('input.js', 'utf-8') +}); +``` + +## Why not just use Prettier? + +Because it's ginormous. + +## Developing + +This repo uses [Bun](https://bun.sh/). Once it's installed, do `bun install` to install dependencies, and `bun test` to run the tests. + +## License + +[MIT](LICENSE) diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/package.json b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1e61613254e23635619a479731676cd90c95405c --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/package.json @@ -0,0 +1,39 @@ +{ + "name": "esrap", + "version": "1.2.2", + "description": "Parse in reverse", + "repository": { + "type": "git", + "url": "https://github.com/Rich-Harris/esrap" + }, + "type": "module", + "files": [ + "src", + "types" + ], + "exports": { + ".": { + "types": "./types/index.d.ts", + "default": "./src/index.js" + } + }, + "types": "./types/index.d.ts", + "devDependencies": { + "acorn": "^8.10.0", + "bun-types": "^1.0.9", + "dts-buddy": "^0.2.4", + "prettier": "^3.0.3", + "typescript": "^5.2.2", + "zimmerframe": "^1.0.0" + }, + "scripts": { + "check": "tsc", + "prepublishOnly": "bun test && dts-buddy", + "sandbox": "bun run test/sandbox/index.js" + }, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15", + "@types/estree": "^1.0.1" + } +} diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/handlers.js b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/handlers.js new file mode 100644 index 0000000000000000000000000000000000000000..b91fbe56f43cd989d7b36da425a36c0a35d7f0c8 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/handlers.js @@ -0,0 +1,1265 @@ +/** @type {import('./types').Newline} */ +const newline = { type: 'Newline' }; + +/** @type {import('./types').Indent} */ +const indent = { type: 'Indent' }; + +/** @type {import('./types').Dedent} */ +const dedent = { type: 'Dedent' }; + +/** + * @param {import('./types').Command[]} children + * @returns {import('./types').Sequence} + */ +function create_sequence(...children) { + return { type: 'Sequence', children }; +} + +/** + * Rough estimate of the combined width of a group of commands + * @param {import('./types').Command[]} commands + * @param {number} from + * @param {number} to + */ +function measure(commands, from, to = commands.length) { + let total = 0; + for (let i = from; i < to; i += 1) { + const command = commands[i]; + if (typeof command === 'string') { + total += command.length; + } else if (command.type === 'Chunk') { + total += command.content.length; + } else if (command.type === 'Sequence') { + // assume this is ', ' + total += 2; + } + } + + return total; +} + +/** + * @param {import('estree').Node} node + * @param {import('./types').State} state + */ +export function handle(node, state) { + const handler = handlers[node.type]; + + if (!handler) { + throw new Error(`Not implemented ${node.type}`); + } + + if (node.leadingComments) { + prepend_comments(node.leadingComments, state, false); + } + + // @ts-expect-error + handler(node, state); + + if (node.trailingComments) { + state.comments.push(node.trailingComments[0]); // there is only ever one + } +} + +/** + * @param {string} content + * @param {import('estree').Node} node + * @returns {import('./types').Chunk} + */ +function c(content, node) { + return { + type: 'Chunk', + content, + loc: node?.loc ?? null + }; +} + +/** + * @param {import('estree').Comment[]} comments + * @param {import('./types').State} state + * @param {boolean} newlines + */ +function prepend_comments(comments, state, newlines) { + for (const comment of comments) { + state.commands.push({ type: 'Comment', comment }); + + if (newlines || comment.type === 'Line' || /\n/.test(comment.value)) { + state.commands.push(newline); + } else { + state.commands.push(' '); + } + } +} + +const OPERATOR_PRECEDENCE = { + '||': 2, + '&&': 3, + '??': 4, + '|': 5, + '^': 6, + '&': 7, + '==': 8, + '!=': 8, + '===': 8, + '!==': 8, + '<': 9, + '>': 9, + '<=': 9, + '>=': 9, + in: 9, + instanceof: 9, + '<<': 10, + '>>': 10, + '>>>': 10, + '+': 11, + '-': 11, + '*': 12, + '%': 12, + '/': 12, + '**': 13 +}; + +/** @type {Record} */ +const EXPRESSIONS_PRECEDENCE = { + ArrayExpression: 20, + TaggedTemplateExpression: 20, + ThisExpression: 20, + Identifier: 20, + Literal: 18, + TemplateLiteral: 20, + Super: 20, + SequenceExpression: 20, + MemberExpression: 19, + MetaProperty: 19, + CallExpression: 19, + ChainExpression: 19, + ImportExpression: 19, + NewExpression: 19, + AwaitExpression: 17, + ClassExpression: 17, + FunctionExpression: 17, + ObjectExpression: 17, + UpdateExpression: 16, + UnaryExpression: 15, + BinaryExpression: 14, + LogicalExpression: 13, + ConditionalExpression: 4, + ArrowFunctionExpression: 3, + AssignmentExpression: 3, + YieldExpression: 2, + RestElement: 1 +}; + +/** + * + * @param {import('estree').Expression} node + * @param {import('estree').BinaryExpression | import('estree').LogicalExpression} parent + * @param {boolean} is_right + * @returns + */ +function needs_parens(node, parent, is_right) { + // special case where logical expressions and coalesce expressions cannot be mixed, + // either of them need to be wrapped with parentheses + if ( + node.type === 'LogicalExpression' && + parent.type === 'LogicalExpression' && + ((parent.operator === '??' && node.operator !== '??') || + (parent.operator !== '??' && node.operator === '??')) + ) { + return true; + } + + const precedence = EXPRESSIONS_PRECEDENCE[node.type]; + const parent_precedence = EXPRESSIONS_PRECEDENCE[parent.type]; + + if (precedence !== parent_precedence) { + // Different node types + return ( + (!is_right && precedence === 15 && parent_precedence === 14 && parent.operator === '**') || + precedence < parent_precedence + ); + } + + if (precedence !== 13 && precedence !== 14) { + // Not a `LogicalExpression` or `BinaryExpression` + return false; + } + + if ( + /** @type {import('estree').BinaryExpression} */ (node).operator === '**' && + parent.operator === '**' + ) { + // Exponentiation operator has right-to-left associativity + return !is_right; + } + + if (is_right) { + // Parenthesis are used if both operators have the same precedence + return ( + OPERATOR_PRECEDENCE[/** @type {import('estree').BinaryExpression} */ (node).operator] <= + OPERATOR_PRECEDENCE[parent.operator] + ); + } + + return ( + OPERATOR_PRECEDENCE[/** @type {import('estree').BinaryExpression} */ (node).operator] < + OPERATOR_PRECEDENCE[parent.operator] + ); +} + +/** @param {import('estree').Node} node */ +function has_call_expression(node) { + while (node) { + if (node.type === 'CallExpression') { + return true; + } else if (node.type === 'MemberExpression') { + node = node.object; + } else { + return false; + } + } +} + +const grouped_expression_types = [ + 'ImportDeclaration', + 'VariableDeclaration', + 'ExportDefaultDeclaration', + 'ExportNamedDeclaration' +]; + +/** + * @param {import('estree').Node[]} nodes + * @param {import('./types').State} state + */ +const handle_body = (nodes, state) => { + let last_statement = /** @type {import('estree').Node} */ ({ type: 'EmptyStatement' }); + let first = true; + let needs_margin = false; + + for (const statement of nodes) { + if (statement.type === 'EmptyStatement') continue; + + const margin = create_sequence(); + + if (!first) state.commands.push(margin, newline); + first = false; + + const leadingComments = statement.leadingComments; + delete statement.leadingComments; + + if (leadingComments && leadingComments.length > 0) { + prepend_comments(leadingComments, state, true); + } + + const child_state = { ...state, multiline: false }; + handle(statement, child_state); + + if ( + child_state.multiline || + needs_margin || + ((grouped_expression_types.includes(statement.type) || + grouped_expression_types.includes(last_statement.type)) && + last_statement.type !== statement.type) + ) { + margin.children.push('\n'); + } + + let add_newline = false; + + while (state.comments.length) { + const comment = /** @type {import('estree').Comment} */ (state.comments.shift()); + + state.commands.push(add_newline ? newline : ' ', { type: 'Comment', comment }); + add_newline = comment.type === 'Line'; + } + + needs_margin = child_state.multiline; + last_statement = statement; + } +}; + +/** + * @param {import('estree').VariableDeclaration} node + * @param {import('./types').State} state + */ +const handle_var_declaration = (node, state) => { + const index = state.commands.length; + + const open = create_sequence(); + const join = create_sequence(); + const child_state = { ...state, multiline: false }; + + state.commands.push(`${node.kind} `, open); + + let first = true; + + for (const d of node.declarations) { + if (!first) state.commands.push(join); + first = false; + + handle(d, child_state); + } + + const multiline = + child_state.multiline || (node.declarations.length > 1 && measure(state.commands, index) > 50); + + if (multiline) { + state.multiline = true; + if (node.declarations.length > 1) open.children.push(indent); + join.children.push(',', newline); + if (node.declarations.length > 1) state.commands.push(dedent); + } else { + join.children.push(', '); + } +}; + +/** + * @template {import('estree').Node} T + * @param {Array} nodes + * @param {import('./types').State} state + * @param {boolean} spaces + * @param {(node: T, state: import('./types').State) => void} fn + */ +function sequence(nodes, state, spaces, fn) { + if (nodes.length === 0) return; + + const index = state.commands.length; + + const open = create_sequence(); + const join = create_sequence(); + const close = create_sequence(); + + state.commands.push(open); + + const child_state = { ...state, multiline: false }; + + let prev; + + for (let i = 0; i < nodes.length; i += 1) { + const node = nodes[i]; + const is_first = i === 0; + const is_last = i === nodes.length - 1; + + if (node) { + if (!is_first && !prev) { + state.commands.push(join); + } + + fn(node, child_state); + + if (!is_last) { + state.commands.push(','); + } + + if (state.comments.length > 0) { + state.commands.push(' '); + + while (state.comments.length) { + const comment = /** @type {import('estree').Comment} */ (state.comments.shift()); + state.commands.push({ type: 'Comment', comment }); + if (!is_last) state.commands.push(join); + } + + child_state.multiline = true; + } else { + if (!is_last) state.commands.push(join); + } + } else { + // This is only used for ArrayPattern and ArrayExpression, but + // it makes more sense to have the logic here than there, because + // otherwise we'd duplicate a lot more stuff + state.commands.push(','); + } + + prev = node; + } + + state.commands.push(close); + + const multiline = child_state.multiline || measure(state.commands, index) > 50; + + if (multiline) { + state.multiline = true; + + open.children.push(indent, newline); + join.children.push(newline); + close.children.push(dedent, newline); + } else { + if (spaces) open.children.push(' '); + join.children.push(' '); + if (spaces) close.children.push(' '); + } +} + +/** @satisfies {Record undefined>} */ +const shared = { + /** + * @param {import('estree').ArrayExpression | import('estree').ArrayPattern} node + * @param {import('./types').State} state + */ + 'ArrayExpression|ArrayPattern': (node, state) => { + state.commands.push('['); + sequence(/** @type {import('estree').Node[]} */ (node.elements), state, false, handle); + state.commands.push(']'); + }, + + /** + * @param {import('estree').BinaryExpression | import('estree').LogicalExpression} node + * @param {import('./types').State} state + */ + 'BinaryExpression|LogicalExpression': (node, state) => { + // TODO + // const is_in = node.operator === 'in'; + // if (is_in) { + // // Avoids confusion in `for` loops initializers + // chunks.push(c('(')); + // } + + if (needs_parens(node.left, node, false)) { + state.commands.push('('); + handle(node.left, state); + state.commands.push(')'); + } else { + handle(node.left, state); + } + + state.commands.push(` ${node.operator} `); + + if (needs_parens(node.right, node, true)) { + state.commands.push('('); + handle(node.right, state); + state.commands.push(')'); + } else { + handle(node.right, state); + } + }, + + /** + * @param {import('estree').BlockStatement | import('estree').ClassBody} node + * @param {import('./types').State} state + */ + 'BlockStatement|ClassBody': (node, state) => { + if (node.body.length === 0) { + state.commands.push('{}'); + return; + } + + state.multiline = true; + + state.commands.push('{', indent, newline); + handle_body(node.body, state); + state.commands.push(dedent, newline, '}'); + }, + + /** + * @param {import('estree').CallExpression | import('estree').NewExpression} node + * @param {import('./types').State} state + */ + 'CallExpression|NewExpression': (node, state) => { + const index = state.commands.length; + + if (node.type === 'NewExpression') { + state.commands.push('new '); + } + + const needs_parens = + EXPRESSIONS_PRECEDENCE[node.callee.type] < EXPRESSIONS_PRECEDENCE.CallExpression || + (node.type === 'NewExpression' && has_call_expression(node.callee)); + + if (needs_parens) { + state.commands.push('('); + handle(node.callee, state); + state.commands.push(')'); + } else { + handle(node.callee, state); + } + + if (/** @type {import('estree').SimpleCallExpression} */ (node).optional) { + state.commands.push('?.'); + } + + const open = create_sequence(); + const join = create_sequence(); + const close = create_sequence(); + + state.commands.push('(', open); + + // if the final argument is multiline, it doesn't need to force all the + // other arguments to also be multiline + const child_state = { ...state, multiline: false }; + const final_state = { ...state, multiline: false }; + + for (let i = 0; i < node.arguments.length; i += 1) { + if (i > 0) { + if (state.comments.length > 0) { + state.commands.push(', '); + + while (state.comments.length) { + const comment = /** @type {import('estree').Comment} */ (state.comments.shift()); + + state.commands.push({ type: 'Comment', comment }); + + if (comment.type === 'Line') { + child_state.multiline = true; + state.commands.push(newline); + } else { + state.commands.push(' '); + } + } + } else { + state.commands.push(join); + } + } + + const p = node.arguments[i]; + + handle(p, i === node.arguments.length - 1 ? final_state : child_state); + } + + state.commands.push(close, ')'); + + const multiline = child_state.multiline; + + if (multiline || final_state.multiline) { + state.multiline = true; + } + + if (multiline) { + open.children.push(indent, newline); + join.children.push(',', newline); + close.children.push(dedent, newline); + } else { + join.children.push(', '); + } + }, + + /** + * @param {import('estree').ClassDeclaration | import('estree').ClassExpression} node + * @param {import('./types').State} state + */ + 'ClassDeclaration|ClassExpression': (node, state) => { + state.commands.push('class '); + + if (node.id) { + handle(node.id, state); + state.commands.push(' '); + } + + if (node.superClass) { + state.commands.push('extends '); + handle(node.superClass, state); + state.commands.push(' '); + } + + handle(node.body, state); + }, + + /** + * @param {import('estree').ForInStatement | import('estree').ForOfStatement} node + * @param {import('./types').State} state + */ + 'ForInStatement|ForOfStatement': (node, state) => { + state.commands.push('for '); + if (node.type === 'ForOfStatement' && node.await) state.commands.push('await '); + state.commands.push('('); + + if (node.left.type === 'VariableDeclaration') { + handle_var_declaration(node.left, state); + } else { + handle(node.left, state); + } + + state.commands.push(node.type === 'ForInStatement' ? ` in ` : ` of `); + handle(node.right, state); + state.commands.push(') '); + handle(node.body, state); + }, + + /** + * @param {import('estree').FunctionDeclaration | import('estree').FunctionExpression} node + * @param {import('./types').State} state + */ + 'FunctionDeclaration|FunctionExpression': (node, state) => { + if (node.async) state.commands.push('async '); + state.commands.push(node.generator ? 'function* ' : 'function '); + if (node.id) handle(node.id, state); + + state.commands.push('('); + sequence(node.params, state, false, handle); + state.commands.push(') '); + + handle(node.body, state); + }, + + /** + * @param {import('estree').RestElement | import('estree').SpreadElement} node + * @param {import('./types').State} state + */ + 'RestElement|SpreadElement': (node, state) => { + state.commands.push('...'); + handle(node.argument, state); + } +}; + +/** @type {import('./types').Handlers} */ +const handlers = { + ArrayExpression: shared['ArrayExpression|ArrayPattern'], + + ArrayPattern: shared['ArrayExpression|ArrayPattern'], + + ArrowFunctionExpression: (node, state) => { + if (node.async) state.commands.push('async '); + + state.commands.push('('); + sequence(node.params, state, false, handle); + state.commands.push(') => '); + + if ( + node.body.type === 'ObjectExpression' || + (node.body.type === 'AssignmentExpression' && node.body.left.type === 'ObjectPattern') || + (node.body.type === 'LogicalExpression' && node.body.left.type === 'ObjectExpression') || + (node.body.type === 'ConditionalExpression' && node.body.test.type === 'ObjectExpression') + ) { + state.commands.push('('); + handle(node.body, state); + state.commands.push(')'); + } else { + handle(node.body, state); + } + }, + + AssignmentExpression(node, state) { + handle(node.left, state); + state.commands.push(` ${node.operator} `); + handle(node.right, state); + }, + + AssignmentPattern(node, state) { + handle(node.left, state); + state.commands.push(' = '); + handle(node.right, state); + }, + + AwaitExpression(node, state) { + if (node.argument) { + const precedence = EXPRESSIONS_PRECEDENCE[node.argument.type]; + + if (precedence && precedence < EXPRESSIONS_PRECEDENCE.AwaitExpression) { + state.commands.push('await ('); + handle(node.argument, state); + state.commands.push(')'); + } else { + state.commands.push('await '); + handle(node.argument, state); + } + } else { + state.commands.push('await'); + } + }, + + BinaryExpression: shared['BinaryExpression|LogicalExpression'], + + BlockStatement: shared['BlockStatement|ClassBody'], + + BreakStatement(node, state) { + if (node.label) { + state.commands.push('break '); + handle(node.label, state); + state.commands.push(';'); + } else { + state.commands.push('break;'); + } + }, + + CallExpression: shared['CallExpression|NewExpression'], + + ChainExpression(node, state) { + handle(node.expression, state); + }, + + ClassBody: shared['BlockStatement|ClassBody'], + + ClassDeclaration: shared['ClassDeclaration|ClassExpression'], + + ClassExpression: shared['ClassDeclaration|ClassExpression'], + + ConditionalExpression(node, state) { + if (EXPRESSIONS_PRECEDENCE[node.test.type] > EXPRESSIONS_PRECEDENCE.ConditionalExpression) { + handle(node.test, state); + } else { + state.commands.push('('); + handle(node.test, state); + state.commands.push(')'); + } + + const if_true = create_sequence(); + const if_false = create_sequence(); + + const child_state = { ...state, multiline: false }; + + state.commands.push(if_true); + handle(node.consequent, child_state); + state.commands.push(if_false); + handle(node.alternate, child_state); + + const multiline = child_state.multiline; + + if (multiline) { + if_true.children.push(indent, newline, '? '); + if_false.children.push(newline, ': '); + state.commands.push(dedent); + } else { + if_true.children.push(' ? '); + if_false.children.push(' : '); + } + }, + + ContinueStatement(node, state) { + if (node.label) { + state.commands.push('continue '); + handle(node.label, state); + state.commands.push(';'); + } else { + state.commands.push('continue;'); + } + }, + + DebuggerStatement(node, state) { + state.commands.push(c('debugger', node), ';'); + }, + + DoWhileStatement(node, state) { + state.commands.push('do '); + handle(node.body, state); + state.commands.push(' while ('); + handle(node.test, state); + state.commands.push(');'); + }, + + EmptyStatement(node, state) { + state.commands.push(';'); + }, + + ExportAllDeclaration(node, state) { + state.commands.push('export * from '); + handle(node.source, state); + state.commands.push(';'); + }, + + ExportDefaultDeclaration(node, state) { + state.commands.push('export default '); + + handle(node.declaration, state); + + if (node.declaration.type !== 'FunctionDeclaration') { + state.commands.push(';'); + } + }, + + ExportNamedDeclaration(node, state) { + state.commands.push('export '); + + if (node.declaration) { + handle(node.declaration, state); + return; + } + + state.commands.push('{'); + sequence(node.specifiers, state, true, (s, state) => { + handle(s.local, state); + + if (s.local.name !== s.exported.name) { + state.commands.push(' as '); + handle(s.exported, state); + } + }); + state.commands.push('}'); + + if (node.source) { + state.commands.push(' from '); + handle(node.source, state); + } + + state.commands.push(';'); + }, + + ExpressionStatement(node, state) { + if ( + node.expression.type === 'AssignmentExpression' && + node.expression.left.type === 'ObjectPattern' + ) { + // is an AssignmentExpression to an ObjectPattern + state.commands.push('('); + handle(node.expression, state); + state.commands.push(');'); + return; + } + + handle(node.expression, state); + state.commands.push(';'); + }, + + ForStatement: (node, state) => { + state.commands.push('for ('); + + if (node.init) { + if (node.init.type === 'VariableDeclaration') { + handle_var_declaration(node.init, state); + } else { + handle(node.init, state); + } + } + + state.commands.push('; '); + if (node.test) handle(node.test, state); + state.commands.push('; '); + if (node.update) handle(node.update, state); + + state.commands.push(') '); + handle(node.body, state); + }, + + ForInStatement: shared['ForInStatement|ForOfStatement'], + + ForOfStatement: shared['ForInStatement|ForOfStatement'], + + FunctionDeclaration: shared['FunctionDeclaration|FunctionExpression'], + + FunctionExpression: shared['FunctionDeclaration|FunctionExpression'], + + Identifier(node, state) { + let name = node.name; + state.commands.push(c(name, node)); + }, + + IfStatement(node, state) { + state.commands.push('if ('); + handle(node.test, state); + state.commands.push(') '); + handle(node.consequent, state); + + if (node.alternate) { + state.commands.push(' else '); + handle(node.alternate, state); + } + }, + + ImportDeclaration(node, state) { + if (node.specifiers.length === 0) { + state.commands.push('import '); + handle(node.source, state); + state.commands.push(';'); + return; + } + + /** @type {import('estree').ImportNamespaceSpecifier | null} */ + let namespace_specifier = null; + + /** @type {import('estree').ImportDefaultSpecifier | null} */ + let default_specifier = null; + + /** @type {import('estree').ImportSpecifier[]} */ + const named_specifiers = []; + + for (const s of node.specifiers) { + if (s.type === 'ImportNamespaceSpecifier') { + namespace_specifier = s; + } else if (s.type === 'ImportDefaultSpecifier') { + default_specifier = s; + } else { + named_specifiers.push(s); + } + } + + state.commands.push('import '); + + if (default_specifier) { + state.commands.push(c(default_specifier.local.name, default_specifier)); + if (namespace_specifier || named_specifiers.length > 0) state.commands.push(', '); + } + + if (namespace_specifier) { + state.commands.push(c('* as ' + namespace_specifier.local.name, namespace_specifier)); + } + + if (named_specifiers.length > 0) { + state.commands.push('{'); + sequence(named_specifiers, state, true, (s, state) => { + if (s.local.name !== s.imported.name) { + handle(s.imported, state); + state.commands.push(' as '); + } + + handle(s.local, state); + }); + state.commands.push('}'); + } + + state.commands.push(' from '); + handle(node.source, state); + state.commands.push(';'); + }, + + ImportExpression(node, state) { + state.commands.push('import('); + handle(node.source, state); + state.commands.push(')'); + }, + + LabeledStatement(node, state) { + handle(node.label, state); + state.commands.push(': '); + handle(node.body, state); + }, + + Literal(node, state) { + // TODO do we need to handle weird unicode characters somehow? + // str.replace(/\\u(\d{4})/g, (m, n) => String.fromCharCode(+n)) + const value = + node.raw ?? + (typeof node.value === 'string' ? JSON.stringify(node.value) : String(node.value)); + + state.commands.push(c(value, node)); + }, + + LogicalExpression: shared['BinaryExpression|LogicalExpression'], + + MemberExpression(node, state) { + if (EXPRESSIONS_PRECEDENCE[node.object.type] < EXPRESSIONS_PRECEDENCE.MemberExpression) { + state.commands.push('('); + handle(node.object, state); + state.commands.push(')'); + } else { + handle(node.object, state); + } + + if (node.computed) { + if (node.optional) { + state.commands.push('?.'); + } + state.commands.push('['); + handle(node.property, state); + state.commands.push(']'); + } else { + state.commands.push(node.optional ? '?.' : '.'); + handle(node.property, state); + } + }, + + MetaProperty(node, state) { + handle(node.meta, state); + state.commands.push('.'); + handle(node.property, state); + }, + + MethodDefinition(node, state) { + if (node.static) { + state.commands.push('static '); + } + + if (node.kind === 'get' || node.kind === 'set') { + // Getter or setter + state.commands.push(node.kind + ' '); + } + + if (node.value.async) { + state.commands.push('async '); + } + + if (node.value.generator) { + state.commands.push('*'); + } + + if (node.computed) state.commands.push('['); + handle(node.key, state); + if (node.computed) state.commands.push(']'); + + state.commands.push('('); + sequence(node.value.params, state, false, handle); + state.commands.push(') '); + + handle(node.value.body, state); + }, + + NewExpression: shared['CallExpression|NewExpression'], + + ObjectExpression(node, state) { + state.commands.push('{'); + sequence(node.properties, state, true, (p, state) => { + if (p.type === 'Property' && p.value.type === 'FunctionExpression') { + const fn = /** @type {import('estree').FunctionExpression} */ (p.value); + + if (p.kind === 'get' || p.kind === 'set') { + state.commands.push(p.kind + ' '); + } else { + if (fn.async) state.commands.push('async '); + if (fn.generator) state.commands.push('*'); + } + + if (p.computed) state.commands.push('['); + handle(p.key, state); + if (p.computed) state.commands.push(']'); + + state.commands.push('('); + sequence(fn.params, state, false, handle); + state.commands.push(') '); + + handle(fn.body, state); + } else { + handle(p, state); + } + }); + state.commands.push('}'); + }, + + ObjectPattern(node, state) { + state.commands.push('{'); + sequence(node.properties, state, true, handle); + state.commands.push('}'); + }, + + // @ts-expect-error this isn't a real node type, but Acorn produces it + ParenthesizedExpression(node, state) { + return handle(node.expression, state); + }, + + PrivateIdentifier(node, state) { + state.commands.push('#', c(node.name, node)); + }, + + Program(node, state) { + handle_body(node.body, state); + }, + + Property(node, state) { + const value = node.value.type === 'AssignmentPattern' ? node.value.left : node.value; + + const shorthand = + !node.computed && + node.kind === 'init' && + node.key.type === 'Identifier' && + value.type === 'Identifier' && + node.key.name === value.name; + + if (shorthand) { + handle(node.value, state); + return; + } + + if (node.computed) state.commands.push('['); + handle(node.key, state); + state.commands.push(node.computed ? ']: ' : ': '); + handle(node.value, state); + }, + + PropertyDefinition(node, state) { + if (node.static) { + state.commands.push('static '); + } + + if (node.computed) { + state.commands.push('['); + handle(node.key, state); + state.commands.push(']'); + } else { + handle(node.key, state); + } + + if (node.value) { + state.commands.push(' = '); + + handle(node.value, state); + } + + state.commands.push(';'); + }, + + RestElement: shared['RestElement|SpreadElement'], + + ReturnStatement(node, state) { + if (node.argument) { + const contains_comment = + node.argument.leadingComments && + node.argument.leadingComments.some((comment) => comment.type === 'Line'); + + state.commands.push(contains_comment ? 'return (' : 'return '); + handle(node.argument, state); + state.commands.push(contains_comment ? ');' : ';'); + } else { + state.commands.push('return;'); + } + }, + + SequenceExpression(node, state) { + state.commands.push('('); + sequence(node.expressions, state, false, handle); + state.commands.push(')'); + }, + + SpreadElement: shared['RestElement|SpreadElement'], + + StaticBlock(node, state) { + state.commands.push(indent, 'static {', newline); + + handle_body(node.body, state); + + state.commands.push(dedent, newline, '}'); + }, + + Super(node, state) { + state.commands.push(c('super', node)); + }, + + SwitchStatement(node, state) { + state.commands.push('switch ('); + handle(node.discriminant, state); + state.commands.push(') {', indent); + + let first = true; + + for (const block of node.cases) { + if (!first) state.commands.push('\n'); + first = false; + + if (block.test) { + state.commands.push(newline, `case `); + handle(block.test, state); + state.commands.push(':'); + } else { + state.commands.push(newline, `default:`); + } + + state.commands.push(indent); + + for (const statement of block.consequent) { + state.commands.push(newline); + handle(statement, state); + } + + state.commands.push(dedent); + } + + state.commands.push(dedent, newline, `}`); + }, + + TaggedTemplateExpression(node, state) { + handle(node.tag, state); + handle(node.quasi, state); + }, + + TemplateLiteral(node, state) { + state.commands.push('`'); + + const { quasis, expressions } = node; + + for (let i = 0; i < expressions.length; i++) { + const raw = quasis[i].value.raw; + + state.commands.push(raw, '${'); + handle(expressions[i], state); + state.commands.push('}'); + + if (/\n/.test(raw)) state.multiline = true; + } + + const raw = quasis[quasis.length - 1].value.raw; + + state.commands.push(raw, '`'); + if (/\n/.test(raw)) state.multiline = true; + }, + + ThisExpression(node, state) { + state.commands.push(c('this', node)); + }, + + ThrowStatement(node, state) { + state.commands.push('throw '); + handle(node.argument, state); + state.commands.push(';'); + }, + + TryStatement(node, state) { + state.commands.push('try '); + handle(node.block, state); + + if (node.handler) { + if (node.handler.param) { + state.commands.push(' catch('); + handle(node.handler.param, state); + state.commands.push(') '); + } else { + state.commands.push(' catch '); + } + + handle(node.handler.body, state); + } + + if (node.finalizer) { + state.commands.push(' finally '); + handle(node.finalizer, state); + } + }, + + UnaryExpression(node, state) { + state.commands.push(node.operator); + + if (node.operator.length > 1) { + state.commands.push(' '); + } + + if (EXPRESSIONS_PRECEDENCE[node.argument.type] < EXPRESSIONS_PRECEDENCE.UnaryExpression) { + state.commands.push('('); + handle(node.argument, state); + state.commands.push(')'); + } else { + handle(node.argument, state); + } + }, + + UpdateExpression(node, state) { + if (node.prefix) { + state.commands.push(node.operator); + handle(node.argument, state); + } else { + handle(node.argument, state); + state.commands.push(node.operator); + } + }, + + VariableDeclaration(node, state) { + handle_var_declaration(node, state); + state.commands.push(';'); + }, + + VariableDeclarator(node, state) { + handle(node.id, state); + + if (node.init) { + state.commands.push(' = '); + handle(node.init, state); + } + }, + + WhileStatement(node, state) { + state.commands.push('while ('); + handle(node.test, state); + state.commands.push(') '); + handle(node.body, state); + }, + + WithStatement(node, state) { + state.commands.push('with ('); + handle(node.object, state); + state.commands.push(') '); + handle(node.body, state); + }, + + YieldExpression(node, state) { + if (node.argument) { + state.commands.push(node.delegate ? `yield* ` : `yield `); + handle(node.argument, state); + } else { + state.commands.push(node.delegate ? `yield*` : `yield`); + } + } +}; diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/index.js b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1fc17dbbb0d2c69497c97ab7a1991c9ec4f6a5f7 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/index.js @@ -0,0 +1,179 @@ +import { handle } from './handlers.js'; +import { encode } from '@jridgewell/sourcemap-codec'; + +/** @type {(str: string) => string} str */ +let btoa = () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); +}; + +if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + btoa = (str) => window.btoa(unescape(encodeURIComponent(str))); + // @ts-expect-error +} else if (typeof Buffer === 'function') { + // @ts-expect-error + btoa = (str) => Buffer.from(str, 'utf-8').toString('base64'); +} + +/** + * @typedef {{ + * sourceMapSource?: string; + * sourceMapContent?: string; + * sourceMapEncodeMappings?: boolean; // default true + * }} PrintOptions + */ + +/** + * @param {import('estree').Node} node + * @param {PrintOptions} opts + * @returns {{ code: string, map: any }} // TODO + */ +export function print(node, opts = {}) { + if (Array.isArray(node)) { + return print( + { + type: 'Program', + body: node, + sourceType: 'module' + }, + opts + ); + } + + /** @type {import('./types').State} */ + const state = { + commands: [], + comments: [], + multiline: false + }; + + handle(node, state); + + /** @typedef {[number, number, number, number]} Segment */ + + let code = ''; + let current_column = 0; + + /** @type {Segment[][]} */ + let mappings = []; + + /** @type {Segment[]} */ + let current_line = []; + + /** @param {string} str */ + function append(str) { + code += str; + + for (let i = 0; i < str.length; i += 1) { + if (str[i] === '\n') { + mappings.push(current_line); + current_line = []; + current_column = 0; + } else { + current_column += 1; + } + } + } + + let newline = '\n'; + + /** @param {import('./types').Command} command */ + function run(command) { + if (typeof command === 'string') { + append(command); + return; + } + + switch (command.type) { + case 'Chunk': + const loc = command.loc; + + if (loc) { + current_line.push([ + current_column, + 0, // source index is always zero + loc.start.line - 1, + loc.start.column + ]); + } + + append(command.content); + + if (loc) { + current_line.push([ + current_column, + 0, // source index is always zero + loc.end.line - 1, + loc.end.column + ]); + } + + break; + + case 'Newline': + append(newline); + break; + + case 'Indent': + newline += '\t'; + break; + + case 'Dedent': + newline = newline.slice(0, -1); + break; + + case 'Sequence': + for (let i = 0; i < command.children.length; i += 1) { + run(command.children[i]); + } + + break; + + case 'Comment': + if (command.comment.type === 'Line') { + append(`//${command.comment.value}`); + } else { + append(`/*${command.comment.value.replace(/\n/g, newline)}*/`); + } + + break; + } + } + + for (let i = 0; i < state.commands.length; i += 1) { + run(state.commands[i]); + } + + mappings.push(current_line); + + const map = { + version: 3, + /** @type {string[]} */ + names: [], + sources: [opts.sourceMapSource || null], + sourcesContent: [opts.sourceMapContent || null], + mappings: + opts.sourceMapEncodeMappings == undefined || opts.sourceMapEncodeMappings + ? encode(mappings) + : mappings + }; + + Object.defineProperties(map, { + toString: { + enumerable: false, + value: function toString() { + return JSON.stringify(this); + } + }, + toUrl: { + enumerable: false, + value: function toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); + } + } + }); + + return { + code, + map + }; +} diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/types.d.ts b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e7bc264f73fdf0d073eff0429cf5aa26d33c767 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/src/types.d.ts @@ -0,0 +1,53 @@ +import { Comment, Node } from 'estree'; + +type NodeOf = X extends { type: T } ? X : never; + +type Handler = (node: T, state: State) => undefined; + +export type Handlers = { + [K in Node['type']]: Handler>; +}; + +export interface State { + commands: Command[]; + comments: Comment[]; + multiline: boolean; +} + +export interface Chunk { + type: 'Chunk'; + content: string; + loc: null | { + start: { line: number; column: number }; + end: { line: number; column: number }; + }; +} + +export interface Newline { + type: 'Newline'; +} + +export interface Indent { + type: 'Indent'; +} + +export interface Dedent { + type: 'Dedent'; +} + +export interface IndentChange { + type: 'IndentChange'; + offset: number; +} + +export interface Sequence { + type: 'Sequence'; + children: Command[]; +} + +export interface CommentChunk { + type: 'Comment'; + comment: Comment; +} + +export type Command = string | Chunk | Newline | Indent | Dedent | Sequence | CommentChunk; diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/types/index.d.ts b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06f6b861d8e9d138334f970a6dd547fe9b7711c1 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/types/index.d.ts @@ -0,0 +1,16 @@ +declare module 'esrap' { + /** + * @returns // TODO + */ + export function print(node: import('estree').Node, opts?: PrintOptions): { + code: string; + map: any; + }; + export type PrintOptions = { + sourceMapSource?: string; + sourceMapContent?: string; + sourceMapEncodeMappings?: boolean; + }; +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/types/index.d.ts.map b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/types/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..4c5e3f26bc2e389740badf8bdb0b118fa66c89af --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/esrap/types/index.d.ts.map @@ -0,0 +1,14 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "print" + ], + "sources": [ + "../src/index.js" + ], + "sourcesContent": [ + null + ], + "mappings": ";;;;iBA6BgBA,KAAKA" +} \ No newline at end of file diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/LICENSE b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..de8796a3f3b5d29a458927dfd6892ab1c1b3468a --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 [these people](https://github.com/Rich-Harris/zimmerframe/graphs/contributors) + +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. diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/README.md b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/README.md new file mode 100644 index 0000000000000000000000000000000000000000..44ef2a83e3ceb0f841ca896fb1ec0c74b8a9d7c4 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/README.md @@ -0,0 +1,180 @@ +# zimmerframe + +A tool for walking. + +Specifically, it's a tool for walking an abstract syntax tree (AST), where every node is an object with a `type: string`. This includes [ESTree](https://github.com/estree/estree) nodes, such as you might generate with [Acorn](https://github.com/acornjs/acorn) or [Meriyah](https://github.com/meriyah/meriyah), but also includes things like [CSSTree](https://github.com/csstree/csstree) or an arbitrary AST of your own devising. + +## Usage + +```ts +import { walk } from 'zimmerframe'; +import { parse } from 'acorn'; +import { Node } from 'estree'; + +const program = parse(` +let message = 'hello'; +console.log(message); + +if (true) { + let answer = 42; + console.log(answer); +} +`); + +// You can pass in arbitrary state +const state = { + declarations: [], + depth: 0 +}; + +const transformed = walk(program as Node, state, { + _(node, { state, next }) { + // the `_` visitor is 'universal' — if provided, + // it will run for every node, before deferring + // to specialised visitors. you can pass a new + // `state` object to `next` + next({ ...state, answer: 42 }); + }, + VariableDeclarator(node, { state }) { + // `state` is passed into each visitor + if (node.id.type === 'Identifier') { + state.declarations.push({ + depth: state.depth, + name: node.id.name + }); + } + }, + BlockStatement(node, { state, next, stop }) { + // you must call `next()` or `next(childState)` + // to visit child nodes + console.log('entering BlockStatement'); + next({ ...state, depth: state.depth + 1 }); + console.log('leaving BlockStatement'); + }, + Literal(node) { + // if you return something, it will replace + // the current node + if (node.value === 'hello') { + return { + ...node, + value: 'goodbye' + }; + } + }, + IfStatement(node, { visit }) { + // normally, returning a value will halt + // traversal into child nodes. you can + // transform children with the current + // visitors using `visit(node, state?)` + if (node.test.type === 'Literal' && node.test.value === true) { + return visit(node.consequent); + } + } +}); +``` + +The `transformed` AST would look like this: + +```js +let message = 'goodbye'; +console.log(message); + +{ + let answer = 42; + console.log(answer); +} +``` + +## Types + +The type of `node` in each visitor is inferred from the visitor's name. For example: + +```ts +walk(ast as estree.Node, state, { + ArrowFunctionExpression(node) { + // `node` is of type estree.ArrowFunctionExpression + } +}); +``` + +For this to work, the first argument should be casted to an union of all the types you plan to visit. + +You can import types from 'zimmerframe': + +```ts +import { + walk, + type Visitor, + type Visitors, + type Context +} from 'zimmerframe'; +import type { Node } from 'estree'; + +interface State {...} + +const node: Node = {...}; +const state: State = {...}; +const visitors: Visitors = {...} + +walk(node, state, visitors); +``` + +## Context + +Each visitor receives a second argument, `context`, which is an object with the following properties and methods: + +- `next(state?: State): void` — a function that allows you to control when child nodes are visited, and which state they are visited with. If child visitors transform their inputs, this will return the transformed node (if not, returns `undefined`) +- `path: Node[]` — an array of parent nodes. For example, to get the root node you would do `path.at(0)`; to get the current node's immediate parent you would do `path.at(-1)` +- `state: State` — an object of the same type as the second argument to `walk`. Visitors can pass new state objects to their children with `next(childState)` or `visit(node, childState)` +- `stop(): void` — prevents any subsequent traversal +- `visit(node: Node, state?: State): Node` — returns the result of visiting `node` with the current set of visitors. If no `state` is provided, children will inherit the current state + +## Immutability + +ASTs are regarded as immutable. If you return a transformed node from a visitor, then all parents of the node will be replaced with clones, but unchanged subtrees will reuse the existing nodes. + +For example in this case, no transformation takes place, meaning that the returned value is identical to the original AST: + +```js +const transformed = walk(original, state, { + Literal(node) { + console.log(node.value); + } +}); + +transformed === original; // true +``` + +In this case, however, we replace one of the nodes: + +```js +const original = { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'foo' + }, + left: { + type: 'Identifier', + name: 'bar' + } +}; + +const transformed = walk(original, state, { + Identifier(node) { + if (node.name === 'bar') { + return { ...node, name: 'baz' }; + } + } +}); + +transformed === original; // false, the BinaryExpression node is cloned +transformed.left === original.left; // true, we can safely reuse this node +``` + +This makes it very easy to transform parts of your AST without incurring the performance and memory overhead of cloning the entire thing, and without the footgun of mutating it in place. + +## License + +MIT diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/package.json b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c679309cf4a0ee7bfcde15120b44b4dcc2a90565 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/package.json @@ -0,0 +1,34 @@ +{ + "name": "zimmerframe", + "description": "A tool for walking ASTs", + "version": "1.1.2", + "repository": { + "type": "git", + "url": "https://github.com/Rich-Harris/zimmerframe" + }, + "type": "module", + "exports": { + ".": { + "types": "./types/index.d.ts", + "import": "./src/walk.js" + } + }, + "types": "./types/index.d.ts", + "files": [ + "src", + "types" + ], + "devDependencies": { + "dts-buddy": "^0.1.13", + "typescript": "^5.1.6", + "vitest": "^0.34.2" + }, + "scripts": { + "prepublishOnly": "dts-buddy -m zimmerframe:src/index.d.ts", + "check": "tsc", + "test": "vitest --run", + "test:watch": "vitest" + }, + "license": "MIT", + "packageManager": "pnpm@8.6.12" +} diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/index.d.ts b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfa492b539c08398dea24e3e2e7c679788dda472 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/index.d.ts @@ -0,0 +1,2 @@ +export * from './walk.js'; +export * from './types.d.ts'; diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/types.d.ts b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73095274b4d846032036dbb4c3accd39b9e0783a --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/types.d.ts @@ -0,0 +1,21 @@ +type BaseNode = { type: string }; + +type NodeOf = X extends { type: T } ? X : never; + +type SpecialisedVisitors = { + [K in T['type']]?: Visitor, U, T>; +}; + +export type Visitor = (node: T, context: Context) => V | void; + +export type Visitors = T['type'] extends '_' + ? never + : SpecialisedVisitors & { _?: Visitor }; + +export interface Context { + next: (state?: U) => T | void; + path: T[]; + state: U; + stop: () => void; + visit: (node: T, state?: U) => T; +} diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/walk.js b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/walk.js new file mode 100644 index 0000000000000000000000000000000000000000..5a2fa7645fb27926e5a5e93f44cc0e74201d4a22 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/src/walk.js @@ -0,0 +1,159 @@ +/** + * @template {{type: string}} T + * @template {Record | null} U + * @param {T} node + * @param {U} state + * @param {import('./types').Visitors} visitors + */ +export function walk(node, state, visitors) { + const universal = visitors._; + + let stopped = false; + + /** @type {import('./types').Visitor} _ */ + function default_visitor(_, { next, state }) { + next(state); + } + + /** + * @param {T} node + * @param {T[]} path + * @param {U} state + * @returns {T | undefined} + */ + function visit(node, path, state) { + // Don't return the node here or it could lead to false-positive mutation detection + if (stopped) return; + if (!node.type) return; + + /** @type {T | void} */ + let result; + + /** @type {Record} */ + const mutations = {}; + + /** @type {import('./types').Context} */ + const context = { + path, + state, + next: (next_state = state) => { + path.push(node); + for (const key in node) { + if (key === 'type') continue; + + const child_node = node[key]; + if (child_node && typeof child_node === 'object') { + if (Array.isArray(child_node)) { + /** @type {Record} */ + const array_mutations = {}; + + child_node.forEach((node, i) => { + if (node && typeof node === 'object') { + const result = visit(node, path, next_state); + if (result) array_mutations[i] = result; + } + }); + + if (Object.keys(array_mutations).length > 0) { + mutations[key] = child_node.map( + (node, i) => array_mutations[i] ?? node + ); + } + } else { + const result = visit( + /** @type {T} */ (child_node), + path, + next_state + ); + + // @ts-ignore + if (result) { + mutations[key] = result; + } + } + } + } + path.pop(); + + if (Object.keys(mutations).length > 0) { + return apply_mutations(node, mutations); + } + }, + stop: () => { + stopped = true; + }, + visit: (next_node, next_state = state) => { + path.push(node); + const result = visit(next_node, path, next_state) ?? next_node; + path.pop(); + return result; + } + }; + + let visitor = /** @type {import('./types').Visitor} */ ( + visitors[/** @type {T['type']} */ (node.type)] ?? default_visitor + ); + + if (universal) { + /** @type {T | void} */ + let inner_result; + + result = universal(node, { + ...context, + /** @param {U} next_state */ + next: (next_state = state) => { + state = next_state; // make it the default for subsequent specialised visitors + + inner_result = visitor(node, { + ...context, + state: next_state + }); + + return inner_result; + } + }); + + // @ts-expect-error TypeScript doesn't understand that `context.next(...)` is called immediately + if (!result && inner_result) { + result = inner_result; + } + } else { + result = visitor(node, context); + } + + if (!result) { + if (Object.keys(mutations).length > 0) { + result = apply_mutations(node, mutations); + } + } + + if (result) { + return result; + } + } + + return visit(node, [], state) ?? node; +} + +/** + * @template {Record} T + * @param {T} node + * @param {Record} mutations + * @returns {T} + */ +function apply_mutations(node, mutations) { + /** @type {Record} */ + const obj = {}; + + const descriptors = Object.getOwnPropertyDescriptors(node); + + for (const key in descriptors) { + Object.defineProperty(obj, key, descriptors[key]); + } + + for (const key in mutations) { + obj[key] = mutations[key]; + } + + return /** @type {T} */ (obj); +} diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/types/index.d.ts b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c00a042312892df5fcedc59dc5ecf5851aef4cb2 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/types/index.d.ts @@ -0,0 +1,28 @@ +declare module 'zimmerframe' { + export function walk | null>(node: T, state: U, visitors: Visitors): T; + type BaseNode = { type: string }; + + type NodeOf = X extends { type: T } ? X : never; + + type SpecialisedVisitors = { + [K in T['type']]?: Visitor, U, T>; + }; + + export type Visitor = (node: T, context: Context) => V | void; + + export type Visitors = T['type'] extends '_' + ? never + : SpecialisedVisitors & { _?: Visitor }; + + export interface Context { + next: (state?: U) => T | void; + path: T[]; + state: U; + stop: () => void; + visit: (node: T, state?: U) => T; + } +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/types/index.d.ts.map b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/types/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8ffca7c4dbfbb54c48c5c05e7b0e4d79e739b377 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/node_modules/zimmerframe/types/index.d.ts.map @@ -0,0 +1,19 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "walk", + "Visitor", + "Visitors", + "Context" + ], + "sources": [ + "../src/walk.js", + "../src/types.d.ts" + ], + "sourcesContent": [ + null, + null + ], + "mappings": ";iBAOgBA,IAAIA;;;;;;;;;;;aCCRC,OAAOA;;aAEPC,QAAQA;;;;kBAIHC,OAAOA" +} \ No newline at end of file diff --git a/tools/ui/node_modules/svelte-ast-print/package.json b/tools/ui/node_modules/svelte-ast-print/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4fdfab3ee685ce4f6351d4aa9962311e72a9a8da --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/package.json @@ -0,0 +1,130 @@ +{ + "$schema": "https://json.schemastore.org/package", + "name": "svelte-ast-print", + "version": "0.4.2", + "type": "module", + "description": "Print Svelte AST nodes as a string. Aka parse in reverse.", + "keywords": [ + "svelte", + "ast", + "print" + ], + "license": "MIT", + "author": { + "name": "Mateusz Kadlubowski", + "email": "xeho91@pm.me", + "url": "https://github.com/xeho91" + }, + "homepage": "https://github.com/xeho91/svelte-ast-print", + "repository": { + "type": "git", + "url": "git+https://github.com/xeho91/svelte-ast-print.git" + }, + "bugs": "https://github.com/xeho91/svelte-ast-print/issues", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/xeho91" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/xeho91" + } + ], + "publishConfig": { + "access": "public", + "provenance": true + }, + "engines": { + "node": ">=18" + }, + "files": [ + "src/", + "types/" + ], + "imports": { + "#tests/*": { + "types": "./tests/*.ts", + "development": "./tests/*.ts" + }, + "#*": { + "types": "./src/*.js", + "development": "./src/*.js", + "default": "./src/*.js" + } + }, + "exports": { + ".": { + "types": "./types/mod.d.ts", + "default": "./src/mod.js" + }, + "./package.json": "./package.json" + }, + "types": "./types/mod.d.ts", + "packageManager": "pnpm@9.9.0+sha512.60c18acd138bff695d339be6ad13f7e936eea6745660d4cc4a776d5247c540d0edee1a563695c183a66eb917ef88f2b4feb1fc25f32a7adcadc7aaf3438e99c1", + "scripts": { + "build": "pnpm run \"/^build:.*/\" ", + "build:doc": "typedoc", + "build:types": "dts-buddy", + "clean": "pnpm run \"/^clean:.*/\"; rm -rf \"./**/node_modules\" ", + "clean:cache": "rm -rf \"./node_modules/.cache\" ", + "clean:doc": "rm -rf \"./docs\" ", + "clean:test": "rm -rf \"./coverage\" ", + "clean:types": "rm -rf \"./types\" ", + "dev": "pnpm run \"/^dev:.*/\" ", + "dev:doc": "typedoc --watch", + "dev:test": "pnpm vitest watch --passWithNoTests --ui", + "fix": "pnpm run \"/^fix:.*/\" ", + "fix:biome": "biome check . --verbose --write", + "fix:format": "biome format . --verbose --write", + "fix:js": "biome lint . --verbose --fix --unsafe", + "fix:md": "markdownlint-cli2 \"**/*.md\" \"#**/node_modules\" \"#./CHANGELOG.md\" --fix", + "fix:typos": "typos --verbose --write-changes", + "lint": "pnpm run \"/^lint:.*/\" ", + "lint:biome": "biome check . --verbose", + "lint:format": "biome format . --verbose", + "lint:js": "biome lint . --verbose", + "lint:md": "markdownlint-cli2 \"**/*.md\" \"#**/node_modules\" \"#./CHANGELOG.md\" ", + "lint:ts": "tsc --noEmit", + "lint:typos": "typos --verbose", + "prepare": "pnpm build:types", + "prepublishOnly": "pnpm test && pnpm build:types", + "release": "pnpm build:types && pnpm auto shipit", + "serve:doc": "serve \"./docs\" ", + "test": "vitest run . --passWithNoTests" + }, + "dependencies": { + "esrap": "1.2.2", + "zimmerframe": "1.1.2" + }, + "devDependencies": { + "@auto-it/all-contributors": "11.3.0", + "@auto-it/conventional-commits": "11.3.0", + "@auto-it/first-time-contributor": "11.3.0", + "@auto-it/npm": "11.3.0", + "@auto-it/released": "11.3.0", + "@biomejs/biome": "1.9.4", + "@total-typescript/ts-reset": "0.6.1", + "@total-typescript/tsconfig": "1.0.4", + "@types/estree": "1.0.6", + "@types/node": "22.8.4", + "@vitest/coverage-v8": "2.1.4", + "@vitest/ui": "2.1.4", + "all-contributors-cli": "6.26.1", + "auto": "11.3.0", + "dedent": "1.5.3", + "dts-buddy": "0.5.3", + "markdownlint-cli2": "0.14.0", + "serve": "14.2.4", + "svelte": "5.1.4", + "type-fest": "4.26.1", + "typedoc": "0.26.10", + "typedoc-plugin-coverage": "3.3.0", + "typedoc-plugin-mdn-links": "3.3.5", + "typescript": "5.6.3", + "vitest": "2.1.4" + }, + "peerDependencies": { + "svelte": "^5.0.0" + } +} diff --git a/tools/ui/node_modules/svelte-ast-print/src/mod.js b/tools/ui/node_modules/svelte-ast-print/src/mod.js new file mode 100644 index 0000000000000000000000000000000000000000..cffadab7c01807e5c0f5982b14df26b9d67b4278 --- /dev/null +++ b/tools/ui/node_modules/svelte-ast-print/src/mod.js @@ -0,0 +1,1587 @@ +/** + * @import * as EstreeAST from "estree"; + * @import { AST as SvelteAST } from "svelte/compiler"; + * @import { Context } from "zimmerframe"; + * + * @import { Node, SvelteNode } from "./nodes.js"; + */ + +import { print as print_es } from "esrap"; +import { walk } from "zimmerframe"; + +import { is_attribute_like_node, is_element_like_node, is_svelte_node } from "./nodes.js"; +import { Options } from "./options.js"; + +export { + is_attribute_like_node as isAttributeLikeNode, + is_block_node as isBlockNode, + is_css_node as isCssNode, + is_element_like_node as isElementLikeNode, + is_html_node as isHtmlNode, + is_svelte_node as isSvelteNode, + is_tag_node as isTagNode, + is_template_node as isTemplateNode, +} from "./nodes.js"; + +/** + * Print AST {@link SvelteAST.BaseNode} as a string. + * Aka parse in reverse. + * + * ## How does it work under the hood? + * + * 1. Firstly, it determines whether the provided AST node is unique node for Svelte {@link SvelteAST.Node}. + * 2. Based on type check guard from above: + * - it uses either this package's {@link Printer} to print Svelte AST node, + * - otherwise it uses `esrap` {@link print_es} to print ESTree specification-complaint AST node + * + * ## How to use it? + * + * @example writing a codemode using Node.js + ```js + import fs from "node:fs"; + + import { print } from "svelte-ast-print"; + import { parse } from "svelte/compiler"; + + const originalSvelteCode = fs.readFileSync("src/App.svelte", "utf-8"); + let svelteAST = parse(originalSvelteCode, { modern: true }); + // 👆 For now, only modern is supported. + // By default is 'false'. + // Is it planned to be 'true' from Svelte v6+ + + // ... + // Do some modifications on this AST... + // e.g. transform `` to `{@render children()}` + // ... + + const output = print(svelteAST); // AST is now a stringified code output! 🎉 + + fs.writeFileSync("src/App.svelte", output, { encoding: " utf-8" }); + ``` + * + * @param {Node} node - Svelte or ESTree AST node + * @param {Partial[0]>} options - printing options + * @returns {string} Stringified Svelte AST node + * TODO: Ask Svelte maintainers if `Script` and `SvelteOptions` were omittted from `SvelteNode` intentionally - possibly forgotten to include + */ +export function print(node, options = {}) { + if (is_svelte_node(node)) { + return new Printer(node, new Options(options)).toString(); + } + + return print_es(node).code; +} + +class Printer { + /** + * @type {SvelteNode} + */ + #node; + /** + * @type {Options} + */ + #options; + + /** + * @type {number} + */ + #depth = 0; + /** + * @type {string} + */ + #output = ""; + /** + * @type {Set} + */ + #attributes = new Set(); + /** + * @type {boolean} + */ + #has_template_literal = false; + + /** + * @param {Node} node - Svelte or ESTree AST node + * @param {Options} options - transformed options + */ + constructor(node, options) { + this.#node = node; + this.#options = options; + this.#produce(); + } + + /** + * @returns {string} + */ + toString() { + if (is_attribute_like_node(this.#node)) { + return this.#stringified_attributes; + } + return this.#output; + } + + /** + * @param {string} code + * @returns {void} + */ + #print(code) { + this.#output += code; + } + + /** + * @returns {void} + */ + #print_new_line() { + this.#output += "\n"; + } + + #print_opening_new_line() { + if (this.#is_last_output_script_closing_tag) { + this.#print_new_line(); + this.#print_new_line(); + } else if ( + this.#is_last_output_closing_block || + this.#is_last_output_closing_comment || + this.#is_last_output_opening_element_like || + this.#is_last_output_closing_element_like + ) { + this.#print_new_line(); + } + } + + /** + * @returns {void} + */ + #print_space() { + this.#output += " "; + } + + /** + * Depth aware indent + * @returns {string} + */ + get #indent() { + const { indent } = this.#options; + return Array(this.#depth).fill(indent).join(""); + } + + /** + * @returns {void} + */ + #print_indent() { + this.#output += this.#indent; + } + + get #stringified_attributes() { + // TODO: Determine what join should be, space or new line, based on options. + if (this.#attributes.size > 0) { + return [...this.#attributes].join(" "); + } + return ""; + } + + /** + * @typedef PrintEsNodeOptions + * @property {boolean} [skip_indent] + */ + + /** + * @param {Parameters[0]} node + * @param {Partial | undefined} options + * @returns {void} + */ + #print_es_node(node, options = {}) { + const { skip_indent = false } = options; + let { code } = print_es(node); + if (skip_indent) this.#output += code; + else { + code = code.replace(/^(?=.+)/gm, this.#indent); + this.#output += code.replace( + // NOTE: This temporary solution is supposed to remove auto-indentation from the content inside + // `TemplateLiteral`. + // Reference: https://github.com/storybookjs/addon-svelte-csf/issues/227 + /`[^`].*[^`]*`/g, + (match) => { + return match.replace(new RegExp(this.#indent, "g"), ""); + }, + ); + } + } + + /** + * By default we assume everything starts with an indent or new line + * @type {boolean} + */ + #was_last_text_indent_or_space_only = true; + + /** + * @param {SvelteAST.Text} node + * @returns {boolean} + */ + #is_text_new_line_or_indents_only(node) { + // TODO: Refactor, there's probably a smarter regex to achieve it + const { raw } = node; + if (raw === " ") return this.#was_last_text_indent_or_space_only; + if (this.#depth === 0) return /^(?: {1,}|\t|\n)*$/.test(raw); + return /^(?: {2,}|\t|\n)*$/.test(raw); + } + + /** + * @param {SvelteAST.Fragment} fragment + * @returns {boolean} + */ + #has_fragment_element_like_node(fragment) { + const { nodes } = fragment; + for (const node of nodes) { + if (is_element_like_node(node)) return true; + if (node.type === "Text" && this.#is_text_new_line_or_indents_only(node)) continue; + break; + } + return false; + } + + /** + * @param {SvelteAST.Fragment} fragment + * @returns {boolean} + */ + #is_fragment_empty(fragment) { + return fragment.nodes.length === 0; + } + + /** + * @param {"await" | "each" | "if" | "key" | "snippet"} name + * @param {string} content + * @returns {void} + */ + #print_block_opening_tag(name, content) { + this.#print_opening_new_line(); + this.#print_indent(); + this.#print("{"); + this.#print("#"); + this.#print(name); + this.#print_space(); + this.#print(content); + this.#print("}"); + } + + /** + * @param {"then" | "catch" | "else if" | "else"} name + * @param {string} [content] + * @returns {void} + */ + #print_block_middle_tag(name, content) { + this.#print_opening_new_line(); + if (this.#is_last_output_new_line) this.#print_indent(); + this.#print("{:"); + this.#print(name); + if (content) { + this.#print_space(); + this.#print(content); + } + this.#print("}"); + } + + /** + * @param {"await" | "each" | "if" | "key" | "snippet"} name + * @returns {void} + */ + #print_block_closing_tag(name) { + this.#print_new_line(); + this.#print_indent(); + this.#print("{/"); + this.#print(name); + this.#print("}"); + } + + /** + * @param {SvelteAST.Fragment} node + * @param {Context} context + * @returns {void} + */ + #print_block_fragment(node, context) { + const { visit } = context; + this.#print_new_line(); + this.#depth++; + visit(node, this); + if (this.#depth > 0) this.#depth--; + } + + /** + * @typedef PrintElementLikeOpeningTagOptions + * @property {boolean}[self_close] + */ + + /** + * @param {string} name + * @param {Partial} [options] + * @returns {void} + */ + #print_element_like_opening_tag(name, options = {}) { + const { self_close = false } = options; + this.#print_opening_new_line(); + if (this.#is_last_output_new_line) this.#print_indent(); + this.#print("<"); + this.#print(name); + if (this.#attributes.size > 0) { + this.#print_space(); + this.#print(this.#stringified_attributes); + this.#attributes.clear(); + } + if (self_close) { + if (!this.#is_last_output_new_line) this.#print_space(); + this.#print("/"); + } + this.#print(">"); + } + + /** + * @param {string} name + * @returns {void} + */ + #print_element_like_closing_tag(name) { + if (this.#is_last_output_closing_element_like || this.#is_last_output_closing_block) this.#print_new_line(); + if (this.#is_last_output_new_line) this.#print_indent(); + this.#print("<"); + this.#print("/"); + this.#print(name); + this.#print(">"); + } + + /** + * @param {SvelteAST.Fragment} node + * @param {Context} context + * @returns {void} + */ + #print_element_like_fragment(node, context) { + const { visit } = context; + if (this.#has_fragment_element_like_node(node)) this.#print_new_line(); + visit(node, this); + } + + /** + * @param {SvelteAST.ElementLike} node + * @param {Context} context + * @returns {void} + */ + #print_element_like(node, context) { + const { attributes, fragment, name } = node; + const { state, visit } = context; + const is_self_closing = this.#is_fragment_empty(fragment); + for (const attribute_like of attributes) { + visit(attribute_like, state); + } + this.#print_element_like_opening_tag(name, { self_close: is_self_closing }); + if (fragment && !is_self_closing) { + this.#depth++; + this.#print_element_like_fragment(fragment, context); + this.#depth--; + this.#print_element_like_closing_tag(name); + } + } + + /** + * @param {SvelteAST.ExpressionTag} node + * @returns {string} + */ + #serialize_expression_tag(node) { + const { expression } = node; + return `{${print_es(expression).code}}`; + } + + /** + * @param {SvelteAST.Text | SvelteAST.ExpressionTag} node + * @returns {string} + */ + #serialize_attribute_like_text_or_expression_tag(node) { + if (node.type === "Text") { + const { raw } = node; + return `"${raw}"`; + } + return this.#serialize_expression_tag(node); + } + + /** + * @typedef StringifyDirectiveParams + * @property {"animate" | "bind" | "class" | "let" | "on" | "style" | "in" | "out" | "transition" | "use"} directive + * @property {string} name + * @property {EstreeAST.Expression | EstreeAST.MemberExpression | null} expression + * @property {string[]} [modifiers] + */ + + /** + * @param {StringifyDirectiveParams["directive"]} directive + * @param {StringifyDirectiveParams["name"]} name + * @returns {string} + */ + #stringify_directive_name(directive, name) { + return `${directive}:${name}`; + } + + /** + * @param {NonNullable} modifiers + * @returns {string} + */ + #stringify_directive_modifiers(modifiers) { + let results = ""; + if (modifiers?.length > 0) { + results += "|"; + results += modifiers.join("|"); + } + return results; + } + + /** + * @param {StringifyDirectiveParams} params + * @returns {string} + */ + #stringify_directive(params) { + const { directive, name, expression, modifiers } = params; + const is_shorthand = expression?.type === "Identifier" && expression.name === name; + let results = this.#stringify_directive_name(directive, name); + if (modifiers) results += this.#stringify_directive_modifiers(modifiers); + if (!is_shorthand && expression) { + results += "="; + results += "{"; + results += print_es(expression).code; + results += "}"; + } + return results; + } + + /** + * @param {true | SvelteAST.ExpressionTag | (SvelteAST.Text | SvelteAST.ExpressionTag)[]} node + * @param {string} name + * @returns {boolean} + */ + #is_attribute_shorthand_expression_tag(node, name) { + if (node === true) return false; + if (Array.isArray(node)) { + if (!node[0]) return false; + if (node[0].type === "Text") return node[0].raw === name; + const { expression } = node[0]; + return expression.type === "Identifier" && expression.name === name; + } + const { expression } = node; + return expression.type === "Identifier" && expression.name === name; + } + + /** + * @returns {boolean} + */ + get #is_last_output_closing_block() { + return /\{\/\w*\}$$/.test(this.#output); + } + + /** + * @returns {boolean} + */ + get #is_last_output_opening_element_like() { + return /<(?!\/).*>$/s.test(this.#output); + } + + /** + * @returns {boolean} + */ + get #is_last_output_closing_element_like() { + return /(<\/[^>:]+(:[^>]+)?>|\/>)$/.test(this.#output); + } + + /** + * @returns {boolean} + */ + get #is_last_output_closing_comment() { + return /-->$/.test(this.#output); + } + + /** + * @returns {boolean} + */ + get #is_last_output_new_line() { + return /\n$/.test(this.#output); + } + + /** + * @returns {boolean} + */ + get #is_last_output_script_closing_tag() { + return /<\/script>$/.test(this.#output); + } + + /** + * @returns {void} + */ + #produce() { + walk(this.#node, this, { + _(_node, context) { + const { next, state } = context; + next(state); + }, + + Root(node, context) { + const { state, stop, visit } = context; + const { order } = state.#options; + for (const name of order) { + const root_node = node[name]; + if (name === "options" && node.options) { + // @ts-ignore FIXME: This is likely a bug - at runtime Svelte AST node `SvelteOptions` _(aliased as SvelteOptionsRaw)_ doesn't have 'type' & 'name' entry + visit({ ...node.options, type: "SvelteOptions", name: "svelte:options" }, state); + // @ts-ignore FIXME: Typing issue `SvelteOptions` and `SvelteOptionsRaw` are incompatible + } else if (root_node) visit(root_node, state); + } + // NOTE: There can't be anything next to Root + stop(); + }, + + Script(/** @type {SvelteAST.Script} */ node, context) { + const { attributes, content } = node; + const { state, visit } = context; + state.#print_opening_new_line(); + for (const attribute of attributes) { + visit(attribute, state); + } + state.#print_element_like_opening_tag("script"); + state.#print_new_line(); + state.#depth++; + state.#print_es_node(content); + state.#depth--; + state.#print_new_line(); + state.#print_element_like_closing_tag("script"); + }, + + Fragment(node, context) { + const { nodes } = node; + const { state, visit } = context; + for (const node of nodes) { + visit(node, state); + } + }, + + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Comment} + * + * @example pattern + * ```html + * + * ``` + */ + Comment(node, context) { + const { data } = node; + const { state } = context; + if (state.#is_last_output_script_closing_tag) { + state.#print_new_line(); + state.#print_new_line(); + } else if ( + state.#is_last_output_closing_block || + state.#is_last_output_closing_comment || + state.#is_last_output_closing_element_like + ) { + state.#print_new_line(); + } + if (state.#is_last_output_new_line) state.#print_indent(); + state.#print(""); + }, + + Text(node, context) { + const { raw } = node; + const { state } = context; + if (state.#is_text_new_line_or_indents_only(node)) { + state.#was_last_text_indent_or_space_only = true; + } else { + state.#was_last_text_indent_or_space_only = false; + state.#print(raw); + } + }, + + Attribute(node, context) { + const { name, value } = node; + const { state } = context; + const is_shorthand_expression_tag = state.#is_attribute_shorthand_expression_tag(value, name); + let stringified = ""; + if (!is_shorthand_expression_tag) stringified += name; + if (value !== true && Array.isArray(value)) { + if (!is_shorthand_expression_tag) stringified += "="; + const is_single_expression_tag = value.length === 1 && value[0].type === "ExpressionTag"; + if (!is_single_expression_tag) stringified += '"'; + for (const text_or_expression_tag of value) { + if (text_or_expression_tag.type === "Text") stringified += text_or_expression_tag.raw; + else stringified += state.#serialize_expression_tag(text_or_expression_tag); + } + if (!is_single_expression_tag) stringified += '"'; + } + // NOTE: This is e.g. `