@voidzero-dev/vite-plus-core 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +31 -7
  2. package/dist/rolldown/cli.d.mts +1 -1
  3. package/dist/rolldown/cli.mjs +6 -6
  4. package/dist/rolldown/config.d.mts +16 -17
  5. package/dist/rolldown/config.mjs +2 -2
  6. package/dist/rolldown/experimental-index.d.mts +164 -155
  7. package/dist/rolldown/experimental-index.mjs +23 -14
  8. package/dist/rolldown/experimental-runtime-types.d.ts +111 -41
  9. package/dist/rolldown/filter-index.d.mts +6 -5
  10. package/dist/rolldown/get-log-filter.d.mts +2 -2
  11. package/dist/rolldown/index.d.mts +3 -3
  12. package/dist/rolldown/index.mjs +4 -4
  13. package/dist/rolldown/parallel-plugin-worker.d.mts +1 -1
  14. package/dist/rolldown/parallel-plugin-worker.mjs +2 -2
  15. package/dist/rolldown/parallel-plugin.d.mts +3 -4
  16. package/dist/rolldown/parse-ast-index.d.mts +19 -20
  17. package/dist/rolldown/parse-ast-index.mjs +1 -1
  18. package/dist/rolldown/plugins-index.d.mts +27 -28
  19. package/dist/rolldown/plugins-index.mjs +2 -2
  20. package/dist/rolldown/shared/{binding-D26QphWG.d.mts → binding-Dbbi0RbO.d.mts} +37 -25
  21. package/dist/rolldown/shared/{binding-TuFFIE_J.mjs → binding-Dby9rwGk.mjs} +26 -26
  22. package/dist/rolldown/shared/{bindingify-input-options-CwbcQL6W.mjs → bindingify-input-options-DVQ4K-zY.mjs} +5 -5
  23. package/dist/rolldown/shared/{constructors-BbWPse2X.d.mts → constructors-CSWbNgBZ.d.mts} +9 -10
  24. package/dist/rolldown/shared/{constructors-D_3i7dpX.mjs → constructors-CuGa75s-.mjs} +1 -1
  25. package/dist/rolldown/shared/define-config-B-IDOhDz.d.mts +4003 -0
  26. package/dist/rolldown/shared/{error-BHRSI0R7.mjs → error-DFGNOCle.mjs} +1 -1
  27. package/dist/rolldown/shared/get-log-filter-AjBknEEO.d.mts +34 -0
  28. package/dist/rolldown/shared/{load-config-Bd7MgqCK.mjs → load-config-R0z2olkB.mjs} +1 -1
  29. package/dist/rolldown/shared/{logging-BSNejiLS.d.mts → logging-xuHO4mAy.d.mts} +6 -6
  30. package/dist/rolldown/shared/{normalize-string-or-regex-dnh67V_w.mjs → normalize-string-or-regex-SiXbePVH.mjs} +1 -1
  31. package/dist/rolldown/shared/{parse-B6_waszz.mjs → parse-D5dkElpf.mjs} +2 -2
  32. package/dist/rolldown/shared/{resolve-tsconfig-DxqIJB3x.mjs → resolve-tsconfig-2TXRF_zr.mjs} +2 -2
  33. package/dist/rolldown/shared/{rolldown-CACDGVWV.mjs → rolldown-BnV7isAX.mjs} +1 -1
  34. package/dist/rolldown/shared/{rolldown-build-BV22mk7t.mjs → rolldown-build-BGXNOfvH.mjs} +4 -4
  35. package/dist/rolldown/shared/transform-Cs2bUDRH.d.mts +148 -0
  36. package/dist/rolldown/shared/{watch-CS_JygCu.mjs → watch-DVucf-VG.mjs} +4 -4
  37. package/dist/rolldown/utils-index.d.mts +29 -30
  38. package/dist/rolldown/utils-index.mjs +6 -8
  39. package/dist/tsdown/{build-BlM3pDGJ-C8Uovnt4.js → build-D_enfyvD-DX5mX46j.js} +149 -1255
  40. package/dist/tsdown/debug-CKcBYQLP-GQrJ--dM.js +159 -0
  41. package/dist/tsdown/{detect-BNXt7gkp-DKAC9Z7n.js → detect-DGhJGEqb-Cz6qOZuP.js} +7 -1
  42. package/dist/tsdown/{dist-Pjag7IPt.js → dist-CWolxbYK.js} +1939 -2529
  43. package/dist/tsdown/dist-DCMiHFrJ.js +1061 -0
  44. package/dist/tsdown/index-types.d.ts +740 -554
  45. package/dist/tsdown/index.js +4 -4
  46. package/dist/tsdown/internal-DAh_SWnB.js +3 -0
  47. package/dist/tsdown/load-tsc-BKULZsrs-Bha6Vsu1.js +18 -0
  48. package/dist/tsdown/{main-BlTcyuFi.js → main-DI8qthUB.js} +222 -9
  49. package/dist/tsdown/{resolver-DtsKFXi2-B8Z3WwZh.js → resolver-cwLsPb2o-DvUqSYux.js} +4 -3
  50. package/dist/tsdown/run.js +5 -5
  51. package/dist/tsdown/{src-CK50m8R_.js → src-CPDzmpAq.js} +5 -5
  52. package/dist/tsdown/target-Bab3CUeB-Di6tCARH.js +582 -0
  53. package/dist/tsdown/{tsc-CilQvmj4.js → tsc-BQoNcjeB.js} +49 -116
  54. package/dist/tsdown/tsc-context-BhMGQ9Qr.js +23 -0
  55. package/dist/tsdown/tsdown-css.js +11 -12
  56. package/dist/tsdown/tsdown-exe.js +129 -877
  57. package/dist/vite/client/client.mjs +5 -5
  58. package/dist/vite/node/chunks/build.js +19 -19
  59. package/dist/vite/node/chunks/moduleRunnerTransport.d.ts +25 -26
  60. package/dist/vite/node/chunks/node.js +73 -38
  61. package/dist/vite/node/chunks/postcss-import.js +10 -10
  62. package/dist/vite/node/index.d.ts +1282 -1283
  63. package/dist/vite/node/module-runner.d.ts +76 -77
  64. package/dist/vite/node/module-runner.js +6 -7
  65. package/package.json +16 -16
  66. package/dist/rolldown/shared/define-config-BhJ90aEv.d.mts +0 -3978
  67. package/dist/rolldown/shared/get-log-filter-BpNVNJ5-.d.mts +0 -35
  68. package/dist/rolldown/shared/transform-BPrUvqEZ.d.mts +0 -149
  69. package/dist/tsdown/debug-B1wUEHkd-DhRzGJTf.js +0 -265
  70. package/dist/tsdown/fs-qxJxxoCE-B_amenYz.js +0 -46
  71. package/dist/tsdown/general-Cp4NiJNK-xAqmPhMP.js +0 -97
  72. package/dist/tsdown/internal-Bn6NGoha.js +0 -3
  73. package/dist/tsdown/npm_cjs_chunk_range.cjs +0 -475
  74. package/dist/tsdown/npm_cjs_chunk_semver.cjs +0 -357
  75. package/dist/tsdown/npm_entry_semver_functions_coerce.cjs +0 -52
  76. package/dist/tsdown/npm_entry_semver_functions_satisfies.cjs +0 -19
  77. package/dist/tsdown/npm_entry_semver_ranges_min-version.cjs +0 -46
  78. package/dist/tsdown/target-CqeSqtms-CIvlAiuG.js +0 -35
  79. package/dist/tsdown/tsc-context-BusiAGCd.js +0 -27
@@ -1,6 +1,8 @@
1
- import { r as createDebug } from "./main-BlTcyuFi.js";
2
- import { _ as filename_dts_to, b as replaceTemplateName, c as RE_CSS, d as RE_JS, f as RE_JSON, g as RE_VUE, h as RE_TS, l as RE_DTS, m as RE_ROLLDOWN_RUNTIME, o as at, p as RE_NODE_MODULES, s as ee, u as RE_DTS_MAP, v as filename_js_to_dts, x as resolveTemplateFn, y as filename_to_dts } from "./build-BlM3pDGJ-C8Uovnt4.js";
3
- import { i as __require$1, n as globalContext, r as invalidateContextFile, t as createContext } from "./tsc-context-BusiAGCd.js";
1
+ import { r as createDebug } from "./main-DI8qthUB.js";
2
+ import { C as filename_to_dts, S as filename_js_to_dts, T as resolveTemplateFn, _ as RE_JSON, b as RE_TS, g as RE_JS, h as RE_DTS_MAP, m as RE_DTS, p as RE_CSS, v as RE_NODE_MODULES, w as replaceTemplateName, x as filename_dts_to, y as RE_ROLLDOWN_RUNTIME } from "./target-Bab3CUeB-Di6tCARH.js";
3
+ import { n as ee, t as at } from "./dist-DCMiHFrJ.js";
4
+ import { n as globalContext, r as invalidateContextFile, t as createContext } from "./tsc-context-BhMGQ9Qr.js";
5
+ import { t as requireTS } from "./load-tsc-BKULZsrs-Bha6Vsu1.js";
4
6
  import { createRequire } from "node:module";
5
7
  import process from "node:process";
6
8
  import { styleText } from "node:util";
@@ -12,1431 +14,8 @@ import { importerId, include } from "@voidzero-dev/vite-plus-core/rolldown/filte
12
14
  import { tmpdir } from "node:os";
13
15
  import { ResolverFactory, isolatedDeclarationSync } from "@voidzero-dev/vite-plus-core/rolldown/experimental";
14
16
  import { print } from "yuku-codegen";
15
- import { parse as parse$1, walk } from "yuku-parser";
16
- //#region ../../node_modules/.pnpm/yuku-ast@0.1.7/node_modules/yuku-ast/dist/index.mjs
17
- const span = {
18
- start: 0,
19
- end: 0
20
- };
21
- const isComputedKey = (key) => key.type !== "Identifier" && key.type !== "PrivateIdentifier";
22
- const b = {
23
- identifier(name, opts = {}) {
24
- return {
25
- type: "Identifier",
26
- name,
27
- ...opts,
28
- ...span
29
- };
30
- },
31
- privateIdentifier(name) {
32
- return {
33
- type: "PrivateIdentifier",
34
- name,
35
- ...span
36
- };
37
- },
38
- stringLiteral(value) {
39
- return {
40
- type: "Literal",
41
- value,
42
- raw: JSON.stringify(value),
43
- ...span
44
- };
45
- },
46
- numericLiteral(value) {
47
- return {
48
- type: "Literal",
49
- value,
50
- raw: String(value),
51
- ...span
52
- };
53
- },
54
- booleanLiteral(value) {
55
- return {
56
- type: "Literal",
57
- value,
58
- raw: String(value),
59
- ...span
60
- };
61
- },
62
- nullLiteral() {
63
- return {
64
- type: "Literal",
65
- value: null,
66
- raw: "null",
67
- ...span
68
- };
69
- },
70
- bigIntLiteral(value) {
71
- return {
72
- type: "Literal",
73
- value,
74
- raw: `${value}n`,
75
- bigint: String(value),
76
- ...span
77
- };
78
- },
79
- regExpLiteral(pattern, flags = "") {
80
- let value = null;
81
- try {
82
- value = new RegExp(pattern, flags);
83
- } catch {}
84
- return {
85
- type: "Literal",
86
- value,
87
- raw: `/${pattern}/${flags}`,
88
- regex: {
89
- pattern,
90
- flags
91
- },
92
- ...span
93
- };
94
- },
95
- templateLiteral(quasis, expressions) {
96
- return {
97
- type: "TemplateLiteral",
98
- quasis,
99
- expressions,
100
- ...span
101
- };
102
- },
103
- templateElement(cooked, tail = false) {
104
- return {
105
- type: "TemplateElement",
106
- value: {
107
- raw: cooked,
108
- cooked
109
- },
110
- tail,
111
- ...span
112
- };
113
- },
114
- thisExpression() {
115
- return {
116
- type: "ThisExpression",
117
- ...span
118
- };
119
- },
120
- super() {
121
- return {
122
- type: "Super",
123
- ...span
124
- };
125
- },
126
- arrayPattern(elements) {
127
- return {
128
- type: "ArrayPattern",
129
- elements,
130
- ...span
131
- };
132
- },
133
- objectPattern(properties) {
134
- return {
135
- type: "ObjectPattern",
136
- properties,
137
- ...span
138
- };
139
- },
140
- assignmentPattern(left, right) {
141
- return {
142
- type: "AssignmentPattern",
143
- left,
144
- right,
145
- ...span
146
- };
147
- },
148
- restElement(argument) {
149
- return {
150
- type: "RestElement",
151
- argument,
152
- ...span
153
- };
154
- },
155
- /** A member of an `ObjectExpression`. For an `ObjectPattern` member, use {@link bindingProperty}. */
156
- objectProperty(key, value, opts = {}) {
157
- return {
158
- type: "Property",
159
- kind: opts.kind ?? "init",
160
- key,
161
- value,
162
- method: opts.method ?? false,
163
- shorthand: opts.shorthand ?? false,
164
- computed: opts.computed ?? isComputedKey(key),
165
- ...span
166
- };
167
- },
168
- /** A member of an `ObjectPattern`, whose value is a binding target. For an `ObjectExpression` member, use {@link objectProperty}. */
169
- bindingProperty(key, value, opts = {}) {
170
- return {
171
- type: "Property",
172
- kind: "init",
173
- key,
174
- value,
175
- method: false,
176
- shorthand: opts.shorthand ?? false,
177
- computed: opts.computed ?? isComputedKey(key),
178
- ...span
179
- };
180
- },
181
- arrayExpression(elements = []) {
182
- return {
183
- type: "ArrayExpression",
184
- elements,
185
- ...span
186
- };
187
- },
188
- objectExpression(properties = []) {
189
- return {
190
- type: "ObjectExpression",
191
- properties,
192
- ...span
193
- };
194
- },
195
- spreadElement(argument) {
196
- return {
197
- type: "SpreadElement",
198
- argument,
199
- ...span
200
- };
201
- },
202
- sequenceExpression(expressions) {
203
- return {
204
- type: "SequenceExpression",
205
- expressions,
206
- ...span
207
- };
208
- },
209
- parenthesizedExpression(expression) {
210
- return {
211
- type: "ParenthesizedExpression",
212
- expression,
213
- ...span
214
- };
215
- },
216
- unaryExpression(operator, argument) {
217
- return {
218
- type: "UnaryExpression",
219
- operator,
220
- prefix: true,
221
- argument,
222
- ...span
223
- };
224
- },
225
- updateExpression(operator, argument, prefix = false) {
226
- return {
227
- type: "UpdateExpression",
228
- operator,
229
- argument,
230
- prefix,
231
- ...span
232
- };
233
- },
234
- binaryExpression(operator, left, right) {
235
- return {
236
- type: "BinaryExpression",
237
- operator,
238
- left,
239
- right,
240
- ...span
241
- };
242
- },
243
- logicalExpression(operator, left, right) {
244
- return {
245
- type: "LogicalExpression",
246
- operator,
247
- left,
248
- right,
249
- ...span
250
- };
251
- },
252
- assignmentExpression(operator, left, right) {
253
- return {
254
- type: "AssignmentExpression",
255
- operator,
256
- left,
257
- right,
258
- ...span
259
- };
260
- },
261
- conditionalExpression(test, consequent, alternate) {
262
- return {
263
- type: "ConditionalExpression",
264
- test,
265
- consequent,
266
- alternate,
267
- ...span
268
- };
269
- },
270
- yieldExpression(argument = null, delegate = false) {
271
- return {
272
- type: "YieldExpression",
273
- delegate,
274
- argument,
275
- ...span
276
- };
277
- },
278
- awaitExpression(argument) {
279
- return {
280
- type: "AwaitExpression",
281
- argument,
282
- ...span
283
- };
284
- },
285
- memberExpression(object, property, opts = {}) {
286
- return {
287
- type: "MemberExpression",
288
- object,
289
- property,
290
- computed: opts.computed ?? isComputedKey(property),
291
- optional: opts.optional ?? false,
292
- ...span
293
- };
294
- },
295
- callExpression(callee, args = [], opts = {}) {
296
- return {
297
- type: "CallExpression",
298
- callee,
299
- arguments: args,
300
- optional: opts.optional ?? false,
301
- ...opts,
302
- ...span
303
- };
304
- },
305
- newExpression(callee, args = [], opts = {}) {
306
- return {
307
- type: "NewExpression",
308
- callee,
309
- arguments: args,
310
- ...opts,
311
- ...span
312
- };
313
- },
314
- chainExpression(expression) {
315
- return {
316
- type: "ChainExpression",
317
- expression,
318
- ...span
319
- };
320
- },
321
- taggedTemplateExpression(tag, quasi, opts = {}) {
322
- return {
323
- type: "TaggedTemplateExpression",
324
- tag,
325
- quasi,
326
- ...opts,
327
- ...span
328
- };
329
- },
330
- metaProperty(meta, property) {
331
- return {
332
- type: "MetaProperty",
333
- meta: b.identifier(meta),
334
- property: b.identifier(property),
335
- ...span
336
- };
337
- },
338
- importExpression(source, opts = {}) {
339
- return {
340
- type: "ImportExpression",
341
- source,
342
- options: opts.options ?? null,
343
- phase: opts.phase ?? null,
344
- ...span
345
- };
346
- },
347
- arrowFunctionExpression(params, body, opts = {}) {
348
- return {
349
- type: "ArrowFunctionExpression",
350
- id: null,
351
- generator: false,
352
- async: opts.async ?? false,
353
- params,
354
- body,
355
- expression: body.type !== "BlockStatement",
356
- ...opts,
357
- ...span
358
- };
359
- },
360
- functionExpression(params, body, opts = {}) {
361
- return {
362
- type: "FunctionExpression",
363
- id: opts.id ?? null,
364
- generator: opts.generator ?? false,
365
- async: opts.async ?? false,
366
- params,
367
- body,
368
- expression: false,
369
- ...span
370
- };
371
- },
372
- functionDeclaration(id, params, body, opts = {}) {
373
- return {
374
- type: "FunctionDeclaration",
375
- id,
376
- generator: opts.generator ?? false,
377
- async: opts.async ?? false,
378
- params,
379
- body,
380
- expression: false,
381
- ...span
382
- };
383
- },
384
- classDeclaration(id, body, opts = {}) {
385
- return {
386
- type: "ClassDeclaration",
387
- decorators: opts.decorators ?? [],
388
- id,
389
- superClass: opts.superClass ?? null,
390
- body,
391
- ...opts,
392
- ...span
393
- };
394
- },
395
- classExpression(id, body, opts = {}) {
396
- return {
397
- type: "ClassExpression",
398
- decorators: opts.decorators ?? [],
399
- id,
400
- superClass: opts.superClass ?? null,
401
- body,
402
- ...span
403
- };
404
- },
405
- classBody(body = []) {
406
- return {
407
- type: "ClassBody",
408
- body,
409
- ...span
410
- };
411
- },
412
- methodDefinition(key, value, opts = {}) {
413
- return {
414
- type: "MethodDefinition",
415
- decorators: [],
416
- key,
417
- value,
418
- kind: opts.kind ?? "method",
419
- computed: opts.computed ?? isComputedKey(key),
420
- static: opts.static ?? false,
421
- ...span
422
- };
423
- },
424
- propertyDefinition(key, value = null, opts = {}) {
425
- return {
426
- type: "PropertyDefinition",
427
- decorators: opts.decorators ?? [],
428
- key,
429
- value,
430
- computed: opts.computed ?? isComputedKey(key),
431
- static: opts.static ?? false,
432
- ...span
433
- };
434
- },
435
- accessorProperty(key, value = null, opts = {}) {
436
- return {
437
- type: "AccessorProperty",
438
- decorators: [],
439
- key,
440
- value,
441
- computed: opts.computed ?? isComputedKey(key),
442
- static: opts.static ?? false,
443
- ...span
444
- };
445
- },
446
- tsAbstractMethodDefinition(key, value, opts = {}) {
447
- return {
448
- type: "TSAbstractMethodDefinition",
449
- decorators: [],
450
- key,
451
- value,
452
- kind: opts.kind ?? "method",
453
- computed: opts.computed ?? isComputedKey(key),
454
- static: opts.static ?? false,
455
- ...span
456
- };
457
- },
458
- tsAbstractPropertyDefinition(key, value = null, opts = {}) {
459
- return {
460
- type: "TSAbstractPropertyDefinition",
461
- decorators: [],
462
- key,
463
- value,
464
- computed: opts.computed ?? isComputedKey(key),
465
- static: opts.static ?? false,
466
- ...span
467
- };
468
- },
469
- tsAbstractAccessorProperty(key, value = null, opts = {}) {
470
- return {
471
- type: "TSAbstractAccessorProperty",
472
- decorators: [],
473
- key,
474
- value,
475
- computed: opts.computed ?? isComputedKey(key),
476
- static: opts.static ?? false,
477
- ...span
478
- };
479
- },
480
- staticBlock(body = []) {
481
- return {
482
- type: "StaticBlock",
483
- body,
484
- ...span
485
- };
486
- },
487
- decorator(expression) {
488
- return {
489
- type: "Decorator",
490
- expression,
491
- ...span
492
- };
493
- },
494
- expressionStatement(expression) {
495
- return {
496
- type: "ExpressionStatement",
497
- expression,
498
- ...span
499
- };
500
- },
501
- directive(value) {
502
- return {
503
- type: "ExpressionStatement",
504
- expression: b.stringLiteral(value),
505
- directive: value,
506
- ...span
507
- };
508
- },
509
- blockStatement(body = []) {
510
- return {
511
- type: "BlockStatement",
512
- body,
513
- ...span
514
- };
515
- },
516
- emptyStatement() {
517
- return {
518
- type: "EmptyStatement",
519
- ...span
520
- };
521
- },
522
- debuggerStatement() {
523
- return {
524
- type: "DebuggerStatement",
525
- ...span
526
- };
527
- },
528
- returnStatement(argument = null) {
529
- return {
530
- type: "ReturnStatement",
531
- argument,
532
- ...span
533
- };
534
- },
535
- ifStatement(test, consequent, alternate = null) {
536
- return {
537
- type: "IfStatement",
538
- test,
539
- consequent,
540
- alternate,
541
- ...span
542
- };
543
- },
544
- switchStatement(discriminant, cases) {
545
- return {
546
- type: "SwitchStatement",
547
- discriminant,
548
- cases,
549
- ...span
550
- };
551
- },
552
- switchCase(test, consequent) {
553
- return {
554
- type: "SwitchCase",
555
- test,
556
- consequent,
557
- ...span
558
- };
559
- },
560
- throwStatement(argument) {
561
- return {
562
- type: "ThrowStatement",
563
- argument,
564
- ...span
565
- };
566
- },
567
- tryStatement(block, handler = null, finalizer = null) {
568
- return {
569
- type: "TryStatement",
570
- block,
571
- handler,
572
- finalizer,
573
- ...span
574
- };
575
- },
576
- catchClause(param, body) {
577
- return {
578
- type: "CatchClause",
579
- param,
580
- body,
581
- ...span
582
- };
583
- },
584
- whileStatement(test, body) {
585
- return {
586
- type: "WhileStatement",
587
- test,
588
- body,
589
- ...span
590
- };
591
- },
592
- doWhileStatement(body, test) {
593
- return {
594
- type: "DoWhileStatement",
595
- body,
596
- test,
597
- ...span
598
- };
599
- },
600
- forStatement(init, test, update, body) {
601
- return {
602
- type: "ForStatement",
603
- init,
604
- test,
605
- update,
606
- body,
607
- ...span
608
- };
609
- },
610
- forInStatement(left, right, body) {
611
- return {
612
- type: "ForInStatement",
613
- left,
614
- right,
615
- body,
616
- ...span
617
- };
618
- },
619
- forOfStatement(left, right, body, isAwait = false) {
620
- return {
621
- type: "ForOfStatement",
622
- left,
623
- right,
624
- body,
625
- await: isAwait,
626
- ...span
627
- };
628
- },
629
- labeledStatement(label, body) {
630
- return {
631
- type: "LabeledStatement",
632
- label,
633
- body,
634
- ...span
635
- };
636
- },
637
- breakStatement(label = null) {
638
- return {
639
- type: "BreakStatement",
640
- label,
641
- ...span
642
- };
643
- },
644
- continueStatement(label = null) {
645
- return {
646
- type: "ContinueStatement",
647
- label,
648
- ...span
649
- };
650
- },
651
- withStatement(object, body) {
652
- return {
653
- type: "WithStatement",
654
- object,
655
- body,
656
- ...span
657
- };
658
- },
659
- variableDeclaration(kind, declarations) {
660
- return {
661
- type: "VariableDeclaration",
662
- kind,
663
- declarations,
664
- ...span
665
- };
666
- },
667
- variableDeclarator(id, init = null) {
668
- return {
669
- type: "VariableDeclarator",
670
- id,
671
- init,
672
- ...span
673
- };
674
- },
675
- importDeclaration(specifiers, source, opts = {}) {
676
- return {
677
- type: "ImportDeclaration",
678
- specifiers,
679
- source,
680
- phase: opts.phase ?? null,
681
- attributes: opts.attributes ?? [],
682
- ...opts,
683
- ...span
684
- };
685
- },
686
- importSpecifier(imported, local) {
687
- return {
688
- type: "ImportSpecifier",
689
- imported,
690
- local,
691
- ...span
692
- };
693
- },
694
- importDefaultSpecifier(local) {
695
- return {
696
- type: "ImportDefaultSpecifier",
697
- local,
698
- ...span
699
- };
700
- },
701
- importNamespaceSpecifier(local) {
702
- return {
703
- type: "ImportNamespaceSpecifier",
704
- local,
705
- ...span
706
- };
707
- },
708
- importAttribute(key, value) {
709
- return {
710
- type: "ImportAttribute",
711
- key,
712
- value,
713
- ...span
714
- };
715
- },
716
- exportNamedDeclaration(declaration, specifiers = [], opts = {}) {
717
- return {
718
- type: "ExportNamedDeclaration",
719
- declaration,
720
- specifiers,
721
- source: opts.source ?? null,
722
- attributes: opts.attributes ?? [],
723
- ...opts,
724
- ...span
725
- };
726
- },
727
- exportDefaultDeclaration(declaration) {
728
- return {
729
- type: "ExportDefaultDeclaration",
730
- declaration,
731
- ...span
732
- };
733
- },
734
- exportAllDeclaration(source, opts = {}) {
735
- return {
736
- type: "ExportAllDeclaration",
737
- exported: opts.exported ?? null,
738
- source,
739
- attributes: opts.attributes ?? [],
740
- ...opts,
741
- ...span
742
- };
743
- },
744
- exportSpecifier(local, exported) {
745
- return {
746
- type: "ExportSpecifier",
747
- local,
748
- exported,
749
- ...span
750
- };
751
- },
752
- jsxIdentifier(name) {
753
- return {
754
- type: "JSXIdentifier",
755
- name,
756
- ...span
757
- };
758
- },
759
- jsxNamespacedName(namespace, name) {
760
- return {
761
- type: "JSXNamespacedName",
762
- namespace,
763
- name,
764
- ...span
765
- };
766
- },
767
- jsxMemberExpression(object, property) {
768
- return {
769
- type: "JSXMemberExpression",
770
- object,
771
- property,
772
- ...span
773
- };
774
- },
775
- jsxElement(openingElement, children = [], closingElement = null) {
776
- return {
777
- type: "JSXElement",
778
- openingElement,
779
- children,
780
- closingElement,
781
- ...span
782
- };
783
- },
784
- jsxOpeningElement(name, attributes = [], selfClosing = false) {
785
- return {
786
- type: "JSXOpeningElement",
787
- name,
788
- attributes,
789
- selfClosing,
790
- ...span
791
- };
792
- },
793
- jsxClosingElement(name) {
794
- return {
795
- type: "JSXClosingElement",
796
- name,
797
- ...span
798
- };
799
- },
800
- jsxOpeningFragment() {
801
- return {
802
- type: "JSXOpeningFragment",
803
- ...span
804
- };
805
- },
806
- jsxClosingFragment() {
807
- return {
808
- type: "JSXClosingFragment",
809
- ...span
810
- };
811
- },
812
- jsxFragment(children = []) {
813
- return {
814
- type: "JSXFragment",
815
- openingFragment: b.jsxOpeningFragment(),
816
- children,
817
- closingFragment: b.jsxClosingFragment(),
818
- ...span
819
- };
820
- },
821
- jsxAttribute(name, value = null) {
822
- return {
823
- type: "JSXAttribute",
824
- name,
825
- value,
826
- ...span
827
- };
828
- },
829
- jsxSpreadAttribute(argument) {
830
- return {
831
- type: "JSXSpreadAttribute",
832
- argument,
833
- ...span
834
- };
835
- },
836
- jsxExpressionContainer(expression) {
837
- return {
838
- type: "JSXExpressionContainer",
839
- expression,
840
- ...span
841
- };
842
- },
843
- jsxEmptyExpression() {
844
- return {
845
- type: "JSXEmptyExpression",
846
- ...span
847
- };
848
- },
849
- jsxText(value) {
850
- return {
851
- type: "JSXText",
852
- value,
853
- raw: value,
854
- ...span
855
- };
856
- },
857
- jsxSpreadChild(expression) {
858
- return {
859
- type: "JSXSpreadChild",
860
- expression,
861
- ...span
862
- };
863
- },
864
- tsTypeAnnotation(typeAnnotation) {
865
- return {
866
- type: "TSTypeAnnotation",
867
- typeAnnotation,
868
- ...span
869
- };
870
- },
871
- tsAnyKeyword: () => ({
872
- type: "TSAnyKeyword",
873
- ...span
874
- }),
875
- tsUnknownKeyword: () => ({
876
- type: "TSUnknownKeyword",
877
- ...span
878
- }),
879
- tsNeverKeyword: () => ({
880
- type: "TSNeverKeyword",
881
- ...span
882
- }),
883
- tsVoidKeyword: () => ({
884
- type: "TSVoidKeyword",
885
- ...span
886
- }),
887
- tsNullKeyword: () => ({
888
- type: "TSNullKeyword",
889
- ...span
890
- }),
891
- tsUndefinedKeyword: () => ({
892
- type: "TSUndefinedKeyword",
893
- ...span
894
- }),
895
- tsStringKeyword: () => ({
896
- type: "TSStringKeyword",
897
- ...span
898
- }),
899
- tsNumberKeyword: () => ({
900
- type: "TSNumberKeyword",
901
- ...span
902
- }),
903
- tsBigIntKeyword: () => ({
904
- type: "TSBigIntKeyword",
905
- ...span
906
- }),
907
- tsBooleanKeyword: () => ({
908
- type: "TSBooleanKeyword",
909
- ...span
910
- }),
911
- tsSymbolKeyword: () => ({
912
- type: "TSSymbolKeyword",
913
- ...span
914
- }),
915
- tsObjectKeyword: () => ({
916
- type: "TSObjectKeyword",
917
- ...span
918
- }),
919
- tsIntrinsicKeyword: () => ({
920
- type: "TSIntrinsicKeyword",
921
- ...span
922
- }),
923
- tsThisType: () => ({
924
- type: "TSThisType",
925
- ...span
926
- }),
927
- tsTypeReference(typeName, typeArguments = null) {
928
- return {
929
- type: "TSTypeReference",
930
- typeName,
931
- typeArguments,
932
- ...span
933
- };
934
- },
935
- tsQualifiedName(left, right) {
936
- return {
937
- type: "TSQualifiedName",
938
- left,
939
- right,
940
- ...span
941
- };
942
- },
943
- tsTypeQuery(exprName, typeArguments = null) {
944
- return {
945
- type: "TSTypeQuery",
946
- exprName,
947
- typeArguments,
948
- ...span
949
- };
950
- },
951
- tsImportType(source, opts = {}) {
952
- return {
953
- type: "TSImportType",
954
- source,
955
- options: opts.options ?? null,
956
- qualifier: opts.qualifier ?? null,
957
- typeArguments: opts.typeArguments ?? null,
958
- ...span
959
- };
960
- },
961
- tsTypeParameter(name, opts = {}) {
962
- return {
963
- type: "TSTypeParameter",
964
- name,
965
- constraint: opts.constraint ?? null,
966
- default: opts.default ?? null,
967
- in: opts.in ?? false,
968
- out: opts.out ?? false,
969
- const: opts.const ?? false,
970
- ...span
971
- };
972
- },
973
- tsTypeParameterDeclaration(params) {
974
- return {
975
- type: "TSTypeParameterDeclaration",
976
- params,
977
- ...span
978
- };
979
- },
980
- tsTypeParameterInstantiation(params) {
981
- return {
982
- type: "TSTypeParameterInstantiation",
983
- params,
984
- ...span
985
- };
986
- },
987
- tsLiteralType(literal) {
988
- return {
989
- type: "TSLiteralType",
990
- literal,
991
- ...span
992
- };
993
- },
994
- tsTemplateLiteralType(quasis, types) {
995
- return {
996
- type: "TSTemplateLiteralType",
997
- quasis,
998
- types,
999
- ...span
1000
- };
1001
- },
1002
- tsArrayType(elementType) {
1003
- return {
1004
- type: "TSArrayType",
1005
- elementType,
1006
- ...span
1007
- };
1008
- },
1009
- tsIndexedAccessType(objectType, indexType) {
1010
- return {
1011
- type: "TSIndexedAccessType",
1012
- objectType,
1013
- indexType,
1014
- ...span
1015
- };
1016
- },
1017
- tsTupleType(elementTypes) {
1018
- return {
1019
- type: "TSTupleType",
1020
- elementTypes,
1021
- ...span
1022
- };
1023
- },
1024
- tsNamedTupleMember(label, elementType, optional = false) {
1025
- return {
1026
- type: "TSNamedTupleMember",
1027
- label,
1028
- elementType,
1029
- optional,
1030
- ...span
1031
- };
1032
- },
1033
- tsOptionalType(typeAnnotation) {
1034
- return {
1035
- type: "TSOptionalType",
1036
- typeAnnotation,
1037
- ...span
1038
- };
1039
- },
1040
- tsRestType(typeAnnotation) {
1041
- return {
1042
- type: "TSRestType",
1043
- typeAnnotation,
1044
- ...span
1045
- };
1046
- },
1047
- tsJSDocNullableType(typeAnnotation, postfix = false) {
1048
- return {
1049
- type: "TSJSDocNullableType",
1050
- typeAnnotation,
1051
- postfix,
1052
- ...span
1053
- };
1054
- },
1055
- tsJSDocNonNullableType(typeAnnotation, postfix = false) {
1056
- return {
1057
- type: "TSJSDocNonNullableType",
1058
- typeAnnotation,
1059
- postfix,
1060
- ...span
1061
- };
1062
- },
1063
- tsJSDocUnknownType() {
1064
- return {
1065
- type: "TSJSDocUnknownType",
1066
- ...span
1067
- };
1068
- },
1069
- tsUnionType(types) {
1070
- return {
1071
- type: "TSUnionType",
1072
- types,
1073
- ...span
1074
- };
1075
- },
1076
- tsIntersectionType(types) {
1077
- return {
1078
- type: "TSIntersectionType",
1079
- types,
1080
- ...span
1081
- };
1082
- },
1083
- tsConditionalType(checkType, extendsType, trueType, falseType) {
1084
- return {
1085
- type: "TSConditionalType",
1086
- checkType,
1087
- extendsType,
1088
- trueType,
1089
- falseType,
1090
- ...span
1091
- };
1092
- },
1093
- tsInferType(typeParameter) {
1094
- return {
1095
- type: "TSInferType",
1096
- typeParameter,
1097
- ...span
1098
- };
1099
- },
1100
- tsTypeOperator(operator, typeAnnotation) {
1101
- return {
1102
- type: "TSTypeOperator",
1103
- operator,
1104
- typeAnnotation,
1105
- ...span
1106
- };
1107
- },
1108
- tsParenthesizedType(typeAnnotation) {
1109
- return {
1110
- type: "TSParenthesizedType",
1111
- typeAnnotation,
1112
- ...span
1113
- };
1114
- },
1115
- tsFunctionType(params, returnType, typeParameters = null) {
1116
- return {
1117
- type: "TSFunctionType",
1118
- typeParameters,
1119
- params,
1120
- returnType,
1121
- ...span
1122
- };
1123
- },
1124
- tsConstructorType(params, returnType, opts = {}) {
1125
- return {
1126
- type: "TSConstructorType",
1127
- abstract: opts.abstract ?? false,
1128
- typeParameters: opts.typeParameters ?? null,
1129
- params,
1130
- returnType,
1131
- ...span
1132
- };
1133
- },
1134
- tsTypePredicate(parameterName, typeAnnotation = null, asserts = false) {
1135
- return {
1136
- type: "TSTypePredicate",
1137
- parameterName,
1138
- typeAnnotation,
1139
- asserts,
1140
- ...span
1141
- };
1142
- },
1143
- tsTypeLiteral(members) {
1144
- return {
1145
- type: "TSTypeLiteral",
1146
- members,
1147
- ...span
1148
- };
1149
- },
1150
- tsMappedType(key, constraint, opts = {}) {
1151
- return {
1152
- type: "TSMappedType",
1153
- key,
1154
- constraint,
1155
- nameType: opts.nameType ?? null,
1156
- typeAnnotation: opts.typeAnnotation ?? null,
1157
- optional: opts.optional ?? false,
1158
- readonly: opts.readonly ?? null,
1159
- ...span
1160
- };
1161
- },
1162
- tsPropertySignature(key, opts = {}) {
1163
- return {
1164
- type: "TSPropertySignature",
1165
- key,
1166
- typeAnnotation: opts.typeAnnotation ?? null,
1167
- computed: opts.computed ?? isComputedKey(key),
1168
- optional: opts.optional ?? false,
1169
- readonly: opts.readonly ?? false,
1170
- accessibility: null,
1171
- static: false,
1172
- ...span
1173
- };
1174
- },
1175
- tsMethodSignature(key, params, opts = {}) {
1176
- return {
1177
- type: "TSMethodSignature",
1178
- key,
1179
- computed: opts.computed ?? isComputedKey(key),
1180
- optional: opts.optional ?? false,
1181
- kind: opts.kind ?? "method",
1182
- typeParameters: opts.typeParameters ?? null,
1183
- params,
1184
- returnType: opts.returnType ?? null,
1185
- accessibility: null,
1186
- readonly: false,
1187
- static: false,
1188
- ...span
1189
- };
1190
- },
1191
- tsCallSignatureDeclaration(params, returnType = null, typeParameters = null) {
1192
- return {
1193
- type: "TSCallSignatureDeclaration",
1194
- typeParameters,
1195
- params,
1196
- returnType,
1197
- ...span
1198
- };
1199
- },
1200
- tsConstructSignatureDeclaration(params, returnType = null, typeParameters = null) {
1201
- return {
1202
- type: "TSConstructSignatureDeclaration",
1203
- typeParameters,
1204
- params,
1205
- returnType,
1206
- ...span
1207
- };
1208
- },
1209
- tsIndexSignature(parameters, typeAnnotation, opts = {}) {
1210
- return {
1211
- type: "TSIndexSignature",
1212
- parameters,
1213
- typeAnnotation,
1214
- readonly: opts.readonly ?? false,
1215
- static: opts.static ?? false,
1216
- accessibility: null,
1217
- ...span
1218
- };
1219
- },
1220
- tsTypeAliasDeclaration(id, typeAnnotation, opts = {}) {
1221
- return {
1222
- type: "TSTypeAliasDeclaration",
1223
- id,
1224
- typeParameters: opts.typeParameters ?? null,
1225
- typeAnnotation,
1226
- declare: opts.declare ?? false,
1227
- ...span
1228
- };
1229
- },
1230
- tsInterfaceDeclaration(id, body, opts = {}) {
1231
- return {
1232
- type: "TSInterfaceDeclaration",
1233
- id,
1234
- typeParameters: opts.typeParameters ?? null,
1235
- extends: opts.extends ?? [],
1236
- body,
1237
- declare: opts.declare ?? false,
1238
- ...span
1239
- };
1240
- },
1241
- tsInterfaceBody(body) {
1242
- return {
1243
- type: "TSInterfaceBody",
1244
- body,
1245
- ...span
1246
- };
1247
- },
1248
- tsInterfaceHeritage(expression, typeArguments = null) {
1249
- return {
1250
- type: "TSInterfaceHeritage",
1251
- expression,
1252
- typeArguments,
1253
- ...span
1254
- };
1255
- },
1256
- tsClassImplements(expression, typeArguments = null) {
1257
- return {
1258
- type: "TSClassImplements",
1259
- expression,
1260
- typeArguments,
1261
- ...span
1262
- };
1263
- },
1264
- tsEnumDeclaration(id, body, opts = {}) {
1265
- return {
1266
- type: "TSEnumDeclaration",
1267
- id,
1268
- body,
1269
- const: opts.const ?? false,
1270
- declare: opts.declare ?? false,
1271
- ...span
1272
- };
1273
- },
1274
- tsEnumBody(members) {
1275
- return {
1276
- type: "TSEnumBody",
1277
- members,
1278
- ...span
1279
- };
1280
- },
1281
- tsEnumMember(id, initializer = null) {
1282
- return {
1283
- type: "TSEnumMember",
1284
- id,
1285
- initializer,
1286
- computed: false,
1287
- ...span
1288
- };
1289
- },
1290
- tsModuleDeclaration(id, body, opts = {}) {
1291
- return {
1292
- type: "TSModuleDeclaration",
1293
- id,
1294
- body,
1295
- kind: opts.kind ?? "module",
1296
- declare: opts.declare ?? false,
1297
- global: opts.global ?? false,
1298
- ...span
1299
- };
1300
- },
1301
- tsModuleBlock(body = []) {
1302
- return {
1303
- type: "TSModuleBlock",
1304
- body,
1305
- ...span
1306
- };
1307
- },
1308
- tsParameterProperty(parameter, opts = {}) {
1309
- return {
1310
- type: "TSParameterProperty",
1311
- decorators: opts.decorators ?? [],
1312
- parameter,
1313
- override: opts.override ?? false,
1314
- readonly: opts.readonly ?? false,
1315
- accessibility: opts.accessibility ?? null,
1316
- static: false,
1317
- ...span
1318
- };
1319
- },
1320
- tsAsExpression(expression, typeAnnotation) {
1321
- return {
1322
- type: "TSAsExpression",
1323
- expression,
1324
- typeAnnotation,
1325
- ...span
1326
- };
1327
- },
1328
- tsSatisfiesExpression(expression, typeAnnotation) {
1329
- return {
1330
- type: "TSSatisfiesExpression",
1331
- expression,
1332
- typeAnnotation,
1333
- ...span
1334
- };
1335
- },
1336
- tsTypeAssertion(typeAnnotation, expression) {
1337
- return {
1338
- type: "TSTypeAssertion",
1339
- typeAnnotation,
1340
- expression,
1341
- ...span
1342
- };
1343
- },
1344
- tsNonNullExpression(expression) {
1345
- return {
1346
- type: "TSNonNullExpression",
1347
- expression,
1348
- ...span
1349
- };
1350
- },
1351
- tsInstantiationExpression(expression, typeArguments) {
1352
- return {
1353
- type: "TSInstantiationExpression",
1354
- expression,
1355
- typeArguments,
1356
- ...span
1357
- };
1358
- },
1359
- tsExportAssignment(expression) {
1360
- return {
1361
- type: "TSExportAssignment",
1362
- expression,
1363
- ...span
1364
- };
1365
- },
1366
- tsNamespaceExportDeclaration(id) {
1367
- return {
1368
- type: "TSNamespaceExportDeclaration",
1369
- id,
1370
- ...span
1371
- };
1372
- },
1373
- tsImportEqualsDeclaration(id, moduleReference, importKind = "value") {
1374
- return {
1375
- type: "TSImportEqualsDeclaration",
1376
- id,
1377
- moduleReference,
1378
- importKind,
1379
- ...span
1380
- };
1381
- },
1382
- tsExternalModuleReference(expression) {
1383
- return {
1384
- type: "TSExternalModuleReference",
1385
- expression,
1386
- ...span
1387
- };
1388
- },
1389
- tsDeclareFunction(id, params, opts = {}) {
1390
- return {
1391
- type: "TSDeclareFunction",
1392
- id,
1393
- generator: opts.generator ?? false,
1394
- async: opts.async ?? false,
1395
- params,
1396
- body: null,
1397
- expression: false,
1398
- declare: opts.declare ?? false,
1399
- typeParameters: opts.typeParameters ?? null,
1400
- returnType: opts.returnType ?? null,
1401
- ...span
1402
- };
1403
- },
1404
- tsEmptyBodyFunctionExpression(params, opts = {}) {
1405
- return {
1406
- type: "TSEmptyBodyFunctionExpression",
1407
- id: opts.id ?? null,
1408
- generator: false,
1409
- async: false,
1410
- params,
1411
- body: null,
1412
- expression: false,
1413
- declare: false,
1414
- typeParameters: opts.typeParameters ?? null,
1415
- returnType: opts.returnType ?? null,
1416
- ...span
1417
- };
1418
- },
1419
- hashbang(value) {
1420
- return {
1421
- type: "Hashbang",
1422
- value,
1423
- ...span
1424
- };
1425
- },
1426
- program(body = [], opts = {}) {
1427
- return {
1428
- type: "Program",
1429
- sourceType: opts.sourceType ?? "module",
1430
- hashbang: opts.hashbang ?? null,
1431
- body,
1432
- ...span
1433
- };
1434
- }
1435
- };
1436
- /**
1437
- * Node types grouped under a shared alias. Membership is by node `type`, and
1438
- * each group backs an alias guard such as `is.Expression` or `is.Function`.
1439
- */
17
+ import { parse as parse$1 } from "yuku-parser";
18
+ //#region ../../node_modules/.pnpm/yuku-ast@0.7.0/node_modules/yuku-ast/dist/index.js
1440
19
  const ALIAS_GROUPS = {
1441
20
  Expression: [
1442
21
  "Identifier",
@@ -1525,42 +104,41 @@ const ALIAS_GROUPS = {
1525
104
  Function: [
1526
105
  "FunctionDeclaration",
1527
106
  "FunctionExpression",
1528
- "ArrowFunctionExpression",
1529
107
  "TSDeclareFunction",
1530
- "TSEmptyBodyFunctionExpression"
108
+ "TSEmptyBodyFunctionExpression",
109
+ "ArrowFunctionExpression"
1531
110
  ],
1532
111
  Class: ["ClassDeclaration", "ClassExpression"],
1533
112
  Method: ["MethodDefinition", "TSAbstractMethodDefinition"],
1534
113
  Loop: [
1535
- "ForStatement",
114
+ "DoWhileStatement",
1536
115
  "ForInStatement",
1537
116
  "ForOfStatement",
1538
- "WhileStatement",
1539
- "DoWhileStatement"
117
+ "ForStatement",
118
+ "WhileStatement"
1540
119
  ],
1541
120
  Pattern: [
1542
- "Identifier",
1543
121
  "ArrayPattern",
1544
122
  "ObjectPattern",
1545
123
  "AssignmentPattern",
1546
124
  "RestElement"
1547
125
  ],
1548
126
  JSX: [
1549
- "JSXElement",
1550
- "JSXOpeningElement",
127
+ "JSXAttribute",
1551
128
  "JSXClosingElement",
1552
- "JSXFragment",
1553
- "JSXOpeningFragment",
1554
129
  "JSXClosingFragment",
130
+ "JSXElement",
131
+ "JSXEmptyExpression",
132
+ "JSXExpressionContainer",
133
+ "JSXFragment",
1555
134
  "JSXIdentifier",
1556
- "JSXNamespacedName",
1557
135
  "JSXMemberExpression",
1558
- "JSXAttribute",
136
+ "JSXNamespacedName",
137
+ "JSXOpeningElement",
138
+ "JSXOpeningFragment",
1559
139
  "JSXSpreadAttribute",
1560
- "JSXExpressionContainer",
1561
- "JSXEmptyExpression",
1562
- "JSXText",
1563
- "JSXSpreadChild"
140
+ "JSXSpreadChild",
141
+ "JSXText"
1564
142
  ],
1565
143
  TSType: [
1566
144
  "TSAnyKeyword",
@@ -1602,48 +180,448 @@ const ALIAS_GROUPS = {
1602
180
  "TSMappedType"
1603
181
  ]
1604
182
  };
1605
- /**
1606
- * Every concrete node `type` in the AST. Drives the per-type guards in `is`.
1607
- * The compile-time checks below keep it exhaustive: a node type added to or
1608
- * removed from the parser fails to build until this list is brought in line.
1609
- */
1610
- const NODE_TYPES = [
1611
- "Program",
1612
- "Hashbang",
1613
- "Identifier",
1614
- "PrivateIdentifier",
1615
- "Literal",
1616
- "TemplateElement",
1617
- "Super",
1618
- "ThisExpression",
1619
- "ArrayPattern",
1620
- "ObjectPattern",
1621
- "AssignmentPattern",
1622
- "RestElement",
1623
- "Property",
183
+ Object.keys(ALIAS_GROUPS);
184
+ const KEYS = Object.create(null);
185
+ function ck(type, keys) {
186
+ const prev = KEYS[type];
187
+ if (prev === void 0) KEYS[type] = keys;
188
+ else for (const k of keys) if (!prev.includes(k)) prev.push(k);
189
+ }
190
+ ck("SequenceExpression", ["expressions"]);
191
+ ck("ParenthesizedExpression", ["expression"]);
192
+ ck("ArrowFunctionExpression", [
193
+ "typeParameters",
194
+ "params",
195
+ "returnType",
196
+ "body"
197
+ ]);
198
+ ck("FunctionDeclaration", [
199
+ "id",
200
+ "typeParameters",
201
+ "params",
202
+ "returnType",
203
+ "body"
204
+ ]);
205
+ ck("FunctionExpression", [
206
+ "id",
207
+ "typeParameters",
208
+ "params",
209
+ "returnType",
210
+ "body"
211
+ ]);
212
+ ck("TSDeclareFunction", [
213
+ "id",
214
+ "typeParameters",
215
+ "params",
216
+ "returnType",
217
+ "body"
218
+ ]);
219
+ ck("TSEmptyBodyFunctionExpression", [
220
+ "id",
221
+ "typeParameters",
222
+ "params",
223
+ "returnType",
224
+ "body"
225
+ ]);
226
+ ck("BlockStatement", ["body"]);
227
+ ck("BlockStatement", ["body"]);
228
+ ck("BinaryExpression", ["left", "right"]);
229
+ ck("LogicalExpression", ["left", "right"]);
230
+ ck("ConditionalExpression", [
231
+ "test",
232
+ "consequent",
233
+ "alternate"
234
+ ]);
235
+ ck("UnaryExpression", ["argument"]);
236
+ ck("UpdateExpression", ["argument"]);
237
+ ck("AssignmentExpression", ["left", "right"]);
238
+ ck("ArrayExpression", ["elements"]);
239
+ ck("ObjectExpression", ["properties"]);
240
+ ck("SpreadElement", ["argument"]);
241
+ ck("Property", ["key", "value"]);
242
+ ck("MemberExpression", ["object", "property"]);
243
+ ck("CallExpression", [
244
+ "callee",
245
+ "typeArguments",
246
+ "arguments"
247
+ ]);
248
+ ck("ChainExpression", ["expression"]);
249
+ ck("TaggedTemplateExpression", [
250
+ "tag",
251
+ "typeArguments",
252
+ "quasi"
253
+ ]);
254
+ ck("NewExpression", [
255
+ "callee",
256
+ "typeArguments",
257
+ "arguments"
258
+ ]);
259
+ ck("AwaitExpression", ["argument"]);
260
+ ck("YieldExpression", ["argument"]);
261
+ ck("MetaProperty", ["meta", "property"]);
262
+ ck("Decorator", ["expression"]);
263
+ ck("ClassDeclaration", [
264
+ "decorators",
265
+ "id",
266
+ "typeParameters",
267
+ "superClass",
268
+ "superTypeArguments",
269
+ "implements",
270
+ "body"
271
+ ]);
272
+ ck("ClassExpression", [
273
+ "decorators",
274
+ "id",
275
+ "typeParameters",
276
+ "superClass",
277
+ "superTypeArguments",
278
+ "implements",
279
+ "body"
280
+ ]);
281
+ ck("ClassBody", ["body"]);
282
+ ck("MethodDefinition", [
283
+ "decorators",
284
+ "key",
285
+ "value"
286
+ ]);
287
+ ck("TSAbstractMethodDefinition", [
288
+ "decorators",
289
+ "key",
290
+ "value"
291
+ ]);
292
+ ck("PropertyDefinition", [
293
+ "decorators",
294
+ "key",
295
+ "typeAnnotation",
296
+ "value"
297
+ ]);
298
+ ck("AccessorProperty", [
299
+ "decorators",
300
+ "key",
301
+ "typeAnnotation",
302
+ "value"
303
+ ]);
304
+ ck("TSAbstractPropertyDefinition", [
305
+ "decorators",
306
+ "key",
307
+ "typeAnnotation",
308
+ "value"
309
+ ]);
310
+ ck("TSAbstractAccessorProperty", [
311
+ "decorators",
312
+ "key",
313
+ "typeAnnotation",
314
+ "value"
315
+ ]);
316
+ ck("StaticBlock", ["body"]);
317
+ ck("Super", []);
318
+ ck("Literal", []);
319
+ ck("Literal", []);
320
+ ck("Literal", []);
321
+ ck("Literal", []);
322
+ ck("Literal", []);
323
+ ck("ThisExpression", []);
324
+ ck("Literal", []);
325
+ ck("TemplateLiteral", ["quasis", "expressions"]);
326
+ ck("TemplateElement", []);
327
+ ck("Identifier", []);
328
+ ck("PrivateIdentifier", []);
329
+ ck("Identifier", ["decorators", "typeAnnotation"]);
330
+ ck("Identifier", []);
331
+ ck("Identifier", []);
332
+ ck("ExpressionStatement", ["expression"]);
333
+ ck("IfStatement", [
334
+ "test",
335
+ "consequent",
336
+ "alternate"
337
+ ]);
338
+ ck("SwitchStatement", ["discriminant", "cases"]);
339
+ ck("SwitchCase", ["test", "consequent"]);
340
+ ck("ForStatement", [
341
+ "init",
342
+ "test",
343
+ "update",
344
+ "body"
345
+ ]);
346
+ ck("ForInStatement", [
347
+ "left",
348
+ "right",
349
+ "body"
350
+ ]);
351
+ ck("ForOfStatement", [
352
+ "left",
353
+ "right",
354
+ "body"
355
+ ]);
356
+ ck("WhileStatement", ["test", "body"]);
357
+ ck("DoWhileStatement", ["body", "test"]);
358
+ ck("BreakStatement", ["label"]);
359
+ ck("ContinueStatement", ["label"]);
360
+ ck("LabeledStatement", ["label", "body"]);
361
+ ck("WithStatement", ["object", "body"]);
362
+ ck("ReturnStatement", ["argument"]);
363
+ ck("ThrowStatement", ["argument"]);
364
+ ck("TryStatement", [
365
+ "block",
366
+ "handler",
367
+ "finalizer"
368
+ ]);
369
+ ck("CatchClause", ["param", "body"]);
370
+ ck("DebuggerStatement", []);
371
+ ck("EmptyStatement", []);
372
+ ck("VariableDeclaration", ["declarations"]);
373
+ ck("VariableDeclarator", ["id", "init"]);
374
+ ck("ExpressionStatement", ["expression"]);
375
+ ck("AssignmentPattern", [
376
+ "decorators",
377
+ "left",
378
+ "typeAnnotation",
379
+ "right"
380
+ ]);
381
+ ck("RestElement", [
382
+ "decorators",
383
+ "argument",
384
+ "typeAnnotation"
385
+ ]);
386
+ ck("ArrayPattern", [
387
+ "decorators",
388
+ "elements",
389
+ "typeAnnotation"
390
+ ]);
391
+ ck("ObjectPattern", [
392
+ "decorators",
393
+ "properties",
394
+ "typeAnnotation"
395
+ ]);
396
+ ck("Property", ["key", "value"]);
397
+ ck("Program", ["hashbang", "body"]);
398
+ ck("ImportExpression", ["source", "options"]);
399
+ ck("ImportDeclaration", [
400
+ "specifiers",
401
+ "source",
402
+ "attributes"
403
+ ]);
404
+ ck("ImportSpecifier", ["imported", "local"]);
405
+ ck("ImportDefaultSpecifier", ["local"]);
406
+ ck("ImportNamespaceSpecifier", ["local"]);
407
+ ck("ImportAttribute", ["key", "value"]);
408
+ ck("ExportNamedDeclaration", [
409
+ "declaration",
410
+ "specifiers",
411
+ "source",
412
+ "attributes"
413
+ ]);
414
+ ck("ExportDefaultDeclaration", ["declaration"]);
415
+ ck("ExportAllDeclaration", [
416
+ "exported",
417
+ "source",
418
+ "attributes"
419
+ ]);
420
+ ck("ExportSpecifier", ["local", "exported"]);
421
+ ck("TSTypeAnnotation", ["typeAnnotation"]);
422
+ ck("TSAnyKeyword", []);
423
+ ck("TSUnknownKeyword", []);
424
+ ck("TSNeverKeyword", []);
425
+ ck("TSVoidKeyword", []);
426
+ ck("TSNullKeyword", []);
427
+ ck("TSUndefinedKeyword", []);
428
+ ck("TSStringKeyword", []);
429
+ ck("TSNumberKeyword", []);
430
+ ck("TSBigIntKeyword", []);
431
+ ck("TSBooleanKeyword", []);
432
+ ck("TSSymbolKeyword", []);
433
+ ck("TSObjectKeyword", []);
434
+ ck("TSIntrinsicKeyword", []);
435
+ ck("TSThisType", []);
436
+ ck("TSTypeReference", ["typeName", "typeArguments"]);
437
+ ck("TSQualifiedName", ["left", "right"]);
438
+ ck("TSTypeQuery", ["exprName", "typeArguments"]);
439
+ ck("TSImportType", [
440
+ "source",
441
+ "options",
442
+ "qualifier",
443
+ "typeArguments"
444
+ ]);
445
+ ck("TSTypeParameter", [
446
+ "name",
447
+ "constraint",
448
+ "default"
449
+ ]);
450
+ ck("TSTypeParameterDeclaration", ["params"]);
451
+ ck("TSTypeParameterInstantiation", ["params"]);
452
+ ck("TSLiteralType", ["literal"]);
453
+ ck("TSTemplateLiteralType", ["quasis", "types"]);
454
+ ck("TSArrayType", ["elementType"]);
455
+ ck("TSIndexedAccessType", ["objectType", "indexType"]);
456
+ ck("TSTupleType", ["elementTypes"]);
457
+ ck("TSNamedTupleMember", ["label", "elementType"]);
458
+ ck("TSOptionalType", ["typeAnnotation"]);
459
+ ck("TSRestType", ["typeAnnotation"]);
460
+ ck("TSJSDocNullableType", ["typeAnnotation"]);
461
+ ck("TSJSDocNonNullableType", ["typeAnnotation"]);
462
+ ck("TSJSDocUnknownType", []);
463
+ ck("TSUnionType", ["types"]);
464
+ ck("TSIntersectionType", ["types"]);
465
+ ck("TSConditionalType", [
466
+ "checkType",
467
+ "extendsType",
468
+ "trueType",
469
+ "falseType"
470
+ ]);
471
+ ck("TSInferType", ["typeParameter"]);
472
+ ck("TSTypeOperator", ["typeAnnotation"]);
473
+ ck("TSParenthesizedType", ["typeAnnotation"]);
474
+ ck("TSFunctionType", [
475
+ "typeParameters",
476
+ "params",
477
+ "returnType"
478
+ ]);
479
+ ck("TSConstructorType", [
480
+ "typeParameters",
481
+ "params",
482
+ "returnType"
483
+ ]);
484
+ ck("TSTypePredicate", ["parameterName", "typeAnnotation"]);
485
+ ck("TSTypeLiteral", ["members"]);
486
+ ck("TSMappedType", [
487
+ "key",
488
+ "constraint",
489
+ "nameType",
490
+ "typeAnnotation"
491
+ ]);
492
+ ck("TSPropertySignature", ["key", "typeAnnotation"]);
493
+ ck("TSMethodSignature", [
494
+ "key",
495
+ "typeParameters",
496
+ "params",
497
+ "returnType"
498
+ ]);
499
+ ck("TSCallSignatureDeclaration", [
500
+ "typeParameters",
501
+ "params",
502
+ "returnType"
503
+ ]);
504
+ ck("TSConstructSignatureDeclaration", [
505
+ "typeParameters",
506
+ "params",
507
+ "returnType"
508
+ ]);
509
+ ck("TSIndexSignature", ["parameters", "typeAnnotation"]);
510
+ ck("TSTypeAliasDeclaration", [
511
+ "id",
512
+ "typeParameters",
513
+ "typeAnnotation"
514
+ ]);
515
+ ck("TSInterfaceDeclaration", [
516
+ "id",
517
+ "typeParameters",
518
+ "extends",
519
+ "body"
520
+ ]);
521
+ ck("TSInterfaceBody", ["body"]);
522
+ ck("TSInterfaceHeritage", ["expression", "typeArguments"]);
523
+ ck("TSClassImplements", ["expression", "typeArguments"]);
524
+ ck("TSEnumDeclaration", ["id", "body"]);
525
+ ck("TSEnumBody", ["members"]);
526
+ ck("TSEnumMember", ["id", "initializer"]);
527
+ ck("TSModuleDeclaration", ["id", "body"]);
528
+ ck("TSModuleBlock", ["body"]);
529
+ ck("TSModuleDeclaration", ["id", "body"]);
530
+ ck("TSParameterProperty", ["decorators", "parameter"]);
531
+ ck("Identifier", ["typeAnnotation"]);
532
+ ck("TSAsExpression", ["expression", "typeAnnotation"]);
533
+ ck("TSSatisfiesExpression", ["expression", "typeAnnotation"]);
534
+ ck("TSTypeAssertion", ["typeAnnotation", "expression"]);
535
+ ck("TSNonNullExpression", ["expression"]);
536
+ ck("TSInstantiationExpression", ["expression", "typeArguments"]);
537
+ ck("TSExportAssignment", ["expression"]);
538
+ ck("TSNamespaceExportDeclaration", ["id"]);
539
+ ck("TSImportEqualsDeclaration", ["id", "moduleReference"]);
540
+ ck("TSExternalModuleReference", ["expression"]);
541
+ ck("JSXElement", [
542
+ "openingElement",
543
+ "children",
544
+ "closingElement"
545
+ ]);
546
+ ck("JSXOpeningElement", [
547
+ "name",
548
+ "typeArguments",
549
+ "attributes"
550
+ ]);
551
+ ck("JSXClosingElement", ["name"]);
552
+ ck("JSXFragment", [
553
+ "openingFragment",
554
+ "children",
555
+ "closingFragment"
556
+ ]);
557
+ ck("JSXOpeningFragment", []);
558
+ ck("JSXClosingFragment", []);
559
+ ck("JSXIdentifier", []);
560
+ ck("JSXNamespacedName", ["namespace", "name"]);
561
+ ck("JSXMemberExpression", ["object", "property"]);
562
+ ck("JSXAttribute", ["name", "value"]);
563
+ ck("JSXSpreadAttribute", ["argument"]);
564
+ ck("JSXExpressionContainer", ["expression"]);
565
+ ck("JSXEmptyExpression", []);
566
+ ck("JSXText", []);
567
+ ck("JSXSpreadChild", ["expression"]);
568
+ ck("Hashbang", []);
569
+ const CHILD_KEYS = KEYS;
570
+ const NODE_TYPES = [.../* @__PURE__ */ new Set([
1624
571
  "SequenceExpression",
1625
572
  "ParenthesizedExpression",
573
+ "ArrowFunctionExpression",
574
+ "FunctionDeclaration",
575
+ "FunctionExpression",
576
+ "TSDeclareFunction",
577
+ "TSEmptyBodyFunctionExpression",
578
+ "BlockStatement",
579
+ "BlockStatement",
1626
580
  "BinaryExpression",
1627
581
  "LogicalExpression",
1628
582
  "ConditionalExpression",
1629
583
  "UnaryExpression",
1630
584
  "UpdateExpression",
1631
585
  "AssignmentExpression",
1632
- "YieldExpression",
1633
- "AwaitExpression",
1634
586
  "ArrayExpression",
1635
587
  "ObjectExpression",
1636
588
  "SpreadElement",
589
+ "Property",
1637
590
  "MemberExpression",
1638
591
  "CallExpression",
1639
592
  "ChainExpression",
1640
593
  "TaggedTemplateExpression",
1641
594
  "NewExpression",
595
+ "AwaitExpression",
596
+ "YieldExpression",
1642
597
  "MetaProperty",
1643
- "ImportExpression",
598
+ "Decorator",
599
+ "ClassDeclaration",
600
+ "ClassExpression",
601
+ "ClassBody",
602
+ "MethodDefinition",
603
+ "TSAbstractMethodDefinition",
604
+ "PropertyDefinition",
605
+ "AccessorProperty",
606
+ "TSAbstractPropertyDefinition",
607
+ "TSAbstractAccessorProperty",
608
+ "StaticBlock",
609
+ "Super",
610
+ "Literal",
611
+ "Literal",
612
+ "Literal",
613
+ "Literal",
614
+ "Literal",
615
+ "ThisExpression",
616
+ "Literal",
1644
617
  "TemplateLiteral",
618
+ "TemplateElement",
619
+ "Identifier",
620
+ "PrivateIdentifier",
621
+ "Identifier",
622
+ "Identifier",
623
+ "Identifier",
1645
624
  "ExpressionStatement",
1646
- "BlockStatement",
1647
625
  "IfStatement",
1648
626
  "SwitchStatement",
1649
627
  "SwitchCase",
@@ -1664,22 +642,14 @@ const NODE_TYPES = [
1664
642
  "EmptyStatement",
1665
643
  "VariableDeclaration",
1666
644
  "VariableDeclarator",
1667
- "FunctionDeclaration",
1668
- "FunctionExpression",
1669
- "TSDeclareFunction",
1670
- "TSEmptyBodyFunctionExpression",
1671
- "ArrowFunctionExpression",
1672
- "ClassDeclaration",
1673
- "ClassExpression",
1674
- "ClassBody",
1675
- "MethodDefinition",
1676
- "TSAbstractMethodDefinition",
1677
- "PropertyDefinition",
1678
- "TSAbstractPropertyDefinition",
1679
- "AccessorProperty",
1680
- "TSAbstractAccessorProperty",
1681
- "StaticBlock",
1682
- "Decorator",
645
+ "ExpressionStatement",
646
+ "AssignmentPattern",
647
+ "RestElement",
648
+ "ArrayPattern",
649
+ "ObjectPattern",
650
+ "Property",
651
+ "Program",
652
+ "ImportExpression",
1683
653
  "ImportDeclaration",
1684
654
  "ImportSpecifier",
1685
655
  "ImportDefaultSpecifier",
@@ -1689,21 +659,6 @@ const NODE_TYPES = [
1689
659
  "ExportDefaultDeclaration",
1690
660
  "ExportAllDeclaration",
1691
661
  "ExportSpecifier",
1692
- "JSXElement",
1693
- "JSXOpeningElement",
1694
- "JSXClosingElement",
1695
- "JSXFragment",
1696
- "JSXOpeningFragment",
1697
- "JSXClosingFragment",
1698
- "JSXIdentifier",
1699
- "JSXNamespacedName",
1700
- "JSXMemberExpression",
1701
- "JSXAttribute",
1702
- "JSXSpreadAttribute",
1703
- "JSXExpressionContainer",
1704
- "JSXEmptyExpression",
1705
- "JSXText",
1706
- "JSXSpreadChild",
1707
662
  "TSTypeAnnotation",
1708
663
  "TSAnyKeyword",
1709
664
  "TSUnknownKeyword",
@@ -1763,7 +718,9 @@ const NODE_TYPES = [
1763
718
  "TSEnumMember",
1764
719
  "TSModuleDeclaration",
1765
720
  "TSModuleBlock",
721
+ "TSModuleDeclaration",
1766
722
  "TSParameterProperty",
723
+ "Identifier",
1767
724
  "TSAsExpression",
1768
725
  "TSSatisfiesExpression",
1769
726
  "TSTypeAssertion",
@@ -1772,17 +729,150 @@ const NODE_TYPES = [
1772
729
  "TSExportAssignment",
1773
730
  "TSNamespaceExportDeclaration",
1774
731
  "TSImportEqualsDeclaration",
1775
- "TSExternalModuleReference"
1776
- ];
732
+ "TSExternalModuleReference",
733
+ "JSXElement",
734
+ "JSXOpeningElement",
735
+ "JSXClosingElement",
736
+ "JSXFragment",
737
+ "JSXOpeningFragment",
738
+ "JSXClosingFragment",
739
+ "JSXIdentifier",
740
+ "JSXNamespacedName",
741
+ "JSXMemberExpression",
742
+ "JSXAttribute",
743
+ "JSXSpreadAttribute",
744
+ "JSXExpressionContainer",
745
+ "JSXEmptyExpression",
746
+ "JSXText",
747
+ "JSXSpreadChild",
748
+ "Hashbang"
749
+ ])];
750
+ /**
751
+ * One constructor per node type, its fields derived from the node type
752
+ * itself. `start` and `end` default to 0, which `ctx.replace` treats
753
+ * as span-less and fills from the replaced node.
754
+ *
755
+ * @example
756
+ * b.Identifier({ name: "x" })
757
+ * b.ExpressionStatement({ expression: b.Identifier({ name: "x" }) })
758
+ */
759
+ const b = Object.fromEntries(NODE_TYPES.map((type) => [type, (fields) => ({
760
+ type,
761
+ start: 0,
762
+ end: 0,
763
+ ...fields
764
+ })]));
765
+ /**
766
+ * The walk context: one reused object exposing the current position and
767
+ * the tree mutation operations. Valid only during the visit that
768
+ * receives it, do not store it. Underscore members are engine state.
769
+ */
770
+ var WalkContext = class {
771
+ _ancestors = [];
772
+ _node = null;
773
+ _key = null;
774
+ _list = null;
775
+ _frame = null;
776
+ _skip = false;
777
+ _stopped = false;
778
+ _removed = false;
779
+ _replacement = null;
780
+ /** State threaded through the walk, the third `walk` argument. */
781
+ state;
782
+ /** The node being visited. */
783
+ get node() {
784
+ return this._node;
785
+ }
786
+ /** The node holding {@link node}, or null at the walk root. */
787
+ get parent() {
788
+ const a = this._ancestors;
789
+ return a.length === 0 ? null : a[a.length - 1];
790
+ }
791
+ /** The field on {@link parent} holding {@link node}, or null at the root. */
792
+ get key() {
793
+ return this._key;
794
+ }
795
+ /** Index within an array field, or null in a plain field. */
796
+ get index() {
797
+ return this._list === null ? null : this._frame.i;
798
+ }
799
+ /** Ancestors from the walk root down to {@link parent}. */
800
+ ancestors() {
801
+ return [...this._ancestors];
802
+ }
803
+ /** Do not descend into the current node's children. */
804
+ skip() {
805
+ this._skip = true;
806
+ }
807
+ /** Stop the walk entirely. */
808
+ stop() {
809
+ this._stopped = true;
810
+ }
811
+ /**
812
+ * Replace the current node. The walk continues into the replacement's
813
+ * children and `leave` fires for the replacement's type. A synthetic
814
+ * node with `start === 0 && end === 0` inherits the original span,
815
+ * for source maps. Throws at the walk root.
816
+ */
817
+ replace(node) {
818
+ if (node === null || typeof node !== "object" || typeof node.type !== "string") throw new TypeError("replace: expected an AST node");
819
+ if (this.parent === null) throw new TypeError("replace: cannot replace the walk root");
820
+ if (node.start === 0 && node.end === 0) {
821
+ node.start = this.node.start;
822
+ node.end = this.node.end;
823
+ }
824
+ this._replacement = node;
825
+ }
826
+ /**
827
+ * Remove the current node from its parent: spliced from array fields,
828
+ * nulled in plain fields. Children are not walked and `leave` does
829
+ * not fire. Throws at the walk root.
830
+ */
831
+ remove() {
832
+ if (this.parent === null) throw new TypeError("remove: cannot remove the walk root");
833
+ this._removed = true;
834
+ }
835
+ /** Insert a sibling before the current node, not visited. Array fields only. */
836
+ insertBefore(node) {
837
+ this.#insert(node, 0);
838
+ this._frame.i++;
839
+ }
840
+ /** Insert a sibling after the current node, visited by the walk. Array fields only. */
841
+ insertAfter(node) {
842
+ this.#insert(node, 1);
843
+ }
844
+ #insert(node, offset) {
845
+ if (this._list === null) throw new TypeError("insertBefore/insertAfter require a node in an array field");
846
+ this._list.splice(this._frame.i + offset, 0, node);
847
+ }
848
+ };
849
+ const IDENTIFIER_NAME = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
850
+ /**
851
+ * True if `name` is a valid ECMAScript `IdentifierName`, the grammar an
852
+ * identifier token must satisfy. Validates a raw string, not a node.
853
+ * Reserved words are syntactically identifier names, so
854
+ * `isIdentifierName("class")` is true, see {@link isValidIdentifier}.
855
+ */
856
+ function isIdentifierName(name) {
857
+ return IDENTIFIER_NAME.test(name);
858
+ }
1777
859
  function aliasGuard(name) {
1778
860
  const set = new Set(ALIAS_GROUPS[name]);
1779
861
  return (node) => node != null && set.has(node.type);
1780
862
  }
863
+ /**
864
+ * Type guards, one per concrete node `type` plus alias and shape
865
+ * guards. Every guard accepts `null` and `undefined` and narrows.
866
+ *
867
+ * @example
868
+ * is.CallExpression(node)
869
+ * is.Identifier(node, "require")
870
+ * is.Expression(node)
871
+ * is.StringLiteral(node)
872
+ */
1781
873
  const is = {
1782
874
  ...Object.fromEntries(NODE_TYPES.map((type) => [type, (node) => node != null && node.type === type])),
1783
- /** True when `node`'s `type` is one of `types`, narrowing to that union. */
1784
- oneOf: (node, types) => node != null && types.includes(node.type),
1785
- /** An `Identifier`, optionally with the exact `name` (e.g. `is.Identifier(node, "this")`). */
875
+ oneOf: (node, types) => node != null && types.some((type) => type === node.type),
1786
876
  Identifier: (node, name) => node?.type === "Identifier" && (name === void 0 || node.name === name),
1787
877
  Expression: aliasGuard("Expression"),
1788
878
  Statement: aliasGuard("Statement"),
@@ -1806,38 +896,195 @@ const is = {
1806
896
  PrivateFieldExpression: (node) => node?.type === "MemberExpression" && node.property.type === "PrivateIdentifier",
1807
897
  Directive: (node) => node?.type === "ExpressionStatement" && node.directive != null
1808
898
  };
1809
- //#endregion
1810
- //#region ../../node_modules/.pnpm/yuku-ast@0.1.7/node_modules/yuku-ast/dist/identifier.mjs
1811
- const IDENTIFIER_NAME = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
899
+ function createDispatch(visitors) {
900
+ let enter = null;
901
+ let leave = null;
902
+ const concrete$1 = /* @__PURE__ */ new Map();
903
+ const add = (type, handler) => {
904
+ const hooks = typeof handler === "function" ? { enter: handler } : handler;
905
+ let entry = concrete$1.get(type);
906
+ if (entry === void 0) {
907
+ entry = {
908
+ enter: [],
909
+ leave: []
910
+ };
911
+ concrete$1.set(type, entry);
912
+ }
913
+ if (hooks.enter) entry.enter.push(hooks.enter);
914
+ if (hooks.leave) entry.leave.unshift(hooks.leave);
915
+ };
916
+ for (const [name, value] of Object.entries(visitors)) {
917
+ if (value == null) continue;
918
+ if (name === "enter") enter = value;
919
+ else if (name === "leave") leave = value;
920
+ else if (name in ALIAS_GROUPS) for (const type of ALIAS_GROUPS[name]) add(type, value);
921
+ }
922
+ for (const [name, value] of Object.entries(visitors)) {
923
+ if (value == null || name === "enter" || name === "leave" || name in ALIAS_GROUPS) continue;
924
+ add(name, value);
925
+ }
926
+ return {
927
+ enter,
928
+ leave,
929
+ typed: (type) => concrete$1.get(type)
930
+ };
931
+ }
1812
932
  /**
1813
- * Returns `true` if `name` is a valid ECMAScript `IdentifierName`: the grammar
1814
- * an identifier token must satisfy. Validates a raw string, not an AST node.
1815
- *
1816
- * @example
1817
- * isIdentifierName("foo"); // true
1818
- * isIdentifierName("$_0"); // true
1819
- * isIdentifierName("π"); // true
1820
- * isIdentifierName("class"); // true - syntactically an IdentifierName
1821
- * isIdentifierName("1foo"); // false - starts with a digit
1822
- * isIdentifierName("foo-bar"); // false - `-` is not an identifier character
1823
- * isIdentifierName(""); // false
933
+ * Walk an AST depth-first, dispatching to typed visitors and mutating
934
+ * in place. Traversal order is driven by tables generated from the
935
+ * parser's AST definition, so it can never drift. Returns the root.
1824
936
  */
1825
- function isIdentifierName(name) {
1826
- return IDENTIFIER_NAME.test(name);
937
+ function walk(root, visitors, state) {
938
+ _walk(root, visitors, state, new WalkContext());
939
+ return root;
1827
940
  }
1828
- //#endregion
1829
- //#region ../../node_modules/.pnpm/yuku-ast@0.1.7/node_modules/yuku-ast/dist/utils.mjs
1830
941
  /**
1831
- * The static name a node denotes: an `Identifier`'s `name`, or a string
1832
- * `Literal`'s `value`. Returns `null` for anything else, and for `null` or
1833
- * `undefined`, so the common `Identifier | StringLiteral` name slots (a
1834
- * `ModuleExportName`, or a static property or member key) read in one call.
1835
- *
1836
- * @example
1837
- * nameOf(b.identifier("x")) // "x"
1838
- * nameOf(b.stringLiteral("y")) // "y"
1839
- * nameOf(b.numericLiteral(1)) // null
942
+ * The async counterpart of {@link walk}: identical traversal order and
943
+ * mutation semantics, with every handler awaited before the walk moves
944
+ * on. Resolves to the root.
1840
945
  */
946
+ async function walkAsync(root, visitors, state) {
947
+ await _walkAsync(root, visitors, state, new WalkContext());
948
+ return root;
949
+ }
950
+ function position(ctx, node, key, list, frame) {
951
+ ctx._node = node;
952
+ ctx._key = key;
953
+ ctx._list = list;
954
+ ctx._frame = frame;
955
+ }
956
+ function applyReplace(ctx, parent, key, list, frame) {
957
+ const next = ctx._replacement;
958
+ ctx._replacement = null;
959
+ if (list !== null) list[frame.i] = next;
960
+ else parent[key] = next;
961
+ return next;
962
+ }
963
+ function applyRemove(ctx, parent, key, list, frame) {
964
+ ctx._removed = false;
965
+ if (list !== null) {
966
+ list.splice(frame.i, 1);
967
+ frame.i--;
968
+ } else parent[key] = null;
969
+ }
970
+ function _walk(root, visitors, state, ctx) {
971
+ const d = createDispatch(visitors);
972
+ ctx.state = state;
973
+ const ancestors = ctx._ancestors;
974
+ (function visit(node, key, list, frame) {
975
+ let typed = d.typed(node.type);
976
+ const parent = ctx.parent;
977
+ position(ctx, node, key, list, frame);
978
+ if (d.enter !== null) {
979
+ d.enter(node, ctx);
980
+ if (ctx._stopped) return false;
981
+ }
982
+ if (typed !== void 0) for (const handler of typed.enter) {
983
+ handler(node, ctx);
984
+ if (ctx._stopped) return false;
985
+ }
986
+ if (ctx._removed) {
987
+ applyRemove(ctx, parent, key, list, frame);
988
+ return true;
989
+ }
990
+ if (ctx._replacement !== null) {
991
+ node = applyReplace(ctx, parent, key, list, frame);
992
+ typed = d.typed(node.type);
993
+ }
994
+ const skipped = ctx._skip;
995
+ ctx._skip = false;
996
+ if (!skipped) {
997
+ const keys = CHILD_KEYS[node.type];
998
+ if (keys !== void 0 && keys.length > 0) {
999
+ ancestors.push(node);
1000
+ for (let k = 0; k < keys.length; k++) {
1001
+ const key2 = keys[k];
1002
+ const value = node[key2];
1003
+ if (value === null || value === void 0 || typeof value !== "object") continue;
1004
+ if (Array.isArray(value)) {
1005
+ const childFrame = { i: 0 };
1006
+ for (; childFrame.i < value.length; childFrame.i++) {
1007
+ const item = value[childFrame.i];
1008
+ if (item !== null && !visit(item, key2, value, childFrame)) return false;
1009
+ }
1010
+ } else if (!visit(value, key2, null, null)) return false;
1011
+ }
1012
+ ancestors.pop();
1013
+ }
1014
+ }
1015
+ position(ctx, node, key, list, frame);
1016
+ if (typed !== void 0) for (const handler of typed.leave) {
1017
+ handler(node, ctx);
1018
+ if (ctx._stopped) return false;
1019
+ }
1020
+ if (d.leave !== null) {
1021
+ d.leave(node, ctx);
1022
+ if (ctx._stopped) return false;
1023
+ }
1024
+ if (ctx._removed) applyRemove(ctx, parent, key, list, frame);
1025
+ else if (ctx._replacement !== null) applyReplace(ctx, parent, key, list, frame);
1026
+ return true;
1027
+ })(root, null, null, null);
1028
+ }
1029
+ async function _walkAsync(root, visitors, state, ctx) {
1030
+ const d = createDispatch(visitors);
1031
+ ctx.state = state;
1032
+ const ancestors = ctx._ancestors;
1033
+ await (async function visit(node, key, list, frame) {
1034
+ let typed = d.typed(node.type);
1035
+ const parent = ctx.parent;
1036
+ position(ctx, node, key, list, frame);
1037
+ if (d.enter !== null) {
1038
+ await d.enter(node, ctx);
1039
+ if (ctx._stopped) return false;
1040
+ }
1041
+ if (typed !== void 0) for (const handler of typed.enter) {
1042
+ await handler(node, ctx);
1043
+ if (ctx._stopped) return false;
1044
+ }
1045
+ if (ctx._removed) {
1046
+ applyRemove(ctx, parent, key, list, frame);
1047
+ return true;
1048
+ }
1049
+ if (ctx._replacement !== null) {
1050
+ node = applyReplace(ctx, parent, key, list, frame);
1051
+ typed = d.typed(node.type);
1052
+ }
1053
+ const skipped = ctx._skip;
1054
+ ctx._skip = false;
1055
+ if (!skipped) {
1056
+ const keys = CHILD_KEYS[node.type];
1057
+ if (keys !== void 0 && keys.length > 0) {
1058
+ ancestors.push(node);
1059
+ for (let k = 0; k < keys.length; k++) {
1060
+ const key2 = keys[k];
1061
+ const value = node[key2];
1062
+ if (value === null || value === void 0 || typeof value !== "object") continue;
1063
+ if (Array.isArray(value)) {
1064
+ const childFrame = { i: 0 };
1065
+ for (; childFrame.i < value.length; childFrame.i++) {
1066
+ const item = value[childFrame.i];
1067
+ if (item !== null && !await visit(item, key2, value, childFrame)) return false;
1068
+ }
1069
+ } else if (!await visit(value, key2, null, null)) return false;
1070
+ }
1071
+ ancestors.pop();
1072
+ }
1073
+ }
1074
+ position(ctx, node, key, list, frame);
1075
+ if (typed !== void 0) for (const handler of typed.leave) {
1076
+ await handler(node, ctx);
1077
+ if (ctx._stopped) return false;
1078
+ }
1079
+ if (d.leave !== null) {
1080
+ await d.leave(node, ctx);
1081
+ if (ctx._stopped) return false;
1082
+ }
1083
+ if (ctx._removed) applyRemove(ctx, parent, key, list, frame);
1084
+ else if (ctx._replacement !== null) applyReplace(ctx, parent, key, list, frame);
1085
+ return true;
1086
+ })(root, null, null, null);
1087
+ }
1841
1088
  function nameOf(node) {
1842
1089
  if (node == null) return null;
1843
1090
  if (node.type === "Identifier") return node.name;
@@ -1957,7 +1204,7 @@ function ensureValue(value) {
1957
1204
  return value && ALLOW_EXTENSIONS.has(extname(value)) ? value.replaceAll("\\", "/") : null;
1958
1205
  }
1959
1206
  //#endregion
1960
- //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.27.9_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_9f43f644337e3a4030148b21b794fdcf/node_modules/rolldown-plugin-dts/dist/index.mjs
1207
+ //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.27.13_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolve_bb5be7aebc807a8d600edaae098a2d6b/node_modules/rolldown-plugin-dts/dist/index.mjs
1961
1208
  function createDtsInputPlugin({ sideEffects }) {
1962
1209
  return {
1963
1210
  name: "rolldown-plugin-dts:dts-input",
@@ -1990,1056 +1237,1221 @@ function createDtsInputPlugin({ sideEffects }) {
1990
1237
  }
1991
1238
  };
1992
1239
  }
1993
- function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }) {
1994
- let declarationIdx = 0;
1995
- const declarationMap = /* @__PURE__ */ new Map();
1996
- const commentsMap = /* @__PURE__ */ new Map();
1997
- const moduleExportsMap = /* @__PURE__ */ new Map();
1998
- const warnedCjsDtsInputs = /* @__PURE__ */ new Set();
1240
+ const require$1 = createRequire(import.meta.url);
1241
+ const debug$5 = createDebug("rolldown-plugin-dts:tsgo");
1242
+ function isTS70Installed() {
1243
+ try {
1244
+ const { versionMajorMinor } = require$1("typescript");
1245
+ return versionMajorMinor === "7.0";
1246
+ } catch {}
1247
+ return false;
1248
+ }
1249
+ const spawnAsync = (...args) => new Promise((resolve, reject) => {
1250
+ const child = spawn(...args);
1251
+ child.on("close", () => resolve());
1252
+ child.on("error", (error) => reject(error));
1253
+ });
1254
+ let tsgoPathCache;
1255
+ async function getTsgoPathFromNodeModules(logger) {
1256
+ if (tsgoPathCache) return tsgoPathCache;
1257
+ const pkgName = isTS70Installed() ? "typescript" : "@typescript/native-preview";
1258
+ const tsgoPkg = import.meta.resolve(`${pkgName}/package.json`);
1259
+ const { default: { version } } = await import(tsgoPkg, { with: { type: "json" } });
1260
+ logger.info(`Emit types with ${styleText("underline", `${pkgName}@${version}`)}`);
1261
+ const { default: getExePath } = await import(new URL("lib/getExePath.js", tsgoPkg).href);
1262
+ return tsgoPathCache = getExePath();
1263
+ }
1264
+ async function runTsgo(logger, rootDir, tsconfig, sourcemap, tsgoPath) {
1265
+ debug$5("[tsgo] rootDir", rootDir);
1266
+ let tsgo;
1267
+ if (tsgoPath) {
1268
+ tsgo = tsgoPath;
1269
+ debug$5("[tsgo] using custom path", tsgo);
1270
+ } else {
1271
+ tsgo = await getTsgoPathFromNodeModules(logger);
1272
+ debug$5("[tsgo] using tsgo from node_modules", tsgo);
1273
+ }
1274
+ const tsgoDist = await mkdtemp(path.join(tmpdir(), "rolldown-plugin-dts-"));
1275
+ debug$5("[tsgo] tsgoDist", tsgoDist);
1276
+ const args = [
1277
+ "--noEmit",
1278
+ "false",
1279
+ "--declaration",
1280
+ "--emitDeclarationOnly",
1281
+ "-p",
1282
+ tsconfig,
1283
+ "--outDir",
1284
+ tsgoDist,
1285
+ "--rootDir",
1286
+ rootDir,
1287
+ "--noCheck",
1288
+ ...sourcemap ? ["--declarationMap"] : []
1289
+ ];
1290
+ debug$5("[tsgo] args %o", args);
1291
+ await spawnAsync(tsgo, args, { stdio: "inherit" });
1292
+ return {
1293
+ path: tsgoDist,
1294
+ async dispose() {
1295
+ if (debug$5.enabled) debug$5("[tsgo] skip cleanup of tsgoDist", tsgoDist);
1296
+ else {
1297
+ debug$5("[tsgo] disposing tsgoDist", tsgoDist);
1298
+ await rm(tsgoDist, {
1299
+ recursive: true,
1300
+ force: true
1301
+ }).catch(() => {});
1302
+ }
1303
+ }
1304
+ };
1305
+ }
1306
+ const debug$4 = createDebug("rolldown-plugin-dts:generate");
1307
+ const WORKER_URL = "./tsc-worker.mjs";
1308
+ const EMPTY_STUB = `export {}`;
1309
+ function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build, incremental, cwd, oxc, emitDtsOnly, volarContext, parallel, eager, tsgo, newContext, emitJs, sourcemap, logger }) {
1310
+ const entryIncludes = entry?.filter((p) => p[0] !== "!");
1311
+ const entryIgnores = entry?.filter((p) => p[0] === "!").map((p) => p.slice(1));
1312
+ const entryMatcher = entry ? (file) => entryIncludes.some((p) => path.matchesGlob(file, p)) && !entryIgnores.some((p) => path.matchesGlob(file, p)) : void 0;
1313
+ const dtsMap = /* @__PURE__ */ new Map();
1314
+ /**
1315
+ * A map of input id to output file name
1316
+ *
1317
+ * @example
1318
+ *
1319
+ * inputAlias = new Map([
1320
+ * ['/absolute/path/to/src/source_file.ts', 'dist/foo/index'],
1321
+ * ])
1322
+ */
1323
+ const inputAliasMap = /* @__PURE__ */ new Map();
1324
+ let tscWorker;
1325
+ let tscModule;
1326
+ let tscContext;
1327
+ let tsgoContext;
1328
+ const rootDir = tsconfig ? path.dirname(tsconfig) : cwd;
1999
1329
  return {
2000
- name: "rolldown-plugin-dts:fake-js",
1330
+ name: "rolldown-plugin-dts:generate",
1331
+ async buildStart(options) {
1332
+ if (generator === "tsgo") tsgoContext = await runTsgo(logger, rootDir, tsconfig, sourcemap, tsgo.path);
1333
+ else if (generator === "tsc") if (parallel) tscWorker = createTscWorker();
1334
+ else {
1335
+ tscModule = await import("./tsc-BQoNcjeB.js");
1336
+ if (newContext) tscContext = createContext();
1337
+ }
1338
+ if (!Array.isArray(options.input)) for (const [name, id] of Object.entries(options.input)) {
1339
+ debug$4("resolving input alias %s -> %s", name, id);
1340
+ let resolved = await this.resolve(id);
1341
+ if (!id.startsWith("./")) resolved ||= await this.resolve(`./${id}`);
1342
+ const resolvedId = resolved?.id || id;
1343
+ debug$4("resolved input alias %s -> %s", id, resolvedId);
1344
+ inputAliasMap.set(resolvedId, name);
1345
+ }
1346
+ },
2001
1347
  outputOptions(options) {
2002
- if (options.format === "cjs" || options.format === "commonjs") throw new Error("[rolldown-plugin-dts] Cannot bundle dts files with `cjs` format.");
2003
- const { chunkFileNames, entryFileNames } = options;
2004
1348
  return {
2005
1349
  ...options,
2006
- sourcemap: options.sourcemap || sourcemap,
2007
- chunkFileNames(chunk) {
2008
- const nameTemplate = resolveTemplateFn(chunk.isEntry ? entryFileNames || "[name].js" : chunkFileNames || "[name]-[hash].js", chunk);
1350
+ entryFileNames(chunk) {
1351
+ const { entryFileNames } = options;
1352
+ const nameTemplate = resolveTemplateFn(entryFileNames || "[name].js", chunk);
2009
1353
  if (chunk.name.endsWith(".d")) {
2010
- const renderedNameWithoutD = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name.slice(0, -2)));
2011
- if (RE_DTS.test(renderedNameWithoutD)) return renderedNameWithoutD;
2012
- const renderedName = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name));
2013
- if (RE_DTS.test(renderedName)) return renderedName;
1354
+ if (RE_DTS.test(nameTemplate)) return replaceTemplateName(nameTemplate, chunk.name.slice(0, -2));
1355
+ if (RE_JS.test(nameTemplate)) return nameTemplate.replace(RE_JS, ".$1ts");
2014
1356
  }
2015
1357
  return nameTemplate;
2016
1358
  }
2017
1359
  };
2018
1360
  },
2019
- transform: {
2020
- filter: { id: RE_DTS },
2021
- handler: transform
2022
- },
2023
- renderChunk,
2024
- generateBundle(options, bundle) {
2025
- for (const chunk of Object.values(bundle)) {
2026
- if (!RE_DTS_MAP.test(chunk.fileName)) continue;
2027
- if (sourcemap) {
2028
- if (chunk.type === "chunk" || typeof chunk.source !== "string") continue;
2029
- const map = JSON.parse(chunk.source);
2030
- map.sourcesContent = void 0;
2031
- chunk.source = JSON.stringify(map);
2032
- } else delete bundle[chunk.fileName];
2033
- }
2034
- }
2035
- };
2036
- async function transform(code, id) {
2037
- let file;
2038
- try {
2039
- file = parse$1(code, {
2040
- lang: "dts",
2041
- sourceType: "module",
2042
- attachComments: true
2043
- });
2044
- } catch (error) {
2045
- throw new Error(`Failed to parse ${id}. This may be caused by a syntax error in the declaration file or a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
2046
- }
2047
- const { program } = file;
2048
- moduleExportsMap.set(id, await collectModuleExports(this, program.body, id));
2049
- const identifierMap = Object.create(null);
2050
- if (!warnedCjsDtsInputs.has(id) && program.body.some(isCjsDtsInputSyntax)) {
2051
- warnedCjsDtsInputs.add(id);
2052
- this.warn(`${id} uses CommonJS dts syntax. ${RE_NODE_MODULES.test(id) ? `CommonJS dts modules cannot be bundled by rolldown-plugin-dts. Please mark this module as external in your Rolldown config.` : `rolldown-plugin-dts does not support bundling CommonJS dts input.`}`);
2053
- }
2054
- const directives = collectReferenceDirectives(file.comments);
2055
- if (directives.length) commentsMap.set(id, directives);
2056
- const appendStmts = [];
2057
- const namespaceStmts = /* @__PURE__ */ new Map();
2058
- for (const [i, stmt] of program.body.entries()) {
2059
- const setStmt = (stmt) => program.body[i] = stmt;
2060
- if (rewriteImportExport(stmt, setStmt)) continue;
2061
- const sideEffect = stmt.type === "TSModuleDeclaration" && stmt.kind !== "namespace";
2062
- if (sideEffect && stmt.type === "TSModuleDeclaration" && is.StringLiteral(stmt.id) && stmt.id.value[0] === ".") this.warn(`\`declare module ${JSON.stringify(stmt.id.value)}\` will be kept as-is in the output. Relative module declaration may cause unexpected issues. Found in ${id}.`);
2063
- if (sideEffect && id.endsWith(".vue.d.ts") && code.slice(stmt.start, stmt.end).includes("__VLS_")) continue;
2064
- const isDefaultExport = stmt.type === "ExportDefaultDeclaration";
2065
- const isExportDecl = is.oneOf(stmt, ["ExportNamedDeclaration", "ExportDefaultDeclaration"]) && !!stmt.declaration;
2066
- const decl = isExportDecl ? stmt.declaration : stmt;
2067
- const setDecl = isExportDecl ? (decl) => stmt.declaration = decl : setStmt;
2068
- if (decl.type !== "TSDeclareFunction" && !is.Declaration(decl)) continue;
2069
- if (is.oneOf(decl, [
2070
- "TSEnumDeclaration",
2071
- "ClassDeclaration",
2072
- "FunctionDeclaration",
2073
- "TSDeclareFunction",
2074
- "TSModuleDeclaration",
2075
- "VariableDeclaration"
2076
- ])) decl.declare = true;
2077
- const bindings = [];
2078
- if (decl.type === "VariableDeclaration") bindings.push(...decl.declarations.map((decl) => decl.id));
2079
- else if ("id" in decl && decl.id) {
2080
- let binding = decl.id;
2081
- if (binding.type === "TSQualifiedName") binding = getIdFromTSEntityName(binding);
2082
- if (sideEffect) binding = b.identifier(`_${getIdentifierIndex(identifierMap, "")}`);
2083
- if (binding.type !== "Identifier") throw new Error(`Unexpected ${binding.type} declaration id`);
2084
- bindings.push(binding);
2085
- } else {
2086
- const binding = b.identifier("export_default");
2087
- bindings.push(binding);
2088
- decl.id = binding;
2089
- }
2090
- const params = collectParams(decl);
2091
- const childrenSet = /* @__PURE__ */ new Set();
2092
- const deps = await collectDependencies(this, decl, id, namespaceStmts, childrenSet, identifierMap);
2093
- const children = Array.from(childrenSet).filter((child) => bindings.every((b) => child !== b));
2094
- if (decl !== stmt) decl.comments = stmt.comments;
2095
- const declarationId = registerDeclaration({
2096
- decl,
2097
- deps,
2098
- bindings,
2099
- params,
2100
- children
2101
- });
2102
- const declarationIdNode = b.numericLiteral(declarationId);
2103
- const depsBody = b.arrayExpression(deps);
2104
- const depsNode = b.arrowFunctionExpression(params.map(({ name }) => b.identifier(name)), depsBody);
2105
- const childrenNode = b.arrayExpression(children.map((node) => {
2106
- const placeholder = b.stringLiteral("");
2107
- placeholder.start = node.start;
2108
- placeholder.end = node.end;
2109
- return placeholder;
2110
- }));
2111
- const sideEffectNode = sideEffect && b.callExpression(b.identifier("sideEffect"), [bindings[0]]);
2112
- const runtimeArrayNode = runtimeBindingArrayExpression([
2113
- declarationIdNode,
2114
- depsNode,
2115
- childrenNode,
2116
- ...sideEffectNode ? [sideEffectNode] : []
2117
- ]);
2118
- const runtimeAssignment = b.variableDeclaration("var", [b.variableDeclarator(b.arrayPattern(bindings.map((binding) => ({
2119
- ...binding,
2120
- typeAnnotation: null
2121
- }))), runtimeArrayNode)]);
2122
- if (isDefaultExport) {
2123
- appendStmts.push(b.exportNamedDeclaration(null, [b.exportSpecifier(bindings[0], b.identifier("default"))]));
2124
- setStmt(runtimeAssignment);
2125
- } else setDecl(runtimeAssignment);
2126
- }
2127
- if (sideEffects) appendStmts.push(b.expressionStatement(b.callExpression(b.identifier("sideEffect"), [])));
2128
- program.body = [
2129
- ...Array.from(namespaceStmts.values()).map(({ stmt }) => stmt),
2130
- ...program.body,
2131
- ...appendStmts
2132
- ];
2133
- const result = print(program, {
2134
- comments: false,
2135
- ...sourcemap && { sourceMaps: {
2136
- source: code,
2137
- sourceFileName: id
2138
- } }
2139
- });
2140
- return {
2141
- code: result.code,
2142
- map: result.map ?? null
2143
- };
2144
- }
2145
- function renderChunk(code, chunk) {
2146
- if (!RE_DTS.test(chunk.fileName)) return;
2147
- const exportInfo = collectChunkExportInfo(chunk, moduleExportsMap);
2148
- let file;
2149
- try {
2150
- file = parse$1(code, {
2151
- lang: "ts",
2152
- sourceType: "module",
2153
- attachComments: true
2154
- });
2155
- } catch (error) {
2156
- throw new Error(`Failed to parse generated code for chunk ${chunk.fileName}. This may be caused by a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
2157
- }
2158
- const { program } = file;
2159
- program.body = patchTsNamespace(program.body);
2160
- program.body = patchReExport(program.body);
2161
- program.body = program.body.map((node) => {
2162
- if (isHelperImport(node)) return null;
2163
- if (node.type === "ExpressionStatement") return null;
2164
- const newNode = patchImportExport(node, exportInfo, cjsDefault);
2165
- if (newNode || newNode === false) return newNode;
2166
- if (node.type !== "VariableDeclaration") return node;
2167
- if (!isRuntimeBindingVariableDeclaration(node)) return null;
2168
- const decl = node.declarations[0];
2169
- const [declarationIdNode, depsFn, children] = decl.init.elements;
2170
- const declarationId = declarationIdNode.value;
2171
- const declaration = getDeclaration(declarationId);
2172
- if (sourcemap) walk(declaration.decl, { enter(node) {
2173
- node.start = void 0;
2174
- node.end = void 0;
2175
- } });
2176
- for (const [i, id] of decl.id.elements.entries()) {
2177
- const transformedBinding = {
2178
- ...id,
2179
- typeAnnotation: declaration.bindings[i].typeAnnotation
2180
- };
2181
- overwriteNode(declaration.bindings[i], transformedBinding);
2182
- }
2183
- if (sourcemap) for (const [i, child] of children.elements.entries()) Object.assign(declaration.children[i], {
2184
- start: child.start,
2185
- end: child.end
2186
- });
2187
- const transformedParams = depsFn.params;
2188
- for (const [i, transformedParam] of transformedParams.entries()) {
2189
- const transformedName = transformedParam.name;
2190
- for (const originalTypeParam of declaration.params[i].typeParams) originalTypeParam.name = transformedName;
1361
+ resolveId(id) {
1362
+ if (dtsMap.has(id)) {
1363
+ debug$4("resolve dts id %s", id);
1364
+ return { id };
2191
1365
  }
2192
- const transformedDeps = depsFn.body.elements;
2193
- for (const [i, originalDep] of declaration.deps.entries()) {
2194
- let transformedDep = transformedDeps[i];
2195
- if (transformedDep.type === "UnaryExpression" && transformedDep.operator === "void") {
2196
- const undefinedDep = b.identifier("undefined");
2197
- undefinedDep.start = transformedDep.start;
2198
- undefinedDep.end = transformedDep.end;
2199
- transformedDep = undefinedDep;
2200
- } else if (isInfer(transformedDep)) transformedDep.name = "__Infer";
2201
- if (originalDep.replace) originalDep.replace(transformedDep);
2202
- else Object.assign(originalDep, transformedDep);
1366
+ },
1367
+ transform: {
1368
+ order: "pre",
1369
+ filter: { id: {
1370
+ include: [
1371
+ RE_JS,
1372
+ RE_TS,
1373
+ RE_JSON,
1374
+ ...volarContext.patterns
1375
+ ],
1376
+ exclude: [
1377
+ RE_DTS,
1378
+ RE_NODE_MODULES,
1379
+ RE_ROLLDOWN_RUNTIME
1380
+ ]
1381
+ } },
1382
+ handler(code, id) {
1383
+ const jsFile = RE_JS.test(id);
1384
+ if (!jsFile || emitJs) {
1385
+ const mod = this.getModuleInfo(id);
1386
+ const isEntry = entryMatcher ? entryMatcher(path.relative(cwd, id)) : !!mod?.isEntry;
1387
+ const dtsId = filename_to_dts(id, volarContext);
1388
+ dtsMap.set(dtsId, {
1389
+ code,
1390
+ id,
1391
+ isEntry,
1392
+ jsFile
1393
+ });
1394
+ debug$4("register dts source: %s", id);
1395
+ if (isEntry) {
1396
+ const name = inputAliasMap.get(id);
1397
+ this.emitFile({
1398
+ type: "chunk",
1399
+ id: dtsId,
1400
+ name: name ? `${name}.d` : void 0
1401
+ });
1402
+ }
1403
+ }
1404
+ if (emitDtsOnly) {
1405
+ if (RE_JSON.test(id)) return "{}";
1406
+ return EMPTY_STUB;
1407
+ }
2203
1408
  }
2204
- return inheritNodeComments(node, declaration.decl);
2205
- }).filter((node) => !!node);
2206
- if (program.body.length === 0) return {
2207
- code: "export { };",
2208
- map: null
2209
- };
2210
- const comments = /* @__PURE__ */ new Set();
2211
- const commentsValue = /* @__PURE__ */ new Set();
2212
- for (const id of chunk.moduleIds) {
2213
- const preserveComments = commentsMap.get(id);
2214
- if (preserveComments) {
2215
- preserveComments.forEach((c) => {
2216
- const id = c.type + c.value;
2217
- if (commentsValue.has(id)) return;
2218
- commentsValue.add(id);
2219
- comments.add(c);
2220
- });
2221
- commentsMap.delete(id);
1409
+ },
1410
+ load: {
1411
+ filter: { id: {
1412
+ include: [RE_DTS],
1413
+ exclude: [RE_NODE_MODULES]
1414
+ } },
1415
+ async handler(dtsId) {
1416
+ const module = dtsMap.get(dtsId);
1417
+ if (!module) return;
1418
+ const { code, id, jsFile } = module;
1419
+ if (jsFile && await access(dtsId).then(() => true).catch(() => false)) {
1420
+ debug$4("dts file already exists for %s, skipping generation", id);
1421
+ return;
1422
+ }
1423
+ let dtsCode;
1424
+ let map;
1425
+ debug$4("generate dts %s from %s", dtsId, id);
1426
+ if (generator === "tsgo") {
1427
+ if (volarContext.isVolarFile(id)) throw new Error(`tsgo does not support .${path.extname(id)} file.`);
1428
+ const dtsPath = path.resolve(tsgoContext.path, path.relative(path.resolve(rootDir), filename_to_dts(id, volarContext)));
1429
+ if (!existsSync(dtsPath)) {
1430
+ debug$4("[tsgo]", dtsPath, "is missing");
1431
+ throw new Error(`tsgo did not generate dts file for ${id}, please check your tsconfig.`);
1432
+ }
1433
+ dtsCode = await readFile(dtsPath, "utf8");
1434
+ const mapPath = `${dtsPath}.map`;
1435
+ if (existsSync(mapPath)) {
1436
+ const mapRaw = await readFile(mapPath, "utf8");
1437
+ map = {
1438
+ ...JSON.parse(mapRaw),
1439
+ sources: [id]
1440
+ };
1441
+ }
1442
+ } else if (generator === "oxc" && !volarContext.isVolarFile(id)) {
1443
+ const result = isolatedDeclarationSync(id, code, oxc);
1444
+ if (result.errors.length) {
1445
+ const [error] = result.errors;
1446
+ return this.error({
1447
+ message: error.message,
1448
+ frame: error.codeframe || void 0
1449
+ });
1450
+ }
1451
+ dtsCode = result.code;
1452
+ if (result.map) {
1453
+ map = result.map;
1454
+ map.sourcesContent = void 0;
1455
+ }
1456
+ } else {
1457
+ const options = {
1458
+ tsconfig,
1459
+ tsconfigRaw,
1460
+ build,
1461
+ incremental,
1462
+ cwd,
1463
+ entries: eager ? void 0 : Array.from(dtsMap.values()).filter((v) => v.isEntry).map((v) => v.id),
1464
+ id,
1465
+ sourcemap,
1466
+ volarContext,
1467
+ context: tscContext
1468
+ };
1469
+ let result;
1470
+ if (parallel) result = await tscWorker.emit(options);
1471
+ else result = tscModule.tscEmit(options);
1472
+ if (result.error) return this.error(result.error);
1473
+ dtsCode = result.code;
1474
+ map = result.map;
1475
+ if (dtsCode && RE_JSON.test(id)) if (dtsCode.includes("declare const _exports")) {
1476
+ if (dtsCode.includes("declare const _exports: {") && !dtsCode.includes("\n}[];")) {
1477
+ const exports = collectJsonExports(dtsCode);
1478
+ let i = 0;
1479
+ dtsCode += exports.map((e) => {
1480
+ const valid = `_${e.replaceAll(/[^\w$]/g, "_")}${i++}`;
1481
+ const jsonKey = JSON.stringify(e);
1482
+ return `declare let ${valid}: typeof _exports[${jsonKey}]\nexport { ${valid} as ${jsonKey} }`;
1483
+ }).join("\n");
1484
+ }
1485
+ } else {
1486
+ const exportMap = collectJsonExportMap(dtsCode);
1487
+ dtsCode += `
1488
+ declare namespace __json_default_export {
1489
+ export { ${Array.from(exportMap.entries()).map(([exported, local]) => exported === local ? exported : `${local} as ${exported}`).join(", ")} }
1490
+ }
1491
+ export { __json_default_export as default }`;
1492
+ }
1493
+ }
1494
+ return {
1495
+ code: dtsCode || "",
1496
+ map
1497
+ };
2222
1498
  }
1499
+ },
1500
+ generateBundle: emitDtsOnly ? (options, bundle) => {
1501
+ for (const fileName of Object.keys(bundle)) if (bundle[fileName].type === "chunk" && !RE_DTS.test(fileName) && !RE_DTS_MAP.test(fileName)) delete bundle[fileName];
1502
+ } : void 0,
1503
+ async buildEnd() {
1504
+ tscWorker?.kill();
1505
+ tscWorker = void 0;
1506
+ await tsgoContext?.dispose();
1507
+ tsgoContext = void 0;
1508
+ if (newContext) tscContext = void 0;
1509
+ },
1510
+ watchChange(id) {
1511
+ if (tscModule) invalidateContextFile(tscContext || globalContext, id);
2223
1512
  }
2224
- if (comments.size) {
2225
- program.body[0].comments ||= [];
2226
- program.body[0].comments.unshift(...Array.from(comments, (c) => ({
2227
- type: c.type,
2228
- value: c.value,
2229
- position: "before",
2230
- sameLine: false
2231
- })));
2232
- }
2233
- const result = print(program, {
2234
- comments: true,
2235
- ...sourcemap && { sourceMaps: {
2236
- source: code,
2237
- sourceFileName: chunk.fileName
2238
- } }
2239
- });
2240
- return {
2241
- code: result.code,
2242
- map: result.map ?? null
2243
- };
2244
- }
2245
- function registerDeclaration(info) {
2246
- const declarationId = declarationIdx++;
2247
- declarationMap.set(declarationId, info);
2248
- return declarationId;
2249
- }
2250
- function getDeclaration(declarationId) {
2251
- return declarationMap.get(declarationId);
2252
- }
2253
- }
2254
- async function collectModuleExports(context, nodes, id) {
2255
- const info = {
2256
- typeOnlyLocals: /* @__PURE__ */ new Set(),
2257
- exports: /* @__PURE__ */ new Map(),
2258
- reExports: [],
2259
- exportAlls: []
2260
1513
  };
2261
- for (const node of nodes) collectTypeOnlyLocals(node, info.typeOnlyLocals);
2262
- for (const node of nodes) await collectExportInfo(context, node, id, info);
2263
- return info;
2264
- }
2265
- function collectTypeOnlyLocals(node, typeOnlyLocals) {
2266
- if (node.type !== "ImportDeclaration") return;
2267
- for (const specifier of node.specifiers) if (node.importKind === "type" || "importKind" in specifier && specifier.importKind === "type") typeOnlyLocals.add(specifier.local.name);
2268
- }
2269
- function collectDeclarationNames(node) {
2270
- if (node.type === "VariableDeclaration") return node.declarations.flatMap((decl) => collectPatternNames(decl.id));
2271
- if ("id" in node && node.id) {
2272
- if (node.id.type !== "Identifier" && node.id.type !== "TSQualifiedName") return [];
2273
- const id = getIdFromTSEntityName(node.id);
2274
- return id.type === "Identifier" ? [id.name] : [];
2275
- }
2276
- return [];
2277
1514
  }
2278
- function collectPatternNames(node) {
2279
- if (!node) return [];
2280
- if (node.type === "Identifier") return [node.name];
2281
- if (node.type === "RestElement") return collectPatternNames(node.argument);
2282
- if (node.type === "AssignmentPattern") return collectPatternNames(node.left);
2283
- if (node.type === "ArrayPattern") return node.elements.flatMap((element) => collectPatternNames(element));
2284
- if (node.type === "ObjectPattern") return node.properties.flatMap((property) => {
2285
- if (property.type === "RestElement") return collectPatternNames(property.argument);
2286
- return collectPatternNames(property.value);
1515
+ function createTscWorker() {
1516
+ const childProcess = fork(new URL(WORKER_URL, import.meta.url), {
1517
+ stdio: "inherit",
1518
+ serialization: "advanced"
1519
+ });
1520
+ const pending = /* @__PURE__ */ new Map();
1521
+ let nextId = 0;
1522
+ childProcess.on("message", (response) => {
1523
+ const handler = pending.get(response.id);
1524
+ if (!handler) return;
1525
+ pending.delete(response.id);
1526
+ if (response.error) handler.reject(response.error);
1527
+ else handler.resolve(response.result);
1528
+ });
1529
+ childProcess.on("exit", (code) => {
1530
+ for (const handler of pending.values()) handler.reject(/* @__PURE__ */ new Error(`tsc worker exited with code ${code}`));
1531
+ pending.clear();
2287
1532
  });
2288
- return [];
2289
- }
2290
- function isTypeOnlyExport(node, specifier) {
2291
- return node.exportKind === "type" || specifier.exportKind === "type";
2292
- }
2293
- async function collectExportInfo(context, node, id, info) {
2294
- if (node.type === "ExportNamedDeclaration") {
2295
- if (node.declaration) {
2296
- for (const name of collectDeclarationNames(node.declaration)) info.exports.set(name, false);
2297
- return;
2298
- }
2299
- const source = await resolveExportSource(context, node.source, id);
2300
- for (const specifier of node.specifiers) {
2301
- const typeOnly = isTypeOnlyExport(node, specifier);
2302
- const exported = nameOf(specifier.exported);
2303
- const local = nameOf(specifier.local);
2304
- if (source) info.reExports.push({
2305
- source,
2306
- local,
2307
- exported,
2308
- typeOnly
2309
- });
2310
- else info.exports.set(exported, typeOnly || info.typeOnlyLocals.has(local));
2311
- }
2312
- return;
2313
- }
2314
- if (node.type === "ExportDefaultDeclaration") {
2315
- info.exports.set("default", false);
2316
- return;
2317
- }
2318
- if (node.type === "ExportAllDeclaration") {
2319
- if (node.exported) {
2320
- info.exports.set(nameOf(node.exported), node.exportKind === "type");
2321
- return;
2322
- }
2323
- info.exportAlls.push({
2324
- source: await resolveExportSource(context, node.source, id),
2325
- rawSource: node.source.value,
2326
- typeOnly: node.exportKind === "type"
2327
- });
2328
- }
2329
- }
2330
- async function resolveExportSource(context, source, importer) {
2331
- if (!source) return;
2332
- const resolved = await context.resolve(source.value, importer);
2333
- if (!resolved || resolved.external) return;
2334
- return resolved.id;
2335
- }
2336
- function collectChunkExportInfo(chunk, moduleExportsMap) {
2337
- const exportsByModule = resolveAllModuleExports(moduleExportsMap);
2338
- const roots = chunk.facadeModuleId && moduleExportsMap.has(chunk.facadeModuleId) ? [chunk.facadeModuleId] : chunk.moduleIds;
2339
- const mergedExports = /* @__PURE__ */ new Map();
2340
- const typeOnlyExportAllSources = /* @__PURE__ */ new Set();
2341
- for (const root of roots) {
2342
- const exports = exportsByModule.get(root);
2343
- if (exports) for (const [name, typeOnly] of exports) setExportTypeOnly(mergedExports, name, typeOnly);
2344
- const moduleExports = moduleExportsMap.get(root);
2345
- if (!moduleExports) continue;
2346
- for (const exportAll of moduleExports.exportAlls) {
2347
- if (!exportAll.typeOnly || exportAll.source) continue;
2348
- typeOnlyExportAllSources.add(exportAll.rawSource);
2349
- }
2350
- }
2351
- const typeOnlyNames = /* @__PURE__ */ new Set();
2352
- for (const [name, typeOnly] of mergedExports) if (typeOnly) typeOnlyNames.add(name);
2353
1533
  return {
2354
- typeOnlyNames,
2355
- typeOnlyExportAllSources
1534
+ emit: (options) => new Promise((resolve, reject) => {
1535
+ const id = nextId++;
1536
+ pending.set(id, {
1537
+ resolve,
1538
+ reject
1539
+ });
1540
+ childProcess.send({
1541
+ id,
1542
+ options
1543
+ });
1544
+ }),
1545
+ kill: () => childProcess.kill()
2356
1546
  };
2357
1547
  }
2358
- function resolveAllModuleExports(moduleExportsMap) {
2359
- const exportsByModule = /* @__PURE__ */ new Map();
2360
- for (const [id, info] of moduleExportsMap) exportsByModule.set(id, new Map(info.exports));
2361
- let changed = true;
2362
- while (changed) {
2363
- changed = false;
2364
- for (const [id, info] of moduleExportsMap) {
2365
- const exports = exportsByModule.get(id);
2366
- for (const reExport of info.reExports) {
2367
- const sourceTypeOnly = (reExport.source ? exportsByModule.get(reExport.source) : void 0)?.get(reExport.local) ?? false;
2368
- if (setExportTypeOnly(exports, reExport.exported, reExport.typeOnly || sourceTypeOnly)) changed = true;
2369
- }
2370
- for (const exportAll of info.exportAlls) {
2371
- if (!exportAll.source) continue;
2372
- const sourceExports = exportsByModule.get(exportAll.source);
2373
- if (!sourceExports) continue;
2374
- for (const [name, typeOnly] of sourceExports) {
2375
- if (name === "default") continue;
2376
- if (setExportTypeOnly(exports, name, exportAll.typeOnly || typeOnly)) changed = true;
2377
- }
2378
- }
1548
+ function collectJsonExportMap(code) {
1549
+ const exportMap = /* @__PURE__ */ new Map();
1550
+ const { program } = parse$1(code, {
1551
+ sourceType: "module",
1552
+ lang: "dts"
1553
+ });
1554
+ for (const decl of program.body) if (decl.type === "ExportNamedDeclaration") {
1555
+ if (decl.declaration) {
1556
+ if (decl.declaration.type === "VariableDeclaration") {
1557
+ for (const vdecl of decl.declaration.declarations) if (vdecl.id.type === "Identifier") exportMap.set(vdecl.id.name, vdecl.id.name);
1558
+ } else if (decl.declaration.type === "TSModuleDeclaration" && decl.declaration.id.type === "Identifier") exportMap.set(decl.declaration.id.name, decl.declaration.id.name);
1559
+ } else if (decl.specifiers.length) {
1560
+ for (const spec of decl.specifiers) if (spec.type === "ExportSpecifier" && spec.exported.type === "Identifier") exportMap.set(spec.exported.name, spec.local.type === "Identifier" ? spec.local.name : spec.exported.name);
2379
1561
  }
2380
1562
  }
2381
- return exportsByModule;
2382
- }
2383
- function setExportTypeOnly(exports, name, typeOnly) {
2384
- const current = exports.get(name);
2385
- if (current === false || current === typeOnly) return false;
2386
- if (current === void 0 || !typeOnly) {
2387
- exports.set(name, typeOnly);
2388
- return true;
2389
- }
2390
- return false;
1563
+ return exportMap;
2391
1564
  }
2392
- /**
2393
- * Collects all TSTypeParameter nodes from the given node and groups them by
2394
- * their name. One name can associate with one or more type parameters. These
2395
- * names will be used as the parameter name in the generated JavaScript
2396
- * dependency function.
2397
- */
2398
- function collectParams(node) {
2399
- const typeParams = [];
2400
- walk(node, { leave(node) {
2401
- if ("typeParameters" in node && node.typeParameters?.type === "TSTypeParameterDeclaration") typeParams.push(...node.typeParameters.params.map(({ name }) => name));
2402
- } });
2403
- const paramMap = /* @__PURE__ */ new Map();
2404
- for (const typeParam of typeParams) {
2405
- const name = typeParam.name;
2406
- const group = paramMap.get(name);
2407
- if (group) group.push(typeParam);
2408
- else paramMap.set(name, [typeParam]);
2409
- }
2410
- return Array.from(paramMap.entries()).map(([name, typeParams]) => ({
2411
- name,
2412
- typeParams
2413
- }));
1565
+ /** `declare const _exports` mode */
1566
+ function collectJsonExports(code) {
1567
+ const exports = [];
1568
+ const { program } = parse$1(code, {
1569
+ sourceType: "module",
1570
+ lang: "dts"
1571
+ });
1572
+ const members = program.body[0].declarations[0].id.typeAnnotation.typeAnnotation.members;
1573
+ for (const member of members) if (member.key.type === "Identifier") exports.push(member.key.name);
1574
+ else if (is.StringLiteral(member.key)) exports.push(member.key.value);
1575
+ return exports;
2414
1576
  }
2415
- async function collectDependencies(context, node, importer, namespaceStmts, children, identifierMap) {
2416
- const deps = /* @__PURE__ */ new Set();
2417
- const seen = /* @__PURE__ */ new Set();
2418
- const preserveImportTypeCache = /* @__PURE__ */ new Map();
2419
- const importSources = /* @__PURE__ */ new Set();
2420
- walk(node, { TSImportType(node) {
2421
- importSources.add(node.source.value);
2422
- } });
2423
- if (importSources.size) await Promise.all(Array.from(importSources, async (source) => {
2424
- const resolved = await context.resolve(source, importer);
2425
- preserveImportTypeCache.set(source, !resolved || !!resolved.external);
2426
- }));
2427
- const inferredStack = [];
2428
- let currentInferred = /* @__PURE__ */ new Set();
2429
- function isInferred(node) {
2430
- return node.type === "Identifier" && currentInferred.has(node.name);
2431
- }
2432
- walk(node, {
2433
- enter(node) {
2434
- if (node.type === "TSConditionalType") {
2435
- const inferred = collectInferredNames(node.extendsType);
2436
- inferredStack.push(inferred);
2437
- }
2438
- },
2439
- leave(node, path) {
2440
- const { parent } = path;
2441
- if (node.type === "TSConditionalType") inferredStack.pop();
2442
- else if (parent?.type === "TSConditionalType") {
2443
- const trueBranch = parent.trueType === node;
2444
- currentInferred = new Set((trueBranch ? inferredStack : inferredStack.slice(0, -1)).flat());
2445
- } else currentInferred = /* @__PURE__ */ new Set();
2446
- if (node.type === "ExportNamedDeclaration") {
2447
- for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") addDependency(specifier.local);
2448
- } else if (node.type === "TSInterfaceDeclaration" && node.extends) for (const heritage of node.extends || []) addDependency(heritage.expression);
2449
- else if (node.type === "ClassDeclaration") {
2450
- if (node.superClass) addDependency(node.superClass);
2451
- if (node.implements) for (const implement of node.implements) addDependency(implement.expression);
2452
- } else if (is.oneOf(node, [
2453
- "Property",
2454
- "PropertyDefinition",
2455
- "TSAbstractPropertyDefinition",
2456
- "MethodDefinition",
2457
- "TSAbstractMethodDefinition",
2458
- "TSPropertySignature",
2459
- "TSMethodSignature"
2460
- ])) {
2461
- if (node.computed && isReferenceId(node.key)) addDependency(node.key);
2462
- if ("value" in node && isReferenceId(node.value)) addDependency(node.value);
2463
- } else switch (node.type) {
2464
- case "TSTypeReference":
2465
- addDependency(TSEntityNameToRuntime(node.typeName));
2466
- break;
2467
- case "TSTypeQuery":
2468
- if (seen.has(node.exprName)) return;
2469
- if (node.exprName.type === "TSImportType") break;
2470
- addDependency(TSEntityNameToRuntime(node.exprName));
2471
- break;
2472
- case "TSImportType": {
2473
- seen.add(node);
2474
- const { source, qualifier } = node;
2475
- const dep = importNamespace(node, qualifier, source, namespaceStmts, identifierMap, preserveImportTypeCache);
2476
- if (dep) addDependency(dep);
2477
- break;
1577
+ function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }) {
1578
+ let declarationIdx = 0;
1579
+ const declarationMap = /* @__PURE__ */ new Map();
1580
+ const commentsMap = /* @__PURE__ */ new Map();
1581
+ const moduleExportsMap = /* @__PURE__ */ new Map();
1582
+ const warnedCjsDtsInputs = /* @__PURE__ */ new Set();
1583
+ return {
1584
+ name: "rolldown-plugin-dts:fake-js",
1585
+ outputOptions(options) {
1586
+ if (options.format === "cjs" || options.format === "commonjs") throw new Error("[rolldown-plugin-dts] Cannot bundle dts files with `cjs` format.");
1587
+ const { chunkFileNames, entryFileNames } = options;
1588
+ return {
1589
+ ...options,
1590
+ sourcemap: options.sourcemap || sourcemap,
1591
+ chunkFileNames(chunk) {
1592
+ const nameTemplate = resolveTemplateFn(chunk.isEntry ? entryFileNames || "[name].js" : chunkFileNames || "[name]-[hash].js", chunk);
1593
+ if (chunk.name.endsWith(".d")) {
1594
+ const renderedNameWithoutD = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name.slice(0, -2)));
1595
+ if (RE_DTS.test(renderedNameWithoutD)) return renderedNameWithoutD;
1596
+ const renderedName = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name));
1597
+ if (RE_DTS.test(renderedName)) return renderedName;
1598
+ }
1599
+ return nameTemplate;
2478
1600
  }
1601
+ };
1602
+ },
1603
+ transform: {
1604
+ filter: { id: RE_DTS },
1605
+ handler: transform
1606
+ },
1607
+ renderChunk,
1608
+ generateBundle(options, bundle) {
1609
+ for (const chunk of Object.values(bundle)) {
1610
+ if (!RE_DTS_MAP.test(chunk.fileName)) continue;
1611
+ if (sourcemap) {
1612
+ if (chunk.type === "chunk" || typeof chunk.source !== "string") continue;
1613
+ const map = JSON.parse(chunk.source);
1614
+ map.sourcesContent = void 0;
1615
+ chunk.source = JSON.stringify(map);
1616
+ } else delete bundle[chunk.fileName];
2479
1617
  }
2480
- if (parent && !deps.has(node) && isChildSymbol(node, parent)) children.add(node);
2481
1618
  }
2482
- });
2483
- return Array.from(deps);
2484
- function addDependency(node) {
2485
- if (isThisExpression(node) || isInferred(node)) return;
2486
- deps.add(node);
2487
- }
2488
- }
2489
- function importNamespace(node, imported, source, namespaceStmts, identifierMap, preserveCache) {
2490
- if (preserveCache.get(source.value) ?? true) return;
2491
- const sourceText = source.value.replaceAll(/\W/g, "_");
2492
- const localName = `_$${isIdentifierName(source.value) ? source.value : `${sourceText}${getIdentifierIndex(identifierMap, sourceText)}`}`;
2493
- let local = b.identifier(localName);
2494
- if (namespaceStmts.has(source.value)) local = namespaceStmts.get(source.value).local;
2495
- else namespaceStmts.set(source.value, {
2496
- stmt: b.importDeclaration([b.importNamespaceSpecifier(local)], source),
2497
- local
2498
- });
2499
- if (imported) {
2500
- const importedLeft = getIdFromTSEntityName(imported);
2501
- if (imported.type === "ThisExpression" || importedLeft.type === "ThisExpression") throw new Error("Cannot import `this` from module.");
2502
- overwriteNode(importedLeft, b.tsQualifiedName(local, { ...importedLeft }));
2503
- local = imported;
1619
+ };
1620
+ async function transform(code, id) {
1621
+ let file;
1622
+ try {
1623
+ file = parse$1(code, {
1624
+ lang: "dts",
1625
+ sourceType: "module",
1626
+ attachComments: true
1627
+ });
1628
+ } catch (error) {
1629
+ throw new Error(`Failed to parse ${id}. This may be caused by a syntax error in the declaration file or a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
1630
+ }
1631
+ const { program } = file;
1632
+ moduleExportsMap.set(id, await collectModuleExports(this, program.body, id));
1633
+ const identifierMap = Object.create(null);
1634
+ if (!warnedCjsDtsInputs.has(id) && program.body.some(isCjsDtsInputSyntax)) {
1635
+ warnedCjsDtsInputs.add(id);
1636
+ this.warn(`${id} uses CommonJS dts syntax. ${RE_NODE_MODULES.test(id) ? `CommonJS dts modules cannot be bundled by rolldown-plugin-dts. Please mark this module as external in your Rolldown config.` : `rolldown-plugin-dts does not support bundling CommonJS dts input.`}`);
1637
+ }
1638
+ const directives = collectReferenceDirectives(file.comments);
1639
+ if (directives.length) commentsMap.set(id, directives);
1640
+ const appendStmts = [];
1641
+ const namespaceStmts = /* @__PURE__ */ new Map();
1642
+ for (const [i, stmt] of program.body.entries()) {
1643
+ const setStmt = (stmt) => program.body[i] = stmt;
1644
+ if (rewriteImportExport(stmt, setStmt)) continue;
1645
+ const sideEffect = stmt.type === "TSModuleDeclaration" && stmt.kind !== "namespace";
1646
+ if (sideEffect && stmt.type === "TSModuleDeclaration" && is.StringLiteral(stmt.id) && stmt.id.value[0] === ".") this.warn(`\`declare module ${JSON.stringify(stmt.id.value)}\` will be kept as-is in the output. Relative module declaration may cause unexpected issues. Found in ${id}.`);
1647
+ const isDefaultExport = stmt.type === "ExportDefaultDeclaration";
1648
+ const isExportDecl = is.oneOf(stmt, ["ExportNamedDeclaration", "ExportDefaultDeclaration"]) && !!stmt.declaration;
1649
+ const decl = isExportDecl ? stmt.declaration : stmt;
1650
+ const setDecl = isExportDecl ? (decl) => stmt.declaration = decl : setStmt;
1651
+ if (decl.type !== "TSDeclareFunction" && !is.Declaration(decl)) continue;
1652
+ if (is.oneOf(decl, [
1653
+ "TSEnumDeclaration",
1654
+ "ClassDeclaration",
1655
+ "FunctionDeclaration",
1656
+ "TSDeclareFunction",
1657
+ "TSModuleDeclaration",
1658
+ "VariableDeclaration"
1659
+ ])) decl.declare = true;
1660
+ const bindings = [];
1661
+ if (decl.type === "VariableDeclaration") bindings.push(...decl.declarations.map((decl) => decl.id));
1662
+ else if ("id" in decl && decl.id) {
1663
+ let binding = decl.id;
1664
+ if (binding.type === "TSQualifiedName") binding = getIdFromTSEntityName(binding);
1665
+ if (sideEffect) binding = b.Identifier({ name: `_${getIdentifierIndex(identifierMap, "")}` });
1666
+ if (binding.type !== "Identifier") throw new Error(`Unexpected ${binding.type} declaration id`);
1667
+ bindings.push(binding);
1668
+ } else {
1669
+ const binding = b.Identifier({ name: "export_default" });
1670
+ bindings.push(binding);
1671
+ decl.id = binding;
1672
+ }
1673
+ const params = collectParams(decl);
1674
+ const childrenSet = /* @__PURE__ */ new Set();
1675
+ const deps = await collectDependencies(this, decl, id, namespaceStmts, childrenSet, identifierMap);
1676
+ const children = Array.from(childrenSet).filter((child) => bindings.every((b) => child !== b));
1677
+ if (decl !== stmt) decl.comments = stmt.comments;
1678
+ const declarationId = registerDeclaration({
1679
+ decl,
1680
+ deps,
1681
+ bindings,
1682
+ params,
1683
+ children
1684
+ });
1685
+ const declarationIdNode = b.Literal({
1686
+ value: declarationId,
1687
+ raw: String(declarationId)
1688
+ });
1689
+ const depsBody = b.ArrayExpression({ elements: deps });
1690
+ const depsNode = b.ArrowFunctionExpression({
1691
+ id: null,
1692
+ generator: false,
1693
+ async: false,
1694
+ params: params.map(({ name }) => b.Identifier({ name })),
1695
+ body: depsBody,
1696
+ expression: true
1697
+ });
1698
+ const childrenNode = b.ArrayExpression({ elements: children.map((node) => b.Literal({
1699
+ value: "",
1700
+ raw: "\"\"",
1701
+ start: node.start,
1702
+ end: node.end
1703
+ })) });
1704
+ const sideEffectNode = sideEffect && b.CallExpression({
1705
+ callee: b.Identifier({ name: "sideEffect" }),
1706
+ arguments: [bindings[0]],
1707
+ optional: false
1708
+ });
1709
+ const runtimeArrayNode = runtimeBindingArrayExpression([
1710
+ declarationIdNode,
1711
+ depsNode,
1712
+ childrenNode,
1713
+ ...sideEffectNode ? [sideEffectNode] : []
1714
+ ]);
1715
+ const runtimeAssignment = b.VariableDeclaration({
1716
+ kind: "var",
1717
+ declarations: [b.VariableDeclarator({
1718
+ id: b.ArrayPattern({ elements: bindings.map((binding) => ({
1719
+ ...binding,
1720
+ typeAnnotation: null
1721
+ })) }),
1722
+ init: runtimeArrayNode
1723
+ })]
1724
+ });
1725
+ if (isDefaultExport) {
1726
+ appendStmts.push(b.ExportNamedDeclaration({
1727
+ declaration: null,
1728
+ specifiers: [b.ExportSpecifier({
1729
+ local: bindings[0],
1730
+ exported: b.Identifier({ name: "default" })
1731
+ })],
1732
+ source: null,
1733
+ attributes: []
1734
+ }));
1735
+ setStmt(runtimeAssignment);
1736
+ } else setDecl(runtimeAssignment);
1737
+ }
1738
+ if (sideEffects) appendStmts.push(b.ExpressionStatement({ expression: b.CallExpression({
1739
+ callee: b.Identifier({ name: "sideEffect" }),
1740
+ arguments: [],
1741
+ optional: false
1742
+ }) }));
1743
+ program.body = [
1744
+ ...Array.from(namespaceStmts.values()).map(({ stmt }) => stmt),
1745
+ ...program.body,
1746
+ ...appendStmts
1747
+ ];
1748
+ const result = print(program, {
1749
+ comments: false,
1750
+ ...sourcemap && { sourceMaps: {
1751
+ source: code,
1752
+ sourceFileName: id
1753
+ } }
1754
+ });
1755
+ return {
1756
+ code: result.code,
1757
+ map: result.map ?? null
1758
+ };
2504
1759
  }
2505
- let replacement = node;
2506
- if (node.typeArguments) {
2507
- overwriteNode(node, b.tsTypeReference(local, node.typeArguments));
2508
- replacement = local;
2509
- } else overwriteNode(node, local);
2510
- return {
2511
- ...TSEntityNameToRuntime(local),
2512
- replace(newNode) {
2513
- overwriteNode(replacement, newNode);
1760
+ function renderChunk(code, chunk) {
1761
+ if (!RE_DTS.test(chunk.fileName)) return;
1762
+ const exportInfo = collectChunkExportInfo(chunk, moduleExportsMap);
1763
+ let file;
1764
+ try {
1765
+ file = parse$1(code, {
1766
+ lang: "ts",
1767
+ sourceType: "module",
1768
+ attachComments: true
1769
+ });
1770
+ } catch (error) {
1771
+ throw new Error(`Failed to parse generated code for chunk ${chunk.fileName}. This may be caused by a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
2514
1772
  }
2515
- };
2516
- }
2517
- function isChildSymbol(node, parent) {
2518
- if (node.type === "Identifier") return true;
2519
- if (is.oneOf(parent, ["TSPropertySignature", "TSMethodSignature"]) && parent.key === node) return true;
2520
- return false;
2521
- }
2522
- function collectInferredNames(node) {
2523
- const inferred = [];
2524
- walk(node, { enter(node) {
2525
- if (node.type === "TSInferType" && node.typeParameter) inferred.push(node.typeParameter.name.name);
2526
- } });
2527
- return inferred;
2528
- }
2529
- const REFERENCE_RE = /\/\s*<reference\s+(?:path|types)=/;
2530
- function collectReferenceDirectives(comment, negative = false) {
2531
- return comment.filter((c) => REFERENCE_RE.test(c.value) !== negative);
2532
- }
2533
- const SOURCE_MAP_PRAGMA_RE = /^#\s*source(?:Mapping)?URL=/;
2534
- function isSourceMapPragma(comment) {
2535
- return SOURCE_MAP_PRAGMA_RE.test(comment.value);
2536
- }
2537
- function isCjsDtsInputSyntax(node) {
2538
- return node.type === "TSExportAssignment" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
2539
- }
2540
- /**
2541
- * Check if the given node is a {@link RuntimeBindingVariableDeclration}
2542
- */
2543
- function isRuntimeBindingVariableDeclaration(node) {
2544
- return node?.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].type === "VariableDeclarator" && node.declarations[0].id.type === "ArrayPattern" && isRuntimeBindingArrayExpression(node.declarations[0].init);
2545
- }
2546
- /**
2547
- * Check if the given node is a {@link RuntimeBindingArrayExpression}
2548
- */
2549
- function isRuntimeBindingArrayExpression(node) {
2550
- return node?.type === "ArrayExpression" && isRuntimeBindingArrayElements(node.elements);
2551
- }
2552
- /**
2553
- * Check if the given array is a {@link RuntimeBindingArrayElements}
2554
- */
2555
- function isRuntimeBindingArrayElements(elements) {
2556
- const [declarationId, deps, children, effect] = elements;
2557
- return is.NumericLiteral(declarationId) && deps?.type === "ArrowFunctionExpression" && children?.type === "ArrayExpression" && (!effect || effect.type === "CallExpression");
2558
- }
2559
- function runtimeBindingArrayExpression(elements) {
2560
- return b.arrayExpression([...elements]);
2561
- }
2562
- function isThisExpression(node) {
2563
- return is.Identifier(node, "this") || node.type === "ThisExpression" || node.type === "MemberExpression" && isThisExpression(node.object);
2564
- }
2565
- function isInfer(node) {
2566
- return is.Identifier(node, "infer");
2567
- }
2568
- function TSEntityNameToRuntime(node) {
2569
- if (node.type === "Identifier" || node.type === "ThisExpression") return node;
2570
- const left = TSEntityNameToRuntime(node.left);
2571
- return Object.assign(node, {
2572
- type: "MemberExpression",
2573
- object: left,
2574
- property: node.right,
2575
- computed: false
2576
- });
2577
- }
2578
- function getIdFromTSEntityName(node) {
2579
- if (node.type === "Identifier" || node.type === "ThisExpression") return node;
2580
- return getIdFromTSEntityName(node.left);
2581
- }
2582
- function isReferenceId(node) {
2583
- return is.oneOf(node, ["Identifier", "MemberExpression"]);
2584
- }
2585
- function isHelperImport(node) {
2586
- return node.type === "ImportDeclaration" && node.specifiers.length && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.imported.type === "Identifier" && ["__exportAll", "__reExport"].includes(spec.local.name));
2587
- }
2588
- /**
2589
- * patch `.d.ts` suffix in import source to `.js`
2590
- */
2591
- function patchImportExport(node, exportInfo, cjsDefault) {
2592
- if (node.type === "ExportNamedDeclaration" && !node.declaration && !node.source && !node.specifiers.length && !node.attributes?.length) return false;
2593
- if (node.type === "ImportDeclaration" && node.specifiers.length) {
2594
- for (const specifier of node.specifiers) if (isInfer(specifier.local)) specifier.local.name = "__Infer";
2595
- }
2596
- if (is.oneOf(node, [
2597
- "ImportDeclaration",
2598
- "ExportAllDeclaration",
2599
- "ExportNamedDeclaration"
2600
- ])) {
2601
- if (node.type === "ExportAllDeclaration" && node.source && exportInfo.typeOnlyExportAllSources.has(node.source.value)) node.exportKind = "type";
2602
- if (node.type === "ExportNamedDeclaration" && exportInfo.typeOnlyNames.size) {
2603
- for (const spec of node.specifiers) {
2604
- const name = nameOf(spec.exported);
2605
- if (exportInfo.typeOnlyNames.has(name)) if (spec.type === "ExportSpecifier") spec.exportKind = "type";
2606
- else node.exportKind = "type";
1773
+ const { program } = file;
1774
+ program.body = patchTsNamespace(program.body);
1775
+ program.body = patchReExport(program.body);
1776
+ program.body = program.body.map((node) => {
1777
+ if (isHelperImport(node)) return null;
1778
+ if (node.type === "ExpressionStatement") return null;
1779
+ const newNode = patchImportExport(node, exportInfo, cjsDefault);
1780
+ if (newNode || newNode === false) return newNode;
1781
+ if (node.type !== "VariableDeclaration") return node;
1782
+ if (!isRuntimeBindingVariableDeclaration(node)) return null;
1783
+ const decl = node.declarations[0];
1784
+ const [declarationIdNode, depsFn, children] = decl.init.elements;
1785
+ const declarationId = declarationIdNode.value;
1786
+ const declaration = getDeclaration(declarationId);
1787
+ if (sourcemap) walk(declaration.decl, { enter(node) {
1788
+ node.start = void 0;
1789
+ node.end = void 0;
1790
+ } });
1791
+ for (const [i, id] of decl.id.elements.entries()) {
1792
+ const transformedBinding = {
1793
+ ...id,
1794
+ typeAnnotation: declaration.bindings[i].typeAnnotation
1795
+ };
1796
+ overwriteNode(declaration.bindings[i], transformedBinding);
1797
+ }
1798
+ if (sourcemap) for (const [i, child] of children.elements.entries()) Object.assign(declaration.children[i], {
1799
+ start: child.start,
1800
+ end: child.end
1801
+ });
1802
+ const transformedParams = depsFn.params;
1803
+ for (const [i, transformedParam] of transformedParams.entries()) {
1804
+ const transformedName = transformedParam.name;
1805
+ for (const originalTypeParam of declaration.params[i].typeParams) originalTypeParam.name = transformedName;
1806
+ }
1807
+ const transformedDeps = depsFn.body.elements;
1808
+ for (const [i, originalDep] of declaration.deps.entries()) {
1809
+ let transformedDep = transformedDeps[i];
1810
+ if (transformedDep.type === "UnaryExpression" && transformedDep.operator === "void") {
1811
+ const undefinedDep = b.Identifier({ name: "undefined" });
1812
+ undefinedDep.start = transformedDep.start;
1813
+ undefinedDep.end = transformedDep.end;
1814
+ transformedDep = undefinedDep;
1815
+ } else if (isInfer(transformedDep)) transformedDep.name = "__Infer";
1816
+ if (originalDep.replace) originalDep.replace(transformedDep);
1817
+ else Object.assign(originalDep, transformedDep);
1818
+ }
1819
+ return inheritNodeComments(node, declaration.decl);
1820
+ }).filter((node) => !!node);
1821
+ if (program.body.length === 0) return {
1822
+ code: EMPTY_STUB,
1823
+ map: null
1824
+ };
1825
+ const comments = /* @__PURE__ */ new Set();
1826
+ const commentsValue = /* @__PURE__ */ new Set();
1827
+ for (const id of chunk.moduleIds) {
1828
+ const preserveComments = commentsMap.get(id);
1829
+ if (preserveComments) {
1830
+ preserveComments.forEach((c) => {
1831
+ const id = c.type + c.value;
1832
+ if (commentsValue.has(id)) return;
1833
+ commentsValue.add(id);
1834
+ comments.add(c);
1835
+ });
1836
+ commentsMap.delete(id);
2607
1837
  }
2608
- normalizeTypeOnlyExport(node);
2609
- }
2610
- if (node.source?.value && RE_DTS.test(node.source.value)) {
2611
- node.source.value = filename_dts_to(node.source.value, "js");
2612
- return node;
2613
1838
  }
2614
- if (cjsDefault && node.type === "ExportNamedDeclaration" && !node.source && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && nameOf(node.specifiers[0].exported) === "default") {
2615
- const defaultExport = node.specifiers[0];
2616
- return b.tsExportAssignment(defaultExport.local);
1839
+ if (comments.size) {
1840
+ program.body[0].comments ||= [];
1841
+ program.body[0].comments.unshift(...Array.from(comments, (c) => ({
1842
+ type: c.type,
1843
+ value: c.value,
1844
+ position: "before",
1845
+ sameLine: false
1846
+ })));
2617
1847
  }
2618
- }
2619
- }
2620
- function normalizeTypeOnlyExport(node) {
2621
- if (node.declaration || !node.specifiers.length) return;
2622
- for (const specifier of node.specifiers) if (specifier.type !== "ExportSpecifier" || specifier.exportKind !== "type") return;
2623
- node.exportKind = "type";
2624
- for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2625
- }
2626
- /**
2627
- * Handle `__exportAll` call
2628
- */
2629
- function patchTsNamespace(nodes) {
2630
- const removed = /* @__PURE__ */ new Set();
2631
- for (const [i, node] of nodes.entries()) {
2632
- const result = getExportAllNamespace(node);
2633
- if (!result) continue;
2634
- const [binding, exports] = result;
2635
- if (!exports.properties.length) continue;
2636
- const namespaceExport = b.exportNamedDeclaration(null, exports.properties.filter((property) => property.type === "Property").map((property) => {
2637
- const local = property.value.body;
2638
- const exported = property.key;
2639
- return b.exportSpecifier(local, exported);
2640
- }));
2641
- nodes[i] = b.tsModuleDeclaration(binding, b.tsModuleBlock([namespaceExport]), {
2642
- kind: "namespace",
2643
- declare: true
1848
+ const result = print(program, {
1849
+ comments: true,
1850
+ ...sourcemap && { sourceMaps: {
1851
+ source: code,
1852
+ sourceFileName: chunk.fileName
1853
+ } }
2644
1854
  });
1855
+ return {
1856
+ code: result.code,
1857
+ map: result.map ?? null
1858
+ };
1859
+ }
1860
+ function registerDeclaration(info) {
1861
+ const declarationId = declarationIdx++;
1862
+ declarationMap.set(declarationId, info);
1863
+ return declarationId;
1864
+ }
1865
+ function getDeclaration(declarationId) {
1866
+ return declarationMap.get(declarationId);
2645
1867
  }
2646
- return nodes.filter((node) => !removed.has(node));
2647
1868
  }
2648
- function getExportAllNamespace(node) {
2649
- if (node.type !== "VariableDeclaration" || node.declarations.length !== 1 || node.declarations[0].id.type !== "Identifier" || node.declarations[0].init?.type !== "CallExpression" || node.declarations[0].init.callee.type !== "Identifier" || node.declarations[0].init.callee.name !== "__exportAll" || node.declarations[0].init.arguments.length !== 1 || node.declarations[0].init.arguments[0].type !== "ObjectExpression") return false;
2650
- return [node.declarations[0].id, node.declarations[0].init.arguments[0]];
1869
+ async function collectModuleExports(context, nodes, id) {
1870
+ const info = {
1871
+ typeOnlyLocals: /* @__PURE__ */ new Set(),
1872
+ exports: /* @__PURE__ */ new Map(),
1873
+ reExports: [],
1874
+ exportAlls: []
1875
+ };
1876
+ for (const node of nodes) collectTypeOnlyLocals(node, info.typeOnlyLocals);
1877
+ for (const node of nodes) await collectExportInfo(context, node, id, info);
1878
+ return info;
2651
1879
  }
2652
- /**
2653
- * Handle `__reExport` call
2654
- */
2655
- function patchReExport(nodes) {
2656
- const exportsNames = /* @__PURE__ */ new Map();
2657
- for (const [i, node] of nodes.entries()) if (node.type === "ImportDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ImportSpecifier" && node.specifiers[0].local.type === "Identifier" && node.specifiers[0].local.name.endsWith("_exports")) exportsNames.set(node.specifiers[0].local.name, node.specifiers[0].local.name);
2658
- else if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && is.Identifier(node.expression.callee, "__reExport")) {
2659
- const args = node.expression.arguments;
2660
- exportsNames.set(args[0].name, args[1].name);
2661
- } else if (node.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].init?.type === "MemberExpression" && node.declarations[0].init.object.type === "Identifier" && exportsNames.has(node.declarations[0].init.object.name)) nodes[i] = b.tsTypeAliasDeclaration(b.identifier(node.declarations[0].id.name), b.tsTypeReference(b.tsQualifiedName(b.identifier(exportsNames.get(node.declarations[0].init.object.name)), b.identifier(node.declarations[0].init.property.name))));
2662
- else if (node.type === "ExportNamedDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && node.specifiers[0].local.type === "Identifier" && exportsNames.has(node.specifiers[0].local.name)) node.specifiers[0].local.name = exportsNames.get(node.specifiers[0].local.name);
2663
- return nodes;
1880
+ function collectTypeOnlyLocals(node, typeOnlyLocals) {
1881
+ if (node.type !== "ImportDeclaration") return;
1882
+ for (const specifier of node.specifiers) if (node.importKind === "type" || "importKind" in specifier && specifier.importKind === "type") typeOnlyLocals.add(specifier.local.name);
2664
1883
  }
2665
- function rewriteImportExport(node, set) {
2666
- if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" && !node.declaration) {
2667
- for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") specifier.importKind = "value";
2668
- else if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2669
- if (node.type === "ImportDeclaration") node.importKind = "value";
2670
- else if (node.type === "ExportNamedDeclaration") node.exportKind = "value";
2671
- return true;
2672
- } else if (node.type === "ExportAllDeclaration") {
2673
- node.exportKind = "value";
2674
- return true;
2675
- } else if (node.type === "TSImportEqualsDeclaration") {
2676
- if (node.moduleReference.type === "TSExternalModuleReference") set(b.importDeclaration([b.importDefaultSpecifier(node.id)], node.moduleReference.expression));
2677
- return true;
2678
- } else if (node.type === "TSExportAssignment" && node.expression.type === "Identifier") {
2679
- set(b.exportNamedDeclaration(null, [b.exportSpecifier(node.expression, b.identifier("default"))]));
2680
- return true;
2681
- } else if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "Identifier") {
2682
- set(b.exportNamedDeclaration(null, [b.exportSpecifier(node.declaration, b.identifier("default"))]));
2683
- return true;
1884
+ function collectDeclarationNames(node) {
1885
+ if (node.type === "VariableDeclaration") return node.declarations.flatMap((decl) => collectPatternNames(decl.id));
1886
+ if ("id" in node && node.id) {
1887
+ if (node.id.type !== "Identifier" && node.id.type !== "TSQualifiedName") return [];
1888
+ const id = getIdFromTSEntityName(node.id);
1889
+ return id.type === "Identifier" ? [id.name] : [];
2684
1890
  }
2685
- return false;
2686
- }
2687
- function overwriteNode(node, newNode) {
2688
- for (const key of Object.keys(node)) Reflect.deleteProperty(node, key);
2689
- Object.assign(node, newNode);
2690
- return node;
1891
+ return [];
2691
1892
  }
2692
- function inheritNodeComments(oldNode, newNode) {
2693
- newNode.comments ||= [];
2694
- const pragmas = oldNode.comments?.filter((comment) => comment.position === "before" && comment.value.startsWith("#") && !isSourceMapPragma(comment));
2695
- if (pragmas) newNode.comments.unshift(...pragmas);
2696
- newNode.comments = newNode.comments.filter((comment) => !REFERENCE_RE.test(comment.value) && !isSourceMapPragma(comment));
2697
- return newNode;
1893
+ function collectPatternNames(node) {
1894
+ if (!node) return [];
1895
+ if (node.type === "Identifier") return [node.name];
1896
+ if (node.type === "RestElement") return collectPatternNames(node.argument);
1897
+ if (node.type === "AssignmentPattern") return collectPatternNames(node.left);
1898
+ if (node.type === "ArrayPattern") return node.elements.flatMap((element) => collectPatternNames(element));
1899
+ if (node.type === "ObjectPattern") return node.properties.flatMap((property) => {
1900
+ if (property.type === "RestElement") return collectPatternNames(property.argument);
1901
+ return collectPatternNames(property.value);
1902
+ });
1903
+ return [];
2698
1904
  }
2699
- function getIdentifierIndex(identifierMap, name) {
2700
- if (name in identifierMap) return ++identifierMap[name];
2701
- return identifierMap[name] = 0;
1905
+ function isTypeOnlyExport(node, specifier) {
1906
+ return node.exportKind === "type" || specifier.exportKind === "type";
2702
1907
  }
2703
- const require$1 = createRequire(import.meta.url);
2704
- const debug$4 = createDebug("rolldown-plugin-dts:tsgo");
2705
- function isTS70Installed() {
2706
- try {
2707
- const { versionMajorMinor } = require$1("typescript");
2708
- return versionMajorMinor === "7.0";
2709
- } catch {}
2710
- return false;
1908
+ async function collectExportInfo(context, node, id, info) {
1909
+ if (node.type === "ExportNamedDeclaration") {
1910
+ if (node.declaration) {
1911
+ for (const name of collectDeclarationNames(node.declaration)) info.exports.set(name, false);
1912
+ return;
1913
+ }
1914
+ const source = await resolveExportSource(context, node.source, id);
1915
+ for (const specifier of node.specifiers) {
1916
+ const typeOnly = isTypeOnlyExport(node, specifier);
1917
+ const exported = nameOf(specifier.exported);
1918
+ const local = nameOf(specifier.local);
1919
+ if (source) info.reExports.push({
1920
+ source,
1921
+ local,
1922
+ exported,
1923
+ typeOnly
1924
+ });
1925
+ else info.exports.set(exported, typeOnly || info.typeOnlyLocals.has(local));
1926
+ }
1927
+ return;
1928
+ }
1929
+ if (node.type === "ExportDefaultDeclaration") {
1930
+ info.exports.set("default", false);
1931
+ return;
1932
+ }
1933
+ if (node.type === "ExportAllDeclaration") {
1934
+ if (node.exported) {
1935
+ info.exports.set(nameOf(node.exported), node.exportKind === "type");
1936
+ return;
1937
+ }
1938
+ info.exportAlls.push({
1939
+ source: await resolveExportSource(context, node.source, id),
1940
+ rawSource: node.source.value,
1941
+ typeOnly: node.exportKind === "type"
1942
+ });
1943
+ }
2711
1944
  }
2712
- const spawnAsync = (...args) => new Promise((resolve, reject) => {
2713
- const child = spawn(...args);
2714
- child.on("close", () => resolve());
2715
- child.on("error", (error) => reject(error));
2716
- });
2717
- let tsgoPathCache;
2718
- async function getTsgoPathFromNodeModules(logger) {
2719
- if (tsgoPathCache) return tsgoPathCache;
2720
- const pkgName = isTS70Installed() ? "typescript" : "@typescript/native-preview";
2721
- const tsgoPkg = import.meta.resolve(`${pkgName}/package.json`);
2722
- const { default: { version } } = await import(tsgoPkg, { with: { type: "json" } });
2723
- logger.info(`Emit types with ${styleText("underline", `${pkgName}@${version}`)}`);
2724
- const { default: getExePath } = await import(new URL("lib/getExePath.js", tsgoPkg).href);
2725
- return tsgoPathCache = getExePath();
1945
+ async function resolveExportSource(context, source, importer) {
1946
+ if (!source) return;
1947
+ const resolved = await context.resolve(source.value, importer);
1948
+ if (!resolved || resolved.external) return;
1949
+ return resolved.id;
2726
1950
  }
2727
- async function runTsgo(logger, rootDir, tsconfig, sourcemap, tsgoPath) {
2728
- debug$4("[tsgo] rootDir", rootDir);
2729
- let tsgo;
2730
- if (tsgoPath) {
2731
- tsgo = tsgoPath;
2732
- debug$4("[tsgo] using custom path", tsgo);
2733
- } else {
2734
- tsgo = await getTsgoPathFromNodeModules(logger);
2735
- debug$4("[tsgo] using tsgo from node_modules", tsgo);
1951
+ function collectChunkExportInfo(chunk, moduleExportsMap) {
1952
+ const exportsByModule = resolveAllModuleExports(moduleExportsMap);
1953
+ const roots = chunk.facadeModuleId && moduleExportsMap.has(chunk.facadeModuleId) ? [chunk.facadeModuleId] : chunk.moduleIds;
1954
+ const mergedExports = /* @__PURE__ */ new Map();
1955
+ const typeOnlyExportAllSources = /* @__PURE__ */ new Set();
1956
+ for (const root of roots) {
1957
+ const exports = exportsByModule.get(root);
1958
+ if (exports) for (const [name, typeOnly] of exports) setExportTypeOnly(mergedExports, name, typeOnly);
1959
+ const moduleExports = moduleExportsMap.get(root);
1960
+ if (!moduleExports) continue;
1961
+ for (const exportAll of moduleExports.exportAlls) {
1962
+ if (!exportAll.typeOnly || exportAll.source) continue;
1963
+ typeOnlyExportAllSources.add(exportAll.rawSource);
1964
+ }
2736
1965
  }
2737
- const tsgoDist = await mkdtemp(path.join(tmpdir(), "rolldown-plugin-dts-"));
2738
- debug$4("[tsgo] tsgoDist", tsgoDist);
2739
- const args = [
2740
- "--noEmit",
2741
- "false",
2742
- "--declaration",
2743
- "--emitDeclarationOnly",
2744
- "-p",
2745
- tsconfig,
2746
- "--outDir",
2747
- tsgoDist,
2748
- "--rootDir",
2749
- rootDir,
2750
- "--noCheck",
2751
- ...sourcemap ? ["--declarationMap"] : []
2752
- ];
2753
- debug$4("[tsgo] args %o", args);
2754
- await spawnAsync(tsgo, args, { stdio: "inherit" });
1966
+ const typeOnlyNames = /* @__PURE__ */ new Set();
1967
+ for (const [name, typeOnly] of mergedExports) if (typeOnly) typeOnlyNames.add(name);
2755
1968
  return {
2756
- path: tsgoDist,
2757
- async dispose() {
2758
- if (debug$4.enabled) debug$4("[tsgo] skip cleanup of tsgoDist", tsgoDist);
2759
- else {
2760
- debug$4("[tsgo] disposing tsgoDist", tsgoDist);
2761
- await rm(tsgoDist, {
2762
- recursive: true,
2763
- force: true
2764
- }).catch(() => {});
2765
- }
2766
- }
1969
+ typeOnlyNames,
1970
+ typeOnlyExportAllSources
2767
1971
  };
2768
1972
  }
2769
- const debug$3 = createDebug("rolldown-plugin-dts:generate");
2770
- const WORKER_URL = "./tsc-worker.mjs";
2771
- function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build, incremental, cwd, oxc, emitDtsOnly, vue, tsMacro, parallel, eager, tsgo, newContext, emitJs, sourcemap, logger }) {
2772
- const entryIncludes = entry?.filter((p) => p[0] !== "!");
2773
- const entryIgnores = entry?.filter((p) => p[0] === "!").map((p) => p.slice(1));
2774
- const entryMatcher = entry ? (file) => entryIncludes.some((p) => path.matchesGlob(file, p)) && !entryIgnores.some((p) => path.matchesGlob(file, p)) : void 0;
2775
- const dtsMap = /* @__PURE__ */ new Map();
2776
- /**
2777
- * A map of input id to output file name
2778
- *
2779
- * @example
2780
- *
2781
- * inputAlias = new Map([
2782
- * ['/absolute/path/to/src/source_file.ts', 'dist/foo/index'],
2783
- * ])
2784
- */
2785
- const inputAliasMap = /* @__PURE__ */ new Map();
2786
- let tscWorker;
2787
- let tscModule;
2788
- let tscContext;
2789
- let tsgoContext;
2790
- const rootDir = tsconfig ? path.dirname(tsconfig) : cwd;
2791
- return {
2792
- name: "rolldown-plugin-dts:generate",
2793
- async buildStart(options) {
2794
- if (generator === "tsgo") tsgoContext = await runTsgo(logger, rootDir, tsconfig, sourcemap, tsgo.path);
2795
- else if (generator === "tsc") if (parallel) tscWorker = createTscWorker();
2796
- else {
2797
- tscModule = await import("./tsc-CilQvmj4.js");
2798
- if (newContext) tscContext = createContext();
2799
- }
2800
- if (!Array.isArray(options.input)) for (const [name, id] of Object.entries(options.input)) {
2801
- debug$3("resolving input alias %s -> %s", name, id);
2802
- let resolved = await this.resolve(id);
2803
- if (!id.startsWith("./")) resolved ||= await this.resolve(`./${id}`);
2804
- const resolvedId = resolved?.id || id;
2805
- debug$3("resolved input alias %s -> %s", id, resolvedId);
2806
- inputAliasMap.set(resolvedId, name);
2807
- }
2808
- },
2809
- outputOptions(options) {
2810
- return {
2811
- ...options,
2812
- entryFileNames(chunk) {
2813
- const { entryFileNames } = options;
2814
- const nameTemplate = resolveTemplateFn(entryFileNames || "[name].js", chunk);
2815
- if (chunk.name.endsWith(".d")) {
2816
- if (RE_DTS.test(nameTemplate)) return replaceTemplateName(nameTemplate, chunk.name.slice(0, -2));
2817
- if (RE_JS.test(nameTemplate)) return nameTemplate.replace(RE_JS, ".$1ts");
2818
- }
2819
- return nameTemplate;
2820
- }
2821
- };
2822
- },
2823
- resolveId(id) {
2824
- if (dtsMap.has(id)) {
2825
- debug$3("resolve dts id %s", id);
2826
- return { id };
1973
+ function resolveAllModuleExports(moduleExportsMap) {
1974
+ const exportsByModule = /* @__PURE__ */ new Map();
1975
+ for (const [id, info] of moduleExportsMap) exportsByModule.set(id, new Map(info.exports));
1976
+ let changed = true;
1977
+ while (changed) {
1978
+ changed = false;
1979
+ for (const [id, info] of moduleExportsMap) {
1980
+ const exports = exportsByModule.get(id);
1981
+ for (const reExport of info.reExports) {
1982
+ const sourceTypeOnly = (reExport.source ? exportsByModule.get(reExport.source) : void 0)?.get(reExport.local) ?? false;
1983
+ if (setExportTypeOnly(exports, reExport.exported, reExport.typeOnly || sourceTypeOnly)) changed = true;
2827
1984
  }
2828
- },
2829
- transform: {
2830
- order: "pre",
2831
- filter: { id: {
2832
- include: [
2833
- RE_JS,
2834
- RE_TS,
2835
- RE_VUE,
2836
- RE_JSON
2837
- ],
2838
- exclude: [
2839
- RE_DTS,
2840
- RE_NODE_MODULES,
2841
- RE_ROLLDOWN_RUNTIME
2842
- ]
2843
- } },
2844
- handler(code, id) {
2845
- const jsFile = RE_JS.test(id);
2846
- if (!jsFile || emitJs) {
2847
- const mod = this.getModuleInfo(id);
2848
- const isEntry = entryMatcher ? entryMatcher(path.relative(cwd, id)) : !!mod?.isEntry;
2849
- const dtsId = filename_to_dts(id);
2850
- dtsMap.set(dtsId, {
2851
- code,
2852
- id,
2853
- isEntry,
2854
- jsFile
2855
- });
2856
- debug$3("register dts source: %s", id);
2857
- if (isEntry) {
2858
- const name = inputAliasMap.get(id);
2859
- this.emitFile({
2860
- type: "chunk",
2861
- id: dtsId,
2862
- name: name ? `${name}.d` : void 0
2863
- });
2864
- }
2865
- }
2866
- if (emitDtsOnly) {
2867
- if (RE_JSON.test(id)) return "{}";
2868
- return "export { }";
1985
+ for (const exportAll of info.exportAlls) {
1986
+ if (!exportAll.source) continue;
1987
+ const sourceExports = exportsByModule.get(exportAll.source);
1988
+ if (!sourceExports) continue;
1989
+ for (const [name, typeOnly] of sourceExports) {
1990
+ if (name === "default") continue;
1991
+ if (setExportTypeOnly(exports, name, exportAll.typeOnly || typeOnly)) changed = true;
2869
1992
  }
2870
1993
  }
2871
- },
2872
- load: {
2873
- filter: { id: {
2874
- include: [RE_DTS],
2875
- exclude: [RE_NODE_MODULES]
2876
- } },
2877
- async handler(dtsId) {
2878
- const module = dtsMap.get(dtsId);
2879
- if (!module) return;
2880
- const { code, id, jsFile } = module;
2881
- if (jsFile && await access(dtsId).then(() => true).catch(() => false)) {
2882
- debug$3("dts file already exists for %s, skipping generation", id);
2883
- return;
2884
- }
2885
- let dtsCode;
2886
- let map;
2887
- debug$3("generate dts %s from %s", dtsId, id);
2888
- if (generator === "tsgo") {
2889
- if (RE_VUE.test(id)) throw new Error("tsgo does not support Vue files.");
2890
- const dtsPath = path.resolve(tsgoContext.path, path.relative(path.resolve(rootDir), filename_to_dts(id)));
2891
- if (!existsSync(dtsPath)) {
2892
- debug$3("[tsgo]", dtsPath, "is missing");
2893
- throw new Error(`tsgo did not generate dts file for ${id}, please check your tsconfig.`);
2894
- }
2895
- dtsCode = await readFile(dtsPath, "utf8");
2896
- const mapPath = `${dtsPath}.map`;
2897
- if (existsSync(mapPath)) {
2898
- const mapRaw = await readFile(mapPath, "utf8");
2899
- map = {
2900
- ...JSON.parse(mapRaw),
2901
- sources: [id]
2902
- };
2903
- }
2904
- } else if (generator === "oxc" && !RE_VUE.test(id)) {
2905
- const result = isolatedDeclarationSync(id, code, oxc);
2906
- if (result.errors.length) {
2907
- const [error] = result.errors;
2908
- return this.error({
2909
- message: error.message,
2910
- frame: error.codeframe || void 0
2911
- });
2912
- }
2913
- dtsCode = result.code;
2914
- if (result.map) {
2915
- map = result.map;
2916
- map.sourcesContent = void 0;
2917
- }
2918
- } else {
2919
- const options = {
2920
- tsconfig,
2921
- tsconfigRaw,
2922
- build,
2923
- incremental,
2924
- cwd,
2925
- entries: eager ? void 0 : Array.from(dtsMap.values()).filter((v) => v.isEntry).map((v) => v.id),
2926
- id,
2927
- sourcemap,
2928
- vue,
2929
- tsMacro,
2930
- context: tscContext
2931
- };
2932
- let result;
2933
- if (parallel) result = await tscWorker.emit(options);
2934
- else result = tscModule.tscEmit(options);
2935
- if (result.error) return this.error(result.error);
2936
- dtsCode = result.code;
2937
- map = result.map;
2938
- if (dtsCode && RE_JSON.test(id)) if (dtsCode.includes("declare const _exports")) {
2939
- if (dtsCode.includes("declare const _exports: {") && !dtsCode.includes("\n}[];")) {
2940
- const exports = collectJsonExports(dtsCode);
2941
- let i = 0;
2942
- dtsCode += exports.map((e) => {
2943
- const valid = `_${e.replaceAll(/[^\w$]/g, "_")}${i++}`;
2944
- const jsonKey = JSON.stringify(e);
2945
- return `declare let ${valid}: typeof _exports[${jsonKey}]\nexport { ${valid} as ${jsonKey} }`;
2946
- }).join("\n");
2947
- }
2948
- } else {
2949
- const exportMap = collectJsonExportMap(dtsCode);
2950
- dtsCode += `
2951
- declare namespace __json_default_export {
2952
- export { ${Array.from(exportMap.entries()).map(([exported, local]) => exported === local ? exported : `${local} as ${exported}`).join(", ")} }
1994
+ }
1995
+ }
1996
+ return exportsByModule;
2953
1997
  }
2954
- export { __json_default_export as default }`;
1998
+ function setExportTypeOnly(exports, name, typeOnly) {
1999
+ const current = exports.get(name);
2000
+ if (current === false || current === typeOnly) return false;
2001
+ if (current === void 0 || !typeOnly) {
2002
+ exports.set(name, typeOnly);
2003
+ return true;
2004
+ }
2005
+ return false;
2006
+ }
2007
+ /**
2008
+ * Collects all TSTypeParameter nodes from the given node and groups them by
2009
+ * their name. One name can associate with one or more type parameters. These
2010
+ * names will be used as the parameter name in the generated JavaScript
2011
+ * dependency function.
2012
+ */
2013
+ function collectParams(node) {
2014
+ const typeParams = [];
2015
+ walk(node, { leave(node) {
2016
+ if ("typeParameters" in node && node.typeParameters?.type === "TSTypeParameterDeclaration") typeParams.push(...node.typeParameters.params.map(({ name }) => name));
2017
+ } });
2018
+ const paramMap = /* @__PURE__ */ new Map();
2019
+ for (const typeParam of typeParams) {
2020
+ const name = typeParam.name;
2021
+ const group = paramMap.get(name);
2022
+ if (group) group.push(typeParam);
2023
+ else paramMap.set(name, [typeParam]);
2024
+ }
2025
+ return Array.from(paramMap.entries()).map(([name, typeParams]) => ({
2026
+ name,
2027
+ typeParams
2028
+ }));
2029
+ }
2030
+ async function collectDependencies(context, node, importer, namespaceStmts, children, identifierMap) {
2031
+ const deps = /* @__PURE__ */ new Set();
2032
+ const seen = /* @__PURE__ */ new Set();
2033
+ const preserveImportTypeCache = /* @__PURE__ */ new Map();
2034
+ const inferredStack = [];
2035
+ let currentInferred = /* @__PURE__ */ new Set();
2036
+ function isInferred(node) {
2037
+ return node.type === "Identifier" && currentInferred.has(node.name);
2038
+ }
2039
+ await walkAsync(node, {
2040
+ enter(node) {
2041
+ if (node.type === "TSConditionalType") {
2042
+ const inferred = collectInferredNames(node.extendsType);
2043
+ inferredStack.push(inferred);
2044
+ }
2045
+ },
2046
+ async leave(node, path) {
2047
+ const { parent } = path;
2048
+ if (node.type === "TSConditionalType") inferredStack.pop();
2049
+ else if (parent?.type === "TSConditionalType") {
2050
+ const trueBranch = parent.trueType === node;
2051
+ currentInferred = new Set((trueBranch ? inferredStack : inferredStack.slice(0, -1)).flat());
2052
+ } else currentInferred = /* @__PURE__ */ new Set();
2053
+ if (node.type === "ExportNamedDeclaration") {
2054
+ for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") addDependency(specifier.local);
2055
+ } else if (node.type === "TSInterfaceDeclaration" && node.extends) for (const heritage of node.extends || []) addDependency(heritage.expression);
2056
+ else if (node.type === "ClassDeclaration") {
2057
+ if (node.superClass) addDependency(node.superClass);
2058
+ if (node.implements) for (const implement of node.implements) addDependency(implement.expression);
2059
+ } else if (is.oneOf(node, [
2060
+ "Property",
2061
+ "PropertyDefinition",
2062
+ "TSAbstractPropertyDefinition",
2063
+ "MethodDefinition",
2064
+ "TSAbstractMethodDefinition",
2065
+ "TSPropertySignature",
2066
+ "TSMethodSignature"
2067
+ ])) {
2068
+ if (node.computed && isReferenceId(node.key)) addDependency(node.key);
2069
+ if ("value" in node && isReferenceId(node.value)) addDependency(node.value);
2070
+ } else switch (node.type) {
2071
+ case "TSTypeReference":
2072
+ addDependency(TSEntityNameToRuntime(node.typeName));
2073
+ break;
2074
+ case "TSTypeQuery":
2075
+ if (seen.has(node.exprName)) return;
2076
+ if (node.exprName.type === "TSImportType") break;
2077
+ addDependency(TSEntityNameToRuntime(node.exprName));
2078
+ break;
2079
+ case "TSImportType": {
2080
+ seen.add(node);
2081
+ const { source, qualifier } = node;
2082
+ const resolved = await context.resolve(source.value, importer);
2083
+ if (!resolved || !!resolved.external) {
2084
+ preserveImportTypeCache.set(source.value, true);
2085
+ break;
2955
2086
  }
2087
+ const dep = importNamespace(node, qualifier, source, namespaceStmts, identifierMap);
2088
+ if (dep) addDependency(dep);
2089
+ break;
2956
2090
  }
2957
- return {
2958
- code: dtsCode || "",
2959
- map
2960
- };
2961
2091
  }
2962
- },
2963
- generateBundle: emitDtsOnly ? (options, bundle) => {
2964
- for (const fileName of Object.keys(bundle)) if (bundle[fileName].type === "chunk" && !RE_DTS.test(fileName) && !RE_DTS_MAP.test(fileName)) delete bundle[fileName];
2965
- } : void 0,
2966
- async buildEnd() {
2967
- tscWorker?.kill();
2968
- tscWorker = void 0;
2969
- await tsgoContext?.dispose();
2970
- tsgoContext = void 0;
2971
- if (newContext) tscContext = void 0;
2972
- },
2973
- watchChange(id) {
2974
- if (tscModule) invalidateContextFile(tscContext || globalContext, id);
2092
+ if (parent && !deps.has(node) && isChildSymbol(node, parent)) children.add(node);
2975
2093
  }
2976
- };
2977
- }
2978
- function createTscWorker() {
2979
- const childProcess = fork(new URL(WORKER_URL, import.meta.url), {
2980
- stdio: "inherit",
2981
- serialization: "advanced"
2982
2094
  });
2983
- const pending = /* @__PURE__ */ new Map();
2984
- let nextId = 0;
2985
- childProcess.on("message", (response) => {
2986
- const handler = pending.get(response.id);
2987
- if (!handler) return;
2988
- pending.delete(response.id);
2989
- if (response.error) handler.reject(response.error);
2990
- else handler.resolve(response.result);
2991
- });
2992
- childProcess.on("exit", (code) => {
2993
- for (const handler of pending.values()) handler.reject(/* @__PURE__ */ new Error(`tsc worker exited with code ${code}`));
2994
- pending.clear();
2095
+ return Array.from(deps);
2096
+ function addDependency(node) {
2097
+ if (isThisExpression(node) || isInferred(node)) return;
2098
+ deps.add(node);
2099
+ }
2100
+ }
2101
+ function importNamespace(node, imported, source, namespaceStmts, identifierMap) {
2102
+ const sourceText = source.value.replaceAll(/\W/g, "_");
2103
+ const localName = `_$${isIdentifierName(source.value) ? source.value : `${sourceText}${getIdentifierIndex(identifierMap, sourceText)}`}`;
2104
+ let local = b.Identifier({ name: localName });
2105
+ if (namespaceStmts.has(source.value)) local = namespaceStmts.get(source.value).local;
2106
+ else namespaceStmts.set(source.value, {
2107
+ stmt: b.ImportDeclaration({
2108
+ specifiers: [b.ImportNamespaceSpecifier({ local })],
2109
+ source,
2110
+ phase: null,
2111
+ attributes: []
2112
+ }),
2113
+ local
2995
2114
  });
2115
+ if (imported) {
2116
+ const importedLeft = getIdFromTSEntityName(imported);
2117
+ if (imported.type === "ThisExpression" || importedLeft.type === "ThisExpression") throw new Error("Cannot import `this` from module.");
2118
+ overwriteNode(importedLeft, b.TSQualifiedName({
2119
+ left: local,
2120
+ right: { ...importedLeft }
2121
+ }));
2122
+ local = imported;
2123
+ }
2124
+ let replacement = node;
2125
+ if (node.typeArguments) {
2126
+ overwriteNode(node, b.TSTypeReference({
2127
+ typeName: local,
2128
+ typeArguments: node.typeArguments
2129
+ }));
2130
+ replacement = local;
2131
+ } else overwriteNode(node, local);
2996
2132
  return {
2997
- emit: (options) => new Promise((resolve, reject) => {
2998
- const id = nextId++;
2999
- pending.set(id, {
3000
- resolve,
3001
- reject
3002
- });
3003
- childProcess.send({
3004
- id,
3005
- options
3006
- });
3007
- }),
3008
- kill: () => childProcess.kill()
2133
+ ...TSEntityNameToRuntime(local),
2134
+ replace(newNode) {
2135
+ overwriteNode(replacement, newNode);
2136
+ }
3009
2137
  };
3010
2138
  }
3011
- function collectJsonExportMap(code) {
3012
- const exportMap = /* @__PURE__ */ new Map();
3013
- const { program } = parse$1(code, {
3014
- sourceType: "module",
3015
- lang: "dts"
2139
+ function isChildSymbol(node, parent) {
2140
+ if (node.type === "Identifier") return true;
2141
+ if (is.oneOf(parent, ["TSPropertySignature", "TSMethodSignature"]) && parent.key === node) return true;
2142
+ return false;
2143
+ }
2144
+ function collectInferredNames(node) {
2145
+ const inferred = [];
2146
+ walk(node, { enter(node) {
2147
+ if (node.type === "TSInferType" && node.typeParameter) inferred.push(node.typeParameter.name.name);
2148
+ } });
2149
+ return inferred;
2150
+ }
2151
+ const REFERENCE_RE = /\/\s*<reference\s+(?:path|types)=/;
2152
+ function collectReferenceDirectives(comment, negative = false) {
2153
+ return comment.filter((c) => REFERENCE_RE.test(c.value) !== negative);
2154
+ }
2155
+ const SOURCE_MAP_PRAGMA_RE = /^#\s*source(?:Mapping)?URL=/;
2156
+ function isSourceMapPragma(comment) {
2157
+ return SOURCE_MAP_PRAGMA_RE.test(comment.value);
2158
+ }
2159
+ function isCjsDtsInputSyntax(node) {
2160
+ return node.type === "TSExportAssignment" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
2161
+ }
2162
+ /**
2163
+ * Check if the given node is a {@link RuntimeBindingVariableDeclration}
2164
+ */
2165
+ function isRuntimeBindingVariableDeclaration(node) {
2166
+ return node?.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].type === "VariableDeclarator" && node.declarations[0].id.type === "ArrayPattern" && isRuntimeBindingArrayExpression(node.declarations[0].init);
2167
+ }
2168
+ /**
2169
+ * Check if the given node is a {@link RuntimeBindingArrayExpression}
2170
+ */
2171
+ function isRuntimeBindingArrayExpression(node) {
2172
+ return node?.type === "ArrayExpression" && isRuntimeBindingArrayElements(node.elements);
2173
+ }
2174
+ /**
2175
+ * Check if the given array is a {@link RuntimeBindingArrayElements}
2176
+ */
2177
+ function isRuntimeBindingArrayElements(elements) {
2178
+ const [declarationId, deps, children, effect] = elements;
2179
+ return is.NumericLiteral(declarationId) && deps?.type === "ArrowFunctionExpression" && children?.type === "ArrayExpression" && (!effect || effect.type === "CallExpression");
2180
+ }
2181
+ function runtimeBindingArrayExpression(elements) {
2182
+ return b.ArrayExpression({ elements: [...elements] });
2183
+ }
2184
+ function isThisExpression(node) {
2185
+ return is.Identifier(node, "this") || node.type === "ThisExpression" || node.type === "MemberExpression" && isThisExpression(node.object);
2186
+ }
2187
+ function isInfer(node) {
2188
+ return is.Identifier(node, "infer");
2189
+ }
2190
+ function TSEntityNameToRuntime(node) {
2191
+ if (node.type === "Identifier" || node.type === "ThisExpression") return node;
2192
+ const left = TSEntityNameToRuntime(node.left);
2193
+ return Object.assign(node, {
2194
+ type: "MemberExpression",
2195
+ object: left,
2196
+ property: node.right,
2197
+ computed: false
3016
2198
  });
3017
- for (const decl of program.body) if (decl.type === "ExportNamedDeclaration") {
3018
- if (decl.declaration) {
3019
- if (decl.declaration.type === "VariableDeclaration") {
3020
- for (const vdecl of decl.declaration.declarations) if (vdecl.id.type === "Identifier") exportMap.set(vdecl.id.name, vdecl.id.name);
3021
- } else if (decl.declaration.type === "TSModuleDeclaration" && decl.declaration.id.type === "Identifier") exportMap.set(decl.declaration.id.name, decl.declaration.id.name);
3022
- } else if (decl.specifiers.length) {
3023
- for (const spec of decl.specifiers) if (spec.type === "ExportSpecifier" && spec.exported.type === "Identifier") exportMap.set(spec.exported.name, spec.local.type === "Identifier" ? spec.local.name : spec.exported.name);
2199
+ }
2200
+ function getIdFromTSEntityName(node) {
2201
+ if (node.type === "Identifier" || node.type === "ThisExpression") return node;
2202
+ return getIdFromTSEntityName(node.left);
2203
+ }
2204
+ function isReferenceId(node) {
2205
+ return is.oneOf(node, ["Identifier", "MemberExpression"]);
2206
+ }
2207
+ function isHelperImport(node) {
2208
+ return node.type === "ImportDeclaration" && node.specifiers.length && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.imported.type === "Identifier" && ["__exportAll", "__reExport"].includes(spec.local.name));
2209
+ }
2210
+ /**
2211
+ * patch `.d.ts` suffix in import source to `.js`
2212
+ */
2213
+ function patchImportExport(node, exportInfo, cjsDefault) {
2214
+ if (node.type === "ExportNamedDeclaration" && !node.declaration && !node.source && !node.specifiers.length && !node.attributes?.length) return false;
2215
+ if (node.type === "ImportDeclaration" && node.specifiers.length) {
2216
+ for (const specifier of node.specifiers) if (isInfer(specifier.local)) specifier.local.name = "__Infer";
2217
+ }
2218
+ if (is.oneOf(node, [
2219
+ "ImportDeclaration",
2220
+ "ExportAllDeclaration",
2221
+ "ExportNamedDeclaration"
2222
+ ])) {
2223
+ if (node.type === "ExportAllDeclaration" && node.source && exportInfo.typeOnlyExportAllSources.has(node.source.value)) node.exportKind = "type";
2224
+ if (node.type === "ExportNamedDeclaration" && exportInfo.typeOnlyNames.size) {
2225
+ for (const spec of node.specifiers) {
2226
+ const name = nameOf(spec.exported);
2227
+ if (exportInfo.typeOnlyNames.has(name)) if (spec.type === "ExportSpecifier") spec.exportKind = "type";
2228
+ else node.exportKind = "type";
2229
+ }
2230
+ normalizeTypeOnlyExport(node);
2231
+ }
2232
+ if (node.source?.value && RE_DTS.test(node.source.value)) {
2233
+ node.source.value = filename_dts_to(node.source.value, "js");
2234
+ return node;
2235
+ }
2236
+ if (cjsDefault && node.type === "ExportNamedDeclaration" && !node.source && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && nameOf(node.specifiers[0].exported) === "default") {
2237
+ const defaultExport = node.specifiers[0];
2238
+ return b.TSExportAssignment({ expression: defaultExport.local });
3024
2239
  }
3025
2240
  }
3026
- return exportMap;
3027
2241
  }
3028
- /** `declare const _exports` mode */
3029
- function collectJsonExports(code) {
3030
- const exports = [];
3031
- const { program } = parse$1(code, {
3032
- sourceType: "module",
3033
- lang: "dts"
2242
+ function normalizeTypeOnlyExport(node) {
2243
+ if (node.declaration || !node.specifiers.length) return;
2244
+ for (const specifier of node.specifiers) if (specifier.type !== "ExportSpecifier" || specifier.exportKind !== "type") return;
2245
+ node.exportKind = "type";
2246
+ for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2247
+ }
2248
+ /**
2249
+ * Handle `__exportAll` call
2250
+ */
2251
+ function patchTsNamespace(nodes) {
2252
+ const removed = /* @__PURE__ */ new Set();
2253
+ for (const [i, node] of nodes.entries()) {
2254
+ const result = getExportAllNamespace(node);
2255
+ if (!result) continue;
2256
+ const [binding, exports] = result;
2257
+ if (!exports.properties.length) continue;
2258
+ const namespaceExport = b.ExportNamedDeclaration({
2259
+ declaration: null,
2260
+ specifiers: exports.properties.filter((property) => property.type === "Property").map((property) => {
2261
+ const local = property.value.body;
2262
+ const exported = property.key;
2263
+ return b.ExportSpecifier({
2264
+ local,
2265
+ exported
2266
+ });
2267
+ }),
2268
+ source: null,
2269
+ attributes: []
2270
+ });
2271
+ nodes[i] = b.TSModuleDeclaration({
2272
+ id: binding,
2273
+ body: b.TSModuleBlock({ body: [namespaceExport] }),
2274
+ kind: "namespace",
2275
+ declare: true,
2276
+ global: false
2277
+ });
2278
+ }
2279
+ return nodes.filter((node) => !removed.has(node));
2280
+ }
2281
+ function getExportAllNamespace(node) {
2282
+ if (node.type !== "VariableDeclaration" || node.declarations.length !== 1 || node.declarations[0].id.type !== "Identifier" || node.declarations[0].init?.type !== "CallExpression" || node.declarations[0].init.callee.type !== "Identifier" || node.declarations[0].init.callee.name !== "__exportAll" || node.declarations[0].init.arguments.length !== 1 || node.declarations[0].init.arguments[0].type !== "ObjectExpression") return false;
2283
+ return [node.declarations[0].id, node.declarations[0].init.arguments[0]];
2284
+ }
2285
+ /**
2286
+ * Handle `__reExport` call
2287
+ */
2288
+ function patchReExport(nodes) {
2289
+ const exportsNames = /* @__PURE__ */ new Map();
2290
+ for (const [i, node] of nodes.entries()) if (node.type === "ImportDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ImportSpecifier" && node.specifiers[0].local.type === "Identifier" && node.specifiers[0].local.name.endsWith("_exports")) exportsNames.set(node.specifiers[0].local.name, node.specifiers[0].local.name);
2291
+ else if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && is.Identifier(node.expression.callee, "__reExport")) {
2292
+ const args = node.expression.arguments;
2293
+ exportsNames.set(args[0].name, args[1].name);
2294
+ } else if (node.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].init?.type === "MemberExpression" && node.declarations[0].init.object.type === "Identifier" && exportsNames.has(node.declarations[0].init.object.name)) nodes[i] = b.TSTypeAliasDeclaration({
2295
+ id: b.Identifier({ name: node.declarations[0].id.name }),
2296
+ typeParameters: null,
2297
+ typeAnnotation: b.TSTypeReference({
2298
+ typeName: b.TSQualifiedName({
2299
+ left: b.Identifier({ name: exportsNames.get(node.declarations[0].init.object.name) }),
2300
+ right: b.Identifier({ name: node.declarations[0].init.property.name })
2301
+ }),
2302
+ typeArguments: null
2303
+ }),
2304
+ declare: false
3034
2305
  });
3035
- const members = program.body[0].declarations[0].id.typeAnnotation.typeAnnotation.members;
3036
- for (const member of members) if (member.key.type === "Identifier") exports.push(member.key.name);
3037
- else if (is.StringLiteral(member.key)) exports.push(member.key.value);
3038
- return exports;
2306
+ else if (node.type === "ExportNamedDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && node.specifiers[0].local.type === "Identifier" && exportsNames.has(node.specifiers[0].local.name)) node.specifiers[0].local.name = exportsNames.get(node.specifiers[0].local.name);
2307
+ return nodes;
2308
+ }
2309
+ function rewriteImportExport(node, set) {
2310
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" && !node.declaration) {
2311
+ for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") specifier.importKind = "value";
2312
+ else if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2313
+ if (node.type === "ImportDeclaration") node.importKind = "value";
2314
+ else if (node.type === "ExportNamedDeclaration") node.exportKind = "value";
2315
+ return true;
2316
+ } else if (node.type === "ExportAllDeclaration") {
2317
+ node.exportKind = "value";
2318
+ return true;
2319
+ } else if (node.type === "TSImportEqualsDeclaration") {
2320
+ if (node.moduleReference.type === "TSExternalModuleReference") set(b.ImportDeclaration({
2321
+ specifiers: [b.ImportDefaultSpecifier({ local: node.id })],
2322
+ source: node.moduleReference.expression,
2323
+ phase: null,
2324
+ attributes: []
2325
+ }));
2326
+ return true;
2327
+ } else if (node.type === "TSExportAssignment" && node.expression.type === "Identifier") {
2328
+ set(b.ExportNamedDeclaration({
2329
+ declaration: null,
2330
+ specifiers: [b.ExportSpecifier({
2331
+ local: node.expression,
2332
+ exported: b.Identifier({ name: "default" })
2333
+ })],
2334
+ source: null,
2335
+ attributes: []
2336
+ }));
2337
+ return true;
2338
+ } else if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "Identifier") {
2339
+ set(b.ExportNamedDeclaration({
2340
+ declaration: null,
2341
+ specifiers: [b.ExportSpecifier({
2342
+ local: node.declaration,
2343
+ exported: b.Identifier({ name: "default" })
2344
+ })],
2345
+ source: null,
2346
+ attributes: []
2347
+ }));
2348
+ return true;
2349
+ }
2350
+ return false;
2351
+ }
2352
+ function overwriteNode(node, newNode) {
2353
+ for (const key of Object.keys(node)) Reflect.deleteProperty(node, key);
2354
+ Object.assign(node, newNode);
2355
+ return node;
2356
+ }
2357
+ function inheritNodeComments(oldNode, newNode) {
2358
+ newNode.comments ||= [];
2359
+ const pragmas = oldNode.comments?.filter((comment) => comment.position === "before" && comment.value.startsWith("#") && !isSourceMapPragma(comment));
2360
+ if (pragmas) newNode.comments.unshift(...pragmas);
2361
+ newNode.comments = newNode.comments.filter((comment) => !REFERENCE_RE.test(comment.value) && !isSourceMapPragma(comment));
2362
+ return newNode;
2363
+ }
2364
+ function getIdentifierIndex(identifierMap, name) {
2365
+ if (name in identifierMap) return ++identifierMap[name];
2366
+ return identifierMap[name] = 0;
2367
+ }
2368
+ const require = createRequire(import.meta.url);
2369
+ const debug$3 = createDebug("rolldown-plugin-dts:vue");
2370
+ const RE_VUE = /\.vue$/;
2371
+ function getVueVolarPlugin() {
2372
+ const ts = requireTS(`Vue support requires TypeScript to be installed. Please install \`typescript\` package.`);
2373
+ const [volarTypeScript, vue] = loadVueLanguageTools();
2374
+ const getLanguagePlugin = (ts, options) => {
2375
+ const $rootDir = options.options.$rootDir;
2376
+ const $configRaw = options.options.$configRaw;
2377
+ const resolver = new vue.CompilerOptionsResolver(ts, ts.sys.readFile);
2378
+ resolver.addConfig($configRaw?.vueCompilerOptions ?? {}, $rootDir);
2379
+ const vueOptions = resolver.build();
2380
+ return vue.createVueLanguagePlugin(ts, options.options, vueOptions, (id) => id);
2381
+ };
2382
+ return {
2383
+ extensionPatterns: [RE_VUE],
2384
+ tsFileExtensionInfos: [{
2385
+ extension: "vue",
2386
+ isMixedContent: true,
2387
+ scriptKind: ts.ScriptKind.Deferred
2388
+ }],
2389
+ volarTypeScript,
2390
+ create(ts, options) {
2391
+ return [getLanguagePlugin(ts, options)];
2392
+ },
2393
+ toTsFilename(id) {
2394
+ return id.replace(RE_VUE, ".vue.ts");
2395
+ }
2396
+ };
2397
+ }
2398
+ function loadVueLanguageTools() {
2399
+ debug$3("loading vue language tools");
2400
+ try {
2401
+ const vueTscPath = require.resolve("vue-tsc");
2402
+ return [require(require.resolve("@volar/typescript", { paths: [vueTscPath] })), require(require.resolve("@vue/language-core", { paths: [vueTscPath] }))];
2403
+ } catch (cause) {
2404
+ debug$3("vue language tools not found", cause);
2405
+ throw new Error("Failed to load vue language tools. Please manually install vue-tsc.", { cause });
2406
+ }
3039
2407
  }
2408
+ var VolarContext = class {
2409
+ plugins;
2410
+ patterns;
2411
+ constructor(plugins) {
2412
+ this.plugins = plugins;
2413
+ this.patterns = plugins.flatMap((plugin) => plugin.extensionPatterns);
2414
+ }
2415
+ isVolarFile(id) {
2416
+ return this.patterns.some((pattern) => pattern.test(id));
2417
+ }
2418
+ getExtraFileExtensions() {
2419
+ if (!this.plugins.length) return;
2420
+ return this.plugins.flatMap((plugin) => plugin.tsFileExtensionInfos || []);
2421
+ }
2422
+ getCreateProgram(ts) {
2423
+ if (!this.plugins.length) return ts.createProgram;
2424
+ const volarTypeScript = this.plugins.find((plugin) => plugin.volarTypeScript)?.volarTypeScript;
2425
+ if (!volarTypeScript) return ts.createProgram;
2426
+ const { proxyCreateProgram } = volarTypeScript;
2427
+ return proxyCreateProgram(ts, ts.createProgram, (ts, options) => {
2428
+ const setups = [];
2429
+ const plugins = [];
2430
+ for (const plugin of this.plugins) {
2431
+ if (!plugin.create) continue;
2432
+ const result = plugin.create(ts, options);
2433
+ if (Array.isArray(result)) plugins.push(...result);
2434
+ else {
2435
+ if (result.setup) setups.push(result.setup);
2436
+ plugins.push(...result.languagePlugins);
2437
+ }
2438
+ }
2439
+ return {
2440
+ setup: setups.length ? (language) => {
2441
+ for (const setup of setups) setup(language);
2442
+ } : void 0,
2443
+ languagePlugins: plugins
2444
+ };
2445
+ });
2446
+ }
2447
+ toTsFilename(id) {
2448
+ for (const plugin of this.plugins) if (plugin.toTsFilename && plugin.extensionPatterns.some((pattern) => pattern.test(id))) return plugin.toTsFilename(id);
2449
+ return id;
2450
+ }
2451
+ };
3040
2452
  const debug$2 = createDebug("rolldown-plugin-dts:options");
3041
2453
  let warnedTsgo = false;
3042
- function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = false, emitDtsOnly = false, tsconfig, tsconfigRaw: overriddenTsconfigRaw = {}, compilerOptions = {}, sourcemap, resolver = "oxc", cjsDefault = false, sideEffects = false, logger = console, build = false, incremental = false, vue = false, tsMacro = false, parallel = false, eager = false, newContext = false, emitJs, oxc, tsgo }) {
2454
+ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = false, emitDtsOnly = false, tsconfig, tsconfigRaw: overriddenTsconfigRaw = {}, compilerOptions = {}, sourcemap, resolver = "oxc", cjsDefault = false, sideEffects = false, logger = console, volarPlugins, build = false, incremental = false, vue = false, parallel = false, eager = false, newContext = false, emitJs, oxc, tsgo }) {
3043
2455
  let resolvedTsconfig;
3044
2456
  if (tsconfig === true || tsconfig == null) {
3045
2457
  const { config, path } = at(cwd) || {};
@@ -3061,20 +2473,19 @@ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = fals
3061
2473
  ...overriddenTsconfigRaw,
3062
2474
  compilerOptions
3063
2475
  };
3064
- if (vue || tsMacro) {
3065
- if (isTS70Installed()) throw new Error("TypeScript 7.0 does not yet have a stable API and is experimental. The `vue` and `tsMacro` options are not yet supported with TypeScript 7.0.");
3066
- if (generator && generator !== "tsc") logger.warn("The `vue` and `tsMacro` options are enabled, which requires the `tsc` generator. The `generator` option is ignored.");
2476
+ volarPlugins ||= [];
2477
+ if (vue) volarPlugins.push(getVueVolarPlugin());
2478
+ if (volarPlugins.length) {
2479
+ if (isTS70Installed()) throw new Error("TypeScript 7.0 does not yet have a stable API and is experimental. The `vue` and `volarPlugins` options are not yet supported with TypeScript 7.0.");
2480
+ if (generator && generator !== "tsc") logger.warn("The `vue` and `volarPlugins` options are enabled, which requires the `tsc` generator. The `generator` option is ignored.");
3067
2481
  generator = "tsc";
3068
2482
  }
2483
+ const volarContext = new VolarContext(volarPlugins);
3069
2484
  if (!generator) if (tsgo) generator = "tsgo";
3070
2485
  else if (oxc || compilerOptions?.isolatedDeclarations) generator = "oxc";
3071
2486
  else if (isTS70Installed()) generator = "tsgo";
3072
2487
  else generator = "tsc";
3073
- if (generator === "tsc") try {
3074
- __require$1.resolve("typescript");
3075
- } catch {
3076
- throw new Error("TypeScript is not installed. You can install `typescript` package, or enable `isolatedDeclarations` in your `tsconfig.json` to use Oxc instead.");
3077
- }
2488
+ if (generator === "tsc") requireTS("Or enable `isolatedDeclarations` in your `tsconfig.json` to use Oxc instead.");
3078
2489
  else if (generator === "tsgo") {
3079
2490
  if (!tsconfig) throw new Error("tsgo generator requires a tsconfig file to be specified.");
3080
2491
  if (!warnedTsgo) {
@@ -3103,12 +2514,11 @@ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = fals
3103
2514
  sideEffects,
3104
2515
  build,
3105
2516
  incremental,
3106
- vue,
3107
- tsMacro,
3108
2517
  parallel,
3109
2518
  eager,
3110
2519
  newContext,
3111
2520
  emitJs,
2521
+ volarContext,
3112
2522
  oxc,
3113
2523
  tsgo,
3114
2524
  logger
@@ -3117,10 +2527,10 @@ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = fals
3117
2527
  return resolved;
3118
2528
  }
3119
2529
  const debug$1 = createDebug("rolldown-plugin-dts:resolver");
3120
- function isSourceFile(id) {
3121
- return RE_TS.test(id) || RE_VUE.test(id) || RE_JSON.test(id);
3122
- }
3123
- function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffects }) {
2530
+ function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffects, volarContext }) {
2531
+ function isSourceFile(id) {
2532
+ return RE_TS.test(id) || RE_JSON.test(id) || volarContext.isVolarFile(id);
2533
+ }
3124
2534
  const baseDtsResolver = createResolver({
3125
2535
  tsconfig,
3126
2536
  resolveNodeModules: true,
@@ -3166,7 +2576,7 @@ function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffe
3166
2576
  debug$1("Resolving dts import to source file:", id);
3167
2577
  await this.load({ id: dtsResolution });
3168
2578
  return {
3169
- id: filename_to_dts(dtsResolution),
2579
+ id: filename_to_dts(dtsResolution, volarContext),
3170
2580
  moduleSideEffects
3171
2581
  };
3172
2582
  }
@@ -3176,7 +2586,7 @@ function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffe
3176
2586
  async function resolveDtsPath(id, importer, rolldownResolution) {
3177
2587
  let dtsPath;
3178
2588
  if (resolver === "tsc") {
3179
- const { tscResolve } = await import("./resolver-DtsKFXi2-B8Z3WwZh.js");
2589
+ const { tscResolve } = await import("./resolver-cwLsPb2o-DvUqSYux.js");
3180
2590
  dtsPath = tscResolve(id, importer, cwd, tsconfig, tsconfigRaw);
3181
2591
  } else dtsPath = baseDtsResolver(id, importer);
3182
2592
  debug$1("Using %s for dts import: %O -> %O", resolver, id, dtsPath);