vize_canon 0.170.0

Canon - The standard of correctness for Vize type checking
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! Main virtual TypeScript generation entry points.
//!
//! Contains the public `generate_virtual_ts` and `generate_virtual_ts_with_offsets`
//! functions that orchestrate the full virtual TypeScript generation pipeline.

use vize_croquis::{BindingType, Croquis, ScopeData, ScopeKind};

use super::{
    helpers::{
        IMPORT_META_AUGMENTATION, SETUP_SCOPE_HELPER_NAMES, VUE_SETUP_HELPERS, VUE_TYPE_HELPERS,
        generate_template_context, to_safe_identifier,
    },
    props::{
        add_generic_defaults, collect_template_prop_names, extract_generic_names,
        generate_props_type, generate_props_variables,
    },
    scope::generate_scope_closures,
    types::{VirtualTsGenerationOptions, VirtualTsOptions, VirtualTsOutput, VizeMapping},
};
use vize_carton::append;
use vize_carton::cstr;
use vize_carton::profile;
use vize_carton::{FxHashMap, FxHashSet, String};

/// Generate virtual TypeScript from Vue SFC analysis.
///
/// The generated TypeScript uses proper scope hierarchy:
/// 1. Module scope: imports only
/// 2. Setup scope (__setup function): compiler macros + script content
/// 3. Template scope (nested in setup): template expressions
///
/// This ensures compiler macros like defineProps are ONLY valid in setup scope.
pub fn generate_virtual_ts(
    summary: &Croquis,
    script_content: Option<&str>,
    template_ast: Option<&vize_relief::ast::RootNode<'_>>,
    template_offset: u32,
) -> VirtualTsOutput {
    generate_virtual_ts_with_offsets(
        summary,
        script_content,
        template_ast,
        0,
        template_offset,
        &VirtualTsOptions::default(),
    )
}

/// Generate virtual TypeScript with explicit script and template offsets.
///
/// `script_offset` is the byte offset of the script content within the SFC file.
/// `template_offset` is the byte offset of the template content within the SFC file.
/// When these are provided, source mappings point to SFC-absolute positions.
/// `options` controls template globals and other generation settings.
pub fn generate_virtual_ts_with_offsets(
    summary: &Croquis,
    script_content: Option<&str>,
    template_ast: Option<&vize_relief::ast::RootNode<'_>>,
    script_offset: u32,
    template_offset: u32,
    options: &VirtualTsOptions,
) -> VirtualTsOutput {
    generate_virtual_ts_with_offsets_and_checks(
        summary,
        script_content,
        template_ast,
        script_offset,
        template_offset,
        options,
        VirtualTsGenerationOptions::default(),
    )
}

/// Generate virtual TypeScript with Vue 2.7 / Nuxt 2 compatibility enabled.
pub fn generate_virtual_ts_with_offsets_legacy_vue2(
    summary: &Croquis,
    script_content: Option<&str>,
    template_ast: Option<&vize_relief::ast::RootNode<'_>>,
    script_offset: u32,
    template_offset: u32,
    options: &VirtualTsOptions,
) -> VirtualTsOutput {
    generate_virtual_ts_with_offsets_and_checks(
        summary,
        script_content,
        template_ast,
        script_offset,
        template_offset,
        options,
        VirtualTsGenerationOptions {
            legacy_vue2: true,
            ..Default::default()
        },
    )
}

pub(crate) fn generate_virtual_ts_with_offsets_and_checks(
    summary: &Croquis,
    script_content: Option<&str>,
    template_ast: Option<&vize_relief::ast::RootNode<'_>>,
    script_offset: u32,
    template_offset: u32,
    options: &VirtualTsOptions,
    generation_options: VirtualTsGenerationOptions,
) -> VirtualTsOutput {
    let check_options = generation_options.check_options;
    let legacy_vue2 = generation_options.legacy_vue2;
    let mut ts = String::default();
    let mut mappings: Vec<VizeMapping> = Vec::new();

    // Header with ES target library references.
    // These ensure import.meta, Promise, Array.includes(), etc. are available.
    ts.push_str("/// <reference lib=\"es2022\" />\n");
    ts.push_str("/// <reference lib=\"dom\" />\n");
    ts.push_str("/// <reference lib=\"dom.iterable\" />\n");
    ts.push_str("// ============================================\n");
    ts.push_str("// Virtual TypeScript for Vue SFC Type Checking\n");
    ts.push_str("// Generated by vize\n");
    ts.push_str("// ============================================\n\n");

    // Check for generic type parameter from <script setup generic="T">
    let (generic_param, mut is_async) = summary
        .scopes
        .iter()
        .find(|s| matches!(s.kind, ScopeKind::ScriptSetup))
        .map(|s| {
            if let ScopeData::ScriptSetup(data) = s.data() {
                (data.generic.as_ref().map(|s| s.as_str()), data.is_async)
            } else {
                (None, false)
            }
        })
        .unwrap_or((None, false));

    // Also detect top-level await in script content (Vue 3 script setup supports this)
    if let Some(script) = script_content
        && script.contains("await ")
        && !is_async
    {
        is_async = true;
    }

    // ImportMeta augmentation (must be at top level, before any code)
    ts.push_str(IMPORT_META_AUGMENTATION);
    ts.push('\n');

    // Module scope: Extract imports, re-exports, and type declarations to module level.
    // Type declarations (interface, type, enum) must be at module level so they
    // are accessible from `export type Props = ...` outside __setup().
    ts.push_str("// ========== Module Scope (imports) ==========\n");
    ts.push_str(VUE_TYPE_HELPERS);
    ts.push('\n');

    // Collect all module-level statement spans from croquis analysis once and
    // keep them sorted. Later script-body emission advances an index through
    // this list, so each source line checks only the overlapping tail instead
    // of rescanning imports/re-exports/type declarations from the start.
    let module_spans: Vec<(u32, u32)> = profile!("canon.virtual_ts.collect_module_spans", {
        let mut module_spans = Vec::new();
        for imp in &summary.import_statements {
            module_spans.push((imp.start, imp.end));
        }
        for re in &summary.re_exports {
            module_spans.push((re.start, re.end));
        }
        let has_script_setup = summary
            .scopes
            .iter()
            .any(|scope| matches!(scope.kind, ScopeKind::ScriptSetup));
        if has_script_setup {
            module_spans.extend(summary.scopes.iter().filter_map(|scope| {
                matches!(scope.kind, ScopeKind::NonScriptSetup)
                    .then_some((scope.span.start, scope.span.end))
            }));
        }
        for te in &summary.type_exports {
            // Non-hoisted types reference setup-scope values via `typeof`
            // and must stay inside `__setup` so TS can resolve them.
            if te.hoisted {
                module_spans.push((te.start, te.end));
            }
        }
        merge_overlapping_spans(module_spans)
    });

    // For a `<script setup generic="...">` SFC, hoisted type declarations are
    // lifted verbatim to module scope, but the generic parameters only live on
    // `__setup<...>()`. A lifted declaration that mentions a generic parameter
    // (e.g. `type Option = { key: T }`) would reference an unbound name there.
    // Re-declare the SFC generics as defaulted parameters on each such
    // declaration (`type Option<T extends string = any> = ...`) so the
    // reference resolves at module scope while bare uses (`Option[]`) still
    // work via the `= any` defaults.
    let generic_injection: Option<(String, Vec<String>)> = generic_param.map(|g| {
        let defaults = add_generic_defaults(g);
        let names = extract_generic_names(g)
            .split(',')
            .map(|n| String::from(n.trim()))
            .filter(|n| !n.is_empty())
            .collect();
        (defaults, names)
    });
    let hoisted_type_spans: FxHashMap<(u32, u32), &str> = if generic_injection.is_some() {
        summary
            .type_exports
            .iter()
            .filter(|te| te.hoisted)
            .map(|te| ((te.start, te.end), te.name.as_str()))
            .collect()
    } else {
        FxHashMap::default()
    };

    if let Some(script) = script_content {
        profile!("canon.virtual_ts.emit_module_statements", {
            // Emit each module-level statement with source mapping
            for &(start, end) in &module_spans {
                let text = &script[start as usize..end as usize];

                // Splice the SFC generic parameters into a hoisted
                // type/interface declaration that references them, so the
                // reference resolves at module scope.
                if let Some((defaults, names)) = &generic_injection
                    && let Some(type_name) = hoisted_type_spans.get(&(start, end))
                    && references_any_identifier(text, names)
                    && let Some(inject_at) = generic_injection_point(text, type_name)
                {
                    let (prefix, suffix) = text.split_at(inject_at);
                    let src_base = script_offset as usize + start as usize;

                    let gen_start = ts.len();
                    ts.push_str(prefix);
                    mappings.push(VizeMapping {
                        gen_range: gen_start..ts.len(),
                        src_range: src_base..(src_base + prefix.len()),
                        sub_spans: Vec::new(),
                    });

                    // Synthetic parameter list; no corresponding source span.
                    append!(ts, "<{defaults}>");
                    // Avoid forming `>=` when the alias has no space before `=`.
                    if suffix.starts_with('=') {
                        ts.push(' ');
                    }

                    let gen_start = ts.len();
                    ts.push_str(suffix);
                    ts.push('\n');
                    mappings.push(VizeMapping {
                        gen_range: gen_start..ts.len(),
                        src_range: (src_base + prefix.len())
                            ..(src_base + prefix.len() + suffix.len()),
                        sub_spans: Vec::new(),
                    });
                    continue;
                }

                let gen_start = ts.len();
                if text.contains("export default") {
                    let text = rewrite_export_default_for_module_scope(text);
                    ts.push_str(&text);
                } else {
                    ts.push_str(text);
                }
                ts.push('\n');
                let gen_end = ts.len();
                mappings.push(VizeMapping {
                    gen_range: gen_start..gen_end,
                    src_range: (script_offset as usize + start as usize)
                        ..(script_offset as usize + end as usize),
                    sub_spans: Vec::new(),
                });
            }

            // Void-reference imported names that match setup-scope helper names.
            // These get shadowed by __setup() declarations, causing TS6133 at module level.
            let shadowed_imports: Vec<&&str> = SETUP_SCOPE_HELPER_NAMES
                .iter()
                .filter(|&&name| summary.bindings.bindings.contains_key(name))
                .collect();
            if !shadowed_imports.is_empty() {
                ts.push_str(
                    "// Prevent TS6133 for imports shadowed by setup-scope compiler macros\n",
                );
                for name in &shadowed_imports {
                    append!(ts, "void {name};\n");
                }
            }
        });
    }

    // Auto-import stubs (e.g., Nuxt composables)
    // Only emit stubs for names NOT already declared via imports or bindings.
    // Collect imported names from all module-level import statements to handle
    // cases where plain <script> imports are not in summary.bindings (which
    // only holds <script setup> bindings when both blocks exist).
    if !options.auto_import_stubs.is_empty() {
        let imported_names: FxHashSet<&str> = profile!(
            "canon.virtual_ts.extract_imported_names",
            if let Some(script) = script_content {
                summary
                    .import_statements
                    .iter()
                    .flat_map(|imp| {
                        let text = script
                            .get(imp.start as usize..imp.end as usize)
                            .unwrap_or("");
                        extract_import_names(text)
                    })
                    .collect()
            } else {
                FxHashSet::default()
            }
        );
        profile!("canon.virtual_ts.emit_auto_import_stubs", {
            let mut has_header = false;
            for stub in &options.auto_import_stubs {
                let name = extract_declared_name(stub);
                if let Some(name) = name {
                    // Skip if already imported or declared in script bindings
                    if summary.bindings.bindings.contains_key(name)
                        || imported_names.contains(&name)
                    {
                        continue;
                    }
                }
                if !has_header {
                    ts.push_str("\n// Auto-import stubs (framework-provided globals)\n");
                    has_header = true;
                }
                ts.push_str(stub);
                ts.push('\n');
            }
        });
    }
    ts.push('\n');

    // Props type (defined at module level so it's available inside __setup)
    profile!(
        "canon.virtual_ts.generate_props_type",
        generate_props_type(&mut ts, summary, generic_param)
    );

    // Setup scope: function that contains setup helpers and script content
    ts.push_str("// ========== Setup Scope ==========\n");
    let async_prefix = if is_async { "async " } else { "" };
    let generic_params = generic_param.map(|g| cstr!("<{g}>")).unwrap_or_default();
    append!(ts, "{async_prefix}function __setup{generic_params}() {{\n",);

    // Setup helpers (only valid inside setup scope)
    ts.push_str(VUE_SETUP_HELPERS);
    ts.push_str("\n\n");

    // User's script content (minus imports)
    if let Some(script) = script_content {
        profile!("canon.virtual_ts.emit_script_body", {
            ts.push_str("  // User setup code\n");
            let script_gen_start = ts.len();
            // Use split('\n') to correctly track byte offsets for CRLF files.
            // Rust's lines() strips \r from CRLF but +1 for \n undercounts,
            // causing src_byte_offset drift that incorrectly skips user code.
            let mut src_byte_offset: usize = 0; // offset within script content
            let mut module_span_index = 0usize;

            // Check if script uses import.meta and add a polyfill variable.
            // This avoids TS1343 when module is not set to es2020+.
            let uses_import_meta = script.contains("import.meta");
            if uses_import_meta {
                ts.push_str("  const __import_meta: any = {};\n");
            }

            for raw_line in script.split('\n') {
                // Strip trailing \r for output (normalize CRLF to LF)
                let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
                // raw_line.len() includes \r if present; +1 for the \n from split
                let raw_byte_len = raw_line.len() + 1;

                // Skip lines that overlap with module-level spans (imports, re-exports, type decls)
                let line_start = src_byte_offset;
                let line_end = line_start + raw_line.len(); // use raw length for span check
                while module_span_index < module_spans.len()
                    && module_spans[module_span_index].1 as usize <= line_start
                {
                    module_span_index += 1;
                }
                let is_module_level = module_spans[module_span_index..]
                    .iter()
                    .take_while(|&&(start, _)| (start as usize) < line_end)
                    .any(|&(start, end)| line_start < end as usize && line_end > start as usize);
                if is_module_level {
                    src_byte_offset += raw_byte_len;
                    continue;
                }
                let gen_line_start = ts.len();
                ts.push_str("  "); // indentation (not in source)
                let gen_content_start = ts.len();

                // Process the line: strip `export` keyword (invalid inside function),
                // replace import.meta with polyfill variable
                let mut output_line = std::borrow::Cow::Borrowed(line);

                // Strip `export` from non-import lines inside setup scope
                let trimmed_line = output_line.trim_start();
                if let Some(default_expr) = trimmed_line
                    .strip_prefix("export default")
                    .filter(|rest| rest.chars().next().is_none_or(char::is_whitespace))
                {
                    let leading_ws = &output_line[..output_line.len() - trimmed_line.len()];
                    #[allow(clippy::disallowed_types)]
                    {
                        output_line = std::borrow::Cow::Owned(
                            cstr!("{leading_ws}const __default__ ={}", default_expr).into(),
                        );
                    }
                } else if trimmed_line.starts_with("export ")
                    && !trimmed_line.starts_with("export type ")
                    && !trimmed_line.starts_with("export interface ")
                {
                    let leading_ws = &output_line[..output_line.len() - trimmed_line.len()];
                    if let Some(rest) = trimmed_line.strip_prefix("export ") {
                        #[allow(clippy::disallowed_types)]
                        {
                            output_line =
                                std::borrow::Cow::Owned(cstr!("{leading_ws}{rest}").into());
                        }
                    }
                }

                // Replace import.meta with polyfill variable to avoid TS1343
                if uses_import_meta && output_line.contains("import.meta") {
                    #[allow(clippy::disallowed_types)]
                    {
                        output_line = std::borrow::Cow::Owned(
                            output_line.replace("import.meta", "__import_meta"),
                        );
                    }
                }

                ts.push_str(&output_line);
                let gen_content_end = ts.len();
                ts.push('\n');
                // Map the line content (excluding the "  " indent prefix)
                if !line.is_empty() {
                    let src_line_start = script_offset as usize + src_byte_offset;
                    let src_line_end = src_line_start + line.len();
                    mappings.push(VizeMapping {
                        gen_range: gen_content_start..gen_content_end,
                        src_range: src_line_start..src_line_end,
                        sub_spans: Vec::new(),
                    });
                }
                let _ = gen_line_start; // suppress unused warning
                src_byte_offset += raw_byte_len;
            }
            let script_gen_end = ts.len();
            append!(
                ts,
                "  // @vize-map: {script_gen_start}:{script_gen_end} -> 0:{}\n\n",
                script.len()
            );
        });
    }

    // Template scope (nested inside setup)
    if template_ast.is_some() {
        profile!("canon.virtual_ts.emit_template_scope", {
            ts.push_str("  // ========== Template Scope (inherits from setup) ==========\n");

            // Collect ref bindings for auto-unwrapping in template
            let mut ref_bindings: Vec<&str> = summary
                .bindings
                .bindings
                .iter()
                .filter(|(name, binding_type)| {
                    summary.reactivity.needs_value_access(name.as_str())
                        || matches!(binding_type, BindingType::SetupMaybeRef)
                            && is_local_setup_binding(summary, name.as_str())
                })
                .map(|(name, _)| name.as_str())
                .collect();
            ref_bindings.sort_unstable();

            // Capture ref types BEFORE template scope to avoid circular references.
            // `typeof count` here refers to the setup-scope Ref<number>.
            if !ref_bindings.is_empty() {
                ts.push_str("  // Ref type captures (before template scope shadows them)\n");
                for name in &ref_bindings {
                    append!(ts, "  type __R_{name} = typeof {name};\n");
                }
            }

            // Semicolon prevents ASI issues when user script doesn't end with `;`
            // (e.g., `console.log(x)\n(function...)` would be parsed as a call)
            ts.push_str("  ;(function __template() {\n");

            // Shadow ref bindings with unwrapped types.
            // `var` allows reassignment (Vue templates can assign to refs).
            if !ref_bindings.is_empty() {
                ts.push_str("    // Auto-unwrap Vue refs in template scope\n");
                ts.push_str(
                    "    type __U<T> = T extends import('vue').Ref<infer V, any> ? V : T;\n",
                );
                for name in &ref_bindings {
                    append!(ts, "    var {name}: __U<__R_{name}> = undefined as any;\n");
                }
            }

            // Vue template context (available in template expressions)
            let template_context = profile!(
                "canon.virtual_ts.generate_template_context",
                generate_template_context(options)
            );
            ts.push_str(&template_context);
            ts.push('\n');

            // Props are available in template as variables
            profile!(
                "canon.virtual_ts.generate_props_variables",
                generate_props_variables(&mut ts, summary, script_content, generic_param)
            );
            if legacy_vue2 {
                profile!(
                    "canon.virtual_ts.generate_legacy_vue2_variables",
                    generate_legacy_vue2_variables(&mut ts, summary, options)
                );
            }
            let template_prop_names = profile!(
                "canon.virtual_ts.collect_template_prop_names",
                collect_template_prop_names(summary, script_content)
            );

            // Generate scope closures
            if check_options.any_enabled() {
                profile!(
                    "canon.virtual_ts.generate_scope_closures",
                    generate_scope_closures(
                        &mut ts,
                        &mut mappings,
                        summary,
                        &template_prop_names,
                        template_offset,
                        check_options,
                        options,
                    )
                );
            }

            // Declare unresolved components (auto-imported or built-in) as `any`.
            // Names known to be provided by ambient project declarations stay
            // unshadowed so their actual component prop types are preserved.
            if !summary.used_components.is_empty() {
                let external_template_bindings: FxHashSet<&str> = options
                    .external_template_bindings
                    .iter()
                    .map(|name| name.as_str())
                    .collect();
                let mut has_unresolved = false;
                for component in &summary.used_components {
                    let name = component.as_str();
                    // Skip if already declared via script bindings (import/const)
                    if summary.bindings.bindings.contains_key(name)
                        || external_template_bindings.contains(name)
                    {
                        continue;
                    }
                    if !has_unresolved {
                        ts.push_str(
                            "\n  // Auto-imported/built-in components (not in script bindings)\n",
                        );
                        has_unresolved = true;
                    }
                    let safe = to_safe_identifier(name);
                    append!(ts, "  const {safe}: any = undefined as any;\n");
                }

                ts.push_str("\n  // Mark used components as referenced\n");
                for component in &summary.used_components {
                    let safe = to_safe_identifier(component.as_str());
                    append!(ts, "  void {safe};\n");
                }
            }

            // Reference all setup bindings to prevent TS6133 for variables
            // used only in CSS v-bind() or other non-template contexts
            if !summary.bindings.bindings.is_empty() {
                ts.push_str("\n  // Reference setup bindings (used in template/CSS v-bind)\n  ");
                let mut first = true;
                let mut binding_names: Vec<&str> = summary
                    .bindings
                    .bindings
                    .keys()
                    .map(|name| name.as_str())
                    .collect();
                binding_names.sort_unstable();
                for name in binding_names {
                    // Skip bindings that are JS keywords or would cause syntax errors
                    if matches!(
                        name,
                        "default"
                            | "class"
                            | "new"
                            | "delete"
                            | "void"
                            | "typeof"
                            | "in"
                            | "instanceof"
                            | "return"
                            | "switch"
                            | "case"
                            | "break"
                            | "continue"
                            | "throw"
                            | "try"
                            | "catch"
                            | "finally"
                            | "if"
                            | "else"
                            | "for"
                            | "while"
                            | "do"
                            | "with"
                            | "var"
                            | "let"
                            | "const"
                            | "function"
                            | "this"
                            | "super"
                            | "import"
                            | "export"
                            | "yield"
                            | "await"
                            | "async"
                            | "static"
                            | "enum"
                            | "implements"
                            | "interface"
                            | "package"
                            | "private"
                            | "protected"
                            | "public"
                    ) {
                        continue;
                    }
                    if !first {
                        ts.push(' ');
                    }
                    append!(ts, "void {name};");
                    first = false;
                }
                ts.push('\n');
            }

            ts.push_str("  })();\n");
        });
    }

    // Reference props destructure bindings at setup scope level.
    // These variables are declared in user script (e.g., `const { foo } = defineProps<...>()`)
    // but shadowed inside __template() by generate_props_variables, so void them here.
    if let Some(destructure) = summary.macros.props_destructure()
        && !destructure.bindings.is_empty()
    {
        ts.push_str("\n  // Reference destructured props (prevent TS6133)\n  ");
        let mut first = true;
        for binding in destructure.bindings.values() {
            if !first {
                ts.push(' ');
            }
            append!(ts, "void {};", binding.local);
            first = false;
        }
        if let Some(ref rest) = destructure.rest_id {
            if !first {
                ts.push(' ');
            }
            append!(ts, "void {};", rest);
        }
        ts.push('\n');
    }

    // Return exposed object from __setup() so its type can be extracted at module level.
    // This keeps the runtime args expression in scope (where the bindings are defined).
    if let Some(expose) = summary.macros.define_expose()
        && expose.type_args.is_none()
        && let Some(runtime_args) = expose.runtime_args.as_ref()
    {
        append!(ts, "\n  return ({runtime_args});\n");
    }

    // Close setup function
    ts.push_str("}\n\n");

    // Invoke setup to keep diagnostics inside the generated setup body.
    ts.push_str("// Invoke setup to verify types\n");
    ts.push_str("__setup();\n\n");

    // Emits type
    let emits_already_defined = summary
        .type_exports
        .iter()
        .any(|te| te.name.as_str() == "Emits");
    let define_emits_type_args = summary
        .macros
        .define_emits()
        .and_then(|call| call.type_args.as_ref());
    let has_emits_for_props = emits_already_defined
        || define_emits_type_args.is_some()
        || !summary.macros.emits().is_empty();
    if !emits_already_defined {
        if let Some(type_args) = define_emits_type_args {
            let inner_type = type_args
                .strip_prefix('<')
                .and_then(|s| s.strip_suffix('>'))
                .unwrap_or(type_args.as_str());
            append!(ts, "export type Emits = {inner_type};\n");
        } else if !summary.macros.emits().is_empty() {
            ts.push_str("export type Emits = {\n");
            for emit in summary.macros.emits() {
                let payload = emit.payload_type.as_deref().unwrap_or("any[]");
                append!(ts, "  \"{}\": {payload};\n", emit.name);
            }
            ts.push_str("};\n");
        } else {
            ts.push_str("export type Emits = {};\n");
        }
    }

    // Slots type
    let slots_type_args = summary
        .macros
        .define_slots()
        .and_then(|m| m.type_args.as_ref());
    if let Some(type_args) = slots_type_args {
        let inner_type = type_args
            .strip_prefix('<')
            .and_then(|s| s.strip_suffix('>'))
            .unwrap_or(type_args.as_str());
        append!(ts, "export type Slots = {inner_type};\n");
    } else {
        ts.push_str("export type Slots = {};\n");
    }

    // Exposed type (for InstanceType and useTemplateRef)
    if let Some(expose) = summary.macros.define_expose() {
        if let Some(ref type_args) = expose.type_args {
            let inner_type = type_args
                .strip_prefix('<')
                .and_then(|s| s.strip_suffix('>'))
                .unwrap_or(type_args.as_str());
            append!(ts, "export type Exposed = {inner_type};\n");
        } else if expose.runtime_args.is_some() {
            // Runtime args are returned from __setup() to keep them in scope.
            // Use Awaited<ReturnType<...>> to handle both sync and async setup.
            ts.push_str("export type Exposed = Awaited<ReturnType<typeof __setup>>;\n");
        }
    }
    ts.push('\n');

    if has_emits_for_props {
        ts.push_str("type __VizeOverloadProps<TOverload> = Pick<TOverload, keyof TOverload>;\n");
        ts.push_str("type __VizeOverloadUnionRecursive<TOverload, TPartialOverload = unknown> = TOverload extends (...args: infer TArgs) => infer TReturn ? TPartialOverload extends TOverload ? never : __VizeOverloadUnionRecursive<TPartialOverload & TOverload, TPartialOverload & ((...args: TArgs) => TReturn) & __VizeOverloadProps<TOverload>> | ((...args: TArgs) => TReturn) : never;\n");
        ts.push_str("type __VizeOverloadUnion<TOverload extends (...args: any[]) => any> = Exclude<__VizeOverloadUnionRecursive<(() => never) & TOverload>, TOverload extends () => never ? never : () => never>;\n");
        ts.push_str("type __VizeOverloadParameters<T extends (...args: any[]) => any> = Parameters<__VizeOverloadUnion<T>>;\n");
        ts.push_str("type __VizeIsStringLiteral<T> = T extends string ? string extends T ? false : true : false;\n");
        ts.push_str("type __VizeParametersToFns<T extends any[]> = { [K in T[0]]: __VizeIsStringLiteral<K> extends true ? (...args: T extends [e: infer E, ...args: infer P] ? K extends E ? P : never : never) => any : never };\n");
        ts.push_str("type __EmitOptions<T> = { [K in keyof __EmitShape<T> & string]: (...args: __EmitArgs<__EmitShape<T>, K>) => any } & (__EmitShape<T> extends (...args: any[]) => any ? __VizeParametersToFns<__VizeOverloadParameters<__EmitShape<T>>> : {});\n");
        ts.push_str("type __EmitProps<T> = import('vue').EmitsToProps<__EmitOptions<T>>;\n\n");
    }

    // Default export
    ts.push_str("// ========== Default Export ==========\n");
    ts.push_str("type __VizeComponentInstance = {\n");
    if has_emits_for_props {
        ts.push_str("  $props: Props & __EmitProps<Emits>;\n");
    } else {
        ts.push_str("  $props: Props;\n");
    }
    ts.push_str("  $emit: __EmitFn<Emits>;\n");
    ts.push_str("  $slots: Slots;\n");
    ts.push_str("};\n");
    // For a `<script setup generic="...">` component the construct signature's
    // `$props` collapses `Props<T>` to its constraint, so a parent that extracts
    // props via `typeof Comp extends { new (): { $props } }` cannot infer `T`
    // from the passed prop values. Expose a generic functional prop-checker on
    // the default export so the parent can invoke it with the assembled props
    // object and let TypeScript infer `T` from the call (see #775). Non-generic
    // components keep the plain construct signature unchanged.
    if let Some(generic) = generic_param {
        let generic_decl = add_generic_defaults(generic);
        let generic_names = extract_generic_names(generic);
        append!(
            ts,
            "declare const __vize_component__: (new (...args: any[]) => __VizeComponentInstance) & {{ __vizeCheck: <{generic_decl}>(props: Partial<Props<{generic_names}>> & Record<string, unknown>) => void; }};\n",
        );
    } else {
        ts.push_str(
            "declare const __vize_component__: new (...args: any[]) => __VizeComponentInstance;\n",
        );
    }
    ts.push_str("export default __vize_component__;\n");

    VirtualTsOutput { code: ts, mappings }
}

fn merge_overlapping_spans(mut spans: Vec<(u32, u32)>) -> Vec<(u32, u32)> {
    spans.retain(|(start, end)| start < end);
    spans.sort_by_key(|&(start, end)| (start, end));

    let mut merged: Vec<(u32, u32)> = Vec::with_capacity(spans.len());
    for (start, end) in spans {
        if let Some((_, previous_end)) = merged.last_mut()
            && start <= *previous_end
        {
            *previous_end = (*previous_end).max(end);
            continue;
        }
        merged.push((start, end));
    }
    merged
}

fn rewrite_export_default_for_module_scope(text: &str) -> String {
    let mut output = String::with_capacity(text.len());
    for segment in text.split_inclusive('\n') {
        let (line_with_optional_cr, newline) = segment
            .strip_suffix('\n')
            .map_or((segment, ""), |line| (line, "\n"));
        let (line, carriage_return) = line_with_optional_cr
            .strip_suffix('\r')
            .map_or((line_with_optional_cr, ""), |line| (line, "\r"));

        let trimmed_line = line.trim_start();
        if let Some(default_expr) = trimmed_line
            .strip_prefix("export default")
            .filter(|rest| rest.chars().next().is_none_or(char::is_whitespace))
        {
            let leading_ws = &line[..line.len() - trimmed_line.len()];
            append!(output, "{leading_ws}const __default__ ={default_expr}");
        } else {
            output.push_str(line);
        }
        output.push_str(carriage_return);
        output.push_str(newline);
    }

    output
}

/// Extract imported identifier names from an import statement string.
/// Handles `import { a, b as c } from "..."` and `import D from "..."`.
/// Returns the local names (e.g., `["a", "c", "D"]`).
fn extract_declared_name(stub: &str) -> Option<&str> {
    for prefix in [
        "declare function ",
        "declare const ",
        "declare let ",
        "declare var ",
    ] {
        let Some(rest) = stub.strip_prefix(prefix) else {
            continue;
        };
        let end = rest
            .find(['<', '(', ':', '=', ';', ' '])
            .unwrap_or(rest.len());
        let name = rest[..end].trim();
        if !name.is_empty() {
            return Some(name);
        }
    }

    None
}

fn extract_import_names(import_text: &str) -> Vec<&str> {
    let mut names = Vec::new();

    // Find the content between { and }
    if let Some(brace_start) = import_text.find('{') {
        if let Some(brace_end) = import_text.find('}') {
            let inner = &import_text[brace_start + 1..brace_end];
            for part in inner.split(',') {
                let part = part.trim();
                if part.is_empty() || part.starts_with("//") || part.starts_with("type ") {
                    continue;
                }
                // Handle "name as alias" -> use alias
                if let Some(as_pos) = part.find(" as ") {
                    let alias = part[as_pos + 4..].trim();
                    if !alias.is_empty() {
                        names.push(alias);
                    }
                } else {
                    // Simple name (strip \r for CRLF files)
                    let name = part.strip_suffix('\r').unwrap_or(part);
                    if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                        names.push(name);
                    }
                }
            }
        }
    } else {
        // Handle `import Name from "..."`
        let text = import_text.trim();
        if let Some(rest) = text.strip_prefix("import ")
            && let Some(from_pos) = rest.find(" from ")
        {
            let name = rest[..from_pos].trim();
            if !name.is_empty()
                && !name.contains('{')
                && !name.contains('*')
                && name.chars().all(|c| c.is_alphanumeric() || c == '_')
            {
                names.push(name);
            }
        }
    }

    names
}

fn is_local_setup_binding(summary: &Croquis, name: &str) -> bool {
    let Some(&(start, end)) = summary.binding_spans.get(name) else {
        return true;
    };

    !summary
        .import_statements
        .iter()
        .any(|import| start >= import.start && end <= import.end)
}

fn generate_legacy_vue2_variables(
    mut ts: &mut String,
    summary: &Croquis,
    options: &VirtualTsOptions,
) {
    let macro_prop_names: FxHashSet<&str> = summary
        .macros
        .props()
        .iter()
        .map(|prop| prop.name.as_str())
        .collect();
    let configured_globals: FxHashSet<&str> = options
        .template_globals
        .iter()
        .map(|global| global.name.as_str())
        .collect();
    let mut names: Vec<&str> = summary
        .bindings
        .bindings
        .iter()
        .filter_map(|(name, binding_type)| {
            let name = name.as_str();
            match binding_type {
                BindingType::Data | BindingType::Options | BindingType::VueGlobal => Some(name),
                BindingType::Props if !macro_prop_names.contains(name) => Some(name),
                _ => None,
            }
        })
        .filter(|name| !configured_globals.contains(name))
        .filter(|name| is_safe_value_identifier(name))
        .collect();
    names.sort_unstable();
    names.dedup();

    if names.is_empty() {
        return;
    }

    ts.push_str("  // Vue 2.7 / Nuxt 2 Options API template bindings\n");
    for name in &names {
        append!(ts, "  const {name}: any = undefined as any;\n");
    }
    ts.push_str("  ");
    for name in &names {
        append!(ts, "void {name};");
    }
    ts.push('\n');
}

fn is_safe_value_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first.is_ascii_alphabetic() || first == '_' || first == '$') {
        return false;
    }
    chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '$')
}

fn is_ident_byte(b: u8) -> bool {
    b == b'_' || b == b'$' || b.is_ascii_alphanumeric()
}

fn skip_ascii_ws(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    i
}

/// Whether `haystack` mentions any of `idents` as a whole-word identifier.
/// Used to decide whether a lifted type declaration depends on an SFC generic
/// parameter and therefore needs that parameter re-declared on it.
fn references_any_identifier(haystack: &str, idents: &[String]) -> bool {
    let bytes = haystack.as_bytes();
    idents.iter().any(|ident| {
        let ident = ident.as_str();
        if ident.is_empty() {
            return false;
        }
        let mut from = 0;
        while let Some(rel) = haystack[from..].find(ident) {
            let at = from + rel;
            let before_ok = at == 0 || !is_ident_byte(bytes[at - 1]);
            let after = at + ident.len();
            let after_ok = after >= bytes.len() || !is_ident_byte(bytes[after]);
            if before_ok && after_ok {
                return true;
            }
            from = at + ident.len();
        }
        false
    })
}

/// Byte offset within a hoisted `type` / `interface` declaration immediately
/// after the declared name, where synthetic generic parameters can be spliced
/// in. Returns `None` if the declaration already has its own `<...>` parameter
/// list or the name can't be located (the declaration is then emitted as-is).
fn generic_injection_point(decl: &str, type_name: &str) -> Option<usize> {
    let bytes = decl.as_bytes();
    let mut i = skip_ascii_ws(bytes, 0);

    // Optional `export` modifier.
    if decl[i..].starts_with("export")
        && matches!(bytes.get(i + 6), Some(b) if b.is_ascii_whitespace())
    {
        i = skip_ascii_ws(bytes, i + 6);
    }

    // Declaration keyword.
    if decl[i..].starts_with("type")
        && matches!(bytes.get(i + 4), Some(b) if b.is_ascii_whitespace())
    {
        i += 4;
    } else if decl[i..].starts_with("interface")
        && matches!(bytes.get(i + 9), Some(b) if b.is_ascii_whitespace())
    {
        i += 9;
    } else {
        return None;
    }
    i = skip_ascii_ws(bytes, i);

    // Declared name.
    if !decl[i..].starts_with(type_name) {
        return None;
    }
    let name_end = i + type_name.len();
    // Reject partial-name matches (`Foo` inside `Foobar`).
    if matches!(bytes.get(name_end), Some(&b) if is_ident_byte(b)) {
        return None;
    }
    // Skip declarations that already declare their own type parameters.
    if bytes.get(skip_ascii_ws(bytes, name_end)) == Some(&b'<') {
        return None;
    }
    Some(name_end)
}