vize_atelier_sfc 0.18.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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Main compiler for function-mode script setup.
//!
//! Contains the `compile_script_setup` function which compiles `<script setup>` blocks
//! in function mode, where the setup function returns bindings for use by a separate
//! render function.

use vize_carton::{Bump, FxHashSet, String, ToCompactString};

use crate::script::{
    resolve_template_used_identifiers, transform_destructured_props, ScriptCompileContext,
    TemplateUsedIdentifiers,
};
use crate::types::{BindingType, SfcError};

use super::super::import_utils::extract_import_identifiers;
use super::super::macros::{
    is_macro_call_line, is_multiline_macro_start, is_paren_macro_start, is_props_destructure_line,
};
use super::super::props::{extract_emit_names_from_type, extract_prop_types_from_type};
use super::super::typescript::transform_typescript_to_js;
use super::super::ScriptCompileResult;
use super::helpers::{count_unescaped_backticks, is_reserved_word, is_typescript_type_alias};
use super::imports::dedupe_imports;

/// Compile script setup content following Vue.js core format
#[allow(dead_code)]
pub fn compile_script_setup(
    content: &str,
    component_name: &str,
    is_vapor: bool,
    is_ts: bool,
    template_content: Option<&str>,
) -> Result<ScriptCompileResult, SfcError> {
    let mut ctx = ScriptCompileContext::new(content);
    ctx.analyze();

    // Use arena-allocated Vec for better performance
    let bump = vize_carton::Bump::new();
    let mut output: vize_carton::Vec<u8> = vize_carton::Vec::with_capacity_in(4096, &bump);

    // Check if we have props destructure
    let has_props_destructure = ctx.macros.props_destructure.is_some();

    // Extract and output imports
    let mut imports = Vec::new();
    let mut setup_lines = Vec::new();
    let mut in_import = false;
    let mut import_buffer = String::default();

    // For multi-line statement tracking
    let mut in_destructure = false;
    let mut destructure_buffer = String::default();
    let mut brace_depth: i32 = 0;
    let mut waiting_for_macro_close = false; // After destructure closes, waiting for macro call to complete

    // For multi-line macro call tracking (e.g., defineEmits<{ ... }>())
    let mut in_macro_call = false;
    let mut macro_buffer = String::default();
    let mut macro_angle_depth: i32 = 0;

    // For multi-line paren-based macro call tracking (e.g., defineExpose({ ... }))
    let mut in_paren_macro_call = false;
    let mut paren_macro_depth: i32 = 0;

    // Track template literal depth to avoid treating content inside backtick strings as code
    let mut template_literal_depth: i32 = 0;

    // Track TypeScript-only declarations (interface, type) to skip them
    let mut in_ts_interface = false;
    let mut ts_interface_brace_depth: i32 = 0;
    let mut in_ts_type = false;
    let mut ts_type_depth: i32 = 0;

    for line in content.lines() {
        // Update template literal depth by counting unescaped backticks
        // This is a simplified approach - we count backticks that aren't preceded by backslash
        // and aren't inside regular strings (approximation)
        template_literal_depth += count_unescaped_backticks(line);
        let trimmed = line.trim();

        // Handle multi-line macro call: const emit = defineEmits<{ ... }>()
        if in_macro_call {
            macro_buffer.push_str(line);
            macro_buffer.push('\n');
            // Track angle brackets but ignore => (arrow functions)
            let line_no_arrow = trimmed.replace("=>", "");
            macro_angle_depth += line_no_arrow.matches('<').count() as i32;
            macro_angle_depth -= line_no_arrow.matches('>').count() as i32;

            // Check if macro call is complete (angle brackets closed and has ())
            if macro_angle_depth <= 0 && (trimmed.contains("()") || trimmed.ends_with(')')) {
                // Skip the entire macro call
                in_macro_call = false;
                macro_buffer.clear();
                continue;
            }
            continue;
        }

        // Handle multi-line paren-based macro call: defineExpose({ ... })
        if in_paren_macro_call {
            paren_macro_depth += trimmed.matches('(').count() as i32;
            paren_macro_depth -= trimmed.matches(')').count() as i32;

            // Check if macro call is complete (parentheses balanced)
            if paren_macro_depth <= 0 {
                in_paren_macro_call = false;
                continue;
            }
            continue;
        }

        // Detect start of multi-line paren-based macro call (e.g., defineExpose({)
        // But not if it's part of a destructure pattern (const { ... } = defineProps)
        if !in_destructure
            && is_paren_macro_start(trimmed)
            && !trimmed.starts_with("const {")
            && !trimmed.starts_with("let {")
            && !trimmed.starts_with("var {")
        {
            in_paren_macro_call = true;
            paren_macro_depth =
                trimmed.matches('(').count() as i32 - trimmed.matches(')').count() as i32;
            continue;
        }

        // Detect start of multi-line macro call (e.g., defineEmits<{ or defineProps<{)
        // But not if it's part of a destructure pattern
        if !in_destructure
            && is_multiline_macro_start(trimmed)
            && !trimmed.starts_with("const {")
            && !trimmed.starts_with("let {")
            && !trimmed.starts_with("var {")
        {
            in_macro_call = true;
            macro_buffer.clear();
            macro_buffer.push_str(line);
            macro_buffer.push('\n');
            macro_angle_depth =
                trimmed.matches('<').count() as i32 - trimmed.matches('>').count() as i32;
            continue;
        }

        // Handle waiting for macro close after destructure (e.g., waiting for }>() )
        if waiting_for_macro_close {
            destructure_buffer.push_str(line);
            destructure_buffer.push('\n');

            let open_angles = destructure_buffer.matches('<').count();
            let close_angles = destructure_buffer.matches('>').count();

            // If angle brackets aren't balanced, keep going
            if open_angles > close_angles {
                continue;
            }

            // Angle brackets are balanced, check for closing ()
            if trimmed.ends_with("()") || trimmed.ends_with(')') {
                // Skip the entire destructure + macro call
                waiting_for_macro_close = false;
                in_destructure = false;
                destructure_buffer.clear();
                continue;
            }
            continue;
        }

        // Handle multi-line destructure pattern: const { ... } = defineProps(...)
        if in_destructure {
            destructure_buffer.push_str(line);
            destructure_buffer.push('\n');
            brace_depth += trimmed.matches('{').count() as i32;
            brace_depth -= trimmed.matches('}').count() as i32;

            // Check if the destructure pattern is closing (brace_depth reaches 0)
            if brace_depth <= 0 {
                // Now check if it's a defineProps/withDefaults call
                let is_props_macro = destructure_buffer.contains("defineProps")
                    || destructure_buffer.contains("withDefaults");

                if is_props_macro {
                    // Check if there are type args that need to close
                    let has_unclosed_type_args = destructure_buffer.contains('<')
                        && destructure_buffer.matches('<').count()
                            > destructure_buffer.matches('>').count();

                    if has_unclosed_type_args {
                        // Switch to waiting for macro close
                        waiting_for_macro_close = true;
                        continue;
                    }

                    // Check if we need to wait for ()
                    if !trimmed.ends_with("()") && !trimmed.ends_with(')') {
                        // Still waiting for the function call parens
                        waiting_for_macro_close = true;
                        continue;
                    }

                    // Skip the entire destructure - it's a props destructure
                    in_destructure = false;
                    destructure_buffer.clear();
                    continue;
                } else {
                    // Not a props destructure, add to setup lines
                    for buf_line in destructure_buffer.lines() {
                        setup_lines.push(buf_line.to_compact_string());
                    }
                    in_destructure = false;
                    destructure_buffer.clear();
                    continue;
                }
            }
            continue;
        }

        // Detect start of destructure pattern
        if (trimmed.starts_with("const {")
            || trimmed.starts_with("let {")
            || trimmed.starts_with("var {"))
            && !trimmed.contains('}')
        {
            in_destructure = true;
            destructure_buffer.clear();
            destructure_buffer.push_str(line);
            destructure_buffer.push('\n');
            brace_depth = trimmed.matches('{').count() as i32 - trimmed.matches('}').count() as i32;
            continue;
        }

        // Handle single-line props destructure (only when outside template literals)
        if template_literal_depth % 2 == 0 && is_props_destructure_line(trimmed) {
            continue;
        }

        // Only process imports when outside template literals (depth is even)
        // When inside a template literal (depth is odd), treat as regular content
        let outside_template_literal = template_literal_depth % 2 == 0;

        if outside_template_literal && trimmed.starts_with("import ") {
            // Handle side-effect imports without semicolons (e.g., import '@/css/reset.scss')
            // These have no 'from' clause and are always single-line
            if !trimmed.contains(" from ") && (trimmed.contains('\'') || trimmed.contains('"')) {
                let mut import = String::with_capacity(line.len() + 1);
                import.push_str(line);
                import.push('\n');
                imports.push(import);
                continue;
            }
            in_import = true;
            import_buffer.clear();
        }

        if in_import && outside_template_literal {
            import_buffer.push_str(line);
            import_buffer.push('\n');

            if trimmed.ends_with(';') || (trimmed.contains(" from ") && !trimmed.ends_with(',')) {
                imports.push(import_buffer.clone());
                in_import = false;
            }
            continue;
        }

        // Handle TypeScript interface declarations (skip them)
        if in_ts_interface {
            ts_interface_brace_depth += trimmed.matches('{').count() as i32;
            ts_interface_brace_depth -= trimmed.matches('}').count() as i32;
            if ts_interface_brace_depth <= 0 {
                in_ts_interface = false;
            }
            continue;
        }

        // Detect TypeScript interface start
        if outside_template_literal
            && (trimmed.starts_with("interface ") || trimmed.starts_with("export interface "))
        {
            in_ts_interface = true;
            ts_interface_brace_depth =
                trimmed.matches('{').count() as i32 - trimmed.matches('}').count() as i32;
            if ts_interface_brace_depth <= 0 {
                in_ts_interface = false;
            }
            continue;
        }

        // Handle TypeScript type declarations (skip them)
        if in_ts_type {
            // Track balanced brackets for complex types like: type X = { a: string } | { b: number }
            // Strip `=>` before counting angle brackets to avoid misinterpreting arrow functions
            // e.g., `onClick: () => void` — the `>` in `=>` is NOT a closing angle bracket
            let line_no_arrow = trimmed.replace("=>", "__");
            ts_type_depth += trimmed.matches('{').count() as i32;
            ts_type_depth -= trimmed.matches('}').count() as i32;
            ts_type_depth += line_no_arrow.matches('<').count() as i32;
            ts_type_depth -= line_no_arrow.matches('>').count() as i32;
            ts_type_depth += trimmed.matches('(').count() as i32;
            ts_type_depth -= trimmed.matches(')').count() as i32;
            // Type declaration ends when balanced and NOT a continuation line
            let is_union_continuation = trimmed.starts_with('|') || trimmed.starts_with('&');
            if ts_type_depth <= 0
                && !is_union_continuation
                && (trimmed.ends_with(';')
                    || (!trimmed.ends_with('|')
                        && !trimmed.ends_with('&')
                        && !trimmed.ends_with(',')
                        && !trimmed.ends_with('{')))
            {
                in_ts_type = false;
            }
            continue;
        }

        // Detect TypeScript type alias start
        if outside_template_literal
            && (trimmed.starts_with("type ") || trimmed.starts_with("export type "))
            && is_typescript_type_alias(trimmed)
        {
            // Check if it's a single-line type
            let has_equals = trimmed.contains('=');
            if has_equals {
                // Strip `=>` before counting angle brackets (arrow functions are not type delimiters)
                let line_no_arrow = trimmed.replace("=>", "__");
                ts_type_depth = trimmed.matches('{').count() as i32
                    - trimmed.matches('}').count() as i32
                    + line_no_arrow.matches('<').count() as i32
                    - line_no_arrow.matches('>').count() as i32
                    + trimmed.matches('(').count() as i32
                    - trimmed.matches(')').count() as i32;
                if ts_type_depth <= 0
                    && (trimmed.ends_with(';')
                        || (!trimmed.ends_with('|')
                            && !trimmed.ends_with('&')
                            && !trimmed.ends_with(',')
                            && !trimmed.ends_with('{')
                            && !trimmed.ends_with('=')))
                {
                    // Single line type, just skip
                    continue;
                }
                in_ts_type = true;
            }
            continue;
        }

        if !trimmed.is_empty() {
            // If we were in an import but now inside a template literal, reset import state
            if in_import && !outside_template_literal {
                // We started an import but crossed into a template literal
                // This shouldn't normally happen, but handle it gracefully
                setup_lines.push(import_buffer.clone());
                in_import = false;
                import_buffer.clear();
            }
            // Skip compiler macro calls (only when outside template literals)
            if outside_template_literal && is_macro_call_line(trimmed) {
                continue;
            }
            setup_lines.push(line.to_compact_string());
        }
    }

    // Check if we need PropType import (type-based defineProps in non-vapor TS mode)
    let needs_prop_type = is_ts
        && !is_vapor
        && ctx
            .macros
            .define_props
            .as_ref()
            .is_some_and(|p| p.type_args.is_some());

    // Add Vapor-specific import or defineComponent import
    if is_vapor {
        output.extend_from_slice(
            b"import { defineVaporComponent as _defineVaporComponent } from 'vue'\n",
        );
    } else if needs_prop_type {
        output.extend_from_slice(
            b"import { defineComponent as _defineComponent, type PropType } from 'vue'\n",
        );
    } else {
        output.extend_from_slice(b"import { defineComponent as _defineComponent } from 'vue'\n");
    }

    // Add mergeDefaults import if props destructure has defaults
    let needs_merge_defaults = has_props_destructure
        && ctx
            .macros
            .props_destructure
            .as_ref()
            .map(|d| d.bindings.values().any(|b| b.default.is_some()))
            .unwrap_or(false);
    if needs_merge_defaults {
        output.extend_from_slice(b"import { mergeDefaults as _mergeDefaults } from 'vue'\n");
    }

    // Add useModel import if defineModel was used
    let has_define_model = !ctx.macros.define_models.is_empty();
    if has_define_model {
        output.extend_from_slice(b"import { useModel as _useModel } from 'vue'\n");
    }

    // Output imports (filtering out type-only imports + dedupe)
    let deduped_imports = dedupe_imports(&imports, false);
    for import in &deduped_imports {
        output.extend_from_slice(import.as_bytes());
    }

    output.push(b'\n');

    // Add comment for props destructure
    if has_props_destructure {
        output.extend_from_slice(b"// Reactive Props Destructure (Vue 3.5+)\n\n");
    }

    // Start __sfc__ definition
    if is_vapor {
        output.extend_from_slice(b"const __sfc__ = /*@__PURE__*/_defineVaporComponent({\n");
    } else {
        output.extend_from_slice(b"const __sfc__ = /*@__PURE__*/_defineComponent({\n");
    }
    output.extend_from_slice(b"  __name: '");
    output.extend_from_slice(component_name.as_bytes());
    output.extend_from_slice(b"',\n");

    // Props definition - handle both regular defineProps and destructure
    emit_props_definition(
        &mut output,
        &ctx,
        has_props_destructure,
        needs_prop_type,
        is_ts,
    );

    // Collect model names for props and emits
    let model_names: Vec<String> = collect_model_names(&ctx);

    // Add model props if defineModel was used (and no defineProps)
    if !model_names.is_empty() && ctx.macros.define_props.is_none() && !has_props_destructure {
        output.extend_from_slice(b"  props: {\n");
        for model_name in &model_names {
            output.extend_from_slice(b"    \"");
            output.extend_from_slice(model_name.as_bytes());
            output.extend_from_slice(b"\": {},\n");
        }
        output.extend_from_slice(b"  },\n");
    }

    // Emits definition - combine defineEmits and defineModel
    emit_emits_definition(&mut output, &ctx, &model_names);

    // Prepare setup code and detect top-level await (async setup)
    let setup_code = setup_lines.join("\n");
    let has_top_level_await = super::helpers::contains_top_level_await(&setup_code, is_ts);

    // Setup function
    if has_top_level_await {
        output.extend_from_slice(b"  async setup(__props, { expose: __expose, emit: __emit }) {\n");
    } else {
        output.extend_from_slice(b"  setup(__props, { expose: __expose, emit: __emit }) {\n");
    }

    // Always call __expose() - Vue runtime requires this for proper component initialization
    // If defineExpose has args, use those; otherwise call with no args
    emit_expose(&mut output, &ctx);

    // Collect emit binding name for inclusion in __returned__
    let emit_binding_name: Option<String> = ctx
        .macros
        .define_emits
        .as_ref()
        .and_then(|m| m.binding_name.as_deref().map(String::from));

    // defineEmits binding: const emit = __emit
    if let Some(ref binding_name) = emit_binding_name {
        output.extend_from_slice(b"  const ");
        output.extend_from_slice(binding_name.as_bytes());
        output.extend_from_slice(b" = __emit\n");
    }

    // Collect props binding for exclusion from __returned__ (props themselves shouldn't be in returned)
    let mut props_binding_names: FxHashSet<String> = FxHashSet::default();

    // defineProps binding: const props = __props (only if not destructured)
    if !has_props_destructure {
        if let Some(ref props_macro) = ctx.macros.define_props {
            if let Some(ref binding_name) = props_macro.binding_name {
                output.extend_from_slice(b"  const ");
                output.extend_from_slice(binding_name.as_bytes());
                output.extend_from_slice(b" = __props\n");
                props_binding_names.insert(String::from(binding_name.as_str()));
            }
        }
    }

    // defineModel bindings: const model = _useModel(__props, 'modelValue')
    // Collect model binding names for __returned__
    let model_binding_names = emit_model_bindings(&mut output, &ctx);

    // Output setup code, transforming props destructure references

    // Debug: Log props destructure status
    #[cfg(debug_assertions)]
    {
        if ctx.macros.props_destructure.is_some() {
            eprintln!(
                "[DEBUG] Props destructure found: {:?}",
                ctx.macros.props_destructure
            );
        } else {
            eprintln!("[DEBUG] No props destructure found");
        }
        eprintln!("[DEBUG] Setup code before transform:\n{}", setup_code);
    }

    let transformed_setup: String = if let Some(ref destructure) = ctx.macros.props_destructure {
        let result = transform_destructured_props(&setup_code, destructure);
        #[cfg(debug_assertions)]
        eprintln!("[DEBUG] Setup code after transform:\n{}", result);
        result
    } else {
        setup_code.into()
    };

    // Indent the setup code
    for line in transformed_setup.lines() {
        if !line.trim().is_empty() {
            output.extend_from_slice(b"  ");
            output.extend_from_slice(line.as_bytes());
        }
        output.push(b'\n');
    }

    // Generate __returned__ object
    let returned_bindings = build_returned_bindings(
        &mut ctx,
        has_props_destructure,
        &props_binding_names,
        &emit_binding_name,
        &imports,
        template_content,
        &model_binding_names,
    );

    let returned_props: Vec<String> = returned_bindings
        .iter()
        .map(|name| {
            if is_reserved_word(name) {
                let mut entry = String::with_capacity(name.len() * 2 + 4);
                entry.push('"');
                entry.push_str(name);
                entry.push_str("\": ");
                entry.push_str(name);
                entry
            } else {
                name.clone()
            }
        })
        .collect();

    output.extend_from_slice(b"  const __returned__ = { ");
    output.extend_from_slice(returned_props.join(", ").as_bytes());
    output.extend_from_slice(b" }\n");
    output.extend_from_slice(b"  Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n");
    output.extend_from_slice(b"  return __returned__\n");

    output.extend_from_slice(b"  }\n\n");
    // Close the component definition
    if is_vapor {
        output.extend_from_slice(b"});\n"); // Close _defineVaporComponent(
    } else {
        output.extend_from_slice(b"});\n"); // Close _defineComponent(
    }

    // Convert arena Vec<u8> to String - SAFETY: we only push valid UTF-8
    #[allow(clippy::disallowed_types)]
    let output_str: std::string::String =
        unsafe { std::string::String::from_utf8_unchecked(output.into_iter().collect()) };

    // Transform TypeScript to JavaScript only when output is not TS.
    let final_code: String = if is_ts {
        output_str.into()
    } else {
        transform_typescript_to_js(&output_str)
    };

    Ok(ScriptCompileResult {
        code: final_code,
        bindings: Some(ctx.bindings),
    })
}

/// Emit props definition to the output buffer.
///
/// Handles regular defineProps, destructured props with defaults, and type-based props.
fn emit_props_definition(
    output: &mut vize_carton::Vec<u8>,
    ctx: &ScriptCompileContext,
    has_props_destructure: bool,
    needs_prop_type: bool,
    _is_ts: bool,
) {
    if has_props_destructure {
        let destructure = ctx.macros.props_destructure.as_ref().unwrap();

        // Check if there are any defaults
        let has_defaults = destructure.bindings.values().any(|b| b.default.is_some());

        if has_defaults {
            // Use mergeDefaults format: _mergeDefaults(runtimeProps, { prop2: default })
            // Get the original props argument from defineProps (or generate from type args)
            let original_props: String = if let Some(ref props_macro) = ctx.macros.define_props {
                if let Some(ref type_args) = props_macro.type_args {
                    let prop_types = extract_prop_types_from_type(type_args);
                    if prop_types.is_empty() {
                        "{}".to_compact_string()
                    } else {
                        let mut names: Vec<_> =
                            prop_types.iter().map(|(n, _)| n.as_str()).collect();
                        names.sort();
                        let mut s = String::from("{ ");
                        for (i, name) in names.iter().enumerate() {
                            if i > 0 {
                                s.push_str(", ");
                            }
                            s.push_str(name);
                            s.push_str(": {}");
                        }
                        s.push_str(" }");
                        s
                    }
                } else if !props_macro.args.is_empty() {
                    String::from(props_macro.args.as_str())
                } else {
                    "[]".to_compact_string()
                }
            } else {
                "[]".to_compact_string()
            };

            output.extend_from_slice(b"  props: /*@__PURE__*/_mergeDefaults(");
            output.extend_from_slice(original_props.as_bytes());
            output.extend_from_slice(b", {\n");

            // Add defaults
            for (key, binding) in &destructure.bindings {
                if let Some(ref default_val) = binding.default {
                    output.extend_from_slice(b"  ");
                    output.extend_from_slice(key.as_bytes());
                    output.extend_from_slice(b": ");
                    output.extend_from_slice(default_val.as_bytes());
                    output.push(b'\n');
                }
            }
            output.extend_from_slice(b"}),\n");
        } else {
            // No defaults - just use the original props array
            if let Some(ref props_macro) = ctx.macros.define_props {
                if !props_macro.args.is_empty() {
                    output.extend_from_slice(b"  props: ");
                    output.extend_from_slice(props_macro.args.as_bytes());
                    output.extend_from_slice(b",\n");
                }
            }
        }
    } else if let Some(ref props_macro) = ctx.macros.define_props {
        if let Some(ref type_args) = props_macro.type_args {
            // For type-based props, extract full prop definitions
            let prop_types = extract_prop_types_from_type(type_args);
            if !prop_types.is_empty() {
                output.extend_from_slice(b"  props: {\n");
                // Sort props for deterministic output
                let mut sorted_props: Vec<_> = prop_types.iter().collect();
                sorted_props.sort_by(|a, b| a.0.cmp(&b.0));
                for (name, prop_type) in sorted_props {
                    output.extend_from_slice(b"    ");
                    output.extend_from_slice(name.as_bytes());
                    output.extend_from_slice(b": { type: ");
                    output.extend_from_slice(prop_type.js_type.as_bytes());
                    if needs_prop_type {
                        if let Some(ref ts_type) = prop_type.ts_type {
                            if prop_type.js_type == "null" {
                                output.extend_from_slice(b" as unknown as PropType<");
                            } else {
                                output.extend_from_slice(b" as PropType<");
                            }
                            // Normalize multi-line types to single line
                            let normalized: String = String::from(
                                ts_type.split_whitespace().collect::<Vec<_>>().join(" "),
                            );
                            output.extend_from_slice(normalized.as_bytes());
                            output.push(b'>');
                        }
                    }
                    output.extend_from_slice(b", required: ");
                    output.extend_from_slice(if prop_type.optional {
                        b"false"
                    } else {
                        b"true"
                    });
                    output.extend_from_slice(b" },\n");
                }
                output.extend_from_slice(b"  },\n");
            }
        } else if !props_macro.args.is_empty() {
            output.extend_from_slice(b"  props: ");
            output.extend_from_slice(props_macro.args.as_bytes());
            output.extend_from_slice(b",\n");
        }
    }
}

/// Collect model names from defineModel calls.
fn collect_model_names(ctx: &ScriptCompileContext) -> Vec<String> {
    ctx.macros
        .define_models
        .iter()
        .map(|m| {
            if m.args.is_empty() {
                "modelValue".to_compact_string()
            } else {
                let args_trimmed = m.args.trim();
                if args_trimmed.starts_with('\'') || args_trimmed.starts_with('"') {
                    let quote_char = args_trimmed.chars().next().unwrap();
                    if let Some(end_pos) = args_trimmed[1..].find(quote_char) {
                        String::from(&args_trimmed[1..end_pos + 1])
                    } else {
                        "modelValue".to_compact_string()
                    }
                } else {
                    "modelValue".to_compact_string()
                }
            }
        })
        .collect()
}

/// Emit emits definition to the output buffer.
///
/// Combines defineEmits and defineModel emit events.
fn emit_emits_definition(
    output: &mut vize_carton::Vec<u8>,
    ctx: &ScriptCompileContext,
    model_names: &[String],
) {
    let mut all_emits: Vec<String> = Vec::new();

    // Add emits from defineEmits
    if let Some(ref emits_macro) = ctx.macros.define_emits {
        if let Some(ref type_args) = emits_macro.type_args {
            let emit_names = extract_emit_names_from_type(type_args);
            all_emits.extend(emit_names);
        } else if !emits_macro.args.is_empty() {
            // Runtime args - we'll output separately
        }
    }

    // Add update:modelValue emits from defineModel
    for model_name in model_names {
        let mut name = String::with_capacity(7 + model_name.len());
        name.push_str("update:");
        name.push_str(model_name);
        all_emits.push(name);
    }

    // Output emits
    if !all_emits.is_empty() {
        output.extend_from_slice(b"  emits: [");
        for (i, name) in all_emits.iter().enumerate() {
            if i > 0 {
                output.extend_from_slice(b", ");
            }
            output.push(b'"');
            output.extend_from_slice(name.as_bytes());
            output.push(b'"');
        }
        output.extend_from_slice(b"],\n");
    } else if let Some(ref emits_macro) = ctx.macros.define_emits {
        if !emits_macro.args.is_empty() {
            output.extend_from_slice(b"  emits: ");
            output.extend_from_slice(emits_macro.args.as_bytes());
            output.extend_from_slice(b",\n");
        }
    }
}

/// Emit the __expose() call to the output buffer.
fn emit_expose(output: &mut vize_carton::Vec<u8>, ctx: &ScriptCompileContext) {
    if let Some(ref expose_macro) = ctx.macros.define_expose {
        // args contains the argument content (e.g., "{ foo, bar }")
        let args = expose_macro.args.trim();
        if args.is_empty() {
            output.extend_from_slice(b"  __expose();\n");
        } else {
            output.extend_from_slice(b"  __expose(");
            output.extend_from_slice(args.as_bytes());
            output.extend_from_slice(b");\n");
        }
    } else {
        // No defineExpose, but still need to call __expose() for Vue runtime
        output.extend_from_slice(b"  __expose();\n");
    }
}

/// Emit defineModel bindings and return the binding names.
fn emit_model_bindings(
    output: &mut vize_carton::Vec<u8>,
    ctx: &ScriptCompileContext,
) -> Vec<String> {
    let mut model_binding_names: Vec<String> = Vec::new();
    for model_call in &ctx.macros.define_models {
        if let Some(ref binding_name) = model_call.binding_name {
            // Extract model name from args (first string argument) or default to "modelValue"
            let model_name = if model_call.args.is_empty() {
                "modelValue".to_compact_string()
            } else {
                // Try to extract the first string argument (e.g., 'title' from defineModel('title'))
                let args_trimmed = model_call.args.trim();
                if args_trimmed.starts_with('\'') || args_trimmed.starts_with('"') {
                    // Extract string content
                    let quote_char = args_trimmed.chars().next().unwrap();
                    if let Some(end_pos) = args_trimmed[1..].find(quote_char) {
                        String::from(&args_trimmed[1..end_pos + 1])
                    } else {
                        "modelValue".to_compact_string()
                    }
                } else {
                    "modelValue".to_compact_string()
                }
            };

            output.extend_from_slice(b"  const ");
            output.extend_from_slice(binding_name.as_bytes());
            output.extend_from_slice(b" = _useModel(__props, \"");
            output.extend_from_slice(model_name.as_bytes());
            output.extend_from_slice(b"\")\n");
            model_binding_names.push(String::from(binding_name.as_str()));
        }
    }
    model_binding_names
}

/// Build the list of bindings to include in `__returned__`.
///
/// Filters out compiler macros, destructured props, props bindings, and typed props.
/// Includes imported identifiers used in the template.
fn build_returned_bindings(
    ctx: &mut ScriptCompileContext,
    _has_props_destructure: bool,
    props_binding_names: &FxHashSet<String>,
    emit_binding_name: &Option<String>,
    imports: &[String],
    template_content: Option<&str>,
    _model_binding_names: &[String],
) -> Vec<String> {
    // Compiler macros preset - these are compile-time only and should not be in __returned__
    let compiler_macros: FxHashSet<&str> = [
        "defineProps",
        "defineEmits",
        "defineExpose",
        "defineOptions",
        "defineSlots",
        "defineModel",
        "withDefaults",
    ]
    .into_iter()
    .collect();

    // Collect destructured prop local names to exclude from __returned__
    let destructured_prop_locals: FxHashSet<String> = ctx
        .macros
        .props_destructure
        .as_ref()
        .map(|d| {
            d.bindings
                .values()
                .map(|b| String::from(b.local.as_str()))
                .collect()
        })
        .unwrap_or_default();

    // Collect prop names from type-based defineProps to exclude from __returned__
    let typed_prop_names: FxHashSet<String> = ctx
        .macros
        .define_props
        .as_ref()
        .and_then(|p| p.type_args.as_ref())
        .map(|type_args| {
            extract_prop_types_from_type(type_args)
                .iter()
                .map(|(n, _)| String::from(n.as_str()))
                .collect()
        })
        .unwrap_or_default();

    // Generate __returned__ object
    let mut returned_bindings: Vec<String> = ctx
        .bindings
        .bindings
        .keys()
        .filter(|name| {
            // Exclude compiler macros, destructured props, props bindings, and typed props
            !compiler_macros.contains(name.as_str())
                && !destructured_prop_locals.contains(*name)
                && !props_binding_names.contains(*name)
                && !typed_prop_names.contains(*name)
        })
        .cloned()
        .collect();

    // Add emit binding to returned (it's a runtime value that should be exposed)
    if let Some(ref emit_name) = emit_binding_name {
        if !returned_bindings.contains(emit_name) {
            returned_bindings.push(emit_name.clone());
        }
    }

    returned_bindings.sort();

    // Parse template to get used identifiers
    let template_used_ids: TemplateUsedIdentifiers = if let Some(template_src) = template_content {
        let allocator = Bump::new();
        let (root, _) = vize_atelier_core::parser::parse(&allocator, template_src);
        resolve_template_used_identifiers(&root)
    } else {
        TemplateUsedIdentifiers::default()
    };

    // Extract all imported identifiers (both named and default imports)
    let mut imported_identifiers: Vec<String> = Vec::new();
    for import in imports {
        // Extract names using OXC parser for accuracy
        let extracted = extract_import_identifiers(import);
        for name in extracted {
            // Exclude compiler macros from imports
            if !compiler_macros.contains(name.as_str()) {
                imported_identifiers.push(name);
            }
        }
    }

    // Include imported identifiers that are used in template
    let mut all_bindings = returned_bindings.clone();
    for name in &imported_identifiers {
        // Include if used in template OR if no template (include all for safety)
        if template_content.is_none() || template_used_ids.used_ids.contains(name.as_str()) {
            if !all_bindings.contains(name) {
                all_bindings.push(name.clone());
            }
            // Also add to binding metadata so template compiler knows about it
            if !ctx.bindings.bindings.contains_key(name.as_str()) {
                ctx.bindings
                    .bindings
                    .insert(name.clone(), BindingType::SetupConst);
            }
        }
    }
    all_bindings.sort();
    all_bindings.dedup();

    all_bindings
}