macroforge_ts 0.1.78

TypeScript macro expansion engine - write compile-time macros in Rust
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
//! # Patch Application Engine
//!
//! This module provides the core patch application functionality that transforms
//! source code according to patches generated by macros. It supports multiple
//! patch types and generates bidirectional source mappings for IDE integration.
//!
//! ## Patch Types
//!
//! The engine supports five patch operations:
//!
//! | Type | Description |
//! |------|-------------|
//! | `Insert` | Insert formatted AST node at position |
//! | `InsertRaw` | Insert raw text at position |
//! | `Replace` | Replace span with formatted AST node |
//! | `ReplaceRaw` | Replace span with raw text |
//! | `Delete` | Remove span entirely |
//!
//! ## Application Strategy
//!
//! Patches are sorted by position and applied in forward order, with the
//! source mapping tracking position shifts:
//!
//! ```text
//! Original:  "class Foo {}"
//!                      ^ Insert " bar: string;" at position 11
//!
//! Expanded:  "class Foo { bar: string;}"
//!
//! Source Mapping:
//!   Segment 1: original[0-11] -> expanded[0-11]  (unchanged: "class Foo {")
//!   Generated: expanded[11-25] = " bar: string;" (from macro "Test")
//!   Segment 2: original[11-12] -> expanded[25-26] (unchanged: "}")
//! ```
//!
//! ## Position Conventions
//!
//! All [`SpanIR`] positions in patches use **1-based** byte offsets (matching SWC's
//! internal convention). The [`SourceMapping`] output uses **0-based** positions
//! (matching the TypeScript language service API). The applicator converts between
//! these conventions internally.
//!
//! ## Source Mapping
//!
//! The engine generates source mapping data that enables:
//! - Converting positions from original to expanded code
//! - Converting positions from expanded back to original
//! - Identifying which macro generated specific code regions
//! - Mapping IDE diagnostics to original source locations
//!
//! ## Example Usage
//!
//! ```rust,no_run
//! use macroforge_ts::host::patch_applicator::{PatchApplicator, PatchCollector};
//! use macroforge_ts::host::Result;
//! use macroforge_ts::ts_syn::abi::{Patch, SpanIR};
//!
//! fn example() -> Result<()> {
//!     let source = "class Foo {}";
//!
//!     // Using PatchApplicator directly
//!     let patch = Patch::Insert {
//!         at: SpanIR { start: 12, end: 12 },  // 1-based position
//!         code: " bar: string;".into(),
//!         source_macro: Some("Test".to_string()),
//!     };
//!
//!     let applicator = PatchApplicator::new(source, vec![patch]);
//!     let result = applicator.apply_with_mapping(None)?;
//!
//!     assert_eq!(result.code, "class Foo { bar: string;}");
//!     assert!(!result.mapping.is_empty());
//!
//!     // Using PatchCollector for multiple macros
//!     let mut collector = PatchCollector::new();
//!
//!     // Add patches from different macros
//!     let debug_patch = Patch::Insert {
//!         at: SpanIR { start: 12, end: 12 },
//!         code: " toString() { return 'Foo'; }".into(),
//!         source_macro: Some("Debug".to_string()),
//!     };
//!     collector.add_runtime_patches(vec![debug_patch]);
//!
//!     // Apply all collected patches
//!     let runtime_result = collector.apply_runtime_patches_with_mapping(source, None)?;
//!     Ok(())
//! }
//! ```

use super::error::{MacroError, Result};
use crate::ts_syn::abi::{
    GeneratedRegion, MappingSegment, Patch, PatchCode, SourceMapping, SpanIR,
};
use std::collections::HashSet;
use swc_core::{
    common::{SourceMap, sync::Lrc},
    ecma::codegen::{Config, Emitter, Node, text_writer::JsWriter},
};

/// Result of applying patches with source mapping
#[derive(Clone, Debug)]
pub struct ApplyResult {
    /// The transformed source code
    pub code: String,
    /// Bidirectional source mapping between original and expanded positions
    pub mapping: SourceMapping,
}

/// Applies patches to source code
pub struct PatchApplicator<'a> {
    source: &'a str,
    patches: Vec<Patch>,
}

impl<'a> PatchApplicator<'a> {
    /// Create a new patch applicator
    pub fn new(source: &'a str, patches: Vec<Patch>) -> Self {
        Self { source, patches }
    }

    /// Apply all patches and return the modified source code
    pub fn apply(mut self) -> Result<String> {
        // Sort patches by position (reverse order for proper application)
        self.sort_patches();

        // Validate patches don't overlap
        self.validate_no_overlaps()?;

        // Apply patches in reverse order (from end to start)
        let mut result = self.source.to_string();

        for patch in self.patches.iter().rev() {
            match patch {
                Patch::Insert { at, code, .. } => {
                    let rendered = render_patch_code(code)?;
                    let formatted =
                        self.format_insertion(&rendered, at.start.saturating_sub(1) as usize, code);
                    // Safety: ensure index is within bounds
                    let idx = at.start.saturating_sub(1) as usize;
                    if idx <= result.len() {
                        result.insert_str(idx, &formatted);
                    }
                }
                Patch::InsertRaw { at, code, .. } => {
                    let idx = at.start.saturating_sub(1) as usize;
                    if idx <= result.len() {
                        result.insert_str(idx, code);
                    }
                }
                Patch::Replace { span, code, .. } => {
                    let rendered = render_patch_code(code)?;
                    let start = span.start.saturating_sub(1) as usize;
                    let end = span.end.saturating_sub(1) as usize;
                    if start <= end && end <= result.len() {
                        result.replace_range(start..end, &rendered);
                    }
                }
                Patch::ReplaceRaw { span, code, .. } => {
                    let start = span.start.saturating_sub(1) as usize;
                    let end = span.end.saturating_sub(1) as usize;
                    if start <= end && end <= result.len() {
                        result.replace_range(start..end, code);
                    }
                }
                Patch::Delete { span } => {
                    let start = span.start.saturating_sub(1) as usize;
                    let end = span.end.saturating_sub(1) as usize;
                    if start <= end && end <= result.len() {
                        result.replace_range(start..end, "");
                    }
                }
            }
        }

        Ok(result)
    }

    /// Apply all patches and return both the modified source code and source mapping.
    ///
    /// The `fallback_macro_name` is used when a patch doesn't have its own `source_macro` set.
    pub fn apply_with_mapping(mut self, fallback_macro_name: Option<&str>) -> Result<ApplyResult> {
        // Sort patches by position (forward order for mapping generation)
        self.sort_patches();

        // Validate patches don't overlap
        self.validate_no_overlaps()?;

        // If no patches, return identity mapping (0-based positions for TS API)
        if self.patches.is_empty() {
            let source_len = self.source.len() as u32;
            let mut mapping = SourceMapping::new();
            if source_len > 0 {
                // 0-based: position 0 to source_len (exclusive end)
                mapping.add_segment(MappingSegment::new(0, source_len, 0, source_len));
            }
            return Ok(ApplyResult {
                code: self.source.to_string(),
                mapping,
            });
        }

        let mut result = String::new();
        let mut mapping = SourceMapping::with_capacity(self.patches.len() + 1, self.patches.len());

        // Track positions: internally use 1-based (matching SWC spans),
        // but convert to 0-based when creating MappingSegments (matching TS API)
        let mut original_pos: u32 = 1; // 1-based position (start of file)
        let mut expanded_pos: u32 = 1; // 1-based position
        let source_len = self.source.len() as u32;
        let source_end_pos = source_len + 1; // 1-based position after last char
        let default_macro_name = fallback_macro_name.unwrap_or("macro");

        for patch in &self.patches {
            // Helper closure to copy unchanged content
            let mut copy_unchanged = |upto: u32| {
                if upto > original_pos {
                    let len = upto - original_pos;
                    let start = original_pos.saturating_sub(1) as usize;
                    let end = upto.saturating_sub(1) as usize;

                    if end <= self.source.len() {
                        let unchanged = &self.source[start..end];
                        result.push_str(unchanged);

                        // Create 0-based segment for SourceMapping API
                        mapping.add_segment(MappingSegment::new(
                            original_pos - 1,       // Convert to 0-based
                            upto - 1,               // Convert to 0-based
                            expanded_pos - 1,       // Convert to 0-based
                            expanded_pos + len - 1, // Convert to 0-based
                        ));

                        expanded_pos += len;
                        original_pos = upto;
                    }
                }
            };

            // Get the macro name for this patch (use per-patch source_macro if available, else fallback)
            let macro_attribution = patch.source_macro().unwrap_or(default_macro_name);

            match patch {
                Patch::Insert { at, code, .. } => {
                    copy_unchanged(at.start);

                    let rendered = render_patch_code(code)?;
                    let formatted =
                        self.format_insertion(&rendered, at.start.saturating_sub(1) as usize, code);
                    let gen_len = formatted.len() as u32;

                    result.push_str(&formatted);
                    // Create 0-based generated region
                    mapping.add_generated(GeneratedRegion::new(
                        expanded_pos - 1,
                        expanded_pos - 1 + gen_len,
                        macro_attribution,
                    ));
                    expanded_pos += gen_len;
                }
                Patch::InsertRaw { at, code, .. } => {
                    copy_unchanged(at.start);

                    let gen_len = code.len() as u32;
                    result.push_str(code);
                    // Create 0-based generated region
                    mapping.add_generated(GeneratedRegion::new(
                        expanded_pos - 1,
                        expanded_pos - 1 + gen_len,
                        macro_attribution,
                    ));
                    expanded_pos += gen_len;
                }
                Patch::Replace { span, code, .. } => {
                    copy_unchanged(span.start);

                    let rendered = render_patch_code(code)?;
                    let gen_len = rendered.len() as u32;

                    result.push_str(&rendered);
                    // Create 0-based generated region
                    mapping.add_generated(GeneratedRegion::new(
                        expanded_pos - 1,
                        expanded_pos - 1 + gen_len,
                        macro_attribution,
                    ));

                    expanded_pos += gen_len;
                    original_pos = span.end;
                }
                Patch::Delete { span } => {
                    copy_unchanged(span.start);
                    // Skip content
                    original_pos = span.end;
                }
                Patch::ReplaceRaw { span, code, .. } => {
                    copy_unchanged(span.start);

                    let gen_len = code.len() as u32;
                    result.push_str(code);
                    // Create 0-based generated region
                    mapping.add_generated(GeneratedRegion::new(
                        expanded_pos - 1,
                        expanded_pos - 1 + gen_len,
                        macro_attribution,
                    ));
                    expanded_pos += gen_len;
                    original_pos = span.end;
                }
            }
        }

        // Copy any remaining unchanged content after the last patch
        if original_pos < source_end_pos {
            let len = source_end_pos - original_pos;
            let start = original_pos.saturating_sub(1) as usize;
            let remaining = &self.source[start..]; // safe slice to end
            result.push_str(remaining);

            // Create 0-based segment
            mapping.add_segment(MappingSegment::new(
                original_pos - 1,
                source_end_pos - 1,
                expanded_pos - 1,
                expanded_pos - 1 + len,
            ));
        }

        Ok(ApplyResult {
            code: result,
            mapping,
        })
    }

    /// Format an insertion with proper indentation and newlines
    fn format_insertion(&self, rendered: &str, position: usize, code: &PatchCode) -> String {
        if !matches!(code, PatchCode::ClassMember(_)) {
            return rendered.to_string();
        }

        let indent = self.detect_indentation(position);
        format!("\n{}{}\n", indent, rendered.trim())
    }

    /// Detect indentation level at a given position by looking backwards
    fn detect_indentation(&self, position: usize) -> String {
        let bytes = self.source.as_bytes();
        let mut search_pos = position.saturating_sub(1);
        let mut found_indent: Option<String> = None;
        let search_limit = position.saturating_sub(500);

        while search_pos > search_limit && search_pos < bytes.len() {
            // Find the start of this line
            let mut line_start = search_pos;
            while line_start > 0 && bytes[line_start - 1] != b'\n' {
                line_start -= 1;
            }

            // Find the end of this line
            let mut line_end = search_pos;
            while line_end < bytes.len() && bytes[line_end] != b'\n' {
                line_end += 1;
            }

            if line_start >= line_end {
                if line_start == 0 {
                    break;
                }
                search_pos = line_start - 1;
                continue;
            }

            let line = &self.source[line_start..line_end];
            let trimmed = line.trim();

            if !trimmed.is_empty()
                && !trimmed.starts_with('}')
                && !trimmed.starts_with('@')
                && (trimmed.contains(':')
                    || trimmed.contains('(')
                    || trimmed.starts_with("constructor"))
            {
                let indent_count = line.chars().take_while(|c| c.is_whitespace()).count();
                if indent_count > 0 {
                    found_indent = Some(line.chars().take(indent_count).collect());
                    break;
                }
            }

            if line_start == 0 {
                break;
            }
            search_pos = line_start - 1;
        }

        found_indent.unwrap_or_else(|| "  ".to_string())
    }

    fn sort_patches(&mut self) {
        self.patches.sort_by_key(|patch| match patch {
            Patch::Insert { at, .. } => at.start,
            Patch::InsertRaw { at, .. } => at.start,
            Patch::Replace { span, .. } => span.start,
            Patch::ReplaceRaw { span, .. } => span.start,
            Patch::Delete { span } => span.start,
        });
    }

    fn validate_no_overlaps(&self) -> Result<()> {
        for i in 0..self.patches.len() {
            for j in i + 1..self.patches.len() {
                if self.patches_overlap(&self.patches[i], &self.patches[j]) {
                    return Err(MacroError::Other(anyhow::anyhow!(
                        "Overlapping patches detected: patches cannot modify the same region"
                    )));
                }
            }
        }
        Ok(())
    }

    fn patches_overlap(&self, a: &Patch, b: &Patch) -> bool {
        let a_span = self.get_patch_span(a);
        let b_span = self.get_patch_span(b);
        !(a_span.end <= b_span.start || b_span.end <= a_span.start)
    }

    fn get_patch_span(&self, patch: &Patch) -> SpanIR {
        match patch {
            Patch::Insert { at, .. } => *at,
            Patch::InsertRaw { at, .. } => *at,
            Patch::Replace { span, .. } => *span,
            Patch::ReplaceRaw { span, .. } => *span,
            Patch::Delete { span } => *span,
        }
    }
}

/// Builder for collecting and applying patches from multiple macros.
///
/// Accumulates runtime patches (`.ts`/`.js` output) and type patches (`.d.ts` output)
/// separately, then applies them with deduplication.
pub struct PatchCollector {
    runtime_patches: Vec<Patch>,
    type_patches: Vec<Patch>,
}

impl PatchCollector {
    /// Create a new empty patch collector.
    pub fn new() -> Self {
        Self {
            runtime_patches: Vec::new(),
            type_patches: Vec::new(),
        }
    }

    /// Append runtime code patches (inserted into `.ts`/`.js` output).
    pub fn add_runtime_patches(&mut self, patches: Vec<Patch>) {
        self.runtime_patches.extend(patches);
    }

    /// Append type-level patches (inserted into `.d.ts` output).
    pub fn add_type_patches(&mut self, patches: Vec<Patch>) {
        self.type_patches.extend(patches);
    }

    /// Returns `true` if any type-level patches have been collected.
    pub fn has_type_patches(&self) -> bool {
        !self.type_patches.is_empty()
    }

    /// Returns `true` if any patches (runtime or type) have been collected.
    pub fn has_patches(&self) -> bool {
        !self.runtime_patches.is_empty() || !self.type_patches.is_empty()
    }

    /// Returns the number of runtime patches collected so far.
    pub fn runtime_patches_count(&self) -> usize {
        self.runtime_patches.len()
    }

    /// Returns a slice of runtime patches starting from the given index.
    pub fn runtime_patches_slice(&self, start: usize) -> &[Patch] {
        &self.runtime_patches[start..]
    }

    /// Apply all collected runtime patches to the source, returning the modified code.
    ///
    /// Deduplicates patches before applying. Returns the original source unchanged
    /// if no runtime patches have been collected.
    pub fn apply_runtime_patches(&self, source: &str) -> Result<String> {
        if self.runtime_patches.is_empty() {
            return Ok(source.to_string());
        }
        let mut patches = self.runtime_patches.clone();
        dedupe_patches(&mut patches)?;
        let applicator = PatchApplicator::new(source, patches);
        applicator.apply()
    }

    /// Apply all collected type patches to the source, returning the modified code.
    ///
    /// Deduplicates patches before applying. Returns the original source unchanged
    /// if no type patches have been collected.
    pub fn apply_type_patches(&self, source: &str) -> Result<String> {
        if self.type_patches.is_empty() {
            return Ok(source.to_string());
        }
        let mut patches = self.type_patches.clone();
        dedupe_patches(&mut patches)?;
        let applicator = PatchApplicator::new(source, patches);
        applicator.apply()
    }

    /// Apply runtime patches and return both the modified code and source mapping.
    ///
    /// # Arguments
    ///
    /// * `source` - The original source code
    /// * `macro_name` - Fallback attribution for patches without `source_macro`
    pub fn apply_runtime_patches_with_mapping(
        &self,
        source: &str,
        macro_name: Option<&str>,
    ) -> Result<ApplyResult> {
        if self.runtime_patches.is_empty() {
            // ... (Empty logic same as before)
            let source_len = source.len() as u32;
            let mut mapping = SourceMapping::new();
            if source_len > 0 {
                mapping.add_segment(MappingSegment::new(0, source_len, 0, source_len));
            }
            return Ok(ApplyResult {
                code: source.to_string(),
                mapping,
            });
        }
        let mut patches = self.runtime_patches.clone();
        dedupe_patches(&mut patches)?;
        let applicator = PatchApplicator::new(source, patches);
        applicator.apply_with_mapping(macro_name)
    }

    /// Apply type patches and return both the modified code and source mapping.
    ///
    /// # Arguments
    ///
    /// * `source` - The original source code
    /// * `macro_name` - Fallback attribution for patches without `source_macro`
    pub fn apply_type_patches_with_mapping(
        &self,
        source: &str,
        macro_name: Option<&str>,
    ) -> Result<ApplyResult> {
        if self.type_patches.is_empty() {
            let source_len = source.len() as u32;
            let mut mapping = SourceMapping::new();
            if source_len > 0 {
                mapping.add_segment(MappingSegment::new(0, source_len, 0, source_len));
            }
            return Ok(ApplyResult {
                code: source.to_string(),
                mapping,
            });
        }
        let mut patches = self.type_patches.clone();
        dedupe_patches(&mut patches)?;
        let applicator = PatchApplicator::new(source, patches);
        applicator.apply_with_mapping(macro_name)
    }

    /// Returns a reference to the collected type patches.
    pub fn get_type_patches(&self) -> &Vec<Patch> {
        &self.type_patches
    }
}

impl Default for PatchCollector {
    fn default() -> Self {
        Self::new()
    }
}

/// Fixed dedupe logic: Separate key generation from filtering.
/// Also performs import-aware deduplication: when both `import type { X }` and
/// `import { X }` exist for the same specifier and module, the value import
/// subsumes the type-only import (since a value import is usable in both
/// value and type positions).
fn dedupe_patches(patches: &mut Vec<Patch>) -> Result<()> {
    // Phase 1: Collect import-aware dedup info.
    // For InsertRaw patches with context == "import", parse the specifier and module,
    // then drop type-only imports when a matching value import exists.
    dedupe_imports(patches);

    // Phase 2: Standard exact-match deduplication.
    let mut seen: HashSet<(u8, u32, u32, Option<String>)> = HashSet::new();
    let mut indices_to_keep = Vec::new();

    for (i, patch) in patches.iter().enumerate() {
        let key = match patch {
            Patch::Insert { at, code, .. } => (0, at.start, at.end, Some(render_patch_code(code)?)),
            Patch::InsertRaw { at, code, .. } => (3, at.start, at.end, Some(code.clone())),
            Patch::Replace { span, code, .. } => {
                (1, span.start, span.end, Some(render_patch_code(code)?))
            }
            Patch::ReplaceRaw { span, code, .. } => (4, span.start, span.end, Some(code.clone())),
            Patch::Delete { span } => (2, span.start, span.end, None),
        };

        if seen.insert(key) {
            indices_to_keep.push(i);
        }
    }

    let old_patches = std::mem::take(patches);
    *patches = indices_to_keep
        .into_iter()
        .map(|i| old_patches[i].clone())
        .collect();

    Ok(())
}

/// Parses an import patch's code string into (specifier, module, is_type_only).
///
/// Handles formats like:
/// - `import { Foo } from "bar";\n`          → ("Foo", "bar", false)
/// - `import type { Foo } from "bar";\n`     → ("Foo", "bar", true)
/// - `import { Foo as Bar } from "bar";\n`   → ("Foo", "bar", false)  (base name = "Foo")
fn parse_import_patch(code: &str) -> Option<(String, String, bool)> {
    let trimmed = code.trim();

    let is_type = trimmed.starts_with("import type ");
    let rest = if is_type {
        trimmed.strip_prefix("import type ")?
    } else {
        trimmed.strip_prefix("import ")?
    };

    // Extract specifier between { and }
    let brace_start = rest.find('{')?;
    let brace_end = rest.find('}')?;
    let specifier_raw = rest[brace_start + 1..brace_end].trim();

    // Get the base specifier name (before " as " if aliased)
    let base_specifier = if let Some(pos) = specifier_raw.find(" as ") {
        specifier_raw[..pos].trim().to_string()
    } else {
        specifier_raw.to_string()
    };

    // Extract module between quotes
    let after_brace = &rest[brace_end + 1..];
    let quote_char = if after_brace.contains('"') { '"' } else { '\'' };
    let first_quote = after_brace.find(quote_char)?;
    let second_quote = after_brace[first_quote + 1..].find(quote_char)?;
    let module = after_brace[first_quote + 1..first_quote + 1 + second_quote].to_string();

    Some((base_specifier, module, is_type))
}

/// Removes type-only import patches when a value import for the same
/// (specifier, module) pair exists. A value import subsumes a type-only import.
fn dedupe_imports(patches: &mut Vec<Patch>) {
    // Collect all (specifier, module) pairs that have value imports
    let mut value_imports: HashSet<(String, String)> = HashSet::new();

    for patch in patches.iter() {
        if let Patch::InsertRaw {
            context: Some(ctx),
            code,
            ..
        } = patch
            && ctx == "import"
            && let Some((specifier, module, is_type)) = parse_import_patch(code)
            && !is_type
        {
            value_imports.insert((specifier, module));
        }
    }

    // If no value imports exist, nothing to dedupe
    if value_imports.is_empty() {
        return;
    }

    // Remove type-only imports that are subsumed by a value import
    patches.retain(|patch| {
        if let Patch::InsertRaw {
            context: Some(ctx),
            code,
            ..
        } = patch
            && ctx == "import"
            && let Some((specifier, module, is_type)) = parse_import_patch(code)
            && is_type
            && value_imports.contains(&(specifier, module))
        {
            return false; // Drop this type-only import
        }
        true
    });
}

fn render_patch_code(code: &PatchCode) -> Result<String> {
    match code {
        PatchCode::Text(s) => Ok(s.clone()),
        PatchCode::ClassMember(member) => emit_node(member),
        PatchCode::Stmt(stmt) => emit_node(stmt),
        PatchCode::ModuleItem(item) => emit_node(item),
    }
}

fn emit_node<N: Node>(node: &N) -> Result<String> {
    let cm: Lrc<SourceMap> = Default::default();
    let mut buf = Vec::new();
    {
        let writer = JsWriter::new(cm.clone(), "\n", &mut buf, None);
        let mut emitter = Emitter {
            cfg: Config::default(),
            cm: cm.clone(),
            comments: None,
            wr: writer,
        };
        node.emit_with(&mut emitter)
            .map_err(|err| anyhow::anyhow!(err))?;
    }
    let output = String::from_utf8(buf).map_err(|err| anyhow::anyhow!(err))?;
    // Trim trailing whitespace and newlines from the emitted code
    Ok(output.trim_end().to_string())
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert_patch() {
        let source = "class Foo {}";
        // Inserting at position 12 (1-based, just before the closing brace at index 11)
        let patch = Patch::Insert {
            at: SpanIR { start: 12, end: 12 },
            code: " bar: string; ".to_string().into(),
            source_macro: None,
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply().unwrap();
        assert_eq!(result, "class Foo { bar: string; }");
    }

    #[test]
    fn test_replace_patch() {
        let source = "class Foo { old: number; }";
        // Replace "old: number;" with "new: string;" (1-based spans)
        let patch = Patch::Replace {
            span: SpanIR { start: 13, end: 26 },
            code: "new: string;".to_string().into(),
            source_macro: None,
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply().unwrap();
        assert_eq!(result, "class Foo { new: string;}");
    }

    #[test]
    fn test_delete_patch() {
        let source = "class Foo { unnecessary: any; }";
        // Delete "unnecessary: any;" (1-based spans)
        let patch = Patch::Delete {
            span: SpanIR { start: 13, end: 31 },
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply().unwrap();
        assert_eq!(result, "class Foo { }");
    }

    #[test]
    fn test_multiple_patches() {
        let source = "class Foo {}";
        let patches = vec![
            Patch::Insert {
                at: SpanIR { start: 12, end: 12 },
                code: " bar: string;".to_string().into(),
                source_macro: None,
            },
            Patch::Insert {
                at: SpanIR { start: 12, end: 12 },
                code: " baz: number;".to_string().into(),
                source_macro: None,
            },
        ];

        let applicator = PatchApplicator::new(source, patches);
        let result = applicator.apply().unwrap();
        assert!(result.contains("bar: string"));
        assert!(result.contains("baz: number"));
    }

    #[test]
    fn test_replace_multiline_block_with_single_line() {
        let source = "class C { constructor() { /* body */ } }";
        let constructor_start = source.find("constructor").unwrap();
        let constructor_end = source.find("} }").unwrap() + 1;

        // Convert 0-based indices to 1-based spans
        let patch = Patch::Replace {
            span: SpanIR {
                start: constructor_start as u32 + 1,
                end: constructor_end as u32 + 1,
            },
            code: "constructor();".to_string().into(),
            source_macro: None,
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply().unwrap();

        let expected = "class C { constructor(); }";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_detect_indentation_spaces() {
        let source = r#"class User {
  id: number;
  name: string;
}"#;
        // Position at closing brace
        let closing_brace_pos = source.rfind('}').unwrap();
        let applicator = PatchApplicator::new(source, vec![]);
        let indent = applicator.detect_indentation(closing_brace_pos);
        // Should detect 2 spaces from the class members
        assert_eq!(indent, "  ");
    }

    #[test]
    fn test_detect_indentation_tabs() {
        let source = "class User {\n\tid: number;\n}";
        let closing_brace_pos = source.rfind('}').unwrap();
        let applicator = PatchApplicator::new(source, vec![]);
        let indent = applicator.detect_indentation(closing_brace_pos);
        // Should detect tab from the class member
        assert_eq!(indent, "\t");
    }

    #[test]
    fn test_format_insertion_adds_newline_and_indent() {
        let source = r#"class User {
  id: number;
}"#;
        let closing_brace_pos = source.rfind('}').unwrap();
        let applicator = PatchApplicator::new(source, vec![]);

        // Simulate a class member insertion
        use swc_core::ecma::ast::{ClassMember, EmptyStmt};
        let code = PatchCode::ClassMember(ClassMember::Empty(EmptyStmt {
            span: swc_core::common::DUMMY_SP,
        }));
        let formatted =
            applicator.format_insertion("toString(): string;", closing_brace_pos, &code);

        // Should start with newline and have proper indentation
        assert!(formatted.starts_with('\n'));
        assert!(formatted.contains("toString(): string;"));
    }

    #[test]
    fn test_insert_class_member_with_proper_formatting() {
        let source = r#"class User {
  id: number;
  name: string;
}"#;
        // Find position just before closing brace (0-based index)
        let closing_brace_pos = source.rfind('}').unwrap();

        // Create a text patch that simulates what emit_node would produce
        // Convert to 1-based span
        let patch = Patch::Insert {
            at: SpanIR {
                start: closing_brace_pos as u32 + 1,
                end: closing_brace_pos as u32 + 1,
            },
            code: "toString(): string;".to_string().into(),
            source_macro: None,
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply().unwrap();

        // The result should have the method on its own line with proper indentation
        // Note: Text patches won't get formatted, only ClassMember patches
        // This test verifies the basic insertion works
        assert!(result.contains("toString(): string;"));
    }

    #[test]
    fn test_multiple_class_member_insertions() {
        let source = r#"class User {
  id: number;
}"#;
        let closing_brace_pos = source.rfind('}').unwrap();

        // Convert to 1-based spans
        let patches = vec![
            Patch::Insert {
                at: SpanIR {
                    start: closing_brace_pos as u32 + 1,
                    end: closing_brace_pos as u32 + 1,
                },
                code: "toString(): string;".to_string().into(),
                source_macro: None,
            },
            Patch::Insert {
                at: SpanIR {
                    start: closing_brace_pos as u32 + 1,
                    end: closing_brace_pos as u32 + 1,
                },
                code: "toJSON(): Record<string, unknown>;".to_string().into(),
                source_macro: None,
            },
        ];

        let applicator = PatchApplicator::new(source, patches);
        let result = applicator.apply().unwrap();

        assert!(result.contains("toString(): string;"));
        assert!(result.contains("toJSON(): Record<string, unknown>;"));
    }

    #[test]
    fn test_indentation_preserved_in_nested_class() {
        let source = r#"export namespace Models {
  class User {
    id: number;
  }
}"#;
        let closing_brace_pos = source.find("  }").unwrap() + 2; // Find the class closing brace
        let applicator = PatchApplicator::new(source, vec![]);
        let indent = applicator.detect_indentation(closing_brace_pos);
        // Should detect the indentation from the class members (4 spaces)
        assert_eq!(indent, "    ");
    }

    #[test]
    fn test_no_formatting_for_text_patches() {
        let source = "class User {}";
        let pos = 11; // 0-based index for format_insertion (internal use)
        let applicator = PatchApplicator::new(source, vec![]);
        let formatted =
            applicator.format_insertion("test", pos, &PatchCode::Text("test".to_string()));
        // Text patches should not get extra formatting
        assert_eq!(formatted, "test");
    }

    #[test]
    fn test_dedupe_patches_removes_identical_inserts() {
        // Using 1-based spans
        let mut patches = vec![
            Patch::Insert {
                at: SpanIR { start: 11, end: 11 },
                code: "console.log('a');".to_string().into(),
                source_macro: None,
            },
            Patch::Insert {
                at: SpanIR { start: 11, end: 11 },
                code: "console.log('a');".to_string().into(),
                source_macro: None,
            },
            Patch::Insert {
                at: SpanIR { start: 21, end: 21 },
                code: "console.log('b');".to_string().into(),
                source_macro: None,
            },
        ];

        dedupe_patches(&mut patches).expect("dedupe should succeed");
        assert_eq!(
            patches.len(),
            2,
            "duplicate inserts should collapse to a single patch"
        );
        assert!(
            patches
                .iter()
                .any(|patch| matches!(patch, Patch::Insert { at, .. } if at.start == 21)),
            "dedupe should retain distinct spans"
        );
    }

    // =========================================================================
    // Source Mapping Tests
    // =========================================================================

    #[test]
    fn test_apply_with_mapping_no_patches() {
        let source = "class Foo {}";
        let applicator = PatchApplicator::new(source, vec![]);
        let result = applicator.apply_with_mapping(None).unwrap();

        assert_eq!(result.code, source);
        assert_eq!(result.mapping.segments.len(), 1);
        assert!(result.mapping.generated_regions.is_empty());

        // Identity mapping
        assert_eq!(result.mapping.original_to_expanded(0), 0);
        assert_eq!(result.mapping.original_to_expanded(5), 5);
        assert_eq!(result.mapping.expanded_to_original(5), Some(5));
    }

    #[test]
    fn test_apply_with_mapping_simple_insert() {
        let source = "class Foo {}";
        // Insert at position 12 (1-based span, just before closing brace at index 11)
        let patch = Patch::Insert {
            at: SpanIR { start: 12, end: 12 },
            code: " bar;".to_string().into(),
            source_macro: Some("Test".to_string()),
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply_with_mapping(None).unwrap();

        // Original: "class Foo {}" (12 chars)
        // Expanded: "class Foo { bar;}" (17 chars)
        assert_eq!(result.code, "class Foo { bar;}");
        assert_eq!(result.code.len(), 17);

        // Should have 2 segments and 1 generated region
        assert_eq!(result.mapping.segments.len(), 2);
        assert_eq!(result.mapping.generated_regions.len(), 1);

        // First segment: "class Foo {" (0-based: 0-11)
        let seg1 = &result.mapping.segments[0];
        assert_eq!(seg1.original_start, 0);
        assert_eq!(seg1.original_end, 11);
        assert_eq!(seg1.expanded_start, 0);
        assert_eq!(seg1.expanded_end, 11);

        // Generated region: " bar;" (0-based: 11-16 in expanded)
        let generated = &result.mapping.generated_regions[0];
        assert_eq!(generated.start, 11);
        assert_eq!(generated.end, 16);
        assert_eq!(generated.source_macro, "Test");

        // Second segment: "}" (0-based: 11-12 original -> 16-17 expanded)
        let seg2 = &result.mapping.segments[1];
        assert_eq!(seg2.original_start, 11);
        assert_eq!(seg2.original_end, 12);
        assert_eq!(seg2.expanded_start, 16);
        assert_eq!(seg2.expanded_end, 17);

        // Test position mappings (0-based positions)
        assert_eq!(result.mapping.original_to_expanded(0), 0);
        assert_eq!(result.mapping.original_to_expanded(10), 10);
        assert_eq!(result.mapping.original_to_expanded(11), 16); // After insert

        assert_eq!(result.mapping.expanded_to_original(5), Some(5));
        assert_eq!(result.mapping.expanded_to_original(12), None); // In generated
        assert_eq!(result.mapping.expanded_to_original(16), Some(11));
    }

    #[test]
    fn test_apply_with_mapping_replace() {
        let source = "let x = old;";
        // Replace "old" (1-based span: 9-12) with "new"
        let patch = Patch::Replace {
            span: SpanIR { start: 9, end: 12 },
            code: "new".to_string().into(),
            source_macro: None,
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply_with_mapping(None).unwrap();

        assert_eq!(result.code, "let x = new;");

        // 2 segments, 1 generated
        assert_eq!(result.mapping.segments.len(), 2);
        assert_eq!(result.mapping.generated_regions.len(), 1);

        // "let x = " unchanged (0-based: 0-8)
        let seg1 = &result.mapping.segments[0];
        assert_eq!(seg1.original_start, 0);
        assert_eq!(seg1.original_end, 8);

        // "new" is generated (0-based: 8-11 in expanded)
        let generated = &result.mapping.generated_regions[0];
        assert_eq!(generated.start, 8);
        assert_eq!(generated.end, 11);

        // ";" unchanged (0-based: 11-12 original -> 11-12 expanded, same length replacement)
        let seg2 = &result.mapping.segments[1];
        assert_eq!(seg2.original_start, 11);
        assert_eq!(seg2.original_end, 12);
        assert_eq!(seg2.expanded_start, 11);
        assert_eq!(seg2.expanded_end, 12);

        // In replaced region
        assert_eq!(result.mapping.expanded_to_original(9), None);
    }

    #[test]
    fn test_apply_with_mapping_delete() {
        let source = "let x = 1; let y = 2;";
        // Delete " let y = 2" (1-based: 11-21)
        let patch = Patch::Delete {
            span: SpanIR { start: 11, end: 21 },
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply_with_mapping(None).unwrap();

        assert_eq!(result.code, "let x = 1;;");

        // 2 segments, no generated regions
        assert_eq!(result.mapping.segments.len(), 2);
        assert_eq!(result.mapping.generated_regions.len(), 0);

        // Position after deletion maps correctly (0-based for SourceMapping API)
        // Original position 20 (final ";") -> expanded position 10
        assert_eq!(result.mapping.original_to_expanded(20), 10);
        assert_eq!(result.mapping.expanded_to_original(10), Some(20));
    }

    #[test]
    fn test_apply_with_mapping_multiple_inserts() {
        let source = "a;b;c;";
        // Insert "X" after "a;" (1-based: 3) and "Y" after "b;" (1-based: 5)
        let patches = vec![
            Patch::Insert {
                at: SpanIR { start: 3, end: 3 },
                code: "X".to_string().into(),
                source_macro: Some("multi".to_string()),
            },
            Patch::Insert {
                at: SpanIR { start: 5, end: 5 },
                code: "Y".to_string().into(),
                source_macro: Some("multi".to_string()),
            },
        ];

        let applicator = PatchApplicator::new(source, patches);
        let result = applicator.apply_with_mapping(None).unwrap();

        // "a;Xb;Yc;"
        assert_eq!(result.code, "a;Xb;Yc;");

        // 3 segments, 2 generated regions
        assert_eq!(result.mapping.segments.len(), 3);
        assert_eq!(result.mapping.generated_regions.len(), 2);

        // Verify position mappings (0-based for SourceMapping API)
        // Original: "a;b;c;" -> Expanded: "a;Xb;Yc;"
        assert_eq!(result.mapping.original_to_expanded(0), 0); // 'a' at 0 -> 0
        assert_eq!(result.mapping.original_to_expanded(2), 3); // 'b' at 2 -> 3 (shifted by 1)
        assert_eq!(result.mapping.original_to_expanded(4), 6); // 'c' at 4 -> 6 (shifted by 2)

        // Verify generated regions (0-based for SourceMapping API)
        // "a;Xb;Yc;" - X is at position 2, Y is at position 5
        assert!(result.mapping.is_in_generated(2)); // 'X'
        assert!(result.mapping.is_in_generated(5)); // 'Y'
        assert!(!result.mapping.is_in_generated(0)); // 'a'
        assert!(!result.mapping.is_in_generated(3)); // 'b'
    }

    #[test]
    fn test_apply_with_mapping_span_mapping() {
        let source = "class Foo {}";
        let patch = Patch::Insert {
            at: SpanIR { start: 12, end: 12 },
            code: " bar();".to_string().into(),
            source_macro: None,
        };

        let applicator = PatchApplicator::new(source, vec![patch]);
        let result = applicator.apply_with_mapping(None).unwrap();

        // Map span from original to expanded (0-based for SourceMapping API)
        let (exp_start, exp_len) = result.mapping.map_span_to_expanded(0, 5);
        assert_eq!(exp_start, 0);
        assert_eq!(exp_len, 5);

        // Map span from expanded to original (in unchanged region, 0-based)
        let orig = result.mapping.map_span_to_original(0, 5);
        assert_eq!(orig, Some((0, 5)));

        // Map span in generated region returns None (0-based)
        // Generated region is at positions 11-18 in expanded (7 chars: " bar();")
        let gen_span = result.mapping.map_span_to_original(12, 3);
        assert_eq!(gen_span, None);
    }

    #[test]
    fn test_patch_collector_with_mapping() {
        let source = "class Foo {}";

        let mut collector = PatchCollector::new();
        collector.add_runtime_patches(vec![Patch::Insert {
            at: SpanIR { start: 12, end: 12 },
            code: " toString() {}".to_string().into(),
            source_macro: Some("Debug".to_string()),
        }]);

        let result = collector
            .apply_runtime_patches_with_mapping(source, None)
            .unwrap();

        assert!(result.code.contains("toString()"));
        assert_eq!(result.mapping.generated_regions.len(), 1);
        assert_eq!(result.mapping.generated_regions[0].source_macro, "Debug");
    }

    // =========================================================================
    // Import Deduplication Tests
    // =========================================================================

    #[test]
    fn test_parse_import_patch_value() {
        let code = "import { Option } from \"effect\";\n";
        let result = parse_import_patch(code);
        assert_eq!(
            result,
            Some(("Option".to_string(), "effect".to_string(), false))
        );
    }

    #[test]
    fn test_parse_import_patch_type_only() {
        let code = "import type { Exit } from \"effect\";\n";
        let result = parse_import_patch(code);
        assert_eq!(
            result,
            Some(("Exit".to_string(), "effect".to_string(), true))
        );
    }

    #[test]
    fn test_parse_import_patch_aliased() {
        let code = "import { Option as __gigaform_reexport_Option } from \"effect\";\n";
        let result = parse_import_patch(code);
        assert_eq!(
            result,
            Some(("Option".to_string(), "effect".to_string(), false))
        );
    }

    #[test]
    fn test_dedupe_imports_value_subsumes_type() {
        let mut patches = vec![
            Patch::InsertRaw {
                at: SpanIR { start: 1, end: 1 },
                code: "import type { Exit } from \"effect\";\n".to_string(),
                context: Some("import".to_string()),
                source_macro: None,
            },
            Patch::InsertRaw {
                at: SpanIR { start: 1, end: 1 },
                code: "import { Exit } from \"effect\";\n".to_string(),
                context: Some("import".to_string()),
                source_macro: None,
            },
        ];

        dedupe_imports(&mut patches);
        assert_eq!(
            patches.len(),
            1,
            "type-only import should be removed when value import exists"
        );
        assert!(patches[0].source_macro().is_none());
        if let Patch::InsertRaw { code, .. } = &patches[0] {
            assert!(
                !code.contains("import type"),
                "remaining import should be the value import"
            );
            assert!(code.contains("import { Exit }"));
        } else {
            panic!("expected InsertRaw");
        }
    }

    #[test]
    fn test_dedupe_imports_keeps_unrelated() {
        let mut patches = vec![
            Patch::InsertRaw {
                at: SpanIR { start: 1, end: 1 },
                code: "import type { FieldController } from \"@dealdraft/macros/gigaform\";\n"
                    .to_string(),
                context: Some("import".to_string()),
                source_macro: None,
            },
            Patch::InsertRaw {
                at: SpanIR { start: 1, end: 1 },
                code: "import { Option } from \"effect\";\n".to_string(),
                context: Some("import".to_string()),
                source_macro: None,
            },
        ];

        dedupe_imports(&mut patches);
        assert_eq!(patches.len(), 2, "unrelated imports should both be kept");
    }

    #[test]
    fn test_dedupe_imports_different_modules_kept() {
        let mut patches = vec![
            Patch::InsertRaw {
                at: SpanIR { start: 1, end: 1 },
                code: "import type { Option } from \"effect/Option\";\n".to_string(),
                context: Some("import".to_string()),
                source_macro: None,
            },
            Patch::InsertRaw {
                at: SpanIR { start: 1, end: 1 },
                code: "import { Option } from \"effect\";\n".to_string(),
                context: Some("import".to_string()),
                source_macro: None,
            },
        ];

        dedupe_imports(&mut patches);
        // Different modules — type import from "effect/Option" is NOT subsumed by value import from "effect"
        assert_eq!(
            patches.len(),
            2,
            "imports from different modules should both be kept"
        );
    }
}