Skip to content

chore: use parse from svelte/compiler #568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@
"esbuild"
]
}
}
}
29 changes: 21 additions & 8 deletions packages/addons/common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { imports, exports, common } from '@sveltejs/cli-core/js';
import { toSvelteFragment, type SvelteAst } from '@sveltejs/cli-core/html';
import { parseScript, parseSvelte } from '@sveltejs/cli-core/parsers';
import process from 'node:process';

Expand Down Expand Up @@ -64,17 +65,29 @@ export function addEslintConfigPrettier(content: string): string {
}

export function addToDemoPage(content: string, path: string): string {
const { template, generateCode } = parseSvelte(content);

for (const node of template.ast.childNodes) {
if (node.type === 'tag' && node.attribs['href'] === `/demo/${path}`) {
return content;
const { ast, generateCode } = parseSvelte(content);

for (const node of ast.fragment.nodes) {
if (node.type === 'RegularElement') {
const hrefAttribute = node.attributes.find(
(x) => x.type === 'Attribute' && x.name === 'href'
) as SvelteAst.Attribute;
if (!hrefAttribute || !hrefAttribute.value) continue;

if (!Array.isArray(hrefAttribute.value)) continue;

const hasDemo = hrefAttribute.value.find(
(x) => x.type === 'Text' && x.data === `/demo/${path}`
);
if (hasDemo) {
return content;
}
}
}

const newLine = template.source ? '\n' : '';
const src = template.source + `${newLine}<a href="/demo/${path}">${path}</a>`;
return generateCode({ template: src });
ast.fragment.nodes.push(...toSvelteFragment(`<a href="/demo/${path}">${path}</a>`));

return generateCode();
}

/**
Expand Down
49 changes: 27 additions & 22 deletions packages/addons/paraglide/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import MagicString from 'magic-string';
import { colors, defineAddon, defineAddonOptions, log } from '@sveltejs/cli-core';
import {
array,
Expand Down Expand Up @@ -187,38 +186,44 @@ export default defineAddon({

// add usage example
sv.file(`${kit.routesDirectory}/demo/paraglide/+page.svelte`, (content) => {
const { script, template, generateCode } = parseSvelte(content, { typescript });
console.log(content);
const { ast, generateCode } = parseSvelte(content);

let scriptAst = ast.instance?.content;
if (!scriptAst) {
scriptAst = parseScript('').ast;
ast.instance = {
type: 'Script',
start: 0,
end: 0,
context: 'default',
attributes: [],
content: scriptAst
};
}

imports.addNamed(script.ast, '$lib/paraglide/messages.js', { m: 'm' });
imports.addNamed(script.ast, '$app/navigation', { goto: 'goto' });
imports.addNamed(script.ast, '$app/state', { page: 'page' });
imports.addNamed(script.ast, '$lib/paraglide/runtime', {
imports.addNamed(scriptAst, '$lib/paraglide/messages.js', { m: 'm' });
imports.addNamed(scriptAst, '$lib/paraglide/runtime', {
setLocale: 'setLocale'
});

const scriptCode = new MagicString(script.generateCode());

const templateCode = new MagicString(template.source);

// add localized message
templateCode.append("\n\n<h1>{m.hello_world({ name: 'SvelteKit User' })}</h1>\n");
let templateCode = "<h1>{m.hello_world({ name: 'SvelteKit User' })}</h1>";

// add links to other localized pages, the first one is the default
// language, thus it does not require any localized route
const { validLanguageTags } = parseLanguageTagInput(options.languageTags);
const links = validLanguageTags
.map(
(x) =>
`${templateCode.getIndentString()}<button onclick={() => setLocale('${x}')}>${x}</button>`
)
.join('\n');
templateCode.append(`<div>\n${links}\n</div>`);

templateCode.append(
'<p>\nIf you use VSCode, install the <a href="https://marketplace.visualstudio.com/items?itemName=inlang.vs-code-extension" target="_blank">Sherlock i18n extension</a> for a better i18n experience.\n</p>'
);
.map((x) => `<button onclick={() => setLocale('${x}')}>${x}</button>`)
.join('');
templateCode += `<div>${links}</div>`;

return generateCode({ script: scriptCode.toString(), template: templateCode.toString() });
templateCode +=
'<p>If you use VSCode, install the <a href="https://marketplace.visualstudio.com/items?itemName=inlang.vs-code-extension" target="_blank">Sherlock i18n extension</a> for a better i18n experience.</p>';

ast.fragment.nodes.push(...html.toSvelteFragment(templateCode));

return generateCode();
});
}

Expand Down
4 changes: 3 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@
"picocolors": "^1.1.1",
"postcss": "^8.4.49",
"silver-fleece": "^1.2.1",
"zimmerframe": "^1.1.2"
"zimmerframe": "^1.1.2",
"svelte": "^5.30.2",
"svelte-ast-print": "^1.0.1"
},
"keywords": [
"create",
Expand Down
10 changes: 9 additions & 1 deletion packages/core/tooling/html/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { AST as SvelteAst } from 'svelte/compiler';
import {
type AstTypes,
type HtmlChildNode,
Expand All @@ -7,9 +8,10 @@ import {
parseHtml
} from '../index.ts';
import { addFromString } from '../js/common.ts';
import { parseSvelte } from '../parsers.ts';

export { HtmlElement, HtmlElementType };
export type { HtmlDocument };
export type { HtmlDocument, SvelteAst };

export function div(attributes: Record<string, string> = {}): HtmlElement {
return element('div', attributes);
Expand Down Expand Up @@ -53,3 +55,9 @@ export function addSlot(
addFromString(jsAst, 'let { children } = $props();');
addFromRawHtml(htmlAst.childNodes, '{@render children()}');
}

export function toSvelteFragment(content: string): SvelteAst.Fragment['nodes'] {
// TODO write test
const { ast } = parseSvelte(content);
return ast.fragment.nodes;
}
13 changes: 12 additions & 1 deletion packages/core/tooling/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import * as fleece from 'silver-fleece';
import { print as esrapPrint } from 'esrap';
import * as acorn from 'acorn';
import { tsPlugin } from '@sveltejs/acorn-typescript';
import { parse as svelteParse, type AST as SvelteAst } from 'svelte/compiler';
import { print as sveltePrint } from 'svelte-ast-print';

export {
// html
Expand All @@ -37,11 +39,12 @@ export {
export type {
// html
ChildNode as HtmlChildNode,
SvelteAst,

// js
TsEstree as AstTypes,

//css
// css
CssChildNode
};

Expand Down Expand Up @@ -240,3 +243,11 @@ export function guessQuoteStyle(ast: TsEstree.Node): 'single' | 'double' | undef

return singleCount > doubleCount ? 'single' : 'double';
}

export function parseSvelte(content: string): SvelteAst.Root {
return svelteParse(content, { modern: true });
}

export function serializeSvelte(ast: SvelteAst.Root): string {
return sveltePrint(ast).code;
}
134 changes: 5 additions & 129 deletions packages/core/tooling/parsers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as utils from './index.ts';
import MagicString from 'magic-string';

type ParseBase = {
source: string;
Expand Down Expand Up @@ -35,136 +34,13 @@ export function parseJson(source: string): { data: any } & ParseBase {
return { data, source, generateCode };
}

type SvelteGenerator = (code: {
script?: string;
module?: string;
css?: string;
template?: string;
}) => string;
export function parseSvelte(
source: string,
options?: { typescript?: boolean }
): {
script: ReturnType<typeof parseScript>;
module: ReturnType<typeof parseScript>;
css: ReturnType<typeof parseCss>;
template: ReturnType<typeof parseHtml>;
generateCode: SvelteGenerator;
} {
// `xTag` captures the whole tag block (ex: <script>...</script>)
// `xSource` is the contents within the tags
const scripts = extractScripts(source);
// instance block
const { tag: scriptTag = '', src: scriptSource = '' } =
scripts.find(({ attrs }) => !attrs.includes('module')) ?? {};
// module block
const { tag: moduleScriptTag = '', src: moduleSource = '' } =
scripts.find(({ attrs }) => attrs.includes('module')) ?? {};
// style block
const { styleTag, cssSource } = extractStyle(source);
// rest of the template
// TODO: needs more testing
const templateSource = source
.replace(moduleScriptTag, '')
.replace(scriptTag, '')
.replace(styleTag, '')
.trim();

const script = parseScript(scriptSource);
const module = parseScript(moduleSource);
const css = parseCss(cssSource);
const template = parseHtml(templateSource);

const generateCode: SvelteGenerator = (code) => {
const ms = new MagicString(source);
// TODO: this is imperfect and needs adjustments
if (code.script !== undefined) {
if (scriptSource.length === 0) {
const ts = options?.typescript ? ' lang="ts"' : '';
const indented = code.script.split('\n').join('\n\t');
const script = `<script${ts}>\n\t${indented}\n</script>\n\n`;
ms.prepend(script);
} else {
const { start, end } = locations(source, scriptSource);
const formatted = indent(code.script, ms.getIndentString());
ms.update(start, end, formatted);
}
}
if (code.module !== undefined) {
if (moduleSource.length === 0) {
const ts = options?.typescript ? ' lang="ts"' : '';
const indented = code.module.split('\n').join('\n\t');
// TODO: make a svelte 5 variant
const module = `<script${ts} context="module">\n\t${indented}\n</script>\n\n`;
ms.prepend(module);
} else {
const { start, end } = locations(source, moduleSource);
const formatted = indent(code.module, ms.getIndentString());
ms.update(start, end, formatted);
}
}
if (code.css !== undefined) {
if (cssSource.length === 0) {
const indented = code.css.split('\n').join('\n\t');
const style = `\n<style>\n\t${indented}\n</style>\n`;
ms.append(style);
} else {
const { start, end } = locations(source, cssSource);
const formatted = indent(code.css, ms.getIndentString());
ms.update(start, end, formatted);
}
}
if (code.template !== undefined) {
if (templateSource.length === 0) {
ms.appendLeft(0, code.template);
} else {
const { start, end } = locations(source, templateSource);
ms.update(start, end, code.template);
}
}
return ms.toString();
};
export function parseSvelte(source: string): { ast: utils.SvelteAst.Root } & ParseBase {
const ast = utils.parseSvelte(source);
const generateCode = () => utils.serializeSvelte(ast);

return {
script: { ...script, source: scriptSource },
module: { ...module, source: moduleSource },
css: { ...css, source: cssSource },
template: { ...template, source: templateSource },
ast,
source,
generateCode
};
}

function locations(source: string, search: string): { start: number; end: number } {
const start = source.indexOf(search);
const end = start + search.length;
return { start, end };
}

function indent(content: string, indent: string): string {
const indented = indent + content.split('\n').join(`\n${indent}`);
return `\n${indented}\n`;
}

// sourced from Svelte: https://github.com/sveltejs/svelte/blob/0d3d5a2a85c0f9eccb2c8dbbecc0532ec918b157/packages/svelte/src/compiler/preprocess/index.js#L253-L256
const regexScriptTags =
/<!--[^]*?-->|<script((?:\s+[^=>'"/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/\s]+)*\s*)(?:\/>|>([\S\s]*?)<\/script>)/;
const regexStyleTags =
/<!--[^]*?-->|<style((?:\s+[^=>'"/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/\s]+)*\s*)(?:\/>|>([\S\s]*?)<\/style>)/;

type Script = { tag: string; attrs: string; src: string };
function extractScripts(source: string): Script[] {
const scripts = [];
const [tag = '', attrs = '', src = ''] = regexScriptTags.exec(source) ?? [];
if (tag) {
const stripped = source.replace(tag, '');
scripts.push({ tag, attrs, src }, ...extractScripts(stripped));
return scripts;
}

return [];
}

function extractStyle(source: string) {
const [styleTag = '', attributes = '', cssSource = ''] = regexStyleTags.exec(source) ?? [];
return { styleTag, attributes, cssSource };
}
Loading
Loading