Skip to content

Commit 5b31e1b

Browse files
1aronclaude
andcommitted
Fix(Source): Split Svelte and Vue script blocks only at real script tags
A `<script` inside a template expression, such as `{@html '<script>' + x}`, or inside another element's attribute value started a script block, so 2.0.4 parsed template text as JavaScript and failed the build. The splitter now skips Svelte `{…}` and Vue `{{ … }}` expressions (with their strings, template literals and comments) and other elements' opening tags. This also stops a `<script type="application/json">` string in `{@html}` from hiding the rest of the template as a data block. A component script block that still does not parse is read as text, as before 2.0.4, and its syntax error is left to the framework's compiler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f9d5433 commit 5b31e1b

8 files changed

Lines changed: 200 additions & 33 deletions

File tree

‎crates/mastercss-source/src/component_blocks.rs‎

Lines changed: 120 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// Locate the `<script>` and `<style>` blocks of a Svelte or Vue single-file component.
22
// Their templates are not HTML (attribute values may be `{expression}`), so only the
33
// block boundaries are read here: scripts are JavaScript, styles are not class sources,
4-
// and everything else stays template text.
4+
// and everything else stays template text. A `<script` inside a template expression,
5+
// an attribute value or a comment is text, not a block, as for the frameworks' parsers.
56
use std::ops::Range;
67

78
pub(super) enum ScriptLanguage {
@@ -18,12 +19,36 @@ pub(super) struct Block {
1819
pub script: Option<(Range<usize>, ScriptLanguage)>,
1920
}
2021

21-
pub(super) fn blocks(source: &str) -> Vec<Block> {
22+
/// The template syntax that decides where an expression starts and ends.
23+
#[derive(Clone, Copy, PartialEq, Eq)]
24+
pub(super) enum Template {
25+
/// `{expression}` in text and attribute values.
26+
Svelte,
27+
/// `{{ expression }}` in text; attribute values are quoted.
28+
Vue,
29+
}
30+
31+
pub(super) fn blocks(source: &str, template: Template) -> Vec<Block> {
2232
let bytes = source.as_bytes();
2333
let mut blocks = Vec::new();
2434
let mut cursor = 0;
25-
while let Some(offset) = source[cursor..].find('<') {
26-
let start = cursor + offset;
35+
while cursor < bytes.len() {
36+
let byte = bytes[cursor];
37+
let expression = match template {
38+
Template::Svelte if byte == b'{' => Some((cursor + 1, "}")),
39+
Template::Vue if bytes[cursor..].starts_with(b"{{") => Some((cursor + 2, "}}")),
40+
_ => None,
41+
};
42+
if let Some((from, close)) = expression {
43+
// An unclosed expression is left to the framework to report; read on as text.
44+
cursor = expression_end(source, from, close).unwrap_or(cursor + 1);
45+
continue;
46+
}
47+
if byte != b'<' {
48+
cursor += 1;
49+
continue;
50+
}
51+
let start = cursor;
2752
cursor = start + 1;
2853
if source[cursor..].starts_with("!--") {
2954
let Some(end) = source[cursor + 3..].find("-->") else {
@@ -32,17 +57,25 @@ pub(super) fn blocks(source: &str) -> Vec<Block> {
3257
cursor += 3 + end + 3;
3358
continue;
3459
}
35-
let Some(name) = ["script", "style"].into_iter().find(|name| {
60+
let name = ["script", "style"].into_iter().find(|name| {
3661
source
3762
.get(cursor..cursor + name.len())
3863
.is_some_and(|tag| tag.eq_ignore_ascii_case(name))
3964
&& bytes
4065
.get(cursor + name.len())
4166
.is_none_or(|b| b.is_ascii_whitespace() || matches!(b, b'>' | b'/'))
42-
}) else {
67+
});
68+
let Some(name) = name else {
69+
// Another element's attributes may hold `<script` in a value or expression.
70+
if bytes.get(cursor).is_some_and(u8::is_ascii_alphabetic) {
71+
match opening_tag_end(source, cursor, template) {
72+
Some(end) => cursor = end + 1,
73+
None => break,
74+
}
75+
}
4376
continue;
4477
};
45-
let Some(tag_end) = opening_tag_end(source, cursor + name.len()) else {
78+
let Some(tag_end) = opening_tag_end(source, cursor + name.len(), template) else {
4679
break;
4780
};
4881
let attributes = &source[cursor + name.len()..tag_end];
@@ -69,17 +102,93 @@ pub(super) fn blocks(source: &str) -> Vec<Block> {
69102
blocks
70103
}
71104

72-
/// The index of the `>` that ends an opening tag, skipping quoted attribute values.
73-
fn opening_tag_end(source: &str, from: usize) -> Option<usize> {
105+
/// The index after the `close` that ends a template expression starting at `from`,
106+
/// skipping nested braces, strings, template literals and comments.
107+
fn expression_end(source: &str, from: usize, close: &str) -> Option<usize> {
108+
let bytes = source.as_bytes();
109+
let mut depth = 0usize;
110+
let mut cursor = from;
111+
while cursor < bytes.len() {
112+
let byte = bytes[cursor];
113+
if depth == 0 && bytes[cursor..].starts_with(close.as_bytes()) {
114+
return Some(cursor + close.len());
115+
}
116+
match byte {
117+
b'{' => depth += 1,
118+
b'}' => depth = depth.checked_sub(1)?,
119+
b'\'' | b'"' => cursor = string_end(bytes, cursor + 1, byte)?,
120+
b'`' => cursor = template_literal_end(source, cursor + 1)?,
121+
b'/' if bytes.get(cursor + 1) == Some(&b'/') => {
122+
cursor = source[cursor..]
123+
.find('\n')
124+
.map_or(bytes.len(), |end| cursor + end);
125+
}
126+
b'/' if bytes.get(cursor + 1) == Some(&b'*') => {
127+
cursor = cursor + 2 + source[cursor + 2..].find("*/")? + 1;
128+
}
129+
_ => {}
130+
}
131+
cursor += 1;
132+
}
133+
None
134+
}
135+
136+
/// The index of the quote that closes a string whose body starts at `from`.
137+
fn string_end(bytes: &[u8], from: usize, quote: u8) -> Option<usize> {
138+
let mut cursor = from;
139+
while cursor < bytes.len() {
140+
match bytes[cursor] {
141+
b'\\' => cursor += 1,
142+
byte if byte == quote => return Some(cursor),
143+
b'\n' => return None,
144+
_ => {}
145+
}
146+
cursor += 1;
147+
}
148+
None
149+
}
150+
151+
/// The index of the backtick that closes a template literal whose body starts at `from`.
152+
fn template_literal_end(source: &str, from: usize) -> Option<usize> {
153+
let bytes = source.as_bytes();
154+
let mut cursor = from;
155+
while cursor < bytes.len() {
156+
match bytes[cursor] {
157+
b'\\' => cursor += 1,
158+
b'`' => return Some(cursor),
159+
b'$' if bytes.get(cursor + 1) == Some(&b'{') => {
160+
cursor = expression_end(source, cursor + 2, "}")? - 1;
161+
}
162+
_ => {}
163+
}
164+
cursor += 1;
165+
}
166+
None
167+
}
168+
169+
/// The index of the `>` that ends an opening tag, skipping quoted attribute values and,
170+
/// in Svelte, `{expression}` values, which may contain `>` and quotes.
171+
fn opening_tag_end(source: &str, from: usize, template: Template) -> Option<usize> {
172+
let bytes = source.as_bytes();
74173
let mut quote = None;
75-
for (index, byte) in source.bytes().enumerate().skip(from) {
174+
let mut cursor = from;
175+
while cursor < bytes.len() {
176+
let byte = bytes[cursor];
177+
if template == Template::Svelte
178+
&& byte == b'{'
179+
&& let Some(end) = expression_end(source, cursor + 1, "}")
180+
{
181+
cursor = end;
182+
continue;
183+
}
76184
match quote {
77185
Some(open) if byte == open => quote = None,
78186
Some(_) => {}
79187
None if matches!(byte, b'"' | b'\'') => quote = Some(byte),
80-
None if byte == b'>' => return Some(index),
188+
None if byte == b'>' => return Some(cursor),
81189
None => {}
82190
}
191+
cursor += 1;
83192
}
84193
None
85194
}

‎crates/mastercss-source/src/extraction.rs‎

Lines changed: 67 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -88,23 +88,29 @@ fn extract(input: &SourceExtractionInputIr) -> SourceExtractionIr {
8888
}
8989

9090
impl Collector<'_> {
91-
/// Svelte and Vue components: each JavaScript block through Oxc like a module,
92-
/// styles skipped, and the template, whose syntax is not HTML, as text.
91+
/// Svelte and Vue components: each JavaScript block through Oxc like a module (or as
92+
/// text when it does not parse), styles skipped, and the template, whose syntax is not
93+
/// HTML, as text.
9394
fn component(&mut self, extension: &str) -> ExtractionResult {
9495
let input = self.input;
9596
let content = input.content.as_str();
9697
let mut cursor = 0;
97-
for block in crate::component_blocks::blocks(content) {
98+
use crate::component_blocks::{ScriptLanguage, Template};
99+
let template = if extension == "vue" {
100+
Template::Vue
101+
} else {
102+
Template::Svelte
103+
};
104+
for block in crate::component_blocks::blocks(content, template) {
98105
self.template_text(cursor..block.range.start);
99106
if let Some((body, language)) = block.script {
100-
use crate::component_blocks::ScriptLanguage;
101107
let source_type = match language {
102108
ScriptLanguage::JavaScript => SourceType::mjs(),
103109
ScriptLanguage::TypeScript => SourceType::ts(),
104110
ScriptLanguage::Jsx => SourceType::jsx(),
105111
ScriptLanguage::Tsx => SourceType::tsx(),
106112
};
107-
self.javascript_as(
113+
let parsed = self.javascript_as(
108114
&content[body.clone()],
109115
body.start,
110116
0,
@@ -114,7 +120,13 @@ impl Collector<'_> {
114120
"svelte-script"
115121
},
116122
Some(source_type),
117-
)?;
123+
);
124+
// The framework compiler reports its own script errors. Read a script that
125+
// does not parse as text, as before script blocks were parsed, instead of
126+
// failing the build over a block this reader may have cut wrongly.
127+
if parsed.is_err() {
128+
self.template_text(body);
129+
}
118130
}
119131
cursor = block.range.end;
120132
}
@@ -749,10 +761,56 @@ const tone = 'fg-red'
749761
assert!(!result.candidates.iter().any(|c| c == "grid.current"));
750762
assert!(!result.candidates.iter().any(|c| c == "defineProps<{"));
751763

752-
// An invalid script is a parse error, as for other JavaScript sources.
764+
// A script that does not parse is read as text; the framework reports the error.
753765
let result = extract("Broken.svelte", "<script>const x = 'p:1px' +</script>");
754-
assert!(result.candidates.is_empty());
755-
assert_eq!(result.diagnostics[0].code, ErrorCode::SourceParseError);
766+
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
767+
assert!(result.candidates.iter().any(|c| c == "p:1px"));
768+
}
769+
770+
#[test]
771+
fn component_script_tags_in_template_expressions_are_text() {
772+
let svelte = r#"<script lang="ts">
773+
const x = "a";
774+
</script>
775+
<div class="mb-lg">{@html '<script>' + x + '</scr' + 'ipt>'}</div>
776+
<p title="<script>" class="mt-xl">{`<script>${x}`}</p>
777+
<button onclick={() => count > 1 && go('<script>')} class="p-md">{x}</button>
778+
<!-- <script> -->
779+
<span class="hidden">好辦 { { a: '}', b: "中文" }.a } 中文</span>
780+
<script context="module">export const tone = 'fg-red'</script>
781+
"#;
782+
let result = extract("Page.svelte", svelte);
783+
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
784+
for candidate in ["mb-lg", "mt-xl", "p-md", "hidden", "fg-red"] {
785+
assert!(
786+
result.candidates.iter().any(|c| c == candidate),
787+
"{candidate}: {:?}",
788+
result.candidates
789+
);
790+
}
791+
let tone = result
792+
.occurrences
793+
.iter()
794+
.find(|occurrence| occurrence.candidate == "fg-red")
795+
.unwrap();
796+
assert_eq!(tone.extractor, "oxc");
797+
798+
let vue = r#"<template>
799+
<div class="mb-lg" :title="'<script>'">中文 {{ '<script>' + x }} 中文</div>
800+
</template>
801+
<script setup lang="ts">
802+
const tone = 'fg-red'
803+
</script>
804+
"#;
805+
let result = extract("Card.vue", vue);
806+
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
807+
assert!(result.candidates.iter().any(|c| c == "mb-lg"));
808+
let tone = result
809+
.occurrences
810+
.iter()
811+
.find(|occurrence| occurrence.candidate == "fg-red")
812+
.unwrap();
813+
assert_eq!(tone.extractor, "oxc");
756814
}
757815

758816
#[test]

‎site/content/guide/class-extraction/contract.cn.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ const className = `px-md r-md ${tones.destructive}`
7171

7272
这些例外适用于共享工作区源文件、外部内容或限定范围的裁剪根目录。相对路径规则与支持的形式见[扫描指令](/reference/directives/scanning)。
7373

74-
框架集成优先使用原始 MDX、Vue 和 Svelte 源文件,而不是再次扫描已编译的显示字符串。Vue 和 Svelte 组件文件的 `<script>` 块按 JavaScript 读取,因此与其他 JavaScript 源文件一样,只有字符串和模板字面量会提供候选项;`items.length` 这类属性访问不是类名。`<style>` 块不是类名来源。提取器的语言类型很重要:有意提供纯文本输入时可以使用 `kind: 'raw'`,但它不是源文件解析失败时的回退方案。
74+
框架集成优先使用原始 MDX、Vue 和 Svelte 源文件,而不是再次扫描已编译的显示字符串。Vue 和 Svelte 组件文件的 `<script>` 块按 JavaScript 读取,因此与其他 JavaScript 源文件一样,只有字符串和模板字面量会提供候选项;`items.length` 这类属性访问不是类名。只有组件自身顶层的 `<script>` 标签才会开启一个 script 块;写在模板表达式或属性值中的 `<script>` 是模板文本。无法按 JavaScript 或 TypeScript 解析的 script 块会改为按文本读取,语法错误交给框架的编译器报告。`<style>` 块不是类名来源。提取器的语言类型很重要:有意提供纯文本输入时可以使用 `kind: 'raw'`,但它不是源文件解析失败时的回退方案。
7575

7676
## Markdown 与 MDX \{#markdown-and-mdx\}
7777

‎site/content/guide/class-extraction/contract.ja.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ const className = `px-md r-md ${tones.destructive}`
7171

7272
これらの例外は、共有ワークスペースのソース、外部コンテンツ、範囲を限定したプルーニングのルートに使います。相対パスの規則と対応形式は[スキャンのディレクティブ](/reference/directives/scanning)を参照してください。
7373

74-
フレームワーク統合は、コンパイル済みの表示用文字列を再スキャンするより、元の MDX、Vue、Svelte ソースを優先します。Vue と Svelte のコンポーネントファイルでは `<script>` ブロックを JavaScript として読むため、ほかの JavaScript ソースと同じく、文字列とテンプレートリテラルだけが候補になります。`items.length` のようなプロパティアクセスはクラスではありません。`<style>` ブロックはクラスのソースになりません。抽出器の言語種別は重要です。意図的なプレーンテキスト入力には `kind: 'raw'` を使えますが、解析に失敗したソースのフォールバックではありません。
74+
フレームワーク統合は、コンパイル済みの表示用文字列を再スキャンするより、元の MDX、Vue、Svelte ソースを優先します。Vue と Svelte のコンポーネントファイルでは `<script>` ブロックを JavaScript として読むため、ほかの JavaScript ソースと同じく、文字列とテンプレートリテラルだけが候補になります。`items.length` のようなプロパティアクセスはクラスではありません。script ブロックを始めるのはコンポーネント自身のトップレベルの `<script>` タグだけです。テンプレート式や属性値に書かれた `<script>` はテンプレートのテキストです。JavaScript または TypeScript として解析できない script ブロックは代わりにテキストとして読み、構文エラーの報告はフレームワークのコンパイラーに任せます。`<style>` ブロックはクラスのソースになりません。抽出器の言語種別は重要です。意図的なプレーンテキスト入力には `kind: 'raw'` を使えますが、解析に失敗したソースのフォールバックではありません。
7575

7676
## Markdown と MDX \{#markdown-and-mdx\}
7777

‎site/content/guide/class-extraction/contract.ko.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ const className = `px-md r-md ${tones.destructive}`
7171

7272
이 예외는 공유 워크스페이스 소스, 외부 콘텐츠, 범위가 지정된 가지치기 루트에 사용합니다. 상대 경로 규칙과 지원 형식은 [스캔 지시문](/reference/directives/scanning)을 참고하세요.
7373

74-
프레임워크 통합은 컴파일된 표시 문자열을 다시 스캔하기보다 원본 MDX, Vue, Svelte 소스를 우선합니다. Vue와 Svelte 컴포넌트 파일의 `<script>` 블록은 JavaScript로 읽으므로, 다른 JavaScript 소스와 마찬가지로 문자열과 템플릿 리터럴만 후보를 제공합니다. `items.length` 같은 속성 접근은 클래스가 아닙니다. `<style>` 블록은 클래스 소스가 아닙니다. 추출기의 언어 종류는 중요합니다. 의도적인 일반 텍스트 입력에는 `kind: 'raw'`를 사용할 수 있지만 파싱에 실패한 소스의 폴백으로 사용해서는 안 됩니다.
74+
프레임워크 통합은 컴파일된 표시 문자열을 다시 스캔하기보다 원본 MDX, Vue, Svelte 소스를 우선합니다. Vue와 Svelte 컴포넌트 파일의 `<script>` 블록은 JavaScript로 읽으므로, 다른 JavaScript 소스와 마찬가지로 문자열과 템플릿 리터럴만 후보를 제공합니다. `items.length` 같은 속성 접근은 클래스가 아닙니다. script 블록을 시작하는 것은 컴포넌트 자체의 최상위 `<script>` 태그뿐입니다. 템플릿 표현식이나 속성 값에 쓰인 `<script>`는 템플릿 텍스트입니다. JavaScript나 TypeScript로 파싱할 수 없는 script 블록은 대신 텍스트로 읽고, 구문 오류 보고는 프레임워크 컴파일러에 맡깁니다. `<style>` 블록은 클래스 소스가 아닙니다. 추출기의 언어 종류는 중요합니다. 의도적인 일반 텍스트 입력에는 `kind: 'raw'`를 사용할 수 있지만 파싱에 실패한 소스의 폴백으로 사용해서는 안 됩니다.
7575

7676
## Markdown과 MDX \{#markdown-and-mdx\}
7777

‎site/content/guide/class-extraction/contract.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ Automatic discovery respects project and ancestor workspace `.gitignore` files,
7171

7272
Use these exceptions for shared workspace source, external content or a scoped pruning root. Their relative-path rules and supported forms belong to [Scanning directives](/reference/directives/scanning).
7373

74-
Framework integrations prefer original MDX, Vue and Svelte source to scanning compiled display strings a second time. Extraction reads the `<script>` blocks of Vue and Svelte component files as JavaScript, so only string and template literals there contribute candidates, as in other JavaScript sources; property access such as `items.length` is not a class. `<style>` blocks are not class sources. An extractor's language kind matters: intentional plain-text input can use `kind: 'raw'`, but that is not a fallback for a source that failed to parse.
74+
Framework integrations prefer original MDX, Vue and Svelte source to scanning compiled display strings a second time. Extraction reads the `<script>` blocks of Vue and Svelte component files as JavaScript, so only string and template literals there contribute candidates, as in other JavaScript sources; property access such as `items.length` is not a class. Only a component's own top-level `<script>` tags start a script block; `<script>` written in a template expression or attribute value is template text. A script block that does not parse as JavaScript or TypeScript is read as text instead, leaving the syntax error to the framework's compiler. `<style>` blocks are not class sources. An extractor's language kind matters: intentional plain-text input can use `kind: 'raw'`, but that is not a fallback for a source that failed to parse.
7575

7676
## Markdown and MDX \{#markdown-and-mdx\}
7777

0 commit comments

Comments
 (0)