vize_atelier_sfc 0.19.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Tests for script compilation.

#[cfg(test)]
mod compile_script_tests {
    use crate::compile_script::compile_script;
    use crate::compile_script::function_mode::compile_script_setup;
    use crate::compile_script::props::{
        extract_prop_types_from_type, extract_with_defaults_defaults, is_valid_identifier,
    };
    use crate::compile_script::typescript::transform_typescript_to_js;
    use crate::types::SfcDescriptor;
    use vize_carton::ToCompactString;

    #[test]
    fn test_compile_empty_script() {
        let descriptor = SfcDescriptor::default();
        let result =
            compile_script(&descriptor, &Default::default(), "Test", false, false).unwrap();
        assert!(result.code.contains("__sfc__"));
    }

    #[test]
    fn test_is_valid_identifier() {
        assert!(is_valid_identifier("foo"));
        assert!(is_valid_identifier("_bar"));
        assert!(is_valid_identifier("$baz"));
        assert!(is_valid_identifier("foo123"));
        assert!(!is_valid_identifier("123foo"));
        assert!(!is_valid_identifier(""));
        assert!(!is_valid_identifier("foo-bar"));
    }

    #[test]
    fn test_extract_with_defaults_defaults() {
        // Test simple case
        let input = r#"withDefaults(defineProps<{ msg?: string }>(), { msg: "hello" })"#;
        let defaults = extract_with_defaults_defaults(input);
        eprintln!("Defaults: {:?}", defaults);
        assert_eq!(defaults.get("msg"), Some(&r#""hello""#.to_compact_string()));

        // Test multiple defaults
        let input2 = r#"withDefaults(defineProps<{ msg?: string, count?: number }>(), { msg: "hello", count: 42 })"#;
        let defaults2 = extract_with_defaults_defaults(input2);
        assert_eq!(
            defaults2.get("msg"),
            Some(&r#""hello""#.to_compact_string())
        );
        assert_eq!(defaults2.get("count"), Some(&"42".to_compact_string()));

        // Test multiline input like AfCheckbox
        let input3 = r#"withDefaults(
  defineProps<{
    checked: boolean;
    label?: string;
    color?: "primary" | "secondary";
  }>(),
  {
    label: undefined,
    color: "primary",
  },
)"#;
        let defaults3 = extract_with_defaults_defaults(input3);
        eprintln!("Defaults3: {:?}", defaults3);
        assert_eq!(
            defaults3.get("label"),
            Some(&"undefined".to_compact_string())
        );
        assert_eq!(
            defaults3.get("color"),
            Some(&r#""primary""#.to_compact_string())
        );
    }

    #[test]
    fn test_compile_script_setup_with_define_props() {
        let content = r#"
import { ref } from 'vue'
const props = defineProps(['msg'])
const count = ref(0)
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Compiled output:\n{}", result.code);

        // Should have __sfc__
        assert!(
            result.code.contains("const __sfc__ ="),
            "Should have __sfc__"
        );
        // Should have __name (may use single or double quotes after OXC formatting)
        assert!(
            result.code.contains("__name:") && result.code.contains("Test"),
            "Should have __name. Got:\n{}",
            result.code
        );
        // Should have props definition (may use double quotes after OXC formatting)
        assert!(
            result.code.contains("props:") && result.code.contains("msg"),
            "Should have props definition. Got:\n{}",
            result.code
        );
        // Should have setup function with proper signature
        assert!(
            result
                .code
                .contains("setup(__props, { expose: __expose, emit: __emit })"),
            "Should have proper setup signature"
        );
        // __expose is only called if defineExpose is used (not in this test)
        // Should have __returned__
        assert!(
            result.code.contains("const __returned__ =")
                || result.code.contains("__returned__ = {"),
            "Should have __returned__"
        );
    }

    #[test]
    fn test_type_only_imports_not_in_bindings() {
        let content = r#"
import type { AnalysisResult } from './wasm'
import type { Diagnostic } from './MonacoEditor.vue'
import { ref } from 'vue'

const analysisResult = ref<AnalysisResult | null>(null)
"#;
        let result = compile_script_setup(content, "Test", false, true, None).unwrap();
        let bindings = result.bindings.expect("bindings should be present");

        assert!(!bindings.bindings.contains_key("AnalysisResult"));
        assert!(!bindings.bindings.contains_key("Diagnostic"));
        assert!(bindings.bindings.contains_key("analysisResult"));
    }

    #[test]
    fn test_compile_script_setup_with_define_emits() {
        let content = r#"
const emit = defineEmits(['click', 'update'])
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Full output:\n{}", result.code);

        assert!(
            result.code.contains("emits:"),
            "Should contain emits definition"
        );
        assert!(
            result.code.contains("const emit = __emit"),
            "Should bind emit to __emit"
        );
        // emit should be in __returned__ as it's a runtime value used in templates
        assert!(
            result.code.contains("emit"),
            "emit should be accessible in template"
        );
        // defineEmits should NOT be in the setup function
        assert!(
            !result.code.contains("defineEmits"),
            "defineEmits should be removed from setup"
        );
    }

    #[test]
    fn test_compile_script_setup_with_define_emits_usage() {
        let content = r#"
import { ref } from 'vue'
const emit = defineEmits(['click', 'update'])
const count = ref(0)
function onClick() {
    emit('click', count.value)
}
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Compiled output:\n{}", result.code);

        // defineEmits call should NOT be in the setup function
        assert!(
            !result.code.contains("defineEmits"),
            "defineEmits call should be removed from setup"
        );
        // emit binding should be present
        assert!(
            result.code.contains("const emit = __emit"),
            "Should bind emit to __emit"
        );
        // onClick function should be in setup
        assert!(
            result.code.contains("function onClick()"),
            "onClick should be in setup"
        );
        // emits definition should be present (may be formatted differently by OXC)
        assert!(
            result.code.contains("emits:")
                && result.code.contains("click")
                && result.code.contains("update"),
            "Should have emits definition. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_compile_script_setup_without_macros() {
        let content = r#"
import { ref } from 'vue'
const msg = ref('hello')
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        // Should have setup
        assert!(result.code.contains("setup(__props"), "Should have setup");
        // Should NOT have props or emits definitions
        assert!(
            !result.code.contains("  props:"),
            "Should not contain props"
        );
        assert!(!result.code.contains("emits:"), "Should not contain emits");
    }

    #[test]
    fn test_compile_script_setup_with_props_destructure() {
        let content = r#"
import { computed } from 'vue'
const { count } = defineProps({ count: Number })
const double = computed(() => count * 2)
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Compiled output:\n{}", result.code);

        // Should transform count to __props.count inside computed
        assert!(
            result.code.contains("__props.count"),
            "Should transform destructured prop to __props.count"
        );
        // The original `count` reference should be replaced
        assert!(
            result.code.contains("computed(() => __props.count * 2)"),
            "Should have transformed computed expression"
        );
        // Destructured props should NOT be in __returned__
        assert!(
            !result.code.contains("__returned__ = { computed, count,"),
            "Destructured props should not be in __returned__"
        );
        // Should have double and computed in __returned__
        assert!(
            result.code.contains("computed") && result.code.contains("double"),
            "Should have computed and double in __returned__"
        );
    }

    #[test]
    fn test_compiler_macros_not_in_returned() {
        let content = r#"
import { defineProps, ref } from 'vue'
const props = defineProps(['msg'])
const count = ref(0)
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Compiled output:\n{}", result.code);

        // Find the __returned__ block (may span multiple lines after OXC formatting)
        let code = &result.code;
        let returned_start = code.find("__returned__").expect("Should have __returned__");
        let returned_block = &code[returned_start..];
        let block_end = returned_block.find(';').unwrap_or(returned_block.len());
        let returned_content = &returned_block[..block_end];

        println!("__returned__ block: {}", returned_content);

        // Compiler macros should NOT be in __returned__
        assert!(
            !returned_content.contains("defineProps"),
            "Compiler macros should not be in __returned__"
        );
        // But regular imports should be
        assert!(
            returned_content.contains("ref"),
            "Regular imports should be in __returned__"
        );
    }

    #[test]
    fn test_props_destructure_with_defaults() {
        let content = r#"
import { computed, watch } from 'vue'

const {
  name,
  count = 0,
  disabled = false,
  items = () => []
} = defineProps<{
  name: string
  count?: number
  disabled?: boolean
  items?: string[]
}>()

const doubled = computed(() => count * 2)
const itemCount = computed(() => items.length)
"#;

        // First check context analysis
        let mut ctx = crate::script::ScriptCompileContext::new(content);
        ctx.analyze();

        println!("=== Context Analysis ===");
        println!("props_destructure: {:?}", ctx.macros.props_destructure);
        println!("bindings: {:?}", ctx.bindings.bindings);

        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("\n=== Compiled output ===\n{}", result.code);

        // Should NOT contain the destructure statement
        assert!(
            !result.code.contains("const {"),
            "Should not contain destructure statement"
        );
        assert!(
            !result.code.contains("} = defineProps"),
            "Should not contain defineProps assignment"
        );

        // Should have props definition with defaults
        assert!(
            result.code.contains("props:"),
            "Should have props definition"
        );

        // Should transform props to __props
        assert!(
            result.code.contains("__props.count"),
            "Should transform count to __props.count"
        );
        assert!(
            result.code.contains("__props.items"),
            "Should transform items to __props.items"
        );

        // Should have the computed expressions transformed
        assert!(
            result.code.contains("computed(() => __props.count * 2)"),
            "Should transform count in computed. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_extract_prop_types() {
        let type_args = r#"{
  name: string
  count?: number
  disabled?: boolean
  items?: string[]
}"#;
        let props = extract_prop_types_from_type(type_args);
        let find = |name: &str| props.iter().find(|(n, _)| n == name).map(|(_, v)| v);
        assert!(find("name").is_some(), "Should extract name");
        assert!(find("count").is_some(), "Should extract count");
        assert!(find("disabled").is_some(), "Should extract disabled");
        assert!(find("items").is_some(), "Should extract items");

        // Check types
        assert_eq!(find("name").unwrap().js_type, "String");
        assert_eq!(find("count").unwrap().js_type, "Number");
        assert_eq!(find("disabled").unwrap().js_type, "Boolean");
        assert_eq!(find("items").unwrap().js_type, "Array");

        // Check optionality
        assert!(!find("name").unwrap().optional);
        assert!(find("count").unwrap().optional);
        assert!(find("disabled").unwrap().optional);
        assert!(find("items").unwrap().optional);
    }

    #[test]
    fn test_compile_script_setup_with_multiline_define_emits() {
        let content = r#"
const emit = defineEmits<{
  (e: 'click', payload: MouseEvent): void
  (e: 'update', value: string): void
}>()

function handleClick(e: MouseEvent) {
    emit('click', e)
}
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Multi-line defineEmits output:\n{}", result.code);

        // defineEmits should NOT be in the setup function
        assert!(
            !result.code.contains("defineEmits"),
            "defineEmits should be removed from setup"
        );
        // emit binding should be present
        assert!(
            result.code.contains("const emit = __emit"),
            "Should bind emit to __emit"
        );
        // handleClick function should be in setup
        assert!(
            result.code.contains("function handleClick"),
            "handleClick should be in setup"
        );
        // emits definition should be present
        assert!(
            result.code.contains("emits:"),
            "Should have emits definition"
        );
    }

    #[test]
    fn test_compile_script_setup_with_typed_define_emits_single_line() {
        let content = r#"
const emit = defineEmits<(e: 'click') => void>()
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Typed defineEmits output:\n{}", result.code);

        // defineEmits should NOT be in the setup function
        assert!(
            !result.code.contains("defineEmits"),
            "defineEmits should be removed from setup"
        );
        // emit binding should be present
        assert!(
            result.code.contains("const emit = __emit"),
            "Should bind emit to __emit"
        );
    }

    #[test]
    fn test_compile_script_setup_with_define_expose() {
        let content = r#"
import { ref } from 'vue'
const count = ref(0)
const reset = () => count.value = 0
defineExpose({ count, reset })
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("defineExpose output:\n{}", result.code);

        // defineExpose should be transformed to __expose(...)
        assert!(
            result.code.contains("__expose({"),
            "Should have __expose call with arguments"
        );
        assert!(
            result.code.contains("count"),
            "__expose should include count"
        );
        assert!(
            result.code.contains("reset"),
            "__expose should include reset"
        );
        // defineExpose should NOT be in the setup function
        assert!(
            !result.code.contains("defineExpose"),
            "defineExpose should be removed from setup"
        );
    }

    #[test]
    fn test_compile_script_setup_without_define_expose() {
        // Test that __expose() is always called, even without defineExpose.
        // This matches the official Vue compiler behavior, which is required for
        // proper component initialization with @vue/test-utils.
        let content = r#"
import { ref } from 'vue'
const count = ref(0)
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Output without defineExpose:\n{}", result.code);

        // __expose() should always be called for proper Vue runtime initialization
        assert!(
            result.code.contains("__expose()"),
            "Should have __expose() call even without defineExpose. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_compile_script_setup_with_empty_define_expose() {
        // Test that defineExpose() (empty) is handled correctly
        let content = r#"
import { ref } from 'vue'
const count = ref(0)
defineExpose()
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();

        println!("Output with empty defineExpose:\n{}", result.code);

        // Should have __expose() call
        assert!(
            result.code.contains("__expose()"),
            "Should have __expose() call for empty defineExpose. Got:\n{}",
            result.code
        );

        // defineExpose should be removed
        assert!(
            !result.code.contains("defineExpose"),
            "defineExpose should be removed from setup"
        );
    }

    #[test]
    fn test_transform_typescript_to_js_strips_types() {
        let ts_code = r#"const getNumber = (x: number): string => {
    return x.toString();
}
const foo: string = "bar";"#;
        let result = transform_typescript_to_js(ts_code);
        eprintln!("TypeScript transform result:\n{}", result);

        // Should NOT contain type annotations
        assert!(
            !result.contains(": number"),
            "Should strip parameter type annotation. Got:\n{}",
            result
        );
        assert!(
            !result.contains(": string"),
            "Should strip return type and variable type annotations. Got:\n{}",
            result
        );
    }

    #[test]
    fn test_compile_script_setup_strips_typescript() {
        let content = r#"
const getNumberOfTeachers = (
  items: Item[]
): string => {
  return items.length.toString();
};
"#;
        // is_ts = false means we want JavaScript output (TypeScript should be stripped)
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();
        eprintln!("Compiled TypeScript output:\n{}", result.code);

        // Should NOT contain type annotations
        assert!(
            !result.code.contains(": Item[]"),
            "Should strip parameter type annotation. Got:\n{}",
            result.code
        );
        assert!(
            !result.code.contains("): string"),
            "Should strip return type annotation. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_compile_script_setup_preserves_typescript_when_is_ts() {
        let content = r#"
const count: number = 1;
const items: Array<string> = [];
"#;
        let result = compile_script_setup(content, "Test", false, true, None).unwrap();
        assert!(
            result.code.contains(": number") || result.code.contains("Array<string>"),
            "Expected TypeScript annotations to be preserved. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_props_destructure_type_based_defaults() {
        let content = r#"
const { color = "primary" } = defineProps<{
  color?: "primary" | "secondary";
}>();
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();
        assert!(
            result.code.contains("_mergeDefaults(")
                && result.code.contains("color")
                && result.code.contains(": {}"),
            "Expected mergeDefaults with runtime props. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_duplicate_imports_filtered() {
        let content = r#"
import { ref } from 'vue'
import { ref } from 'vue'
const count = ref(0)
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();
        let import_ref_lines = result
            .code
            .lines()
            .filter(|line| {
                line.contains("import {") && line.contains("ref") && line.contains("vue")
            })
            .count();
        assert_eq!(
            import_ref_lines, 1,
            "Expected duplicate ref import to be filtered. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_async_setup_detection() {
        let content = r#"
const response = await fetch('/api/data')
const data = await response.json()
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();
        assert!(
            result.code.contains("async setup("),
            "Expected async setup when top-level await is present. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_await_in_string_literal_does_not_trigger_async() {
        let content = r#"
const msg = "await should not trigger async"
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();
        assert!(
            !result.code.contains("async setup("),
            "Did not expect async setup for await in string literal. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_type_comparison_not_stripped() {
        let content = r#"
const props = defineProps(['type'])
const isButton = props.type === 'button'
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();
        assert!(
            result.code.contains("type === 'button'")
                || result.code.contains("type === \"button\""),
            "Expected type comparison to remain. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_generic_function_call_stripped() {
        let content = r#"
const store = useStore<RootState>()
"#;
        let result = compile_script_setup(content, "Test", false, false, None).unwrap();
        assert!(
            !result.code.contains("<RootState>"),
            "Expected generic type arguments to be stripped. Got:\n{}",
            result.code
        );
    }
}