wangzhibo
6 天以前 7bd866831780abcf5a59c4cbb7d1be456eea7c99
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
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs'), require('path'), require('prettier'), require('axios'), require('lodash'), require('@vue/compiler-sfc'), require('magic-string'), require('glob'), require('node:util'), require('svgo'), require('postcss-value-parser')) :
    typeof define === 'function' && define.amd ? define(['exports', 'fs', 'path', 'prettier', 'axios', 'lodash', '@vue/compiler-sfc', 'magic-string', 'glob', 'node:util', 'svgo', 'postcss-value-parser'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.index = {}, global.fs, global.path, global.prettier, global.axios, global.lodash, global.compilerSfc, global.magicString, global.glob, global.util, global.svgo, global.valueParser));
})(this, (function (exports, fs, path, prettier, axios, lodash, compilerSfc, magicString, glob, util, svgo, valueParser) { 'use strict';
 
    const config = {
        type: "admin",
        reqUrl: "",
        nameTag: true,
        eps: {
            enable: true,
            api: "",
            dist: "./build/cool",
            mapping: [
                {
                    // 自定义匹配
                    custom: ({ propertyName, type }) => {
                        // 如果没有,返回null或者不返回,则继续遍历其他匹配规则
                        return null;
                    },
                },
                {
                    type: "string",
                    test: ["varchar", "text", "simple-json"],
                },
                {
                    type: "string[]",
                    test: ["simple-array"],
                },
                {
                    type: "Date",
                    test: ["datetime", "date"],
                },
                {
                    type: "number",
                    test: ["tinyint", "int", "decimal"],
                },
                {
                    type: "BigInt",
                    test: ["bigint"],
                },
                {
                    type: "any",
                    test: ["json"],
                },
            ],
        },
        svg: {
            skipNames: ["base"],
        },
        tailwind: {
            enable: true,
            remUnit: 14,
            remPrecision: 6,
            rpxRatio: 2,
            darkTextClass: "dark:text-surface-50",
        },
        uniapp: {
            isPlugin: false,
        },
        clean: false,
        utsPlatform: "web",
    };
 
    // 根目录
    function rootDir(path$1) {
        switch (config.type) {
            case "app":
            case "uniapp-x":
                return path.join(process.env.UNI_INPUT_DIR, path$1);
            default:
                return path.join(process.cwd(), path$1);
        }
    }
    // 首字母大写
    function firstUpperCase(value) {
        return value.replace(/\b(\w)(\w*)/g, function ($0, $1, $2) {
            return $1.toUpperCase() + $2;
        });
    }
    // 横杠转驼峰
    function toCamel(str) {
        return str.replace(/([^-])(?:-+([^-]))/g, function ($0, $1, $2) {
            return $1 + $2.toUpperCase();
        });
    }
    // 创建目录
    function createDir(path, recursive) {
        try {
            if (!fs.existsSync(path))
                fs.mkdirSync(path, { recursive });
        }
        catch (err) { }
    }
    // 读取文件
    function readFile(path, json) {
        try {
            const content = fs.readFileSync(path, "utf8");
            return json ? JSON.parse(removeJsonComments(content)) : content;
        }
        catch (err) { }
        return "";
    }
    // 安全地移除JSON中的注释
    function removeJsonComments(content) {
        let result = "";
        let inString = false;
        let stringChar = "";
        let escaped = false;
        let i = 0;
        while (i < content.length) {
            const char = content[i];
            const nextChar = content[i + 1];
            // 处理字符串状态
            if (!inString && (char === '"' || char === "'")) {
                inString = true;
                stringChar = char;
                result += char;
            }
            else if (inString && char === stringChar && !escaped) {
                inString = false;
                stringChar = "";
                result += char;
            }
            else if (inString) {
                // 在字符串内,直接添加字符
                result += char;
                escaped = char === "\\" && !escaped;
            }
            else {
                // 不在字符串内,检查注释
                if (char === "/" && nextChar === "/") {
                    // 单行注释,跳过到行尾
                    while (i < content.length && content[i] !== "\n") {
                        i++;
                    }
                    if (i < content.length) {
                        result += content[i]; // 保留换行符
                    }
                }
                else if (char === "/" && nextChar === "*") {
                    // 多行注释,跳过到 */
                    i += 2;
                    while (i < content.length - 1) {
                        if (content[i] === "*" && content[i + 1] === "/") {
                            i += 2;
                            break;
                        }
                        i++;
                    }
                    continue;
                }
                else {
                    result += char;
                    escaped = false;
                }
            }
            i++;
        }
        return result;
    }
    // 写入文件
    function writeFile(path, data) {
        try {
            return fs.writeFileSync(path, data);
        }
        catch (err) { }
        return "";
    }
    // 解析body
    function parseJson(req) {
        return new Promise((resolve) => {
            let d = "";
            req.on("data", function (chunk) {
                d += chunk;
            });
            req.on("end", function () {
                try {
                    resolve(JSON.parse(d));
                }
                catch {
                    resolve({});
                }
            });
        });
    }
    // 格式化内容
    function formatContent(content, options) {
        return prettier.format(content, {
            parser: "typescript",
            useTabs: true,
            tabWidth: 4,
            endOfLine: "lf",
            semi: true,
            ...options,
        });
    }
    function error(message) {
        console.log("\x1B[31m%s\x1B[0m", message);
    }
 
    /**
     * 将模板字符串扁平化处理,转换为 Service 类型定义
     * @param template - 包含 Service 类型定义的模板字符串
     * @returns 处理后的 Service 类型定义字符串
     * @throws {Error} 当模板中找不到 Service 类型定义时抛出错误
     */
    function flatten(template) {
        // 查找 Service 类型定义的起始位置
        const startIndex = template.indexOf("export type Service = {");
        // 保留 Service 类型定义前的内容
        let header = template.substring(0, startIndex);
        // 获取 Service 类型定义及其内容,去除换行和制表符
        const serviceTemplateContent = template.substring(startIndex).replace(/\n|\t/g, "");
        // 找到 Service 的内容部分
        const serviceStartIndex = serviceTemplateContent.indexOf("{") + 1;
        const serviceEndIndex = findClosingBrace(serviceTemplateContent, serviceStartIndex);
        const serviceInnerContent = serviceTemplateContent
            .substring(serviceStartIndex, serviceEndIndex)
            .trim();
        // 存储所有接口定义
        const allInterfaces = new Map();
        // 处理 Service 内容,保持原有结构但替换嵌套对象为接口引用
        const serviceContent = buildCurrentLevelContent(serviceInnerContent);
        // 递归收集所有需要生成的接口
        flattenContent(serviceInnerContent, allInterfaces);
        // 生成所有接口定义
        let interfaces = "";
        allInterfaces.forEach((content, key) => {
            interfaces += `\nexport interface ${firstUpperCase(key)}Interface { ${content} }\n`;
        });
        return `${header}${interfaces}\nexport type Service = { ${serviceContent} }`;
    }
    /**
     * 查找匹配的右花括号位置
     * @param str - 要搜索的字符串
     * @param startIndex - 开始搜索的位置
     * @returns 匹配的右花括号位置
     * @throws {Error} 当找不到匹配的右花括号时抛出错误
     */
    function findClosingBrace(str, startIndex) {
        let braceCount = 1;
        let currentIndex = startIndex;
        while (currentIndex < str.length && braceCount > 0) {
            if (str[currentIndex] === "{")
                braceCount++;
            if (str[currentIndex] === "}")
                braceCount--;
            currentIndex++;
        }
        if (braceCount !== 0) {
            throw new Error("Unmatched braces in the template");
        }
        return currentIndex - 1;
    }
    /**
     * 递归收集所有需要生成的接口
     * @param content - 要处理的内容
     * @param allInterfaces - 存储所有接口定义的 Map
     * @param parentFields - 父级字段数组(暂未使用)
     */
    function flattenContent(content, allInterfaces, parentFields) {
        const interfacePattern = /(\w+)\s*:\s*\{/g;
        let match;
        while ((match = interfacePattern.exec(content)) !== null) {
            const key = match[1];
            const startIndex = match.index + match[0].length;
            const endIndex = findClosingBrace(content, startIndex);
            if (endIndex > startIndex) {
                const innerContent = content.substring(startIndex, endIndex).trim();
                // 构建当前接口的内容,将嵌套对象替换为接口引用
                const currentLevelContent = buildCurrentLevelContent(innerContent);
                allInterfaces.set(key, currentLevelContent);
                // 递归处理嵌套内容
                flattenContent(innerContent, allInterfaces);
            }
        }
    }
    /**
     * 构建当前级别的内容,将嵌套对象替换为接口引用
     * @param content - 内容字符串
     * @returns 处理后的内容
     */
    function buildCurrentLevelContent(content) {
        const interfacePattern = /(\w+)\s*:\s*\{/g;
        let result = content;
        let match;
        // 重置正则表达式的 lastIndex
        interfacePattern.lastIndex = 0;
        while ((match = interfacePattern.exec(content)) !== null) {
            const key = match[1];
            const startIndex = match.index + match[0].length;
            const endIndex = findClosingBrace(content, startIndex);
            if (endIndex > startIndex) {
                const fullMatch = content.substring(match.index, endIndex + 1);
                const replacement = `${key}: ${firstUpperCase(key)}Interface;`;
                result = result.replace(fullMatch, replacement);
            }
        }
        // 清理多余的分号和空格
        result = result.replace(/;+/g, ";").replace(/\s+/g, " ").trim();
        return result;
    }
 
    /**
     * 获取动态类名
     */
    const getDynamicClassNames = (value) => {
        const names = new Set();
        // 匹配函数调用中的对象参数(如 parseClass({'!bg-surface-50': hoverable}))
        const functionCallRegex = /\w+\s*\(\s*\{([^}]*)\}\s*\)/gs;
        let funcMatch;
        while ((funcMatch = functionCallRegex.exec(value)) !== null) {
            const objContent = funcMatch[1];
            // 提取对象中的键
            const keyRegex = /['"](.*?)['"]\s*:/gs;
            let keyMatch;
            while ((keyMatch = keyRegex.exec(objContent)) !== null) {
                keyMatch[1].trim() && names.add(keyMatch[1]);
            }
        }
        // 匹配对象键(如 { 'text-a': 1 })- 优化版本,避免跨行错误匹配
        const objKeyRegex = /[{,]\s*['"](.*?)['"]\s*:/gs;
        let objKeyMatch;
        while ((objKeyMatch = objKeyRegex.exec(value)) !== null) {
            const className = objKeyMatch[1].trim();
            // 确保是有效的CSS类名,避免匹配到错误内容
            if (className && !className.includes("\n") && !className.includes("\t")) {
                names.add(className);
            }
        }
        // 匹配数组中的字符串元素(如 'text-center')- 优化版本
        const arrayStringRegex = /(?:^|[,\[\s])\s*['"](.*?)['"]/gs;
        let arrayMatch;
        while ((arrayMatch = arrayStringRegex.exec(value)) !== null) {
            const className = arrayMatch[1].trim();
            // 确保是有效的CSS类名
            if (className && !className.includes("\n") && !className.includes("\t")) {
                names.add(className);
            }
        }
        // 匹配三元表达式中的字符串(如 'dark' 和 'light')
        const ternaryRegex = /(\?|:)\s*['"](.*?)['"]/gs;
        let ternaryMatch;
        while ((ternaryMatch = ternaryRegex.exec(value)) !== null) {
            ternaryMatch[2].trim() && names.add(ternaryMatch[2]);
        }
        // 匹配反引号模板字符串 - 改进版本
        const templateRegex = /`([^`]*)`/gs;
        let templateMatch;
        while ((templateMatch = templateRegex.exec(value)) !== null) {
            const templateContent = templateMatch[1];
            // 提取模板字符串中的普通文本部分(排除 ${} 表达式)
            const textParts = templateContent.split(/\$\{[^}]*\}/);
            textParts.forEach((part) => {
                part.trim()
                    .split(/\s+/)
                    .forEach((className) => {
                    className.trim() && names.add(className.trim());
                });
            });
            // 提取模板字符串中 ${} 表达式内的字符串
            const expressionRegex = /\$\{([^}]*)\}/gs;
            let expressionMatch;
            while ((expressionMatch = expressionRegex.exec(templateContent)) !== null) {
                const expression = expressionMatch[1];
                // 递归处理表达式中的动态类名
                getDynamicClassNames(expression).forEach((name) => names.add(name));
            }
        }
        // 处理混合字符串(模板字符串 + 普通文本),如 "`text-red-900` text-red-1000"
        const mixedStringRegex = /`[^`]*`\s+([a-zA-Z0-9\-_\s]+)/g;
        let mixedMatch;
        while ((mixedMatch = mixedStringRegex.exec(value)) !== null) {
            const additionalClasses = mixedMatch[1].trim().split(/\s+/);
            additionalClasses.forEach((className) => {
                className.trim() && names.add(className.trim());
            });
        }
        // 处理普通字符串,多个类名用空格分割
        const stringRegex = /['"]([\w\s\-!:\/]+?)['"]/gs;
        let stringMatch;
        while ((stringMatch = stringRegex.exec(value)) !== null) {
            const classNames = stringMatch[1].trim().split(/\s+/);
            classNames.forEach((className) => {
                className.trim() && names.add(className.trim());
            });
        }
        return Array.from(names);
    };
    /**
     * 获取类名
     */
    function getClassNames(code) {
        // 修改正则表达式以支持多行匹配,避免内层引号冲突
        const classRegex = /(?:class|:class|:pt|:hover-class)\s*=\s*(['"`])((?:[^'"`\\]|\\.|`[^`]*`|'[^']*'|"[^"]*")*?)\1/gis;
        const classNames = new Set();
        let match;
        while ((match = classRegex.exec(code)) !== null) {
            const attribute = match[0].split("=")[0].trim();
            const isStaticClass = attribute === "class" || attribute === "hover-class";
            const isPtAttribute = attribute.includes("pt");
            const value = match[2].trim();
            if (isStaticClass) {
                // 处理静态 class 和 hover-class
                value.split(/\s+/).forEach((name) => name && classNames.add(name));
            }
            else if (isPtAttribute) {
                // 处理 :pt 属性中的 className
                parseClasNameFromPt(value, classNames);
            }
            else {
                // 处理动态 :class 和 :hover-class
                getDynamicClassNames(value).forEach((name) => classNames.add(name));
            }
        }
        return Array.from(classNames);
    }
    /**
     * 从 :pt 属性中解析 className
     */
    function parseClasNameFromPt(value, classNames) {
        // 递归查找所有 className 属性
        const classNameRegex = /className\s*:\s*/g;
        let match;
        while ((match = classNameRegex.exec(value)) !== null) {
            const startPos = match.index + match[0].length;
            const classNameValue = extractComplexValue(value, startPos);
            if (classNameValue) {
                // 如果是字符串字面量
                if (classNameValue.startsWith('"') ||
                    classNameValue.startsWith("'") ||
                    classNameValue.startsWith("`")) {
                    if (classNameValue.startsWith("`")) {
                        // 处理模板字符串
                        getDynamicClassNames(classNameValue).forEach((name) => classNames.add(name));
                    }
                    else {
                        // 处理普通字符串
                        const strMatch = classNameValue.match(/['"](.*?)['"]/);
                        if (strMatch) {
                            strMatch[1].split(/\s+/).forEach((name) => name && classNames.add(name));
                        }
                    }
                }
                else {
                    // 处理动态值(如函数调用、对象等)
                    getDynamicClassNames(classNameValue).forEach((name) => classNames.add(name));
                }
            }
        }
    }
    /**
     * 提取复杂值(支持嵌套引号和括号)
     */
    function extractComplexValue(text, startPos) {
        let pos = startPos;
        let depth = 0;
        let inString = false;
        let stringChar = "";
        let result = "";
        // 跳过开头的空白字符
        while (pos < text.length && /\s/.test(text[pos])) {
            pos++;
        }
        while (pos < text.length) {
            const char = text[pos];
            if (!inString) {
                if (char === '"' || char === "'" || char === "`") {
                    inString = true;
                    stringChar = char;
                    result += char;
                }
                else if (char === "{" || char === "(" || char === "[") {
                    depth++;
                    result += char;
                }
                else if (char === "}" || char === ")" || char === "]") {
                    if (depth === 0 && char === "}") {
                        // 遇到顶层的 } 时结束
                        break;
                    }
                    depth--;
                    result += char;
                }
                else if (char === "," && depth === 0) {
                    // 遇到顶层的逗号时结束
                    break;
                }
                else if (char === "\n" && depth === 0 && result.trim() !== "") {
                    // 如果遇到换行且不在嵌套结构中,且已有内容,则结束
                    break;
                }
                else {
                    result += char;
                }
            }
            else {
                result += char;
                if (char === stringChar && text[pos - 1] !== "\\") {
                    inString = false;
                    stringChar = "";
                    // 如果字符串结束且depth为0,检查是否应该结束
                    if (depth === 0) {
                        // 看看下一个非空白字符是什么
                        let nextPos = pos + 1;
                        while (nextPos < text.length && /\s/.test(text[nextPos])) {
                            nextPos++;
                        }
                        if (nextPos < text.length && (text[nextPos] === "," || text[nextPos] === "}")) {
                            // 如果下一个字符是逗号或右括号,则结束
                            break;
                        }
                    }
                }
            }
            pos++;
        }
        return result.trim() || null;
    }
    /**
     * 获取 class 内容
     */
    function getClassContent(code) {
        // 修改正则表达式以支持多行匹配,避免内层引号冲突
        const regex = /(?:class|:class|:pt|:hover-class)\s*=\s*(['"`])((?:[^'"`\\]|\\.|`[^`]*`|'[^']*'|"[^"]*")*?)\1/gis;
        const texts = [];
        let match;
        while ((match = regex.exec(code)) !== null) {
            const attribute = match[0].split("=")[0].trim();
            const isPtAttribute = attribute.includes("pt");
            const value = match[2];
            if (isPtAttribute) {
                // 手动解析 className 值
                const classNameRegex = /className\s*:\s*/g;
                let classNameMatchResult;
                while ((classNameMatchResult = classNameRegex.exec(value)) !== null) {
                    const startPos = classNameMatchResult.index + classNameMatchResult[0].length;
                    const classNameValue = extractComplexValue(value, startPos);
                    if (classNameValue) {
                        texts.push(classNameValue);
                    }
                }
            }
            else {
                texts.push(value);
            }
        }
        return texts;
    }
    /**
     * 获取节点
     */
    function getNodes(code) {
        const nodes = [];
        // 找到所有顶级template标签的完整内容
        function findTemplateContents(content) {
            const results = [];
            let index = 0;
            while (index < content.length) {
                const templateStart = content.indexOf("<template", index);
                if (templateStart === -1)
                    break;
                // 找到模板标签的结束位置
                const tagEnd = content.indexOf(">", templateStart);
                if (tagEnd === -1)
                    break;
                // 使用栈来匹配配对的template标签
                let stack = 1;
                let currentPos = tagEnd + 1;
                while (currentPos < content.length && stack > 0) {
                    const nextTemplateStart = content.indexOf("<template", currentPos);
                    const nextTemplateEnd = content.indexOf("</template>", currentPos);
                    if (nextTemplateEnd === -1)
                        break;
                    // 如果开始标签更近,说明有嵌套
                    if (nextTemplateStart !== -1 && nextTemplateStart < nextTemplateEnd) {
                        // 找到开始标签的完整结束
                        const nestedTagEnd = content.indexOf(">", nextTemplateStart);
                        if (nestedTagEnd !== -1) {
                            stack++;
                            currentPos = nestedTagEnd + 1;
                        }
                        else {
                            break;
                        }
                    }
                    else {
                        // 找到结束标签
                        stack--;
                        currentPos = nextTemplateEnd + 11; // '</template>'.length
                    }
                }
                if (stack === 0) {
                    // 提取template内容(不包括template标签本身)
                    const templateContent = content.substring(tagEnd + 1, currentPos - 11);
                    results.push(templateContent);
                    index = currentPos;
                }
                else {
                    // 如果没有找到匹配的结束标签,跳过这个开始标签
                    index = tagEnd + 1;
                }
            }
            return results;
        }
        // 递归提取所有template内容中的节点
        function extractNodesFromContent(content) {
            // 先提取当前内容中的所有标签
            const regex = /<([^>]+)>/g;
            let match;
            while ((match = regex.exec(content)) !== null) {
                if (!match[1].startsWith("/") && !match[1].startsWith("template")) {
                    nodes.push(match[1]);
                }
            }
            // 递归处理嵌套的template
            const nestedTemplates = findTemplateContents(content);
            nestedTemplates.forEach((templateContent) => {
                extractNodesFromContent(templateContent);
            });
        }
        // 获取所有顶级template内容
        const templateContents = findTemplateContents(code);
        // 处理每个template内容
        templateContents.forEach((templateContent) => {
            extractNodesFromContent(templateContent);
        });
        return nodes.map((e) => `<${e}>`);
    }
    /**
     * 添加 script 标签内容
     */
    function addScriptContent(code, content) {
        const scriptMatch = /<script\b[^>]*>([\s\S]*?)<\/script>/g.exec(code);
        if (!scriptMatch) {
            return code;
        }
        const scriptContent = scriptMatch[1];
        const scriptStartIndex = scriptMatch.index + scriptMatch[0].indexOf(">") + 1;
        const scriptEndIndex = scriptStartIndex + scriptContent.length;
        return (code.substring(0, scriptStartIndex) +
            "\n" +
            content +
            "\n" +
            scriptContent.trim() +
            code.substring(scriptEndIndex));
    }
    /**
     * 判断是否为 Tailwind 类名
     */
    function isTailwindClass(className) {
        const prefixes = [
            // 布局
            "container",
            "flex",
            "grid",
            "block",
            "inline",
            "hidden",
            "visible",
            // 间距
            "p-",
            "px-",
            "py-",
            "pt-",
            "pr-",
            "pb-",
            "pl-",
            "m-",
            "mx-",
            "my-",
            "mt-",
            "mr-",
            "mb-",
            "ml-",
            "space-",
            "gap-",
            // 尺寸
            "w-",
            "h-",
            "min-w-",
            "max-w-",
            "min-h-",
            "max-h-",
            // 颜色
            "bg-",
            "text-",
            "border-",
            "ring-",
            "shadow-",
            // 边框
            "border",
            "rounded",
            "ring",
            // 字体
            "font-",
            "text-",
            "leading-",
            "tracking-",
            "antialiased",
            // 定位
            "absolute",
            "relative",
            "fixed",
            "sticky",
            "static",
            "top-",
            "right-",
            "bottom-",
            "left-",
            "inset-",
            "z-",
            // 变换
            "transform",
            "translate-",
            "rotate-",
            "scale-",
            "skew-",
            // 过渡
            "transition",
            "duration-",
            "ease-",
            "delay-",
            // 交互
            "cursor-",
            "select-",
            "pointer-events-",
            // 溢出
            "overflow-",
            "truncate",
            // 滚动
            "scroll-",
            // 伪类和响应式
            "hover:",
            "focus:",
            "active:",
            "disabled:",
            "group-hover:",
        ];
        const statePrefixes = ["dark:", "dark:!", "light:", "sm:", "md:", "lg:", "xl:", "2xl:"];
        if (className.startsWith("!") && !className.includes("!=")) {
            return true;
        }
        for (const prefix of prefixes) {
            if (className.startsWith(prefix)) {
                return true;
            }
            for (const statePrefix of statePrefixes) {
                if (className.startsWith(statePrefix + prefix)) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 将 interface 转换为 type
     */
    function interfaceToType(code) {
        // 匹配 interface 定义
        const interfaceRegex = /interface\s+(\w+)(\s*extends\s+\w+)?\s*\{([^}]*)\}/g;
        // 将 interface 转换为 type
        return code.replace(interfaceRegex, (match, name, extends_, content) => {
            // 处理可能存在的 extends
            const extendsStr = extends_ ? extends_ : "";
            // 返回转换后的 type 定义
            return `type ${name}${extendsStr} = {${content}}`;
        });
    }
 
    // 全局 service 对象,用于存储服务结构
    const service = {};
    // eps 实体列表
    let list = [];
    /**
     * 获取 eps 请求地址
     * @returns {string} eps url
     */
    function getEpsUrl() {
        let url = config.eps.api;
        if (!url) {
            url = config.type;
        }
        switch (url) {
            case "app":
            case "uniapp-x":
                url = "/app/base/comm/eps";
                break;
            case "admin":
                url = "/admin/base/open/eps";
                break;
        }
        return url;
    }
    /**
     * 获取 eps 路径
     * @param filename 文件名
     * @returns {string} 完整路径
     */
    function getEpsPath(filename) {
        return path.join(config.type == "admin" ? config.eps.dist : rootDir(config.eps.dist), filename || "");
    }
    /**
     * 获取对象方法名(排除 namespace、permission 字段)
     * @param v 对象
     * @returns {string[]} 方法名数组
     */
    function getNames(v) {
        return Object.keys(v).filter((e) => !["namespace", "permission"].includes(e));
    }
    /**
     * 获取字段类型
     */
    function getType({ propertyName, type }) {
        for (const map of config.eps.mapping) {
            if (map.custom) {
                const resType = map.custom({ propertyName, type });
                if (resType)
                    return resType;
            }
            if (map.test) {
                if (map.test.includes(type))
                    return map.type;
            }
        }
        return type;
    }
    /**
     * 格式化方法名,去除特殊字符
     */
    function formatName(name) {
        return (name || "").replace(/[:,\s,\/,-]/g, "");
    }
    /**
     * 检查方法名是否合法(不包含特殊字符)
     */
    function checkName(name) {
        return name && !["{", "}", ":"].some((e) => name.includes(e));
    }
    /**
     * 不支持 uniapp-x 平台显示
     */
    function noUniappX(text, defaultText = "") {
        if (config.type == "uniapp-x") {
            return defaultText;
        }
        else {
            return text;
        }
    }
    /**
     * 查找字段
     * @param sources 字段 source 数组
     * @param item eps 实体
     * @returns {Eps.Column[]} 字段数组
     */
    function findColumns(sources, item) {
        const columns = [item.columns, item.pageColumns].flat().filter(Boolean);
        return (sources || [])
            .map((e) => columns.find((c) => c.source == e))
            .filter(Boolean);
    }
    /**
     * 使用 prettier 格式化 TypeScript 代码
     * @param text 代码文本
     * @returns {Promise<string|null>} 格式化后的代码
     */
    async function formatCode(text) {
        return prettier
            .format(text, {
            parser: "typescript",
            useTabs: true,
            tabWidth: 4,
            endOfLine: "lf",
            semi: true,
            singleQuote: false,
            printWidth: 100,
            trailingComma: "none",
        })
            .catch((err) => {
            console.log(err);
            error(`[cool-eps] File format error, please try again`);
            return null;
        });
    }
    /**
     * 获取 eps 数据(本地优先,远程兜底)
     */
    async function getData() {
        // 读取本地 eps.json
        list = readFile(getEpsPath("eps.json"), true) || [];
        // 拼接请求地址
        const url = config.reqUrl + getEpsUrl();
        // 请求远程 eps 数据
        await axios
            .get(url, {
            timeout: 5000,
        })
            .then((res) => {
            const { code, data, message } = res.data;
            if (code === 1000) {
                if (!lodash.isEmpty(data) && data) {
                    list = lodash.values(data).flat();
                }
            }
            else {
                error(`[cool-eps] ${message || "Failed to fetch data"}`);
            }
        })
            .catch(() => {
            error(`[cool-eps] API service is not running → ${url}`);
        });
        // 初始化处理,补全缺省字段
        list.forEach((e) => {
            if (!e.namespace)
                e.namespace = "";
            if (!e.api)
                e.api = [];
            if (!e.columns)
                e.columns = [];
            if (!e.search) {
                e.search = {
                    fieldEq: findColumns(e.pageQueryOp?.fieldEq, e),
                    fieldLike: findColumns(e.pageQueryOp?.fieldLike, e),
                    keyWordLikeFields: findColumns(e.pageQueryOp?.keyWordLikeFields, e),
                };
            }
        });
        if (config.type == "uniapp-x" || config.type == "app") {
            list = list.filter((e) => e.prefix.startsWith("/app") || e.prefix.startsWith("/admin"));
        }
    }
    /**
     * 创建 eps.json 文件
     * @returns {boolean} 是否有更新
     */
    function createJson() {
        let data = [];
        if (config.type != "uniapp-x") {
            data = list.map((e) => {
                return {
                    prefix: e.prefix,
                    name: e.name || "",
                    api: e.api.map((apiItem) => ({
                        name: apiItem.name,
                        method: apiItem.method,
                        path: apiItem.path,
                    })),
                    search: e.search,
                };
            });
        }
        else {
            data = list;
        }
        const content = JSON.stringify(data);
        const local_content = readFile(getEpsPath("eps.json"));
        // 判断是否需要更新
        const isUpdate = content != local_content;
        if (isUpdate) {
            fs.createWriteStream(getEpsPath("eps.json"), {
                flags: "w",
            }).write(content);
        }
        return isUpdate;
    }
    /**
     * 创建 eps 类型描述文件(d.ts/ts)
     * @param param0 list: eps实体列表, service: service对象
     */
    async function createDescribe({ list, service }) {
        /**
         * 创建 Entity 接口定义
         */
        function createEntity() {
            const ignore = [];
            let t0 = "";
            for (const item of list) {
                if (!checkName(item.name))
                    continue;
                if (formatName(item.name) == "BusinessInterface") {
                    console.log(111);
                }
                let t = `interface ${formatName(item.name)} {`;
                // 合并 columns 和 pageColumns,去重
                const columns = lodash.uniqBy(lodash.compact([...(item.columns || []), ...(item.pageColumns || [])]), "source");
                for (const col of columns || []) {
                    t += `
                    /**
                     * ${col.comment}
                     */
                    ${col.propertyName}?: ${getType({
                    propertyName: col.propertyName,
                    type: col.type,
                })};
                `;
                }
                t += `
                /**
                 * 任意键值
                 */
                [key: string]: any;
            }
            `;
                if (!ignore.includes(item.name)) {
                    ignore.push(item.name);
                    t0 += t + "\n\n";
                }
            }
            return t0;
        }
        /**
         * 创建 Controller 接口定义
         */
        async function createController() {
            let controller = "";
            let chain = "";
            let pageResponse = "";
            /**
             * 递归处理 service 树,生成接口定义
             * @param d 当前节点
             * @param k 前缀
             */
            function deep(d, k) {
                if (!k)
                    k = "";
                for (const i in d) {
                    const name = k + toCamel(firstUpperCase(formatName(i)));
                    // 检查方法名
                    if (!checkName(name))
                        continue;
                    if (d[i].namespace) {
                        // 查找配置
                        const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`);
                        if (item) {
                            //
                            let t = `interface ${name} {`;
                            // 插入方法
                            if (item.api) {
                                // 权限列表
                                const permission = [];
                                item.api.forEach((a) => {
                                    // 方法名
                                    const n = toCamel(formatName(a.name || lodash.last(a.path.split("/"))));
                                    // 检查方法名
                                    if (!checkName(n))
                                        return;
                                    if (n) {
                                        // 参数类型
                                        let q = [];
                                        // 参数列表
                                        const { parameters = [] } = a.dts || {};
                                        parameters.forEach((p) => {
                                            if (p.description) {
                                                q.push(`\n/** ${p.description}  */\n`);
                                            }
                                            // 检查参数名
                                            if (!checkName(p.name)) {
                                                return false;
                                            }
                                            const a = `${p.name}${p.required ? "" : "?"}`;
                                            const b = `${p.schema.type || "string"}`;
                                            q.push(`${a}: ${b};`);
                                        });
                                        if (lodash.isEmpty(q)) {
                                            q = ["any"];
                                        }
                                        else {
                                            q.unshift("{");
                                            q.push("}");
                                        }
                                        // 返回类型
                                        let res = "";
                                        // 实体名
                                        const en = item.name || "any";
                                        switch (a.path) {
                                            case "/page":
                                                res = `${name}PageResponse`;
                                                pageResponse += `
                                                interface ${name}PageResponse {
                                                    pagination: PagePagination;
                                                    list: ${en}[];
                                                }
                                            `;
                                                break;
                                            case "/list":
                                                res = `${en} []`;
                                                break;
                                            case "/info":
                                                res = en;
                                                break;
                                            default:
                                                res = "any";
                                                break;
                                        }
                                        // 方法描述
                                        if (config.type == "uniapp-x") {
                                            t += `
                                            /**
                                             * ${a.summary || n}
                                             */
                                            ${n}(data${q.length == 1 ? "?" : ""}: ${q.join("")}): Promise<any>;
                                        `;
                                        }
                                        else {
                                            t += `
                                            /**
                                             * ${a.summary || n}
                                             */
                                            ${n}(data${q.length == 1 ? "?" : ""}: ${q.join("")}): Promise<${res}>;
                                        `;
                                        }
                                        if (!permission.includes(n)) {
                                            permission.push(n);
                                        }
                                    }
                                });
                                // 权限标识
                                t += noUniappX(`
                                /**
                                 * 权限标识
                                 */
                                permission: { ${permission.map((e) => `${e}: string;`).join("\n")} };
                            `);
                                // 权限状态
                                t += noUniappX(`
                                /**
                                 * 权限状态
                                 */
                                _permission: { ${permission.map((e) => `${e}: boolean;`).join("\n")} };
                            `);
                                // 请求
                                t += noUniappX(`
                                request: Request;
                            `);
                            }
                            t += "}\n\n";
                            controller += t;
                            chain += `${formatName(i)}: ${name};`;
                        }
                    }
                    else {
                        chain += `${formatName(i)}: {`;
                        deep(d[i], name);
                        chain += "};";
                    }
                }
            }
            // 遍历 service 树
            deep(service);
            return `
            type json = any;
 
            ${await createDict()}
 
            interface PagePagination {
                size: number;
                page: number;
                total: number;
                [key: string]: any;
            };
 
            interface PageResponse<T> {
                pagination: PagePagination;
                list: T[];
                [key: string]: any;
            };
 
            ${pageResponse}
 
            ${controller}
 
            ${noUniappX(`interface RequestOptions {
                url: string;
                method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
                data?: any;
                params?: any;
                headers?: any;
                timeout?: number;
                [key: string]: any;
            }`)}
 
            ${noUniappX("type Request = (options: RequestOptions) => Promise<any>;")}
 
            type Service = {
                ${noUniappX("request: Request;")}
 
                ${chain}
            }
        `;
        }
        // 组装文件内容
        let text = `
        ${createEntity()}
        ${await createController()}
    `;
        // 文件名
        let name = "eps.d.ts";
        if (config.type == "uniapp-x") {
            name = "eps.ts";
            text = text
                .replaceAll("interface ", "export interface ")
                .replaceAll("type ", "export type ")
                .replaceAll("[key: string]: any;", "");
            text = flatten(text);
            text = interfaceToType(text);
        }
        else {
            text = `
            declare namespace Eps {
                ${text}
            }
        `;
        }
        // 格式化文本内容
        const content = await formatCode(text);
        const local_content = readFile(getEpsPath(name));
        // 是否需要更新
        if (content && content != local_content && list.length > 0) {
            // 创建 eps 描述文件
            fs.createWriteStream(getEpsPath(name), {
                flags: "w",
            }).write(content);
        }
    }
    /**
     * 构建 service 对象树
     */
    function createService() {
        // 路径第一层作为 id 标识
        const id = getEpsUrl().split("/")[1];
        list.forEach((e) => {
            // 请求地址
            const path = e.prefix[0] == "/" ? e.prefix.substring(1, e.prefix.length) : e.prefix;
            // 分隔路径,去除 id,转驼峰
            const arr = path.replace(id, "").split("/").filter(Boolean).map(toCamel);
            /**
             * 递归构建 service 树
             * @param d 当前节点
             * @param i 当前索引
             */
            function deep(d, i) {
                const k = arr[i];
                if (k) {
                    // 是否最后一个
                    if (arr[i + 1]) {
                        if (!d[k]) {
                            d[k] = {};
                        }
                        deep(d[k], i + 1);
                    }
                    else {
                        // 不存在则创建
                        if (!d[k]) {
                            d[k] = {
                                permission: {},
                            };
                        }
                        if (!d[k].namespace) {
                            d[k].namespace = path;
                        }
                        // 创建权限
                        if (d[k].namespace) {
                            getNames(d[k]).forEach((i) => {
                                d[k].permission[i] =
                                    `${d[k].namespace.replace(`${id}/`, "")}/${i}`.replace(/\//g, ":");
                            });
                        }
                        // 创建搜索
                        d[k].search = e.search;
                        // 创建方法
                        e.api.forEach((a) => {
                            // 方法名
                            const n = a.path.replace("/", "");
                            if (n && !/[-:]/g.test(n)) {
                                d[k][n] = a;
                            }
                        });
                    }
                }
            }
            deep(service, 0);
        });
    }
    /**
     * 创建 service 代码
     * @returns {string} service 代码
     */
    function createServiceCode() {
        const types = [];
        let chain = "";
        /**
         * 递归处理 service 树,生成接口代码
         * @param d 当前节点
         * @param k 前缀
         */
        function deep(d, k) {
            if (!k)
                k = "";
            for (const i in d) {
                if (["swagger"].includes(i)) {
                    continue;
                }
                const name = k + toCamel(firstUpperCase(formatName(i)));
                // 检查方法名
                if (!checkName(name))
                    continue;
                if (d[i].namespace) {
                    // 查找配置
                    const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`);
                    if (item) {
                        //
                        let t = `{`;
                        // 插入方法
                        if (item.api) {
                            item.api.forEach((a) => {
                                // 方法名
                                const n = toCamel(formatName(a.name || lodash.last(a.path.split("/"))));
                                // 检查方法名
                                if (!checkName(n))
                                    return;
                                if (n) {
                                    // 参数类型
                                    let q = [];
                                    // 参数列表
                                    const { parameters = [] } = a.dts || {};
                                    parameters.forEach((p) => {
                                        if (p.description) {
                                            q.push(`\n/** ${p.description}  */\n`);
                                        }
                                        // 检查参数名
                                        if (!checkName(p.name)) {
                                            return false;
                                        }
                                        const a = `${p.name}${p.required ? "" : "?"}`;
                                        const b = `${p.schema.type || "string"}`;
                                        q.push(`${a}: ${b}, `);
                                    });
                                    if (lodash.isEmpty(q)) {
                                        q = ["any"];
                                    }
                                    else {
                                        q.unshift("{");
                                        q.push("}");
                                    }
                                    if (item.name) {
                                        types.push(item.name);
                                    }
                                    // 方法描述
                                    t += `
                                    /**
                                     * ${a.summary || n}
                                     */
                                    ${n}(data?: any): Promise<any> {
                                        return request({
                                            url: "/${d[i].namespace}${a.path}",
                                            method: "${(a.method || "get").toLocaleUpperCase()}",
                                            data,
                                        });
                                    },
                                `;
                                }
                            });
                        }
                        t += `} as ${name}\n`;
                        types.push(name);
                        chain += `${formatName(i)}: ${t},\n`;
                    }
                }
                else {
                    chain += `${formatName(i)}: {`;
                    deep(d[i], name);
                    chain += `} as ${firstUpperCase(i)}Interface,`;
                    types.push(`${firstUpperCase(i)}Interface`);
                }
            }
        }
        // 遍历 service 树
        deep(service);
        return {
            content: `{ ${chain} }`,
            types,
        };
    }
    /**
     * 获取字典类型定义
     * @returns {Promise<string>} 字典类型 type 定义
     */
    async function createDict() {
        let p = "";
        switch (config.type) {
            case "app":
            case "uniapp-x":
                p = "/app";
                break;
            case "admin":
                p = "/admin";
                break;
        }
        const url = config.reqUrl + p + "/dict/info/types";
        const text = await axios
            .get(url)
            .then((res) => {
            const { code, data } = res.data;
            if (code === 1000) {
                let v = "string";
                if (!lodash.isEmpty(data)) {
                    v = data.map((e) => `"${e.key}"`).join(" | ");
                }
                return `type DictKey = ${v}`;
            }
        })
            .catch(() => {
            error(`[cool-eps] Error:${url}`);
        });
        return text || "";
    }
    /**
     * 主入口:创建 eps 相关文件和 service
     */
    async function createEps() {
        if (config.eps.enable) {
            // 获取 eps 数据
            await getData();
            // 构建 service 对象
            createService();
            const serviceCode = createServiceCode();
            // 创建 eps 目录
            createDir(getEpsPath(), true);
            // 创建 eps.json 文件
            const isUpdate = createJson();
            // 创建类型描述文件
            createDescribe({ service, list });
            return {
                service,
                serviceCode,
                list,
                isUpdate,
            };
        }
        else {
            return {
                service: {},
                list: [],
            };
        }
    }
 
    function getPlugin(name) {
        let code = readFile(rootDir(`./src/plugins/${name}/config.ts`));
        // 设置插件配置
        const set = (key, value) => {
            const regex = new RegExp(`(return\\s*{[^}]*?\\b${key}\\b\\s*:\\s*)([^,}]+)`);
            if (regex.test(code)) {
                code = code.replace(regex, `$1${JSON.stringify(value)}`);
            }
            else {
                const insertPos = code.indexOf("return {") + 8;
                code =
                    code.slice(0, insertPos) +
                        `\n  ${key}: ${JSON.stringify(value)},` +
                        code.slice(insertPos);
            }
        };
        // 保存插件配置
        const save = async () => {
            const content = await formatContent(code);
            writeFile(rootDir(`./src/plugins/${name}/config.ts`), content);
        };
        return {
            set,
            save,
        };
    }
    // 修改插件
    async function updatePlugin(options) {
        const plugin = getPlugin(options.name);
        if (options.enable !== undefined) {
            plugin.set("enable", options.enable);
        }
        await plugin.save();
    }
 
    function getPath() {
        return rootDir(`.${config.type == "admin" ? "/src" : ""}/config/proxy.ts`);
    }
    async function updateProxy(data) {
        let code = readFile(getPath());
        const regex = /const\s+value\s*=\s*['"]([^'"]+)['"]/;
        if (regex.test(code)) {
            code = code.replace(regex, `const value = '${data.name}'`);
        }
        writeFile(getPath(), code);
    }
    function getProxyTarget(proxy) {
        const code = readFile(getPath());
        const regex = /const\s+value\s*=\s*['"]([^'"]+)['"]/;
        const match = code.match(regex);
        if (match) {
            const value = match[1];
            try {
                const { target, rewrite } = proxy[`/${value}/`];
                return target + rewrite(`/${value}`);
            }
            catch (err) {
                error(`[cool-proxy] Error:${value} → ` + getPath());
                return "";
            }
        }
    }
 
    // 创建文件
    async function createFile(data) {
        const list = lodash.isArray(data) ? data : [data];
        for (const item of list) {
            const { path: path$1, code } = item;
            // 格式化内容
            const content = await formatContent(code, {
                parser: "vue",
            });
            // 目录路径
            const dir = (path$1 || "").split("/");
            // 文件名
            const fname = dir.pop();
            // 源码路径
            const srcPath = `./src/${dir.join("/")}`;
            // 创建目录
            createDir(srcPath, true);
            // 创建文件
            fs.createWriteStream(path.join(srcPath, fname), {
                flags: "w",
            }).write(content);
        }
    }
 
    function createTag(code, id) {
        if (/\.vue$/.test(id)) {
            let s;
            const str = () => s || (s = new magicString(code));
            const { descriptor } = compilerSfc.parse(code);
            if (!descriptor.script && descriptor.scriptSetup) {
                const res = compilerSfc.compileScript(descriptor, { id });
                const { name, lang } = res.attrs;
                str().appendLeft(0, `<script lang="${lang}">
                    import { defineComponent } from 'vue'
                    export default defineComponent({
                        name: "${name}"
                    })
                <\/script>`);
                return {
                    map: str().generateMap(),
                    code: str().toString(),
                };
            }
        }
        return null;
    }
 
    function base() {
        return {
            name: "vite-cool-base",
            enforce: "pre",
            configureServer(server) {
                server.middlewares.use(async (req, res, next) => {
                    function done(data) {
                        res.writeHead(200, { "Content-Type": "text/html;charset=UTF-8" });
                        res.end(JSON.stringify(data));
                    }
                    if (req.originalUrl?.includes("__cool")) {
                        const body = await parseJson(req);
                        switch (req.url) {
                            // 创建文件
                            case "/__cool_createFile":
                                await createFile(body);
                                break;
                            // 创建 eps 文件
                            case "/__cool_eps":
                                await createEps();
                                break;
                            // 更新插件
                            case "/__cool_updatePlugin":
                                await updatePlugin(body);
                                break;
                            // 设置代理
                            case "/__cool_updateProxy":
                                await updateProxy(body);
                                break;
                            default:
                                return done({
                                    code: 1001,
                                    message: "Unknown request",
                                });
                        }
                        done({
                            code: 1000,
                        });
                    }
                    else {
                        next();
                    }
                });
            },
            transform(code, id) {
                if (config.nameTag) {
                    return createTag(code, id);
                }
                return code;
            },
        };
    }
 
    function demo(enable) {
        const virtualModuleIds = ["virtual:demo"];
        return {
            name: "vite-cool-demo",
            enforce: "pre",
            resolveId(id) {
                if (virtualModuleIds.includes(id)) {
                    return "\0" + id;
                }
            },
            async load(id) {
                if (id === "\0virtual:demo") {
                    const demo = {};
                    if (enable) {
                        const files = await glob.glob(rootDir("./src/modules/demo/views/crud/components") + "/**", {
                            stat: true,
                            withFileTypes: true,
                        });
                        for (const file of files) {
                            if (file.isFile()) {
                                const p = path.join(file.path, file.name);
                                demo[p
                                    .replace(/\\/g, "/")
                                    .split("src/modules/demo/views/crud/components/")[1]] = fs.readFileSync(p, "utf-8");
                            }
                        }
                    }
                    return `
                    export const demo = ${JSON.stringify(demo)};
                `;
                }
            },
        };
    }
 
    async function createCtx() {
        let ctx = {
            serviceLang: "Node",
        };
        if (config.type == "app" || config.type == "uniapp-x") {
            const manifest = readFile(rootDir("manifest.json"), true);
            // 文件路径
            const ctxPath = rootDir("pages.json");
            // 页面配置
            ctx = readFile(ctxPath, true);
            // 原数据,做更新比较用
            const ctxData = lodash.cloneDeep(ctx);
            // 删除临时页面
            ctx.pages = ctx.pages?.filter((e) => !e.isTemp);
            ctx.subPackages = ctx.subPackages?.filter((e) => !e.isTemp);
            // 删除不需要的数据
            for (const i in ctx) {
                if (!["pages", "subPackages", "tabBar", "globalStyle", "uniIdRouter"].includes(i)) {
                    delete ctx[i];
                }
            }
            // 加载 uni_modules 配置文件
            const files = await glob.glob(rootDir("uni_modules") + "/**/pages_init.json", {
                stat: true,
                withFileTypes: true,
            });
            for (const file of files) {
                if (file.isFile()) {
                    const { pages = [], subPackages = [] } = readFile(path.join(file.path, file.name), true);
                    // 合并到 pages 中
                    [...pages, ...subPackages].forEach((e) => {
                        e.isTemp = true;
                        const isSub = !!e.root;
                        const d = isSub
                            ? ctx.subPackages?.find((a) => a.root == e.root)
                            : ctx.pages?.find((a) => a.path == e.path);
                        if (d) {
                            lodash.assign(d, e);
                        }
                        else {
                            if (isSub) {
                                ctx.subPackages?.unshift(e);
                            }
                            else {
                                ctx.pages?.unshift(e);
                            }
                        }
                    });
                }
            }
            // 排序后检测,避免加载顺序问题
            function order(d) {
                return {
                    pages: lodash.orderBy(d.pages, "path"),
                    subPackages: lodash.orderBy(d.subPackages, "root"),
                };
            }
            // 是否需要更新 pages.json
            if (!util.isDeepStrictEqual(order(ctxData), order(ctx))) {
                console.log("[cool-ctx] pages updated");
                writeFile(ctxPath, JSON.stringify(ctx, null, 4));
            }
            // appid
            ctx.appid = manifest.appid;
        }
        if (config.type == "admin") {
            const list = fs.readdirSync(rootDir("./src/modules"));
            ctx.modules = list.filter((e) => !e.includes("."));
            await axios
                .get(config.reqUrl + "/admin/base/comm/program", {
                timeout: 5000,
            })
                .then((res) => {
                const { code, data, message } = res.data;
                if (code === 1000) {
                    ctx.serviceLang = data || "Node";
                }
                else {
                    error(`[cool-ctx] ${message}`);
                }
            })
                .catch((err) => {
                // console.error(['[cool-ctx] ', err.message])
            });
        }
        return ctx;
    }
 
    let svgIcons = [];
    function findSvg(dir) {
        const arr = [];
        const dirs = fs.readdirSync(dir, {
            withFileTypes: true,
        });
        // 获取当前目录的模块名
        const moduleName = dir.match(/[/\\](?:src[/\\](?:plugins|modules)[/\\])([^/\\]+)/)?.[1] || "";
        for (const d of dirs) {
            if (d.isDirectory()) {
                arr.push(...findSvg(dir + d.name + "/"));
            }
            else {
                if (path.extname(d.name) == ".svg") {
                    const baseName = path.basename(d.name, ".svg");
                    // 判断是否需要跳过拼接模块名
                    let shouldSkip = config.svg.skipNames?.includes(moduleName);
                    // 跳过包含icon-
                    if (baseName.includes("icon-")) {
                        shouldSkip = true;
                    }
                    const iconName = shouldSkip ? baseName : `${moduleName}-${baseName}`;
                    svgIcons.push(iconName);
                    const svg = fs.readFileSync(dir + d.name)
                        .toString()
                        .replace(/(\r)|(\n)/g, "")
                        .replace(/<svg([^>+].*?)>/, (_, $2) => {
                        let width = 0;
                        let height = 0;
                        let content = $2.replace(/(width|height)="([^>+].*?)"/g, (_, s2, s3) => {
                            if (s2 === "width") {
                                width = s3;
                            }
                            else if (s2 === "height") {
                                height = s3;
                            }
                            return "";
                        });
                        if (!/(viewBox="[^>+].*?")/g.test($2)) {
                            content += `viewBox="0 0 ${width} ${height}"`;
                        }
                        return `<symbol id="icon-${iconName}" ${content}>`;
                    })
                        .replace("</svg>", "</symbol>");
                    arr.push(svg);
                }
            }
        }
        return arr;
    }
    function compilerSvg() {
        svgIcons = [];
        return findSvg(rootDir("./src/"))
            .map((e) => {
            return svgo.optimize(e)?.data || e;
        })
            .join("");
    }
    async function createSvg() {
        const html = compilerSvg();
        const code = `
if (typeof window !== 'undefined') {
    function loadSvg() {
        const svgDom = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svgDom.style.position = 'absolute';
        svgDom.style.width = '0';
        svgDom.style.height = '0';
        svgDom.setAttribute('xmlns','http://www.w3.org/2000/svg');
        svgDom.setAttribute('xmlns:link','http://www.w3.org/1999/xlink');
        svgDom.innerHTML = '${html}';
        document.body.insertBefore(svgDom, document.body.firstChild);
    }
 
    loadSvg();
}
        `;
        return { code, svgIcons };
    }
 
    async function virtual() {
        const virtualModuleIds = [
            "virtual:eps",
            "virtual:ctx",
            "virtual:svg-register",
            "virtual:svg-icons",
        ];
        createEps();
        return {
            name: "vite-cool-virtual",
            enforce: "pre",
            configureServer(server) {
                server.middlewares.use(async (req, res, next) => {
                    // 页面刷新时触发
                    if (req.url == "/@vite/client") {
                        // 重新加载虚拟模块
                        virtualModuleIds.forEach((vm) => {
                            const mod = server.moduleGraph.getModuleById(`\0${vm}`);
                            if (mod) {
                                server.moduleGraph.invalidateModule(mod);
                            }
                        });
                    }
                    next();
                });
            },
            handleHotUpdate({ file, server }) {
                // 文件修改时触发
                if (!["pages.json", "dist", "build/cool", "eps.json", "eps.d.ts"].some((e) => file.includes(e))) {
                    createCtx();
                    createEps().then((data) => {
                        if (data.isUpdate) {
                            // 通知客户端刷新
                            (server.hot || server.ws).send({
                                type: "custom",
                                event: "eps-update",
                                data,
                            });
                        }
                    });
                }
            },
            resolveId(id) {
                if (virtualModuleIds.includes(id)) {
                    return "\0" + id;
                }
            },
            async load(id) {
                if (id === "\0virtual:eps") {
                    const eps = await createEps();
                    return `
                    export const eps = ${JSON.stringify(eps)}
                `;
                }
                if (id === "\0virtual:ctx") {
                    const ctx = await createCtx();
                    return `
                    export const ctx = ${JSON.stringify(ctx)}
                `;
                }
                if (id == "\0virtual:svg-register") {
                    const { code } = await createSvg();
                    return code;
                }
                if (id == "\0virtual:svg-icons") {
                    const { svgIcons } = await createSvg();
                    return `
                    export const svgIcons = ${JSON.stringify(svgIcons)}
                `;
                }
            },
        };
    }
 
    /**
     * 特殊字符映射表
     */
    const SAFE_CHAR_MAP = {
        "[": "-bracket-start-",
        "]": "-bracket-end-",
        "(": "-paren-start-",
        ")": "-paren-end-",
        "{": "-brace-start-",
        "}": "-brace-end-",
        $: "-dollar-",
        "#": "-hash-",
        "!": "-important-",
        "/": "-slash-",
        ":": "-colon-",
    };
    /**
     * 特殊字符映射表(国际化)
     */
    const SAFE_CHAR_MAP_LOCALE = {
        "[": "-bracket-start-",
        "]": "-bracket-end-",
        "(": "-paren-start-",
        ")": "-paren-end-",
        "{": "-brace-start-",
        "}": "-brace-end-",
        $: "-dollar-",
        "#": "-hash-",
        "!": "-important-",
        "/": "-slash-",
        ":": "-colon-",
        " ": "-space-",
        "<": "-lt-",
        ">": "-gt-",
        "&": "-amp-",
        "|": "-pipe-",
        "^": "-caret-",
        "~": "-tilde-",
        "`": "-backtick-",
        "'": "-single-quote-",
        ".": "-dot-",
        "?": "-question-",
        "*": "-star-",
        "+": "-plus-",
        "-": "-dash-",
        _: "-underscore-",
        "=": "-equal-",
        "%": "-percent-",
        "@": "-at-",
    };
 
    // @ts-ignore
    /**
     * 转换类名中的特殊字符为安全字符
     */
    function toSafeClass(className) {
        if (config.utsPlatform == "web") {
            return className;
        }
        if (className.includes(":host")) {
            return className;
        }
        // 如果是表达式,则不进行转换
        if (["!=", "!==", "?", ":", "="].includes(className)) {
            return className;
        }
        let safeClassName = className;
        // 移除转义字符
        if (safeClassName.includes("\\")) {
            safeClassName = safeClassName.replace(/\\/g, "");
        }
        // 处理暗黑模式
        if (safeClassName.includes(":is")) {
            if (safeClassName.includes(":is(.dark *)")) {
                safeClassName = safeClassName.replace(/:is\(.dark \*\)/g, "");
                if (safeClassName.startsWith(".dark:")) {
                    const className = safeClassName.replace(/^\.dark:/, ".dark:");
                    safeClassName = `${className}`;
                }
            }
        }
        // 替换特殊字符
        for (const [char, replacement] of Object.entries(SAFE_CHAR_MAP)) {
            const regex = new RegExp("\\" + char, "g");
            if (regex.test(safeClassName)) {
                safeClassName = safeClassName.replace(regex, replacement);
            }
        }
        return safeClassName;
    }
    /**
     * 转换 RGB 为 RGBA 格式
     */
    function rgbToRgba(rgbValue) {
        const match = rgbValue.match(/rgb\(([\d\s]+)\/\s*([\d.]+)\)/);
        if (!match)
            return rgbValue;
        const [, rgb, alpha] = match;
        const [r, g, b] = rgb.split(/\s+/);
        return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    }
    function remToRpx(remValue) {
        const { remUnit = 14, remPrecision = 6, rpxRatio = 2 } = config.tailwind;
        const conversionFactor = remUnit * rpxRatio;
        const precision = (remValue.split(".")[1] || "").length;
        const rpxValue = (parseFloat(remValue) * conversionFactor)
            .toFixed(precision || remPrecision)
            .replace(/\.?0+$/, "");
        return `${rpxValue}rpx`;
    }
    /**
     * PostCSS 插件
     * 处理类名和单位转换
     */
    function postcssPlugin() {
        return {
            name: "vite-cool-uniappx-postcss",
            enforce: "pre",
            config() {
                return {
                    css: {
                        postcss: {
                            plugins: [
                                {
                                    postcssPlugin: "vite-cool-uniappx-class-mapping",
                                    prepare() {
                                        return {
                                            // 处理选择器规则
                                            Rule(rule) {
                                                if ([
                                                    ".button-hover",
                                                    ":deep(",
                                                    "&::",
                                                    "uni-",
                                                    ".uni-",
                                                ].some((e) => rule.selector.includes(e))) {
                                                    return;
                                                }
                                                // 转换选择器为安全的类名格式
                                                rule.selector = toSafeClass(rule.selector);
                                            },
                                            // 处理声明规则
                                            Declaration(decl) {
                                                const className = decl.parent.selector || "";
                                                if (!decl.parent._twValues) {
                                                    decl.parent._twValues = {};
                                                }
                                                // 处理 Tailwind 自定义属性
                                                if (decl.prop.includes("--tw-")) {
                                                    decl.parent._twValues[decl.prop] =
                                                        decl.value.includes("rem")
                                                            ? remToRpx(decl.value)
                                                            : decl.value;
                                                    decl.remove();
                                                    return;
                                                }
                                                // 转换 RGB 颜色为 RGBA 格式
                                                if (decl.value.includes("rgb(") &&
                                                    decl.value.includes("/")) {
                                                    decl.value = rgbToRgba(decl.value);
                                                }
                                                // 处理文本大小相关样式
                                                if (decl.value.includes("rpx") &&
                                                    decl.prop == "color" &&
                                                    className.includes("text-")) {
                                                    decl.prop = "font-size";
                                                }
                                                // 删除不支持的属性
                                                if (["filter"].includes(decl.prop)) {
                                                    decl.remove();
                                                    return;
                                                }
                                                // 处理 flex-1
                                                if (decl.prop == "flex") {
                                                    if (decl.value.startsWith("1")) {
                                                        decl.value = "1";
                                                    }
                                                }
                                                // 处理 vertical-align 属性
                                                if (decl.prop == "vertical-align") {
                                                    decl.remove();
                                                }
                                                // 处理 visibility 属性
                                                if (decl.prop == "visibility") {
                                                    decl.remove();
                                                }
                                                // 处理 sticky 属性
                                                if (className == ".sticky") {
                                                    if (decl.prop == "position" ||
                                                        decl.value == "sticky") {
                                                        decl.remove();
                                                    }
                                                }
                                                // 解析声明值
                                                const parsed = valueParser(decl.value);
                                                let hasChanges = false;
                                                // 遍历并处理声明值中的节点
                                                parsed.walk((node) => {
                                                    // 处理单位转换(rem -> rpx)
                                                    if (node.type === "word") {
                                                        const unit = valueParser.unit(node.value);
                                                        if (typeof unit != "boolean") {
                                                            if (unit?.unit === "rem") {
                                                                node.value = remToRpx(unit.number);
                                                                hasChanges = true;
                                                            }
                                                        }
                                                    }
                                                    // 处理 CSS 变量
                                                    if (node.type === "function" &&
                                                        node.value === "var") {
                                                        const twKey = node.nodes[0]?.value;
                                                        // 替换 Tailwind 变量为实际值
                                                        if (twKey?.startsWith("--tw-")) {
                                                            if (decl.parent._twValues) {
                                                                node.type = "word";
                                                                node.value =
                                                                    decl.parent._twValues[twKey] ||
                                                                        "none";
                                                                hasChanges = true;
                                                            }
                                                        }
                                                    }
                                                });
                                                // 更新声明值
                                                if (hasChanges) {
                                                    decl.value = parsed.toString();
                                                }
                                                // 移除 Tailwind 生成的无效 none 变换
                                                const nones = [
                                                    "translate(none, none)",
                                                    "rotate(none)",
                                                    "skewX(none)",
                                                    "skewY(none)",
                                                    "scaleX(none)",
                                                    "scaleY(none)",
                                                ];
                                                if (decl.value) {
                                                    nones.forEach((noneStr) => {
                                                        decl.value = decl.value.replace(noneStr, "");
                                                        if (!decl.value || !decl.value.trim()) {
                                                            decl.value = "none";
                                                        }
                                                    });
                                                }
                                            },
                                        };
                                    },
                                },
                            ],
                        },
                    },
                };
            },
        };
    }
    /**
     * uvue class 转换插件
     */
    function transformPlugin() {
        return {
            name: "vite-cool-uniappx-transform",
            enforce: "pre",
            async transform(code, id) {
                const { darkTextClass } = config.tailwind;
                // 判断是否为 uvue 文件
                if (id.endsWith(".uvue") || id.includes(".uvue?type=page")) {
                    // 避免影响到其他模块/插件
                    if (id.includes("uni_modules/") && !id.includes("uni_modules/cool-")) {
                        return null;
                    }
                    let modifiedCode = code;
                    // 获取所有节点
                    const nodes = getNodes(code);
                    // 遍历处理每个节点
                    nodes.forEach((node) => {
                        if (node.startsWith("<!--")) {
                            return;
                        }
                        let _node = node;
                        // uniappx 插件模式
                        if (!config.uniapp.isPlugin) {
                            // 为 text 节点添加暗黑模式文本颜色
                            if (!_node.includes(darkTextClass) && _node.startsWith("<text")) {
                                let classIndex = _node.indexOf("class=");
                                // 处理动态 class
                                if (classIndex >= 0) {
                                    if (_node[classIndex - 1] == ":") {
                                        classIndex = _node.lastIndexOf("class=");
                                    }
                                }
                                // 添加暗黑模式类名
                                if (classIndex >= 0) {
                                    _node =
                                        _node.substring(0, classIndex + 7) +
                                            `${darkTextClass} ` +
                                            _node.substring(classIndex + 7, _node.length);
                                }
                                else {
                                    _node =
                                        _node.substring(0, 5) +
                                            ` class="${darkTextClass}" ` +
                                            _node.substring(5, _node.length);
                                }
                            }
                        }
                        // 获取所有类名
                        const classNames = getClassNames(_node);
                        // 转换 Tailwind 类名为安全类名
                        classNames.forEach((name, index) => {
                            if (isTailwindClass(name)) {
                                const safeName = toSafeClass(name);
                                _node = _node.replaceAll(name, safeName);
                                classNames[index] = safeName;
                            }
                        });
                        // 检查是否存在动态类名
                        const hasDynamicClass = _node.includes(":class=");
                        // 如果没有动态类名,添加空的动态类名绑定
                        if (!hasDynamicClass) {
                            // 优化写法,避免重复字符串拼接
                            const insertIndex = _node.length - (_node.endsWith("/>") ? 2 : 1);
                            _node =
                                _node.slice(0, insertIndex) + ` :class="{}"` + _node.slice(insertIndex);
                        }
                        // 获取暗黑模式类名
                        let darkClassNames = classNames.filter((name) => name.startsWith("dark-colon-") || name.startsWith("dark:"));
                        // 插件模式,不支持 dark:
                        if (config.uniapp.isPlugin) {
                            darkClassNames = [];
                        }
                        // 生成暗黑模式类名的动态绑定
                        const darkClassContent = darkClassNames
                            .map((name) => {
                            _node = _node.replaceAll(name, "");
                            return `'${name}': __isDark`;
                        })
                            .join(",");
                        // 获取所有 class 内容
                        const classContents = getClassContent(_node);
                        // 处理对象形式的动态类名
                        const dynamicClassContent_1 = classContents.find((content) => content.startsWith("{") && content.endsWith("}"));
                        if (dynamicClassContent_1) {
                            const v = dynamicClassContent_1[0] +
                                (darkClassContent ? `${darkClassContent},` : "") +
                                dynamicClassContent_1.substring(1);
                            _node = _node.replaceAll(dynamicClassContent_1, v);
                        }
                        // 处理数组形式的动态类名
                        const dynamicClassContent_2 = classContents.find((content) => content.startsWith("[") && content.endsWith("]"));
                        if (dynamicClassContent_2) {
                            const v = dynamicClassContent_2[0] +
                                `{${darkClassContent}},` +
                                dynamicClassContent_2.substring(1);
                            _node = _node.replaceAll(dynamicClassContent_2, v);
                        }
                        // 更新节点内容
                        modifiedCode = modifiedCode.replace(node, _node);
                    });
                    // 如果代码有修改
                    if (modifiedCode !== code) {
                        // 添加暗黑模式依赖
                        if (modifiedCode.includes("__isDark")) {
                            if (!modifiedCode.includes("<script")) {
                                modifiedCode += '<script lang="ts" setup></script>';
                            }
                            if (!config.uniapp.isPlugin) {
                                modifiedCode = addScriptContent(modifiedCode, "\nimport { isDark as __isDark } from '@/cool';");
                            }
                        }
                        // 清理空的类名绑定
                        modifiedCode = modifiedCode
                            .replaceAll(':class="{}"', "")
                            .replaceAll('class=""', "")
                            .replaceAll('class=" "', "");
                        return {
                            code: modifiedCode,
                            map: { mappings: "" },
                        };
                    }
                    return null;
                }
                else {
                    return null;
                }
            },
        };
    }
    /**
     * Tailwind 类名转换插件
     */
    function tailwindPlugin() {
        return [postcssPlugin(), transformPlugin()];
    }
 
    // 获取 tailwind.config.ts 中的颜色
    function getTailwindColor() {
        const config = readFile(rootDir("tailwind.config.ts"));
        if (!config) {
            return null;
        }
        try {
            // 从配置文件中动态提取主色和表面色
            const colorResult = {};
            // 提取 getPrimary 调用中的颜色名称
            const primaryMatch = config.match(/getPrimary\(["']([^"']+)["']\)/);
            const primaryColorName = primaryMatch?.[1];
            // 提取 getSurface 调用中的颜色名称
            const surfaceMatch = config.match(/getSurface\(["']([^"']+)["']\)/);
            const surfaceColorName = surfaceMatch?.[1];
            if (primaryColorName) {
                // 提取 PRIMARY_COLOR_PALETTES 中对应的调色板
                const primaryPaletteMatch = config.match(new RegExp(`{\\s*name:\\s*["']${primaryColorName}["'],\\s*palette:\\s*({[^}]+})`, "s"));
                if (primaryPaletteMatch) {
                    // 解析调色板对象
                    const paletteStr = primaryPaletteMatch[1];
                    const paletteEntries = paletteStr.match(/(\d+):\s*["']([^"']+)["']/g);
                    if (paletteEntries) {
                        paletteEntries.forEach((entry) => {
                            const match = entry.match(/(\d+):\s*["']([^"']+)["']/);
                            if (match) {
                                const [, key, value] = match;
                                colorResult[`primary-${key}`] = value;
                            }
                        });
                    }
                }
            }
            if (surfaceColorName) {
                // 提取 SURFACE_PALETTES 中对应的调色板
                const surfacePaletteMatch = config.match(new RegExp(`{\\s*name:\\s*["']${surfaceColorName}["'],\\s*palette:\\s*({[^}]+})`, "s"));
                if (surfacePaletteMatch) {
                    // 解析调色板对象
                    const paletteStr = surfacePaletteMatch[1];
                    const paletteEntries = paletteStr.match(/(\d+):\s*["']([^"']+)["']/g);
                    if (paletteEntries) {
                        paletteEntries.forEach((entry) => {
                            const match = entry.match(/(\d+):\s*["']([^"']+)["']/);
                            if (match) {
                                const [, key, value] = match;
                                // 0 对应 surface,其他对应 surface-*
                                const colorKey = key === "0" ? "surface" : `surface-${key}`;
                                colorResult[colorKey] = value;
                            }
                        });
                    }
                }
            }
            return colorResult;
        }
        catch (error) {
            return null;
        }
    }
    function codePlugin() {
        return [
            {
                name: "vite-cool-uniappx-code-pre",
                enforce: "pre",
                async transform(code, id) {
                    if (id.includes("/cool/ctx/index.ts")) {
                        const ctx = await createCtx();
                        // 主题配置
                        const theme = readFile(rootDir("theme.json"), true);
                        // 主题配置
                        ctx["theme"] = theme || {};
                        // 颜色值
                        ctx["color"] = getTailwindColor();
                        if (!ctx.subPackages) {
                            ctx.subPackages = [];
                        }
                        if (!ctx.tabBar) {
                            ctx.tabBar = {};
                        }
                        if (!ctx.uniIdRouter) {
                            ctx.uniIdRouter = {};
                        }
                        // 安全字符映射
                        ctx["SAFE_CHAR_MAP_LOCALE"] = [];
                        for (const i in SAFE_CHAR_MAP_LOCALE) {
                            ctx["SAFE_CHAR_MAP_LOCALE"].push([i, SAFE_CHAR_MAP_LOCALE[i]]);
                        }
                        let ctxCode = JSON.stringify(ctx, null, 4);
                        ctxCode = ctxCode.replace(`"tabBar": {}`, `"tabBar": {} as TabBar`);
                        ctxCode = ctxCode.replace(`"subPackages": []`, `"subPackages": [] as SubPackage[]`);
                        code = code.replace("const ctx = {}", `const ctx = ${ctxCode}`);
                        code = code.replace("const ctx = parse<Ctx>({})!", `const ctx = parse<Ctx>(${ctxCode})!`);
                    }
                    // if (id.includes("/cool/service/index.ts")) {
                    //     const eps = await createEps();
                    //     if (eps.serviceCode) {
                    //         const { content, types } = eps.serviceCode;
                    //         const typeCode = `import type { ${uniq(types).join(", ")} } from '../types';`;
                    //         code =
                    //             typeCode +
                    //             "\n\n" +
                    //             code.replace("const service = {}", `const service = ${content}`);
                    //     }
                    // }
                    if (id.endsWith(".json")) {
                        const d = JSON.parse(code);
                        for (let i in d) {
                            let k = i;
                            for (let j in SAFE_CHAR_MAP_LOCALE) {
                                k = k.replaceAll(j, SAFE_CHAR_MAP_LOCALE[j]);
                            }
                            if (k != i) {
                                d[k] = d[i];
                                delete d[i];
                            }
                        }
                        // 转字符串,不然会报错:Method too large
                        if (id.includes("/locale/")) {
                            let t = [];
                            d.forEach(([a, b]) => {
                                t.push(`${a}<__=__>${b}`);
                            });
                            code = JSON.stringify([[t.join("<__&__>")]]);
                        }
                        else {
                            code = JSON.stringify(d);
                        }
                    }
                    return {
                        code,
                        map: { mappings: "" },
                    };
                },
            },
            {
                name: "vite-cool-uniappx-code",
                transform(code, id) {
                    if (id.endsWith(".json")) {
                        return {
                            code: code.replace("new UTSJSONObject", ""),
                            map: { mappings: "" },
                        };
                    }
                },
            },
        ];
    }
 
    /**
     * uniappX 入口,自动注入 Tailwind 类名转换插件
     * @param options 配置项
     * @returns Vite 插件数组
     */
    async function uniappX() {
        const plugins = [];
        if (config.type == "uniapp-x") {
            plugins.push(...codePlugin());
            if (config.tailwind.enable) {
                plugins.push(...tailwindPlugin());
            }
        }
        return plugins;
    }
 
    function cool(options) {
        // 应用类型,admin | app
        config.type = options.type;
        // 请求地址
        config.reqUrl = getProxyTarget(options.proxy);
        if (config.type == "uniapp-x") {
            // 编译平台
            config.utsPlatform = process.env.UNI_UTS_PLATFORM ?? "web";
            // 是否纯净版
            config.clean = options.clean ?? true;
            if (config.clean) {
                // 默认设置为测试地址
                config.reqUrl = "https://show.cool-admin.com/api";
            }
        }
        // 是否开启名称标签
        config.nameTag = options.nameTag ?? true;
        // svg
        if (options.svg) {
            lodash.assign(config.svg, options.svg);
        }
        // Eps
        if (options.eps) {
            const { dist, mapping, api, enable = true } = options.eps;
            // 是否开启
            config.eps.enable = enable;
            // 类型
            if (api) {
                config.eps.api = api;
            }
            // 输出目录
            if (dist) {
                config.eps.dist = dist;
            }
            // 匹配规则
            if (mapping) {
                lodash.merge(config.eps.mapping, mapping);
            }
        }
        // 如果类型为 uniapp-x,则关闭 eps
        if (config.type == "uniapp-x") {
            config.eps.enable = false;
        }
        // uniapp
        if (options.uniapp) {
            lodash.assign(config.uniapp, options.uniapp);
        }
        // tailwind
        if (options.tailwind) {
            lodash.assign(config.tailwind, options.tailwind);
        }
        return [base(), virtual(), uniappX(), demo(options.demo)];
    }
 
    exports.cool = cool;
 
}));