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
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
//! # Macroforge TypeScript Macro Engine
//!
//! This crate provides a TypeScript macro expansion engine that brings Rust-like derive macros
//! to TypeScript. It is designed to be used via NAPI bindings from Node.js, enabling compile-time
//! code generation for TypeScript projects.
//!
//! ## Overview
//!
//! Macroforge processes TypeScript source files containing `@derive` decorators and expands them
//! into concrete implementations. For example, a class decorated with `@derive(Debug, Clone)`
//! will have `toString()` and `clone()` methods automatically generated.
//!
//! ## Architecture
//!
//! The crate is organized into several key components:
//!
//! - **NAPI Bindings** (`NativePlugin`, `expand_sync`, `transform_sync`): Entry points for Node.js
//! - **Position Mapping** (`NativePositionMapper`, `NativeMapper`): Bidirectional source mapping
//!   for IDE integration
//! - **Macro Host** (`host` module): Core expansion engine with registry and dispatcher
//! - **Built-in Macros** (`builtin` module): Standard derive macros (Debug, Clone, Serialize, etc.)
//!
//! ## Performance Considerations
//!
//! - Uses a 32MB thread stack to prevent stack overflow during deep SWC AST recursion
//! - Implements early bailout for files without `@derive` decorators
//! - Caches expansion results keyed by filepath and version
//! - Uses binary search for O(log n) position mapping lookups
//!
//! ## Usage from Node.js
//!
//! ```javascript
//! const { NativePlugin, expand_sync } = require('macroforge-ts');
//!
//! // Create a plugin instance with caching
//! const plugin = new NativePlugin();
//!
//! // Process a file (uses cache if version matches)
//! const result = plugin.process_file(filepath, code, { version: '1.0' });
//!
//! // Or use the sync function directly
//! const result = expand_sync(code, filepath, { keep_decorators: false });
//! ```
//!
//! ## Re-exports for Macro Authors
//!
//! This crate re-exports several dependencies for convenience when writing custom macros:
//! - `ts_syn`: TypeScript syntax types for AST manipulation
//! - `macros`: Macro attributes and quote templates
//! - `swc_core`, `swc_common`, `swc_ecma_ast`: SWC compiler infrastructure

use napi::bindgen_prelude::*;
use napi_derive::napi;
use swc_core::{
    common::{FileName, GLOBALS, Globals, SourceMap, errors::Handler, sync::Lrc},
    ecma::{
        ast::{EsVersion, Program},
        codegen::{Emitter, text_writer::JsWriter},
        parser::{Parser, StringInput, Syntax, TsSyntax, lexer::Lexer},
    },
};

// Allow the crate to reference itself as `macroforge_ts`.
// This self-reference is required for the macroforge_ts_macros generated code
// to correctly resolve paths when the macro expansion happens within this crate.
extern crate self as macroforge_ts;

// ============================================================================
// Re-exports for Macro Authors
// ============================================================================
// These re-exports allow users to only depend on `macroforge_ts` in their
// Cargo.toml instead of needing to add multiple dependencies.

// Re-export internal crates (needed for generated code)
pub extern crate inventory;
pub extern crate macroforge_ts_macros;
pub extern crate macroforge_ts_quote;
pub extern crate macroforge_ts_syn;
pub extern crate napi;
pub extern crate napi_derive;
pub extern crate serde_json;

/// Debug logging for external macros.
/// Writes to `.macroforge/debug.log` relative to the project root.
/// Use: `macroforge_ts::debug::log("tag", "message")` or `macroforge_ts::debug_log!("tag", "...")`
pub mod debug;

/// TypeScript syntax types for macro development
/// Use: `use macroforge_ts::ts_syn::*;`
pub use macroforge_ts_syn as ts_syn;

/// Macro attributes and quote templates
/// Use: `use macroforge_ts::macros::*;`
pub mod macros {
    // Re-export the ts_macro_derive attribute
    pub use macroforge_ts_macros::ts_macro_derive;

    // Re-export all quote macros
    pub use macroforge_ts_quote::{ts_quote, ts_template};
}

// ============================================================================
// Wrapper macros for proper $crate resolution
// ============================================================================
// These wrapper macros ensure that $crate resolves to macroforge_ts (this crate)
// rather than macroforge_ts_syn, allowing users to only depend on macroforge_ts.

/// Creates an SWC [`Ident`](swc_core::ecma::ast::Ident) from a string or format expression.
///
/// This is a re-export wrapper that ensures `$crate` resolves correctly when
/// used from crates that only depend on `macroforge_ts`.
///
/// # Examples
///
/// ```rust,ignore
/// use macroforge_ts::ident;
///
/// let simple = ident!("foo");
/// let formatted = ident!("{}Bar", "foo");
/// ```
#[macro_export]
macro_rules! ident {
    ($name:expr) => {
        $crate::swc_core::ecma::ast::Ident::new_no_ctxt(
            AsRef::<str>::as_ref(&$name).into(),
            $crate::swc_core::common::DUMMY_SP,
        )
    };
    ($fmt:expr, $($args:expr),+ $(,)?) => {
        $crate::swc_core::ecma::ast::Ident::new_no_ctxt(
            format!($fmt, $($args),+).into(),
            $crate::swc_core::common::DUMMY_SP,
        )
    };
}

/// Creates a private (marked) SWC [`Ident`](swc_core::ecma::ast::Ident).
///
/// Unlike [`ident!`], this macro creates an identifier with a fresh hygiene mark,
/// making it unique and preventing name collisions with user code.
#[macro_export]
macro_rules! private_ident {
    ($name:expr) => {{
        let mark = $crate::swc_core::common::Mark::fresh($crate::swc_core::common::Mark::root());
        $crate::swc_core::ecma::ast::Ident::new(
            $name.into(),
            $crate::swc_core::common::DUMMY_SP,
            $crate::swc_core::common::SyntaxContext::empty().apply_mark(mark),
        )
    }};
}

// Re-export swc_core and common modules (via ts_syn for version consistency)
pub use macroforge_ts_syn::swc_common;
pub use macroforge_ts_syn::swc_core;
pub use macroforge_ts_syn::swc_ecma_ast;

// ============================================================================
// Internal modules
// ============================================================================
pub mod host;

// Build script utilities (enabled with "build" feature)
#[cfg(feature = "build")]
pub mod build;

// Re-export abi types from ts_syn
pub use ts_syn::abi;

use host::CONFIG_CACHE;
use host::derived;
use ts_syn::{Diagnostic, DiagnosticLevel};

pub mod builtin;

#[cfg(test)]
mod test;

use crate::host::MacroExpander;

// ============================================================================
// Type Registry Cache
// ============================================================================
// Caches deserialized TypeRegistry by hash of the JSON string to avoid
// re-parsing the registry on every expand_sync call.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::LazyLock;

use crate::ts_syn::abi::ir::type_registry::TypeRegistry;

static REGISTRY_CACHE: LazyLock<dashmap::DashMap<u64, TypeRegistry>> =
    LazyLock::new(dashmap::DashMap::new);

fn get_or_parse_registry(json: &str) -> Option<TypeRegistry> {
    let mut hasher = DefaultHasher::new();
    json.hash(&mut hasher);
    let key = hasher.finish();

    if let Some(entry) = REGISTRY_CACHE.get(&key) {
        return Some(entry.clone());
    }

    match serde_json::from_str::<TypeRegistry>(json) {
        Ok(registry) => {
            REGISTRY_CACHE.insert(key, registry.clone());
            Some(registry)
        }
        Err(_) => None,
    }
}

// ============================================================================
// Data Structures
// ============================================================================

/// Result of transforming TypeScript code through the macro system.
///
/// This struct is returned by [`transform_sync`] and contains the transformed code
/// along with optional source maps, type declarations, and metadata about processed classes.
///
/// # Fields
///
/// * `code` - The transformed TypeScript/JavaScript code with macros expanded
/// * `map` - Optional source map for debugging (currently not implemented)
/// * `types` - Optional TypeScript type declarations for generated methods
/// * `metadata` - Optional JSON metadata about processed classes
#[napi(object)]
#[derive(Clone)]
pub struct TransformResult {
    /// The transformed TypeScript/JavaScript code with all macros expanded.
    pub code: String,
    /// Source map for mapping transformed positions back to original.
    /// Currently always `None` - source mapping is handled separately via `SourceMappingResult`.
    pub map: Option<String>,
    /// TypeScript type declarations (`.d.ts` content) for generated methods.
    /// Used by IDEs to provide type information for macro-generated code.
    pub types: Option<String>,
    /// JSON-serialized metadata about processed classes.
    /// Contains information about which classes were processed and what was generated.
    pub metadata: Option<String>,
}

/// A diagnostic message produced during macro expansion.
///
/// Diagnostics can represent errors, warnings, or informational messages
/// that occurred during the macro expansion process.
///
/// # Fields
///
/// * `level` - Severity level: "error", "warning", or "info"
/// * `message` - Human-readable description of the issue
/// * `start` - Optional byte offset where the issue starts in the source
/// * `end` - Optional byte offset where the issue ends in the source
///
/// # Example
///
/// ```rust
/// use macroforge_ts::MacroDiagnostic;
///
/// let _diag = MacroDiagnostic {
///     level: "error".to_string(),
///     message: "Unknown macro 'Foo'".to_string(),
///     start: Some(42),
///     end: Some(45),
/// };
/// ```
#[napi(object)]
#[derive(Clone)]
pub struct MacroDiagnostic {
    /// Severity level of the diagnostic.
    /// One of: "error", "warning", "info".
    pub level: String,
    /// Human-readable message describing the diagnostic.
    pub message: String,
    /// Byte offset in the original source where the issue starts.
    /// `None` if the diagnostic is not associated with a specific location.
    pub start: Option<u32>,
    /// Byte offset in the original source where the issue ends.
    /// `None` if the diagnostic is not associated with a specific location.
    pub end: Option<u32>,
}

/// A segment mapping a range in the original source to a range in the expanded source.
///
/// These segments form the core of the bidirectional source mapping system,
/// enabling IDE features like "go to definition" and error reporting to work
/// correctly with macro-expanded code.
///
/// # Invariants
///
/// - `original_start < original_end`
/// - `expanded_start < expanded_end`
/// - Segments are non-overlapping and sorted by position
#[napi(object)]
#[derive(Clone)]
pub struct MappingSegmentResult {
    /// Byte offset where this segment starts in the original source.
    pub original_start: u32,
    /// Byte offset where this segment ends in the original source.
    pub original_end: u32,
    /// Byte offset where this segment starts in the expanded source.
    pub expanded_start: u32,
    /// Byte offset where this segment ends in the expanded source.
    pub expanded_end: u32,
}

/// A region in the expanded source that was generated by a macro.
///
/// These regions identify code that has no corresponding location in the
/// original source because it was synthesized by a macro.
///
/// # Example
///
/// For a `@derive(Debug)` macro that generates a `toString()` method,
/// a `GeneratedRegionResult` would mark the entire method body as generated
/// with `source_macro = "Debug"`.
#[napi(object)]
#[derive(Clone)]
pub struct GeneratedRegionResult {
    /// Byte offset where the generated region starts in the expanded source.
    pub start: u32,
    /// Byte offset where the generated region ends in the expanded source.
    pub end: u32,
    /// Name of the macro that generated this region (e.g., "Debug", "Clone").
    pub source_macro: String,
}

/// Complete source mapping information for a macro expansion.
///
/// Contains both preserved segments (original code that wasn't modified)
/// and generated regions (new code synthesized by macros).
///
/// # Usage
///
/// This mapping enables:
/// - Converting positions from original source to expanded source and vice versa
/// - Identifying which macro generated a given piece of code
/// - Mapping IDE diagnostics from expanded code back to original source
#[napi(object)]
#[derive(Clone)]
pub struct SourceMappingResult {
    /// Segments mapping preserved regions between original and expanded source.
    /// Sorted by position for efficient binary search lookups.
    pub segments: Vec<MappingSegmentResult>,
    /// Regions in the expanded source that were generated by macros.
    /// Used to identify synthetic code with no original source location.
    pub generated_regions: Vec<GeneratedRegionResult>,
}

/// Result of expanding macros in TypeScript source code.
///
/// This is the primary return type for macro expansion operations,
/// containing the expanded code, diagnostics, and source mapping.
///
/// # Example
///
/// ```rust
/// use macroforge_ts::{ExpandResult, MacroDiagnostic};
///
/// // Create an ExpandResult programmatically
/// let result = ExpandResult {
///     code: "class User {}".to_string(),
///     types: None,
///     metadata: None,
///     diagnostics: vec![],
///     source_mapping: None,
/// };
///
/// // Check for errors
/// if result.diagnostics.iter().any(|d| d.level == "error") {
///     // Handle errors
/// }
/// ```
#[napi(object)]
#[derive(Clone)]
pub struct ExpandResult {
    /// The expanded TypeScript code with all macros processed.
    pub code: String,
    /// Optional TypeScript type declarations for generated methods.
    pub types: Option<String>,
    /// Optional JSON metadata about processed classes.
    pub metadata: Option<String>,
    /// Diagnostics (errors, warnings, info) from the expansion process.
    pub diagnostics: Vec<MacroDiagnostic>,
    /// Source mapping for position translation between original and expanded code.
    pub source_mapping: Option<SourceMappingResult>,
}

impl ExpandResult {
    /// Creates a no-op result with the original code unchanged.
    ///
    /// Used for early bailout when no macros need processing, avoiding
    /// unnecessary parsing and expansion overhead.
    ///
    /// # Arguments
    ///
    /// * `code` - The original source code to return unchanged
    ///
    /// # Returns
    ///
    /// An `ExpandResult` with:
    /// - `code` set to the input
    /// - All other fields empty/None
    /// - No source mapping (identity mapping implied)
    pub fn unchanged(code: &str) -> Self {
        Self {
            code: code.to_string(),
            types: None,
            metadata: None,
            diagnostics: vec![],
            source_mapping: None,
        }
    }
}

/// Information about an imported identifier from a TypeScript module.
///
/// Used to track where decorators and macro-related imports come from.
#[napi(object)]
#[derive(Clone)]
pub struct ImportSourceResult {
    /// Local identifier name in the import statement (e.g., `Derive` in `import { Derive }`).
    pub local: String,
    /// Module specifier this identifier was imported from (e.g., `"macroforge-ts"`).
    pub module: String,
}

/// Result of checking TypeScript syntax validity.
///
/// Returned by [`check_syntax`] to indicate whether code parses successfully.
#[napi(object)]
#[derive(Clone)]
pub struct SyntaxCheckResult {
    /// `true` if the code parsed without errors, `false` otherwise.
    pub ok: bool,
    /// Error message if parsing failed, `None` if successful.
    pub error: Option<String>,
}

/// A span (range) in source code, represented as start position and length.
///
/// Used for mapping diagnostics and other positional information.
#[napi(object)]
#[derive(Clone)]
pub struct SpanResult {
    /// Byte offset where the span starts.
    pub start: u32,
    /// Length of the span in bytes.
    pub length: u32,
}

/// A diagnostic from the TypeScript/JavaScript compiler or IDE.
///
/// This structure mirrors TypeScript's diagnostic format for interoperability
/// with language servers and IDEs.
#[napi(object)]
#[derive(Clone)]
pub struct JsDiagnostic {
    /// Byte offset where the diagnostic starts. `None` for global diagnostics.
    pub start: Option<u32>,
    /// Length of the diagnostic span in bytes.
    pub length: Option<u32>,
    /// Human-readable diagnostic message.
    pub message: Option<String>,
    /// TypeScript diagnostic code (e.g., 2304 for "Cannot find name").
    pub code: Option<u32>,
    /// Diagnostic category: "error", "warning", "suggestion", "message".
    pub category: Option<String>,
}

// ============================================================================
// Position Mapper (Optimized with Binary Search)
// ============================================================================

/// Bidirectional position mapper for translating between original and expanded source positions.
///
/// This mapper enables IDE features like error reporting, go-to-definition, and hover
/// to work correctly with macro-expanded code by translating positions between the
/// original source (what the user wrote) and the expanded source (what the compiler sees).
///
/// # Performance
///
/// Position lookups use binary search for O(log n) complexity, where n is the number
/// of mapping segments. This is critical for responsive IDE interactions.
///
/// # Example
///
/// ```javascript
/// const mapper = new PositionMapper(sourceMapping);
///
/// // Convert original position to expanded
/// const expandedPos = mapper.original_to_expanded(42);
///
/// // Convert expanded position back to original (if not in generated code)
/// const originalPos = mapper.expanded_to_original(100);
///
/// // Check if a position is in macro-generated code
/// if (mapper.is_in_generated(pos)) {
///     const macro = mapper.generated_by(pos); // e.g., "Debug"
/// }
/// ```
#[napi(js_name = "PositionMapper")]
pub struct NativePositionMapper {
    /// Mapping segments sorted by position for binary search.
    segments: Vec<MappingSegmentResult>,
    /// Regions marking code generated by macros.
    generated_regions: Vec<GeneratedRegionResult>,
}

/// Wrapper around `NativePositionMapper` for NAPI compatibility.
///
/// This provides the same functionality as `NativePositionMapper` but with a
/// different JavaScript class name. Used internally by [`NativePlugin::get_mapper`].
#[napi(js_name = "NativeMapper")]
pub struct NativeMapper {
    /// The underlying position mapper implementation.
    inner: NativePositionMapper,
}

#[napi]
impl NativePositionMapper {
    /// Creates a new position mapper from source mapping data.
    ///
    /// # Arguments
    ///
    /// * `mapping` - The source mapping result from macro expansion
    ///
    /// # Returns
    ///
    /// A new `NativePositionMapper` ready for position translation.
    #[napi(constructor)]
    pub fn new(mapping: SourceMappingResult) -> Self {
        Self {
            segments: mapping.segments,
            generated_regions: mapping.generated_regions,
        }
    }

    /// Checks if this mapper has no mapping data.
    ///
    /// An empty mapper indicates no transformations occurred, so position
    /// translation is an identity operation.
    ///
    /// # Returns
    ///
    /// `true` if there are no segments and no generated regions.
    #[napi(js_name = "isEmpty")]
    pub fn is_empty(&self) -> bool {
        self.segments.is_empty() && self.generated_regions.is_empty()
    }

    /// Converts a position in the original source to the corresponding position in expanded source.
    ///
    /// Uses binary search for O(log n) lookup performance.
    ///
    /// # Arguments
    ///
    /// * `pos` - Byte offset in the original source
    ///
    /// # Returns
    ///
    /// The corresponding byte offset in the expanded source. If the position falls
    /// in a gap between segments, returns the position unchanged. If after the last
    /// segment, extrapolates based on the delta.
    ///
    /// # Algorithm
    ///
    /// 1. Binary search to find the segment containing or after `pos`
    /// 2. If inside a segment, compute offset within segment and translate
    /// 3. If after all segments, extrapolate from the last segment
    /// 4. Otherwise, return position unchanged (gap or before first segment)
    #[napi]
    pub fn original_to_expanded(&self, pos: u32) -> u32 {
        // Binary search to find the first segment where original_end > pos.
        // This gives us the segment that might contain pos, or the one after it.
        let idx = self.segments.partition_point(|seg| seg.original_end <= pos);

        if let Some(seg) = self.segments.get(idx) {
            // Check if pos is actually inside this segment (it might be in a gap)
            if pos >= seg.original_start && pos < seg.original_end {
                // Position is within this segment - calculate the offset and translate
                let offset = pos - seg.original_start;
                return seg.expanded_start + offset;
            }
        }

        // Handle case where position is after the last segment.
        // Extrapolate by adding the delta from the end of the last segment.
        if let Some(last) = self.segments.last()
            && pos >= last.original_end
        {
            let delta = pos - last.original_end;
            return last.expanded_end + delta;
        }

        // Fallback for positions before first segment or in gaps between segments.
        // Return unchanged as an identity mapping.
        pos
    }

    /// Converts a position in the expanded source back to the original source position.
    ///
    /// Returns `None` if the position is inside macro-generated code that has no
    /// corresponding location in the original source.
    ///
    /// # Arguments
    ///
    /// * `pos` - Byte offset in the expanded source
    ///
    /// # Returns
    ///
    /// `Some(original_pos)` if the position maps to original code,
    /// `None` if the position is in macro-generated code.
    #[napi]
    pub fn expanded_to_original(&self, pos: u32) -> Option<u32> {
        // First check if the position is in a generated region (no original mapping)
        if self.is_in_generated(pos) {
            return None;
        }

        // Binary search to find the segment containing or after this expanded position
        let idx = self.segments.partition_point(|seg| seg.expanded_end <= pos);

        if let Some(seg) = self.segments.get(idx)
            && pos >= seg.expanded_start
            && pos < seg.expanded_end
        {
            // Position is within this segment - translate back to original
            let offset = pos - seg.expanded_start;
            return Some(seg.original_start + offset);
        }

        // Handle extrapolation after the last segment
        if let Some(last) = self.segments.last()
            && pos >= last.expanded_end
        {
            let delta = pos - last.expanded_end;
            return Some(last.original_end + delta);
        }

        // Position doesn't map to any segment
        None
    }

    /// Returns the name of the macro that generated code at the given position.
    ///
    /// # Arguments
    ///
    /// * `pos` - Byte offset in the expanded source
    ///
    /// # Returns
    ///
    /// `Some(macro_name)` if the position is inside generated code (e.g., "Debug"),
    /// `None` if the position is in original (non-generated) code.
    #[napi]
    pub fn generated_by(&self, pos: u32) -> Option<String> {
        // Generated regions are typically small in number, so linear scan is acceptable.
        // If this becomes a bottleneck with many macros, could be optimized with binary search.
        self.generated_regions
            .iter()
            .find(|r| pos >= r.start && pos < r.end)
            .map(|r| r.source_macro.clone())
    }

    /// Maps a span (start + length) from expanded source to original source.
    ///
    /// # Arguments
    ///
    /// * `start` - Start byte offset in expanded source
    /// * `length` - Length of the span in bytes
    ///
    /// # Returns
    ///
    /// `Some(SpanResult)` with the mapped span in original source,
    /// `None` if either endpoint is in generated code.
    #[napi]
    pub fn map_span_to_original(&self, start: u32, length: u32) -> Option<SpanResult> {
        let end = start.saturating_add(length);
        // Both start and end must successfully map for the span to be valid
        let original_start = self.expanded_to_original(start)?;
        let original_end = self.expanded_to_original(end)?;

        Some(SpanResult {
            start: original_start,
            length: original_end.saturating_sub(original_start),
        })
    }

    /// Maps a span (start + length) from original source to expanded source.
    ///
    /// This always succeeds since every original position has an expanded equivalent.
    ///
    /// # Arguments
    ///
    /// * `start` - Start byte offset in original source
    /// * `length` - Length of the span in bytes
    ///
    /// # Returns
    ///
    /// A `SpanResult` with the mapped span in expanded source.
    #[napi]
    pub fn map_span_to_expanded(&self, start: u32, length: u32) -> SpanResult {
        let end = start.saturating_add(length);
        let expanded_start = self.original_to_expanded(start);
        let expanded_end = self.original_to_expanded(end);

        SpanResult {
            start: expanded_start,
            length: expanded_end.saturating_sub(expanded_start),
        }
    }

    /// Checks if a position is inside macro-generated code.
    ///
    /// # Arguments
    ///
    /// * `pos` - Byte offset in the expanded source
    ///
    /// # Returns
    ///
    /// `true` if the position is inside a generated region, `false` otherwise.
    #[napi]
    pub fn is_in_generated(&self, pos: u32) -> bool {
        self.generated_regions
            .iter()
            .any(|r| pos >= r.start && pos < r.end)
    }
}

#[napi]
impl NativeMapper {
    /// Creates a new mapper wrapping the given source mapping.
    ///
    /// # Arguments
    ///
    /// * `mapping` - The source mapping result from macro expansion
    #[napi(constructor)]
    pub fn new(mapping: SourceMappingResult) -> Self {
        Self {
            inner: NativePositionMapper::new(mapping),
        }
    }

    /// Checks if this mapper has no mapping data.
    #[napi(js_name = "isEmpty")]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Converts a position in the original source to expanded source.
    /// See [`NativePositionMapper::original_to_expanded`] for details.
    #[napi]
    pub fn original_to_expanded(&self, pos: u32) -> u32 {
        self.inner.original_to_expanded(pos)
    }

    /// Converts a position in the expanded source back to original.
    /// See [`NativePositionMapper::expanded_to_original`] for details.
    #[napi]
    pub fn expanded_to_original(&self, pos: u32) -> Option<u32> {
        self.inner.expanded_to_original(pos)
    }

    /// Returns the name of the macro that generated code at the given position.
    /// See [`NativePositionMapper::generated_by`] for details.
    #[napi]
    pub fn generated_by(&self, pos: u32) -> Option<String> {
        self.inner.generated_by(pos)
    }

    /// Maps a span from expanded source to original source.
    /// See [`NativePositionMapper::map_span_to_original`] for details.
    #[napi]
    pub fn map_span_to_original(&self, start: u32, length: u32) -> Option<SpanResult> {
        self.inner.map_span_to_original(start, length)
    }

    /// Maps a span from original source to expanded source.
    /// See [`NativePositionMapper::map_span_to_expanded`] for details.
    #[napi]
    pub fn map_span_to_expanded(&self, start: u32, length: u32) -> SpanResult {
        self.inner.map_span_to_expanded(start, length)
    }

    /// Checks if a position is inside macro-generated code.
    /// See [`NativePositionMapper::is_in_generated`] for details.
    #[napi]
    pub fn is_in_generated(&self, pos: u32) -> bool {
        self.inner.is_in_generated(pos)
    }
}

/// Checks if the given TypeScript code has valid syntax.
///
/// This function attempts to parse the code using SWC's TypeScript parser
/// without performing any macro expansion.
///
/// # Arguments
///
/// * `code` - The TypeScript source code to check
/// * `filepath` - The file path (used to determine if it's TSX based on extension)
///
/// # Returns
///
/// A [`SyntaxCheckResult`] indicating success or containing the parse error.
///
/// # Example
///
/// ```javascript
/// const result = check_syntax("const x: number = 42;", "test.ts");
/// if (!result.ok) {
///     console.error("Syntax error:", result.error);
/// }
/// ```
#[napi]
pub fn check_syntax(code: String, filepath: String) -> SyntaxCheckResult {
    match parse_program(&code, &filepath) {
        Ok(_) => SyntaxCheckResult {
            ok: true,
            error: None,
        },
        Err(err) => SyntaxCheckResult {
            ok: false,
            error: Some(err.to_string()),
        },
    }
}

// ============================================================================
// Core Plugin Logic
// ============================================================================

/// Options for processing a file through the macro system.
///
/// Used by [`NativePlugin::process_file`] to configure expansion behavior
/// and caching.
#[napi(object)]
pub struct ProcessFileOptions {
    /// If `true`, preserves `@derive` decorators in the output.
    /// If `false` (default), decorators are stripped after expansion.
    pub keep_decorators: Option<bool>,
    /// Version string for cache invalidation.
    /// When provided, cached results are only reused if versions match.
    pub version: Option<String>,
    /// Additional decorator module names from external macros.
    /// See [`ExpandOptions::external_decorator_modules`] for details.
    pub external_decorator_modules: Option<Vec<String>>,
    /// Path to a previously loaded config file (for foreign types lookup).
    /// See [`ExpandOptions::config_path`] for details.
    pub config_path: Option<String>,
    /// Pre-built type registry JSON from [`scan_project_sync`].
    /// See [`ExpandOptions::type_registry_json`] for details.
    pub type_registry_json: Option<String>,
}

/// Options for macro expansion.
///
/// Used by [`expand_sync`] to configure expansion behavior.
#[napi(object)]
pub struct ExpandOptions {
    /// If `true`, preserves `@derive` decorators in the output.
    /// If `false` (default), decorators are stripped after expansion.
    pub keep_decorators: Option<bool>,

    /// Additional decorator module names from external macros.
    ///
    /// These are used during decorator stripping to identify Macroforge-specific
    /// decorators that should be removed from the output. Built-in decorator modules
    /// (like "serde", "debug") are automatically included.
    ///
    /// External macro packages should export their decorator module names, which
    /// plugins can collect and pass here.
    ///
    /// # Example
    ///
    /// ```javascript
    /// expandSync(code, filepath, {
    ///   keepDecorators: false,
    ///   externalDecoratorModules: ["myMacro", "customValidator"]
    /// });
    /// ```
    pub external_decorator_modules: Option<Vec<String>>,

    /// Path to a previously loaded config file.
    ///
    /// When provided, the expansion will use the cached configuration
    /// (including foreign types) from this path. The config must have been
    /// previously loaded via [`load_config`].
    ///
    /// # Example
    ///
    /// ```javascript
    /// // First, load the config
    /// const configResult = loadConfig(configContent, configPath);
    ///
    /// // Then use it during expansion
    /// expandSync(code, filepath, { configPath });
    /// ```
    pub config_path: Option<String>,

    /// Pre-built type registry JSON from [`scan_project_sync`].
    ///
    /// When provided, macros receive project-wide type awareness through
    /// the `type_registry` and `resolved_fields` fields on `MacroContextIR`.
    ///
    /// # Example
    ///
    /// ```javascript
    /// const scan = scanProjectSync(projectRoot);
    /// expandSync(code, filepath, { typeRegistryJson: scan.registryJson });
    /// ```
    pub type_registry_json: Option<String>,
}

/// The main plugin class for macro expansion with caching support.
///
/// `NativePlugin` is designed to be instantiated once and reused across multiple
/// file processing operations. It maintains a cache of expansion results keyed
/// by filepath and version, enabling efficient incremental processing.
///
/// # Thread Safety
///
/// The plugin is thread-safe through the use of `Mutex` for internal state.
/// However, macro expansion itself runs in a separate thread with a 32MB stack
/// to prevent stack overflow during deep AST recursion.
///
/// # Example
///
/// ```javascript
/// // Create a single plugin instance (typically at startup)
/// const plugin = new NativePlugin();
///
/// // Process files with caching
/// const result1 = plugin.process_file("src/foo.ts", code1, { version: "1" });
/// const result2 = plugin.process_file("src/foo.ts", code2, { version: "1" }); // Cache hit!
/// const result3 = plugin.process_file("src/foo.ts", code3, { version: "2" }); // Cache miss
///
/// // Get a mapper for position translation
/// const mapper = plugin.get_mapper("src/foo.ts");
/// ```
#[napi]
pub struct NativePlugin {
    /// Cache of expansion results, keyed by filepath.
    /// Protected by a mutex for thread-safe access.
    cache: std::sync::Mutex<std::collections::HashMap<String, CachedResult>>,
    /// Optional path to a log file for debugging.
    /// Protected by a mutex for thread-safe access.
    log_file: std::sync::Mutex<Option<std::path::PathBuf>>,
}

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

/// Internal structure for cached expansion results.
#[derive(Clone)]
struct CachedResult {
    /// Version string at the time of caching.
    /// Used for cache invalidation when version changes.
    version: Option<String>,
    /// The cached expansion result.
    result: ExpandResult,
}

/// Converts `ProcessFileOptions` to `ExpandOptions`.
///
/// Extracts only the options relevant for expansion, discarding cache-related
/// options like `version`.
fn option_expand_options(opts: Option<ProcessFileOptions>) -> Option<ExpandOptions> {
    opts.map(|o| ExpandOptions {
        keep_decorators: o.keep_decorators,
        external_decorator_modules: o.external_decorator_modules,
        config_path: o.config_path,
        type_registry_json: o.type_registry_json,
    })
}

#[napi]
impl NativePlugin {
    /// Creates a new `NativePlugin` instance.
    ///
    /// Initializes the plugin with an empty cache and sets up a default log file
    /// at `/tmp/macroforge-plugin.log` for debugging purposes.
    ///
    /// # Returns
    ///
    /// A new `NativePlugin` ready for processing files.
    ///
    /// # Side Effects
    ///
    /// Creates or clears the log file at `/tmp/macroforge-plugin.log`.
    #[napi(constructor)]
    pub fn new() -> Self {
        let plugin = Self {
            cache: std::sync::Mutex::new(std::collections::HashMap::new()),
            log_file: std::sync::Mutex::new(None),
        };

        // Initialize log file with default path for debugging.
        // This is useful for diagnosing issues in production environments
        // where console output might not be easily accessible.
        if let Ok(mut log_guard) = plugin.log_file.lock() {
            let log_path = std::path::PathBuf::from("/tmp/macroforge-plugin.log");

            // Clear/create log file to start fresh on each plugin instantiation
            if let Err(e) = std::fs::write(&log_path, "=== macroforge plugin loaded ===\n") {
                eprintln!("[macroforge] Failed to initialize log file: {}", e);
            } else {
                *log_guard = Some(log_path);
            }
        }

        plugin
    }

    /// Writes a message to the plugin's log file.
    ///
    /// Useful for debugging macro expansion issues in production environments.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    ///
    /// # Note
    ///
    /// Messages are appended to the log file. If the log file hasn't been
    /// configured or cannot be written to, the message is silently dropped.
    #[napi]
    pub fn log(&self, message: String) {
        if let Ok(log_guard) = self.log_file.lock()
            && let Some(log_path) = log_guard.as_ref()
        {
            use std::io::Write;
            if let Ok(mut file) = std::fs::OpenOptions::new()
                .append(true)
                .create(true)
                .open(log_path)
            {
                let _ = writeln!(file, "{}", message);
            }
        }
    }

    /// Sets the path for the plugin's log file.
    ///
    /// # Arguments
    ///
    /// * `path` - The file path to use for logging
    ///
    /// # Note
    ///
    /// This does not create the file; it will be created when the first
    /// message is logged.
    #[napi]
    pub fn set_log_file(&self, path: String) {
        if let Ok(mut log_guard) = self.log_file.lock() {
            *log_guard = Some(std::path::PathBuf::from(path));
        }
    }

    /// Processes a TypeScript file through the macro expansion system.
    ///
    /// This is the main entry point for file processing. It handles caching,
    /// thread isolation (to prevent stack overflow), and error recovery.
    ///
    /// # Arguments
    ///
    /// * `_env` - NAPI environment (unused but required by NAPI)
    /// * `filepath` - Path to the file (used for TSX detection and caching)
    /// * `code` - The TypeScript source code to process
    /// * `options` - Optional configuration for expansion and caching
    ///
    /// # Returns
    ///
    /// An [`ExpandResult`] containing the expanded code, diagnostics, and source mapping.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Thread spawning fails
    /// - The worker thread panics (often due to stack overflow)
    /// - Macro expansion fails internally
    ///
    /// # Performance
    ///
    /// - Uses a 32MB thread stack to prevent stack overflow during deep AST recursion
    /// - Caches results by filepath and version for efficient incremental processing
    /// - Early bailout for files without `@derive` decorators
    ///
    /// # Thread Safety
    ///
    /// Macro expansion runs in a separate thread because:
    /// 1. SWC AST operations can be deeply recursive, exceeding default stack limits
    /// 2. Node.js thread stack is typically only 2MB
    /// 3. Panics in the worker thread are caught and reported gracefully
    #[napi]
    pub fn process_file(
        &self,
        _env: Env,
        filepath: String,
        code: String,
        options: Option<ProcessFileOptions>,
    ) -> Result<ExpandResult> {
        let version = options.as_ref().and_then(|o| o.version.clone());

        // Cache Check: Return cached result if version matches.
        // This enables efficient incremental processing when files haven't changed.
        if let (Some(ver), Ok(guard)) = (version.as_ref(), self.cache.lock())
            && let Some(cached) = guard.get(&filepath)
            && cached.version.as_ref() == Some(ver)
        {
            return Ok(cached.result.clone());
        }

        // Run expansion in a separate thread with a LARGE stack (32MB).
        // Standard threads (and Node threads) often have 2MB stacks, which causes
        // "Broken pipe" / SEGFAULTS when SWC recurses deeply in macros.
        let opts_clone = option_expand_options(options);
        let filepath_for_thread = filepath.clone();

        let builder = std::thread::Builder::new().stack_size(32 * 1024 * 1024);
        let handle = builder
            .spawn(move || {
                // Set up SWC globals for this thread.
                // SWC uses thread-local storage for some operations.
                let globals = Globals::default();
                GLOBALS.set(&globals, || {
                    // Catch panics to report them gracefully instead of crashing.
                    // Common cause: stack overflow from deeply nested AST.
                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        // Note: NAPI Env is NOT thread safe - we cannot pass it.
                        // The expand_inner function uses pure Rust AST operations.
                        expand_inner(&code, &filepath_for_thread, opts_clone)
                    }))
                })
            })
            .map_err(|e| {
                Error::new(
                    Status::GenericFailure,
                    format!("Failed to spawn worker thread: {}", e),
                )
            })?;

        // Wait for the worker thread and unwrap nested Results.
        // Result structure: join() -> panic catch -> expand_inner -> final result
        let expand_result = handle
            .join()
            .map_err(|_| {
                Error::new(
                    Status::GenericFailure,
                    "Macro expansion worker thread panicked (Stack Overflow?)",
                )
            })?
            .map_err(|_| {
                Error::new(
                    Status::GenericFailure,
                    "Macro expansion panicked inside worker",
                )
            })??;

        // Update Cache: Store the result for future requests with the same version.
        if let Ok(mut guard) = self.cache.lock() {
            guard.insert(
                filepath.clone(),
                CachedResult {
                    version,
                    result: expand_result.clone(),
                },
            );
        }

        Ok(expand_result)
    }

    /// Retrieves a position mapper for a previously processed file.
    ///
    /// The mapper enables translation between original and expanded source positions,
    /// which is essential for IDE features like error reporting and navigation.
    ///
    /// # Arguments
    ///
    /// * `filepath` - Path to the file (must have been previously processed)
    ///
    /// # Returns
    ///
    /// `Some(NativeMapper)` if the file has been processed and has source mapping data,
    /// `None` if the file hasn't been processed or has no mapping (no macros expanded).
    #[napi]
    pub fn get_mapper(&self, filepath: String) -> Option<NativeMapper> {
        let mapping = match self.cache.lock() {
            Ok(guard) => guard
                .get(&filepath)
                .cloned()
                .and_then(|c| c.result.source_mapping),
            Err(_) => None,
        };

        mapping.map(|m| NativeMapper {
            inner: NativePositionMapper::new(m),
        })
    }

    /// Maps diagnostics from expanded source positions back to original source positions.
    ///
    /// This is used by IDE integrations to show errors at the correct locations
    /// in the user's original code, rather than in the macro-expanded output.
    ///
    /// # Arguments
    ///
    /// * `filepath` - Path to the file the diagnostics are for
    /// * `diags` - Diagnostics with positions in the expanded source
    ///
    /// # Returns
    ///
    /// Diagnostics with positions mapped back to the original source.
    /// If no mapper is available for the file, returns diagnostics unchanged.
    #[napi]
    pub fn map_diagnostics(&self, filepath: String, diags: Vec<JsDiagnostic>) -> Vec<JsDiagnostic> {
        let Some(mapper) = self.get_mapper(filepath) else {
            // No mapper available - return diagnostics unchanged
            return diags;
        };

        diags
            .into_iter()
            .map(|mut d| {
                // Attempt to map the diagnostic span back to original source
                if let (Some(start), Some(length)) = (d.start, d.length)
                    && let Some(mapped) = mapper.map_span_to_original(start, length)
                {
                    d.start = Some(mapped.start);
                    d.length = Some(mapped.length);
                }
                // Note: Diagnostics in generated code cannot be mapped and keep
                // their original (expanded) positions
                d
            })
            .collect()
    }
}

// ============================================================================
// Sync Functions (Refactored for Thread Safety & Performance)
// ============================================================================

/// Parses import statements from TypeScript code and returns their sources.
///
/// This function extracts information about all import statements in the code,
/// mapping each imported identifier to its source module. Useful for analyzing
/// dependencies and understanding where decorators come from.
///
/// # Arguments
///
/// * `code` - The TypeScript source code to parse
/// * `filepath` - The file path (used for TSX detection)
///
/// # Returns
///
/// A vector of [`ImportSourceResult`] entries, one for each imported identifier.
///
/// # Errors
///
/// Returns an error if the code cannot be parsed.
///
/// # Example
///
/// ```javascript
/// // For code: import { Derive, Clone } from "macroforge-ts";
/// const imports = parse_import_sources(code, "test.ts");
/// // Returns: [
/// //   { local: "Derive", module: "macroforge-ts" },
/// //   { local: "Clone", module: "macroforge-ts" }
/// // ]
/// ```
#[napi]
pub fn parse_import_sources(code: String, filepath: String) -> Result<Vec<ImportSourceResult>> {
    let (program, _cm) = parse_program(&code, &filepath)?;
    let module = match program {
        Program::Module(module) => module,
        // Scripts don't have import statements
        Program::Script(_) => return Ok(vec![]),
    };

    let import_result = crate::host::collect_import_sources(&module, &code);
    let mut imports = Vec::with_capacity(import_result.sources.len());
    for (local, module) in import_result.sources {
        imports.push(ImportSourceResult { local, module });
    }
    Ok(imports)
}

/// The `@Derive` decorator function exported to JavaScript/TypeScript.
///
/// This is a no-op function that exists purely for TypeScript type checking.
/// The actual decorator processing happens during macro expansion, where
/// `@derive(...)` decorators are recognized and transformed.
///
/// # TypeScript Usage
///
/// ```typescript
/// import { Derive } from "macroforge-ts";
///
/// @Derive(Debug, Clone, Serialize)
/// class User {
///     name: string;
///     email: string;
/// }
/// ```
#[napi(
    js_name = "Derive",
    ts_return_type = "ClassDecorator",
    ts_args_type = "...features: any[]"
)]
pub fn derive_decorator() {}

/// Result of loading a macroforge configuration file.
///
/// Returned by [`load_config`] after parsing a `macroforge.config.js/ts` file.
#[napi(object)]
pub struct LoadConfigResult {
    /// Whether to preserve `@derive` decorators in the output code.
    pub keep_decorators: bool,
    /// Whether to generate a convenience const for non-class types.
    pub generate_convenience_const: bool,
    /// Whether the config has any foreign type handlers defined.
    pub has_foreign_types: bool,
    /// Number of foreign types configured.
    pub foreign_type_count: u32,
}

/// Load and parse a macroforge configuration file.
///
/// Parses a `macroforge.config.js/ts` file and caches the result for use
/// during macro expansion. The configuration includes both simple settings
/// (like `keepDecorators`) and foreign type handlers.
///
/// # Arguments
///
/// * `content` - The raw content of the configuration file
/// * `filepath` - Path to the configuration file (used to determine syntax and as cache key)
///
/// # Returns
///
/// A [`LoadConfigResult`] containing the parsed configuration summary.
///
/// # Example
///
/// ```javascript
/// import { loadConfig, expandSync } from 'macroforge';
/// import fs from 'fs';
///
/// const configPath = 'macroforge.config.js';
/// const configContent = fs.readFileSync(configPath, 'utf-8');
///
/// // Load and cache the configuration
/// const result = loadConfig(configContent, configPath);
/// console.log(`Loaded config with ${result.foreignTypeCount} foreign types`);
///
/// // The config is now cached and will be used by expandSync
/// const expanded = expandSync(code, filepath, { configPath });
/// ```
#[napi]
pub fn load_config(content: String, filepath: String) -> Result<LoadConfigResult> {
    use crate::host::MacroforgeConfigLoader;

    let config = MacroforgeConfigLoader::load_and_cache(&content, &filepath).map_err(|e| {
        Error::new(
            Status::GenericFailure,
            format!("Failed to parse config: {}", e),
        )
    })?;

    Ok(LoadConfigResult {
        keep_decorators: config.keep_decorators,
        generate_convenience_const: config.generate_convenience_const,
        has_foreign_types: !config.foreign_types.is_empty(),
        foreign_type_count: config.foreign_types.len() as u32,
    })
}

/// Clears the configuration cache.
///
/// This is useful for testing to ensure each test starts with a clean state.
/// In production, clearing the cache will force configs to be re-parsed on next access.
///
/// # Example
///
/// ```javascript
/// const { clearConfigCache, loadConfig } = require('macroforge-ts');
///
/// // Clear cache before each test
/// clearConfigCache();
///
/// // Now load a fresh config
/// const result = loadConfig(configContent, configPath);
/// ```
#[napi]
pub fn clear_config_cache() {
    crate::host::clear_config_cache();
}

// ============================================================================
// Project Scanning for Type Awareness
// ============================================================================

/// Options for scanning a TypeScript project for type information.
#[napi(object)]
pub struct ScanOptions {
    /// File extensions to scan (default: `[".ts", ".tsx"]`).
    pub extensions: Option<Vec<String>>,
    /// Whether to only collect exported types (default: `false`).
    pub exported_only: Option<bool>,
}

/// Result of scanning a project for type information.
#[napi(object)]
#[derive(Clone)]
pub struct ScanResult {
    /// JSON-serialized [`TypeRegistry`].
    /// Pass this to `expand_sync` via `ExpandOptions.type_registry_json`.
    pub registry_json: String,
    /// Number of files scanned.
    pub files_scanned: u32,
    /// Number of types found.
    pub types_found: u32,
    /// Diagnostics from scanning (e.g., files that failed to parse).
    pub diagnostics: Vec<MacroDiagnostic>,
}

/// Scan a TypeScript project and build a type registry.
///
/// This should be called once at build start (e.g., in Vite's `buildStart` hook)
/// and the resulting `registry_json` should be passed to [`expand_sync`] via
/// `ExpandOptions.type_registry_json`.
///
/// # Arguments
///
/// * `root_dir` - The project root directory to scan
/// * `options` - Optional scan configuration
///
/// # Returns
///
/// A [`ScanResult`] with the serialized registry and scan statistics.
///
/// # Example
///
/// ```javascript
/// const scan = scanProjectSync(projectRoot);
/// console.log(`Found ${scan.typesFound} types in ${scan.filesScanned} files`);
///
/// // Pass to expand_sync for each file
/// const result = expandSync(code, filepath, {
///   typeRegistryJson: scan.registryJson,
/// });
/// ```
#[napi]
pub fn scan_project_sync(root_dir: String, options: Option<ScanOptions>) -> Result<ScanResult> {
    let builder = std::thread::Builder::new().stack_size(32 * 1024 * 1024);
    let handle = builder
        .spawn(move || scan_project_inner(&root_dir, options))
        .map_err(|e| {
            Error::new(
                Status::GenericFailure,
                format!("Failed to spawn scan thread: {}", e),
            )
        })?;

    handle
        .join()
        .map_err(|_| Error::new(Status::GenericFailure, "Scan worker panicked"))?
}

fn scan_project_inner(root_dir: &str, options: Option<ScanOptions>) -> Result<ScanResult> {
    use crate::host::scanner::{ProjectScanner, ScanConfig};

    let mut config = ScanConfig {
        root_dir: std::path::PathBuf::from(root_dir),
        ..ScanConfig::default()
    };

    if let Some(opts) = options {
        if let Some(exts) = opts.extensions {
            config.extensions = exts;
        }
        if let Some(exported) = opts.exported_only {
            config.exported_only = exported;
        }
    }

    let scanner = ProjectScanner::new(config);
    let output = scanner.scan().map_err(|e| {
        Error::new(
            Status::GenericFailure,
            format!("Project scan failed: {}", e),
        )
    })?;

    let types_found = output.registry.len() as u32;
    let registry_json = serde_json::to_string(&output.registry).map_err(|e| {
        Error::new(
            Status::GenericFailure,
            format!("Failed to serialize registry: {}", e),
        )
    })?;

    let diagnostics = output
        .warnings
        .into_iter()
        .map(|msg| MacroDiagnostic {
            level: "warning".to_string(),
            message: msg,
            start: None,
            end: None,
        })
        .collect();

    Ok(ScanResult {
        registry_json,
        files_scanned: output.files_scanned,
        types_found,
        diagnostics,
    })
}

/// Synchronously transforms TypeScript code through the macro expansion system.
///
/// This is similar to [`expand_sync`] but returns a [`TransformResult`] which
/// includes source map information (when available).
///
/// # Arguments
///
/// * `_env` - NAPI environment (unused but required by NAPI)
/// * `code` - The TypeScript source code to transform
/// * `filepath` - The file path (used for TSX detection)
///
/// # Returns
///
/// A [`TransformResult`] containing the transformed code and metadata.
///
/// # Errors
///
/// Returns an error if:
/// - Thread spawning fails
/// - The worker thread panics
/// - Macro expansion fails
///
/// # Thread Safety
///
/// Uses a 32MB thread stack to prevent stack overflow during deep AST recursion.
#[napi]
pub fn transform_sync(_env: Env, code: String, filepath: String) -> Result<TransformResult> {
    // Run in a separate thread with large stack for deep AST recursion
    let builder = std::thread::Builder::new().stack_size(32 * 1024 * 1024);
    let handle = builder
        .spawn(move || {
            let globals = Globals::default();
            GLOBALS.set(&globals, || {
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    transform_inner(&code, &filepath)
                }))
            })
        })
        .map_err(|e| {
            Error::new(
                Status::GenericFailure,
                format!("Failed to spawn transform thread: {}", e),
            )
        })?;

    handle
        .join()
        .map_err(|_| Error::new(Status::GenericFailure, "Transform worker crashed"))?
        .map_err(|_| Error::new(Status::GenericFailure, "Transform panicked"))?
}

/// Synchronously expands macros in TypeScript code.
///
/// This is the standalone macro expansion function that doesn't use caching.
/// For cached expansion, use [`NativePlugin::process_file`] instead.
///
/// # Arguments
///
/// * `_env` - NAPI environment (unused but required by NAPI)
/// * `code` - The TypeScript source code to expand
/// * `filepath` - The file path (used for TSX detection)
/// * `options` - Optional configuration (e.g., `keep_decorators`)
///
/// # Returns
///
/// An [`ExpandResult`] containing the expanded code, diagnostics, and source mapping.
///
/// # Errors
///
/// Returns an error if:
/// - Thread spawning fails
/// - The worker thread panics
/// - Macro host initialization fails
///
/// # Performance
///
/// - Uses a 32MB thread stack to prevent stack overflow
/// - Performs early bailout for files without `@derive` decorators
///
/// # Example
///
/// ```javascript
/// const result = expand_sync(env, code, "user.ts", { keep_decorators: false });
/// console.log(result.code); // Expanded TypeScript code
/// console.log(result.diagnostics); // Any warnings or errors
/// ```
#[napi]
pub fn expand_sync(
    _env: Env,
    code: String,
    filepath: String,
    options: Option<ExpandOptions>,
) -> Result<ExpandResult> {
    // Run in a separate thread with large stack for deep AST recursion
    let builder = std::thread::Builder::new().stack_size(32 * 1024 * 1024);
    let handle = builder
        .spawn(move || {
            let globals = Globals::default();
            GLOBALS.set(&globals, || {
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    expand_inner(&code, &filepath, options)
                }))
            })
        })
        .map_err(|e| {
            Error::new(
                Status::GenericFailure,
                format!("Failed to spawn expand thread: {}", e),
            )
        })?;

    handle
        .join()
        .map_err(|_| Error::new(Status::GenericFailure, "Expand worker crashed"))?
        .map_err(|_| Error::new(Status::GenericFailure, "Expand panicked"))?
}

// ============================================================================
// Inner Logic (Optimized)
// ============================================================================

/// Core macro expansion logic, decoupled from NAPI Env to allow threading.
///
/// This function contains the actual expansion implementation and is called
/// from a separate thread with a large stack size to prevent stack overflow.
///
/// # Arguments
///
/// * `code` - The TypeScript source code to expand
/// * `filepath` - The file path (used for TSX detection and error reporting)
/// * `options` - Optional expansion configuration
///
/// # Returns
///
/// An [`ExpandResult`] containing the expanded code and metadata.
///
/// # Errors
///
/// Returns an error if:
/// - The macro host fails to initialize
/// - Macro expansion fails internally
///
/// # Algorithm
///
/// Check if source code contains `@derive(` as a standalone JSDoc directive.
///
/// Only matches `@derive(` when it appears at the start of a JSDoc line (after
/// stripping `/**`, `*/`, `*`, and whitespace). Skips `@derive` embedded in prose
/// (e.g., `"result from @derive(Deserialize)"`) and inside fenced code blocks.
fn has_macro_annotations(source: &str) -> bool {
    if !source.contains("@derive") {
        return false;
    }
    let mut in_code_block = false;
    for line in source.lines() {
        // Strip JSDoc comment syntax: /**, */, leading *, and whitespace
        let trimmed = line
            .trim()
            .trim_start_matches('/')
            .trim_start_matches('*')
            .trim_end_matches('/')
            .trim_end_matches('*')
            .trim();
        if trimmed.starts_with("```") {
            in_code_block = !in_code_block;
            continue;
        }
        if in_code_block {
            continue;
        }
        // A line must START with @derive( to be a real directive.
        // This rejects prose like "result from @derive(Deserialize)".
        if trimmed.starts_with("@derive(") {
            return true;
        }
    }
    false
}

/// 1. **Early bailout**: If code doesn't contain `@derive`, return unchanged
/// 2. **Parse**: Convert code to SWC AST
/// 3. **Expand**: Run all registered macros on decorated classes
/// 4. **Collect**: Gather diagnostics and source mapping
/// 5. **Post-process**: Inject type declarations for generated methods
fn expand_inner(
    code: &str,
    filepath: &str,
    options: Option<ExpandOptions>,
) -> Result<ExpandResult> {
    // Early bailout: Skip files without @derive decorator.
    // This optimization avoids expensive parsing for files that don't use macros
    // and prevents issues with Svelte runes ($state, $derived, etc.) that use
    // similar syntax but aren't macroforge decorators.
    // Uses has_macro_annotations to skip @derive inside fenced code blocks in docs.
    if !has_macro_annotations(code) {
        return Ok(ExpandResult::unchanged(code));
    }

    // Create a new macro host for this thread.
    // Each thread needs its own MacroExpander because the expansion process
    // is stateful and cannot be safely shared across threads.
    let mut macro_host = MacroExpander::new().map_err(|err| {
        Error::new(
            Status::GenericFailure,
            format!("Failed to initialize macro host: {err:?}"),
        )
    })?;

    // Apply options if provided
    if let Some(ref opts) = options {
        if let Some(keep) = opts.keep_decorators {
            macro_host.set_keep_decorators(keep);
        }
        if let Some(ref modules) = opts.external_decorator_modules {
            macro_host.set_external_decorator_modules(modules.clone());
        }
        // Deserialize and attach the type registry for type awareness
        if let Some(ref json) = opts.type_registry_json {
            let registry = get_or_parse_registry(json);
            macro_host.set_type_registry(registry);
        }
    }

    // Set up foreign types and config imports on the registry (from config file).
    // The registry's source imports will be built from the AST later in prepare_expansion_context.
    let config_path = options.as_ref().and_then(|o| o.config_path.as_ref());
    if let Some(path) = config_path
        && let Some(config) = CONFIG_CACHE.get(path)
    {
        crate::host::import_registry::set_foreign_types(config.foreign_types.clone());
        crate::host::import_registry::with_registry_mut(|r| {
            r.config_imports = config
                .config_imports
                .iter()
                .map(|(name, info)| (name.clone(), info.source.clone()))
                .collect();
        });
    }

    // Parse the code into an AST.
    // On parse errors, we return a graceful "no-op" result instead of failing,
    // because parse errors can happen frequently during typing in an IDE.
    let (program, _) = match parse_program(code, filepath) {
        Ok(p) => p,
        Err(e) => {
            let error_msg = e.to_string();

            // Clean up registry before returning
            crate::host::import_registry::clear_registry();
            crate::host::import_registry::clear_foreign_types();

            return Ok(ExpandResult {
                code: code.to_string(),
                types: None,
                metadata: None,
                diagnostics: vec![MacroDiagnostic {
                    level: "info".to_string(),
                    message: format!("Macro expansion skipped due to syntax error: {}", error_msg),
                    start: None,
                    end: None,
                }],
                source_mapping: None,
            });
        }
    };

    // Run macro expansion on the parsed AST.
    // expand() internally calls prepare_expansion_context which builds the full registry from the AST.
    let expansion_result = macro_host.expand(code, &program, filepath);

    // Single cleanup — replaces 7 separate clear_* calls
    crate::host::import_registry::clear_registry();

    // Now propagate any error
    let expansion = expansion_result.map_err(|err| {
        Error::new(
            Status::GenericFailure,
            format!("Macro expansion failed: {err:?}"),
        )
    })?;

    // Convert internal diagnostics to NAPI-compatible format
    let diagnostics = expansion
        .diagnostics
        .into_iter()
        .map(|d| MacroDiagnostic {
            level: format!("{:?}", d.level).to_lowercase(),
            message: d.message,
            start: d.span.map(|s| s.start),
            end: d.span.map(|s| s.end),
        })
        .collect();

    // Convert internal source mapping to NAPI-compatible format
    let source_mapping = expansion.source_mapping.map(|mapping| SourceMappingResult {
        segments: mapping
            .segments
            .into_iter()
            .map(|seg| MappingSegmentResult {
                original_start: seg.original_start,
                original_end: seg.original_end,
                expanded_start: seg.expanded_start,
                expanded_end: seg.expanded_end,
            })
            .collect(),
        generated_regions: mapping
            .generated_regions
            .into_iter()
            .map(|region| GeneratedRegionResult {
                start: region.start,
                end: region.end,
                source_macro: region.source_macro,
            })
            .collect(),
    });

    // Post-process type declarations.
    // Heuristic fix: If the expanded code contains toJSON() but the type
    // declarations don't, inject the type signature. This ensures IDEs
    // provide proper type information for serialized objects.
    let mut types_output = expansion.type_output;
    if let Some(types) = &mut types_output
        && expansion.code.contains("toJSON(")
        && !types.contains("toJSON(")
    {
        // Find the last closing brace and insert before it.
        // This is a heuristic that works for simple cases.
        if let Some(insert_at) = types.rfind('}') {
            types.insert_str(insert_at, "  toJSON(): Record<string, unknown>;\n");
        }
    }

    Ok(ExpandResult {
        code: expansion.code,
        types: types_output,
        // Only include metadata if there were classes processed
        metadata: if expansion.classes.is_empty() {
            None
        } else {
            serde_json::to_string(&expansion.classes).ok()
        },
        diagnostics,
        source_mapping,
    })
}

/// Core transform logic, decoupled from NAPI Env to allow threading.
///
/// Similar to [`expand_inner`] but returns a [`TransformResult`] and fails
/// on any error-level diagnostics.
///
/// # Arguments
///
/// * `code` - The TypeScript source code to transform
/// * `filepath` - The file path (used for TSX detection)
///
/// # Returns
///
/// A [`TransformResult`] containing the transformed code.
///
/// # Errors
///
/// Returns an error if:
/// - The macro host fails to initialize
/// - Parsing fails
/// - Expansion fails
/// - Any error-level diagnostic is emitted
fn transform_inner(code: &str, filepath: &str) -> Result<TransformResult> {
    let macro_host = MacroExpander::new().map_err(|err| {
        Error::new(
            Status::GenericFailure,
            format!("Failed to init host: {err:?}"),
        )
    })?;

    let (program, cm) = parse_program(code, filepath)?;

    let expansion = macro_host
        .expand(code, &program, filepath)
        .map_err(|err| Error::new(Status::GenericFailure, format!("Expansion failed: {err:?}")))?;

    // Unlike expand_inner, transform_inner treats errors as fatal
    handle_macro_diagnostics(&expansion.diagnostics, filepath)?;

    // Optimization: Only re-emit if we didn't change anything.
    // If expansion.changed is true, we already have the string from the expander.
    // Otherwise, emit the original AST to string (no changes made).
    let generated = if expansion.changed {
        expansion.code
    } else {
        emit_program(&program, &cm)?
    };

    let metadata = if expansion.classes.is_empty() {
        None
    } else {
        serde_json::to_string(&expansion.classes).ok()
    };

    Ok(TransformResult {
        code: generated,
        map: None, // Source mapping handled separately via SourceMappingResult
        types: expansion.type_output,
        metadata,
    })
}

/// Parses TypeScript source code into an SWC AST.
///
/// # Arguments
///
/// * `code` - The TypeScript source code
/// * `filepath` - The file path (used to determine TSX mode from extension)
///
/// # Returns
///
/// A tuple of `(Program, SourceMap)` on success.
///
/// # Errors
///
/// Returns an error if the code contains syntax errors.
///
/// # Configuration
///
/// - TSX mode is enabled for `.tsx` files
/// - Decorators are always enabled
/// - Uses latest ES version
/// - `no_early_errors` is enabled for better error recovery
fn parse_program(code: &str, filepath: &str) -> Result<(Program, Lrc<SourceMap>)> {
    let cm: Lrc<SourceMap> = Lrc::new(SourceMap::default());
    let fm = cm.new_source_file(
        FileName::Custom(filepath.to_string()).into(),
        code.to_string(),
    );
    // Create a handler that captures errors to a buffer (we don't use its output directly)
    let handler =
        Handler::with_emitter_writer(Box::new(std::io::Cursor::new(Vec::new())), Some(cm.clone()));

    // Configure the lexer for TypeScript with decorator support
    let lexer = Lexer::new(
        Syntax::Typescript(TsSyntax {
            tsx: filepath.ends_with(".tsx"), // Enable TSX for .tsx files
            decorators: true,                // Required for @derive decorators
            dts: false,                      // Not parsing .d.ts files
            no_early_errors: true,           // Better error recovery during typing
            ..Default::default()
        }),
        EsVersion::latest(),
        StringInput::from(&*fm),
        None, // No comments collection
    );

    let mut parser = Parser::new_from(lexer);
    match parser.parse_program() {
        Ok(program) => Ok((program, cm)),
        Err(error) => {
            // Format and emit the error for debugging purposes
            let msg = format!("Failed to parse TypeScript: {:?}", error);
            error.into_diagnostic(&handler).emit();
            Err(Error::new(Status::GenericFailure, msg))
        }
    }
}

/// Emits an SWC AST back to JavaScript/TypeScript source code.
///
/// # Arguments
///
/// * `program` - The AST to emit
/// * `cm` - The source map (used for line/column tracking)
///
/// # Returns
///
/// The generated source code as a string.
///
/// # Errors
///
/// Returns an error if code generation fails (rare).
fn emit_program(program: &Program, cm: &Lrc<SourceMap>) -> Result<String> {
    let mut buf = vec![];
    let mut emitter = Emitter {
        cfg: swc_core::ecma::codegen::Config::default(),
        cm: cm.clone(),
        comments: None,
        wr: Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)),
    };
    emitter
        .emit_program(program)
        .map_err(|e| Error::new(Status::GenericFailure, format!("{:?}", e)))?;
    Ok(String::from_utf8_lossy(&buf).to_string())
}

/// Checks diagnostics for errors and returns the first error as a Result.
///
/// This is used by [`transform_inner`] which treats errors as fatal,
/// unlike [`expand_inner`] which allows non-fatal errors in diagnostics.
///
/// # Arguments
///
/// * `diags` - The diagnostics to check
/// * `file` - The file path for error location reporting
///
/// # Returns
///
/// `Ok(())` if no errors, `Err` with the first error message otherwise.
fn handle_macro_diagnostics(diags: &[Diagnostic], file: &str) -> Result<()> {
    for diag in diags {
        if matches!(diag.level, DiagnosticLevel::Error) {
            // Format error location for helpful error messages
            let loc = diag
                .span
                .map(|s| format!("{}:{}-{}", file, s.start, s.end))
                .unwrap_or_else(|| file.to_string());
            return Err(Error::new(
                Status::GenericFailure,
                format!("Macro error at {}: {}", loc, diag.message),
            ));
        }
    }
    Ok(())
}

// ============================================================================
// Manifest / Debug API
// ============================================================================

/// Entry for a registered macro in the manifest.
///
/// Used by [`MacroManifest`] to describe available macros to tooling
/// such as IDE extensions and documentation generators.
#[napi(object)]
pub struct MacroManifestEntry {
    /// The macro name (e.g., "Debug", "Clone", "Serialize").
    pub name: String,
    /// The macro kind: "derive", "attribute", or "function".
    pub kind: String,
    /// Human-readable description of what the macro does.
    pub description: String,
    /// The package that provides this macro (e.g., "macroforge-ts").
    pub package: String,
}

/// Entry for a registered decorator in the manifest.
///
/// Used by [`MacroManifest`] to describe field-level decorators
/// that can be used with macros.
#[napi(object)]
pub struct DecoratorManifestEntry {
    /// The module this decorator belongs to (e.g., "serde").
    pub module: String,
    /// The exported name of the decorator (e.g., "skip", "rename").
    pub export: String,
    /// The decorator kind: "class", "property", "method", "accessor", "parameter".
    pub kind: String,
    /// Documentation string for the decorator.
    pub docs: String,
}

/// Complete manifest of all available macros and decorators.
///
/// This is returned by [`get_macro_manifest`] and is useful for:
/// - IDE autocompletion
/// - Documentation generation
/// - Tooling integration
#[napi(object)]
pub struct MacroManifest {
    /// ABI version for compatibility checking.
    pub version: u32,
    /// All registered macros (derive, attribute, function).
    pub macros: Vec<MacroManifestEntry>,
    /// All registered field/class decorators.
    pub decorators: Vec<DecoratorManifestEntry>,
}

/// Returns the complete manifest of all registered macros and decorators.
///
/// This is a debug/introspection API that allows tooling to discover
/// what macros are available at runtime.
///
/// # Returns
///
/// A [`MacroManifest`] containing all registered macros and decorators.
///
/// # Example (JavaScript)
///
/// ```javascript
/// const manifest = __macroforgeGetManifest();
/// console.log("Available macros:", manifest.macros.map(m => m.name));
/// // ["Debug", "Clone", "PartialEq", "Hash", "Serialize", "Deserialize", ...]
/// ```
#[napi(js_name = "__macroforgeGetManifest")]
pub fn get_macro_manifest() -> MacroManifest {
    let manifest = derived::get_manifest();
    MacroManifest {
        version: manifest.version,
        macros: manifest
            .macros
            .into_iter()
            .map(|m| MacroManifestEntry {
                name: m.name.to_string(),
                kind: format!("{:?}", m.kind).to_lowercase(),
                description: m.description.to_string(),
                package: m.package.to_string(),
            })
            .collect(),
        decorators: manifest
            .decorators
            .into_iter()
            .map(|d| DecoratorManifestEntry {
                module: d.module.to_string(),
                export: d.export.to_string(),
                kind: format!("{:?}", d.kind).to_lowercase(),
                docs: d.docs.to_string(),
            })
            .collect(),
    }
}

/// Checks if any macros are registered in this package.
///
/// Useful for build tools to determine if macro expansion is needed.
///
/// # Returns
///
/// `true` if at least one macro is registered, `false` otherwise.
#[napi(js_name = "__macroforgeIsMacroPackage")]
pub fn is_macro_package() -> bool {
    !derived::macro_names().is_empty()
}

/// Returns the names of all registered macros.
///
/// # Returns
///
/// A vector of macro names (e.g., `["Debug", "Clone", "Serialize"]`).
#[napi(js_name = "__macroforgeGetMacroNames")]
pub fn get_macro_names() -> Vec<String> {
    derived::macro_names()
        .into_iter()
        .map(|s| s.to_string())
        .collect()
}

/// Returns all registered macro module names (debug API).
///
/// Modules group related macros together (e.g., "builtin", "serde").
///
/// # Returns
///
/// A vector of module names.
#[napi(js_name = "__macroforgeDebugGetModules")]
pub fn debug_get_modules() -> Vec<String> {
    crate::host::derived::modules()
        .into_iter()
        .map(|s| s.to_string())
        .collect()
}

/// Looks up a macro by module and name (debug API).
///
/// Useful for testing macro registration and debugging lookup issues.
///
/// # Arguments
///
/// * `module` - The module name (e.g., "builtin")
/// * `name` - The macro name (e.g., "Debug")
///
/// # Returns
///
/// A string describing whether the macro was found or not.
#[napi(js_name = "__macroforgeDebugLookup")]
pub fn debug_lookup(module: String, name: String) -> String {
    match MacroExpander::new() {
        Ok(host) => match host.dispatcher.registry().lookup(&module, &name) {
            Ok(_) => format!("Found: ({}, {})", module, name),
            Err(_) => format!("Not found: ({}, {})", module, name),
        },
        Err(e) => format!("Host init failed: {}", e),
    }
}

/// Returns debug information about all registered macro descriptors (debug API).
///
/// This provides low-level access to the inventory-based macro registration
/// system for debugging purposes.
///
/// # Returns
///
/// A vector of strings describing each registered macro descriptor.
#[napi(js_name = "__macroforgeDebugDescriptors")]
pub fn debug_descriptors() -> Vec<String> {
    inventory::iter::<crate::host::derived::DerivedMacroRegistration>()
        .map(|entry| {
            format!(
                "name={}, module={}, package={}",
                entry.descriptor.name, entry.descriptor.module, entry.descriptor.package
            )
        })
        .collect()
}