vize_atelier_sfc 0.7.0

Atelier SFC - The Single File Component workshop for Vize
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Props and emit type extraction utilities.
//!
//! This module handles extracting prop types from TypeScript type definitions
//! and processing withDefaults defaults.

use std::collections::HashMap;

/// Prop type information
#[derive(Debug, Clone)]
pub struct PropTypeInfo {
    /// JavaScript type constructor name (String, Number, Boolean, Array, Object, Function)
    pub js_type: String,
    /// Original TypeScript type (for PropType<T> usage)
    pub ts_type: Option<String>,
    /// Whether the prop is optional
    pub optional: bool,
}

/// Strip TypeScript comments from source while preserving string literals.
fn strip_ts_comments(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0;
    let mut in_string = false;
    let mut string_char = b'"';

    while i < bytes.len() {
        if in_string {
            if bytes[i] == string_char && (i == 0 || bytes[i - 1] != b'\\') {
                in_string = false;
            }
            result.push(bytes[i] as char);
            i += 1;
            continue;
        }

        match bytes[i] {
            b'\'' | b'"' | b'`' => {
                in_string = true;
                string_char = bytes[i];
                result.push(bytes[i] as char);
                i += 1;
            }
            b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'/' => {
                // Line comment: skip until newline
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => {
                // Block comment: skip until */
                i += 2;
                while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                    i += 1;
                }
                if i + 1 < bytes.len() {
                    i += 2; // skip */
                }
            }
            _ => {
                result.push(bytes[i] as char);
                i += 1;
            }
        }
    }
    result
}

/// Extract prop types from TypeScript type definition.
/// Returns a Vec to preserve definition order (important for matching Vue's output).
pub fn extract_prop_types_from_type(type_args: &str) -> Vec<(String, PropTypeInfo)> {
    let mut props = Vec::new();

    // Strip comments before parsing
    let stripped = strip_ts_comments(type_args);
    let content = stripped.trim();
    let content = if content.starts_with('{') && content.ends_with('}') {
        &content[1..content.len() - 1]
    } else {
        content
    };

    // Split by commas/semicolons/newlines (but not inside nested braces)
    let mut depth: i32 = 0;
    let mut current = String::new();
    let chars: Vec<char> = content.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let c = chars[i];
        match c {
            '{' | '<' | '(' | '[' => {
                depth += 1;
                current.push(c);
            }
            '}' | ')' | ']' => {
                if depth > 0 {
                    depth -= 1;
                }
                current.push(c);
            }
            '>' => {
                // Don't count `>` as closing angle bracket when preceded by `=` (arrow function `=>`)
                if i > 0 && chars[i - 1] == '=' {
                    current.push(c);
                } else {
                    if depth > 0 {
                        depth -= 1;
                    }
                    current.push(c);
                }
            }
            ',' | ';' | '\n' if depth <= 0 => {
                extract_prop_type_info(&current, &mut props);
                current.clear();
                depth = 0;
            }
            _ => current.push(c),
        }
        i += 1;
    }
    extract_prop_type_info(&current, &mut props);

    props
}

fn extract_prop_type_info(segment: &str, props: &mut Vec<(String, PropTypeInfo)>) {
    let trimmed = segment.trim();
    if trimmed.is_empty() {
        return;
    }

    // Parse "name?: Type" or "name: Type"
    if let Some(colon_pos) = trimmed.find(':') {
        let name_part = &trimmed[..colon_pos];
        let type_part = &trimmed[colon_pos + 1..];

        let optional = name_part.ends_with('?');
        let name = name_part.trim().trim_end_matches('?').trim();

        if !name.is_empty() && is_valid_identifier(name) {
            let ts_type_str = type_part.trim().to_string();
            let js_type = ts_type_to_js_type(&ts_type_str);
            // Avoid duplicates (intersection types may have overlapping props)
            if !props.iter().any(|(n, _)| n == name) {
                props.push((
                    name.to_string(),
                    PropTypeInfo {
                        js_type,
                        ts_type: Some(ts_type_str),
                        optional,
                    },
                ));
            }
        }
    }
}

/// Convert TypeScript type to JavaScript type constructor
fn ts_type_to_js_type(ts_type: &str) -> String {
    let ts_type = ts_type.trim();

    // Handle string literal types: "foo" or 'bar' -> String
    if (ts_type.starts_with('"') && ts_type.ends_with('"'))
        || (ts_type.starts_with('\'') && ts_type.ends_with('\''))
    {
        return "String".to_string();
    }

    // Handle numeric literal types: 123, 1.5 -> Number
    if ts_type.parse::<f64>().is_ok() {
        return "Number".to_string();
    }

    // Handle boolean literal types: true, false -> Boolean
    if ts_type == "true" || ts_type == "false" {
        return "Boolean".to_string();
    }

    // Handle union types - take the first non-undefined/null type
    if ts_type.contains('|') {
        let parts: Vec<&str> = ts_type.split('|').collect();
        for part in parts {
            let part = part.trim();
            if part != "undefined" && part != "null" {
                return ts_type_to_js_type(part);
            }
        }
    }

    // Map TypeScript types to JavaScript constructors
    match ts_type.to_lowercase().as_str() {
        "string" => "String".to_string(),
        "number" => "Number".to_string(),
        "boolean" => "Boolean".to_string(),
        "object" => "Object".to_string(),
        "function" => "Function".to_string(),
        "symbol" => "Symbol".to_string(),
        _ => {
            // Handle array types
            if ts_type.ends_with("[]") || ts_type.starts_with("Array<") {
                "Array".to_string()
            } else if ts_type.starts_with('{') || ts_type.contains(':') {
                // Object literal type
                "Object".to_string()
            } else if ts_type.starts_with('(') && ts_type.contains("=>") {
                // Function type
                "Function".to_string()
            } else {
                // Check if this is a built-in JavaScript constructor type
                let type_name = ts_type.split('<').next().unwrap_or(ts_type).trim();
                match type_name {
                    // Built-in JavaScript types that exist at runtime
                    "Date" | "RegExp" | "Error" | "Map" | "Set" | "WeakMap" | "WeakSet"
                    | "Promise" | "ArrayBuffer" | "DataView" | "Int8Array" | "Uint8Array"
                    | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array"
                    | "Float32Array" | "Float64Array" | "BigInt64Array" | "BigUint64Array"
                    | "URL" | "URLSearchParams" | "FormData" | "Blob" | "File" => {
                        type_name.to_string()
                    }
                    // User-defined interface/type or generic type parameter
                    // - Single uppercase letter (T, U, K, V) = generic param → null
                    // - Otherwise = user-defined type → null (types don't exist at runtime)
                    _ => "null".to_string(),
                }
            }
        }
    }
}

/// Extract emit names from TypeScript type definition
pub fn extract_emit_names_from_type(type_args: &str) -> Vec<String> {
    let mut emits = Vec::new();

    // Match patterns like: (e: 'eventName') or (event: 'eventName', ...)
    let mut in_string = false;
    let mut quote_char = ' ';
    let mut current_string = String::new();

    for c in type_args.chars() {
        if !in_string && (c == '\'' || c == '"') {
            in_string = true;
            quote_char = c;
            current_string.clear();
        } else if in_string && c == quote_char {
            in_string = false;
            if !current_string.is_empty() {
                emits.push(current_string.clone());
            }
        } else if in_string {
            current_string.push(c);
        }
    }

    emits
}

/// Extract default values from withDefaults second argument
/// Input: "withDefaults(defineProps<{...}>(), { prop1: default1, prop2: default2 })"
/// Returns: HashMap of prop name to default value string
pub fn extract_with_defaults_defaults(with_defaults_args: &str) -> HashMap<String, String> {
    let mut defaults = HashMap::new();

    // Find the second argument (the defaults object)
    // withDefaults(defineProps<...>(), { ... })
    // We need to find the { after "defineProps<...>()"

    let content = with_defaults_args.trim();
    let chars: Vec<char> = content.chars().collect();

    // First, find "defineProps" and then its closing parenthesis
    let define_props_pos = content.find("defineProps");
    if define_props_pos.is_none() {
        return defaults;
    }

    let start_search = define_props_pos.unwrap();
    let mut paren_depth = 0;
    let mut in_define_props_call = false;
    let mut found_define_props_end = false;
    let mut defaults_start = None;

    let mut i = start_search;
    while i < chars.len() {
        let c = chars[i];

        if !in_define_props_call {
            // Looking for the opening paren of defineProps()
            if c == '(' {
                in_define_props_call = true;
                paren_depth = 1;
            }
        } else if !found_define_props_end {
            match c {
                '(' => paren_depth += 1,
                ')' => {
                    paren_depth -= 1;
                    if paren_depth == 0 {
                        found_define_props_end = true;
                    }
                }
                _ => {}
            }
        } else {
            // Looking for the defaults object start
            if c == '{' {
                defaults_start = Some(i);
                break;
            }
        }
        i += 1;
    }

    if let Some(start) = defaults_start {
        // Find matching closing brace
        let mut brace_depth = 0;
        let mut end = start;

        for (j, &c) in chars.iter().enumerate().skip(start) {
            match c {
                '{' => brace_depth += 1,
                '}' => {
                    brace_depth -= 1;
                    if brace_depth == 0 {
                        end = j;
                        break;
                    }
                }
                _ => {}
            }
        }

        // Extract the defaults object content (without braces)
        let defaults_content: String = chars[start + 1..end].iter().collect();
        parse_defaults_object(&defaults_content, &mut defaults);
    }

    defaults
}

/// Parse a JavaScript object literal to extract key-value pairs
fn parse_defaults_object(content: &str, defaults: &mut HashMap<String, String>) {
    let content = content.trim();
    if content.is_empty() {
        return;
    }

    // Split by commas, but respect nested braces/parens/brackets
    let mut depth = 0;
    let mut current = String::new();

    for c in content.chars() {
        match c {
            '{' | '(' | '[' => {
                depth += 1;
                current.push(c);
            }
            '}' | ')' | ']' => {
                depth -= 1;
                current.push(c);
            }
            ',' if depth == 0 => {
                extract_default_pair(&current, defaults);
                current.clear();
            }
            _ => current.push(c),
        }
    }
    extract_default_pair(&current, defaults);
}

/// Extract a single key: value pair from a default definition
fn extract_default_pair(pair: &str, defaults: &mut HashMap<String, String>) {
    let trimmed = pair.trim();
    if trimmed.is_empty() {
        return;
    }

    // Find the first : that's not inside a nested structure
    let mut depth = 0;
    let mut colon_pos = None;

    for (i, c) in trimmed.chars().enumerate() {
        match c {
            '{' | '(' | '[' | '<' => depth += 1,
            '}' | ')' | ']' | '>' => depth -= 1,
            ':' if depth == 0 => {
                colon_pos = Some(i);
                break;
            }
            _ => {}
        }
    }

    if let Some(pos) = colon_pos {
        let key = trimmed[..pos].trim();
        let value = trimmed[pos + 1..].trim();

        if !key.is_empty() && !value.is_empty() {
            defaults.insert(key.to_string(), value.to_string());
        }
    }
}

/// Check if a string is a valid JS identifier
pub fn is_valid_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }

    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_alphabetic() || c == '_' || c == '$' => {}
        _ => return false,
    }

    chars.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}