@pulsec/dts 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,1483 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ function toPosix(p) {
7
+ return p.replace(/\\/g, '/');
8
+ }
9
+
10
+ function isRelativeSpec(spec) {
11
+ return spec.startsWith('./') || spec.startsWith('../') || spec === '.' || spec === '..';
12
+ }
13
+
14
+ function normalizeVirtualPath(p) {
15
+ const posix = toPosix(p);
16
+ const norm = path.posix.normalize(posix);
17
+ return norm.startsWith('./') ? norm.slice(2) : norm;
18
+ }
19
+
20
+ function resolveModuleSpec(fromFile, spec, fileMap) {
21
+ if (!isRelativeSpec(spec)) return null;
22
+ const fromDir = path.posix.dirname(fromFile);
23
+ const joined = normalizeVirtualPath(path.posix.join(fromDir, spec));
24
+
25
+ const candidates = [];
26
+ const addExtCandidates = base => {
27
+ candidates.push(base);
28
+ candidates.push(`${base}.ts`, `${base}.mts`, `${base}.cts`, `${base}.tsx`);
29
+ candidates.push(`${base}/index.ts`, `${base}/index.mts`, `${base}/index.cts`, `${base}/index.tsx`);
30
+ };
31
+
32
+ // Support TS ESM extension mapping: `./foo.js` -> `./foo.ts` / `./foo.tsx`, `.mjs` -> `.mts`, `.cjs` -> `.cts`.
33
+ if (/\.mjs$/i.test(joined)) {
34
+ candidates.push(joined.replace(/\.mjs$/i, '.mts'));
35
+ } else if (/\.cjs$/i.test(joined)) {
36
+ candidates.push(joined.replace(/\.cjs$/i, '.cts'));
37
+ } else if (/\.jsx$/i.test(joined)) {
38
+ candidates.push(joined.replace(/\.jsx$/i, '.tsx'));
39
+ } else if (/\.js$/i.test(joined)) {
40
+ candidates.push(joined.replace(/\.js$/i, '.ts'), joined.replace(/\.js$/i, '.tsx'));
41
+ }
42
+ addExtCandidates(joined);
43
+
44
+ if (fileMap) {
45
+ for (const c of candidates) {
46
+ if (Object.prototype.hasOwnProperty.call(fileMap, c)) return c;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ for (const c of candidates) {
52
+ try {
53
+ if (fs.existsSync(c) && fs.statSync(c).isFile()) return c;
54
+ } catch {
55
+ // ignore fs errors
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+
61
+ function readSource(filePath, fileMap) {
62
+ if (fileMap) return fileMap[filePath];
63
+ return fs.readFileSync(filePath);
64
+ }
65
+
66
+ function isIdStartChar(c) {
67
+ return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 36;
68
+ }
69
+
70
+ function isIdPartChar(c) {
71
+ return isIdStartChar(c) || (c >= 48 && c <= 57);
72
+ }
73
+
74
+ function skipWsAndComments(text, pos) {
75
+ const len = text.length;
76
+ while (pos < len) {
77
+ const c = text[pos];
78
+ if (c === ' ' || c === '\t' || c === '\n' || c === '\r') { pos++; continue; }
79
+ if (c === '/' && text[pos + 1] === '/') {
80
+ pos += 2;
81
+ while (pos < len && text[pos] !== '\n' && text[pos] !== '\r') pos++;
82
+ continue;
83
+ }
84
+ if (c === '/' && text[pos + 1] === '*') {
85
+ const end = text.indexOf('*/', pos + 2);
86
+ pos = end < 0 ? len : end + 2;
87
+ continue;
88
+ }
89
+ break;
90
+ }
91
+ return pos;
92
+ }
93
+
94
+ function readQuotedString(text, pos) {
95
+ const len = text.length;
96
+ const q = text[pos];
97
+ if (q !== '"' && q !== "'") return null;
98
+ let i = pos + 1;
99
+ while (i < len && text[i] !== q) {
100
+ if (text[i] === '\\') i += 2;
101
+ else if (text[i] === '\n' || text[i] === '\r') return null;
102
+ else i++;
103
+ }
104
+ if (i >= len) return null;
105
+ return { value: text.slice(pos + 1, i), end: i + 1 };
106
+ }
107
+
108
+ // Syntactically extracts relative module specifiers from:
109
+ // - `import ... from "./spec"` / `import "./spec"`
110
+ // - `export ... from "./spec"` (including multiline `export *\n from "./spec"`)
111
+ // - `import("./spec")` type queries
112
+ // Does NOT capture string values in variable initializers like `export const path: string = "./d";`.
113
+ function extractRelativeSpecifiers(sourceText) {
114
+ const specs = [];
115
+ const len = sourceText.length;
116
+ let i = 0;
117
+ let braceDepth = 0;
118
+ let parenDepth = 0;
119
+ let bracketDepth = 0;
120
+ const templateBraceStack = [];
121
+
122
+ while (i < len) {
123
+ const c = sourceText[i];
124
+ if (c === '/' && sourceText[i + 1] === '/') {
125
+ i += 2;
126
+ while (i < len && sourceText[i] !== '\n' && sourceText[i] !== '\r') i++;
127
+ continue;
128
+ }
129
+ if (c === '/' && sourceText[i + 1] === '*') {
130
+ const end = sourceText.indexOf('*/', i + 2);
131
+ i = end < 0 ? len : end + 2;
132
+ continue;
133
+ }
134
+ if (c === '"' || c === "'") {
135
+ const s = readQuotedString(sourceText, i);
136
+ i = s ? s.end : i + 1;
137
+ continue;
138
+ }
139
+ if (c === '`') {
140
+ i++;
141
+ let hitExpr = false;
142
+ while (i < len && sourceText[i] !== '`') {
143
+ if (sourceText[i] === '\\') { i += 2; continue; }
144
+ if (sourceText[i] === '$' && sourceText[i + 1] === '{') {
145
+ i += 2;
146
+ braceDepth++;
147
+ templateBraceStack.push(braceDepth);
148
+ hitExpr = true;
149
+ break;
150
+ }
151
+ i++;
152
+ }
153
+ if (!hitExpr && i < len && sourceText[i] === '`') i++;
154
+ continue;
155
+ }
156
+ if (c === '{') { braceDepth++; i++; continue; }
157
+ if (c === '}') {
158
+ if (templateBraceStack.length > 0 && templateBraceStack[templateBraceStack.length - 1] === braceDepth) {
159
+ templateBraceStack.pop();
160
+ if (braceDepth > 0) braceDepth--;
161
+ i++;
162
+ let hitExpr = false;
163
+ while (i < len && sourceText[i] !== '`') {
164
+ if (sourceText[i] === '\\') { i += 2; continue; }
165
+ if (sourceText[i] === '$' && sourceText[i + 1] === '{') {
166
+ i += 2;
167
+ braceDepth++;
168
+ templateBraceStack.push(braceDepth);
169
+ hitExpr = true;
170
+ break;
171
+ }
172
+ i++;
173
+ }
174
+ if (!hitExpr && i < len && sourceText[i] === '`') i++;
175
+ continue;
176
+ }
177
+ if (braceDepth > 0) braceDepth--;
178
+ i++;
179
+ continue;
180
+ }
181
+ if (c === '(') { parenDepth++; i++; continue; }
182
+ if (c === ')') { if (parenDepth > 0) parenDepth--; i++; continue; }
183
+ if (c === '[') { bracketDepth++; i++; continue; }
184
+ if (c === ']') { if (bracketDepth > 0) bracketDepth--; i++; continue; }
185
+
186
+ // Inline `import("./spec")` type query anywhere in types
187
+ if (sourceText.startsWith('import', i) &&
188
+ (i === 0 || !isIdPartChar(sourceText.charCodeAt(i - 1))) &&
189
+ !isIdPartChar(sourceText.charCodeAt(i + 6) || 0)) {
190
+ const afterImp = skipWsAndComments(sourceText, i + 6);
191
+ if (sourceText[afterImp] === '(') {
192
+ const argPos = skipWsAndComments(sourceText, afterImp + 1);
193
+ const q = readQuotedString(sourceText, argPos);
194
+ if (q) {
195
+ const closePos = skipWsAndComments(sourceText, q.end);
196
+ if (sourceText[closePos] === ')' && isRelativeSpec(q.value)) {
197
+ specs.push(q.value);
198
+ }
199
+ i = closePos + 1;
200
+ continue;
201
+ }
202
+ }
203
+ }
204
+
205
+ // Top-level `import ...` or `export ... from "..."`
206
+ if (braceDepth === 0 && parenDepth === 0 && bracketDepth === 0 &&
207
+ (sourceText.startsWith('import', i) || sourceText.startsWith('export', i)) &&
208
+ (i === 0 || !isIdPartChar(sourceText.charCodeAt(i - 1))) &&
209
+ !isIdPartChar(sourceText.charCodeAt(i + 6) || 0)) {
210
+ const isImport = sourceText[i] === 'i';
211
+ let j = skipWsAndComments(sourceText, i + 6);
212
+
213
+ if (isImport) {
214
+ // Side-effect import `import "./x";`
215
+ if (sourceText[j] === '"' || sourceText[j] === "'") {
216
+ const q = readQuotedString(sourceText, j);
217
+ if (q && isRelativeSpec(q.value)) specs.push(q.value);
218
+ i = q ? q.end : j + 1;
219
+ continue;
220
+ }
221
+ } else {
222
+ // Only `export * ... from "..."` or `export [type] { ... } from "..."` have a module specifier.
223
+ let p = j;
224
+ if (sourceText.startsWith('type', p) && !isIdPartChar(sourceText.charCodeAt(p + 4) || 0)) {
225
+ p = skipWsAndComments(sourceText, p + 4);
226
+ }
227
+ if (sourceText[p] !== '{' && sourceText[p] !== '*') {
228
+ i += 6;
229
+ continue;
230
+ }
231
+ }
232
+
233
+ // Scan forward until `from "..."` at depth 0, or `;` / non-re-export token.
234
+ let dBrace = 0;
235
+ while (j < len) {
236
+ j = skipWsAndComments(sourceText, j);
237
+ if (j >= len) break;
238
+ const ch = sourceText[j];
239
+ if (ch === '{') { dBrace++; j++; continue; }
240
+ if (ch === '}') { if (dBrace > 0) dBrace--; j++; continue; }
241
+ if (ch === ';' && dBrace === 0) { j++; break; }
242
+ if (dBrace === 0 && sourceText.startsWith('from', j) &&
243
+ !isIdPartChar(sourceText.charCodeAt(j + 4) || 0)) {
244
+ const specPos = skipWsAndComments(sourceText, j + 4);
245
+ const q = readQuotedString(sourceText, specPos);
246
+ if (q) {
247
+ if (isRelativeSpec(q.value)) specs.push(q.value);
248
+ j = q.end;
249
+ break;
250
+ }
251
+ }
252
+ if (ch === '"' || ch === "'") {
253
+ const q = readQuotedString(sourceText, j);
254
+ j = q ? q.end : j + 1;
255
+ continue;
256
+ }
257
+ j++;
258
+ }
259
+ i = j;
260
+ continue;
261
+ }
262
+
263
+ i++;
264
+ }
265
+ return specs;
266
+ }
267
+
268
+ // Splits emitted `.d.ts` text into top-level statements while respecting comments, strings, and `{ ... }` blocks.
269
+ function splitDtsStatements(dtsCode) {
270
+ const stmts = [];
271
+ const len = dtsCode.length;
272
+ let i = 0;
273
+
274
+ while (i < len) {
275
+ i = skipWsAndComments(dtsCode, i);
276
+ if (i >= len) break;
277
+
278
+ const start = i;
279
+ let brace = 0, paren = 0, bracket = 0;
280
+ let sawBlock = false;
281
+ const headSlice = dtsCode.slice(i, i + 80);
282
+ const isBlockDecl = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:const\s+)?(?:interface|class|enum|namespace)\b/.test(headSlice);
283
+
284
+ while (i < len) {
285
+ const c = dtsCode[i];
286
+ if (c === '/' && dtsCode[i + 1] === '/') {
287
+ i += 2;
288
+ while (i < len && dtsCode[i] !== '\n' && dtsCode[i] !== '\r') i++;
289
+ continue;
290
+ }
291
+ if (c === '/' && dtsCode[i + 1] === '*') {
292
+ const end = dtsCode.indexOf('*/', i + 2);
293
+ i = end < 0 ? len : end + 2;
294
+ continue;
295
+ }
296
+ if (c === '"' || c === "'") {
297
+ const s = readQuotedString(dtsCode, i);
298
+ i = s ? s.end : i + 1;
299
+ continue;
300
+ }
301
+ if (c === '`') {
302
+ i++;
303
+ while (i < len && dtsCode[i] !== '`') {
304
+ if (dtsCode[i] === '\\') i += 2;
305
+ else i++;
306
+ }
307
+ i++;
308
+ continue;
309
+ }
310
+ if (c === '(') paren++;
311
+ else if (c === ')') { if (paren > 0) paren--; }
312
+ else if (c === '[') bracket++;
313
+ else if (c === ']') { if (bracket > 0) bracket--; }
314
+ else if (c === '{') { brace++; sawBlock = true; }
315
+ else if (c === '}') {
316
+ if (brace > 0) brace--;
317
+ if (isBlockDecl && sawBlock && brace === 0 && paren === 0 && bracket === 0) {
318
+ i++;
319
+ while (i < len && (dtsCode[i] === ' ' || dtsCode[i] === '\t')) i++;
320
+ if (dtsCode[i] === ';') i++;
321
+ break;
322
+ }
323
+ } else if (c === ';' && brace === 0 && paren === 0 && bracket === 0) {
324
+ i++;
325
+ break;
326
+ } else if ((c === '\n' || c === '\r') && brace === 0 && paren === 0 && bracket === 0 && i > start) {
327
+ // Support semicolonless `.d.ts` declarations separated by newline before a new top-level statement keyword.
328
+ let nextPos = i + 1;
329
+ while (nextPos < len && (dtsCode[nextPos] === ' ' || dtsCode[nextPos] === '\t' || dtsCode[nextPos] === '\n' || dtsCode[nextPos] === '\r')) {
330
+ nextPos++;
331
+ }
332
+ if (/^(?:export|import|declare|type|interface|class|enum|const|let|var|function|abstract|namespace)\b/.test(dtsCode.slice(nextPos, nextPos + 20))) {
333
+ break;
334
+ }
335
+ }
336
+ i++;
337
+ }
338
+ const stmt = dtsCode.slice(start, i).trim();
339
+ if (stmt) stmts.push(stmt);
340
+ }
341
+ return stmts;
342
+ }
343
+
344
+ // Rewrites only the top-level declaration header name (e.g. `declare class Old` -> `declare class New`)
345
+ // and then rewrites symbol references in the remainder without touching property/member keys.
346
+ function rewriteDeclaration(stmt, declName, newDeclName, refRenameMap) {
347
+ let code = stmt;
348
+ let scanFrom = 0;
349
+
350
+ // Locate and optionally rename the declaration identifier in the header.
351
+ const hdr = /^((?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:const\s+)?(?:const|let|var|function|class|interface|type|enum|namespace)\s+)([A-Za-z_$][\w$]*)/.exec(code);
352
+ if (hdr && declName && hdr[2] === declName) {
353
+ const targetName = newDeclName || declName;
354
+ code = hdr[1] + targetName + code.slice(hdr[0].length);
355
+ scanFrom = hdr[1].length + targetName.length;
356
+ }
357
+
358
+ if (!refRenameMap || refRenameMap.size === 0) return code;
359
+
360
+ const len = code.length;
361
+ let out = code.slice(0, scanFrom);
362
+ let lastCopy = scanFrom;
363
+ let i = scanFrom;
364
+ let braceDepth = 0;
365
+ let parenDepth = 0;
366
+ const templateBraceStack = [];
367
+
368
+ while (i < len) {
369
+ const c = code.charCodeAt(i);
370
+ if (c === 47 /* / */ && i + 1 < len) {
371
+ const next = code.charCodeAt(i + 1);
372
+ if (next === 47) {
373
+ i += 2;
374
+ while (i < len && code.charCodeAt(i) !== 10 && code.charCodeAt(i) !== 13) i++;
375
+ continue;
376
+ }
377
+ if (next === 42) {
378
+ const end = code.indexOf('*/', i + 2);
379
+ i = end < 0 ? len : end + 2;
380
+ continue;
381
+ }
382
+ }
383
+ if (c === 34 || c === 39) {
384
+ const s = readQuotedString(code, i);
385
+ i = s ? s.end : i + 1;
386
+ continue;
387
+ }
388
+ if (c === 96 /* ` */) {
389
+ // Skip template literal static text; descend into `${ ... }` interpolations for identifier renaming.
390
+ i++;
391
+ let hitExpr = false;
392
+ while (i < len && code.charCodeAt(i) !== 96) {
393
+ if (code.charCodeAt(i) === 92) { i += 2; continue; }
394
+ if (code.charCodeAt(i) === 36 && code.charCodeAt(i + 1) === 123) {
395
+ i += 2;
396
+ braceDepth++;
397
+ templateBraceStack.push(braceDepth);
398
+ hitExpr = true;
399
+ break;
400
+ }
401
+ i++;
402
+ }
403
+ if (!hitExpr && i < len && code.charCodeAt(i) === 96) i++;
404
+ continue;
405
+ }
406
+ if (c === 123 /* { */) { braceDepth++; i++; continue; }
407
+ if (c === 125 /* } */) {
408
+ if (templateBraceStack.length > 0 && templateBraceStack[templateBraceStack.length - 1] === braceDepth) {
409
+ templateBraceStack.pop();
410
+ if (braceDepth > 0) braceDepth--;
411
+ i++;
412
+ let hitExpr = false;
413
+ while (i < len && code.charCodeAt(i) !== 96) {
414
+ if (code.charCodeAt(i) === 92) { i += 2; continue; }
415
+ if (code.charCodeAt(i) === 36 && code.charCodeAt(i + 1) === 123) {
416
+ i += 2;
417
+ braceDepth++;
418
+ templateBraceStack.push(braceDepth);
419
+ hitExpr = true;
420
+ break;
421
+ }
422
+ i++;
423
+ }
424
+ if (!hitExpr && i < len && code.charCodeAt(i) === 96) i++;
425
+ continue;
426
+ }
427
+ if (braceDepth > 0) braceDepth--;
428
+ i++;
429
+ continue;
430
+ }
431
+ if (c === 40 /* ( */) { parenDepth++; i++; continue; }
432
+ if (c === 41 /* ) */) { if (parenDepth > 0) parenDepth--; i++; continue; }
433
+
434
+ if (isIdStartChar(c)) {
435
+ const st = i;
436
+ i++;
437
+ while (i < len && isIdPartChar(code.charCodeAt(i))) i++;
438
+ const id = code.slice(st, i);
439
+ const replacement = refRenameMap.get(id);
440
+ if (replacement !== undefined) {
441
+ const prevIsDot = st > 0 && code.charCodeAt(st - 1) === 46;
442
+ const prevIsSpread = prevIsDot && st >= 3 && code.charCodeAt(st - 2) === 46 && code.charCodeAt(st - 3) === 46;
443
+
444
+ // Determine if `id` is a property/parameter/method name (never rename member keys).
445
+ let j = i;
446
+ while (j < len && (code[j] === ' ' || code[j] === '\t')) j++;
447
+ const nextIsColon = code[j] === ':' || (code[j] === '?' && code[j + 1] === ':');
448
+ const nextIsMethodOpen = code[j] === '(' || code[j] === '<';
449
+ const beforeSlice = code.slice(Math.max(0, st - 40), st).trimEnd();
450
+ const lastNonWs = beforeSlice.length > 0 ? beforeSlice[beforeSlice.length - 1] : '';
451
+ const prevIsMemberMod = /(?:^|[\s{;,])(?:readonly|public|protected|private|static|abstract|get|set)$/.test(beforeSlice);
452
+ const isMemberKey = (braceDepth > 0 && (nextIsColon || nextIsMethodOpen) &&
453
+ (lastNonWs === '{' || lastNonWs === ';' || lastNonWs === ',' || prevIsMemberMod));
454
+ const isParamName = (parenDepth > 0 && nextIsColon &&
455
+ (lastNonWs === '(' || lastNonWs === ',' || lastNonWs === '.' || prevIsMemberMod));
456
+
457
+ if ((!prevIsDot || prevIsSpread) && !isMemberKey && !isParamName) {
458
+ out += code.slice(lastCopy, st) + replacement;
459
+ lastCopy = i;
460
+ }
461
+ }
462
+ continue;
463
+ }
464
+ i++;
465
+ }
466
+ return out + code.slice(lastCopy);
467
+ }
468
+
469
+ function rebaseExternalSpec(entryFile, fromFile, spec) {
470
+ if (!isRelativeSpec(spec)) return spec;
471
+ const fromDir = path.posix.dirname(toPosix(fromFile));
472
+ const entryDir = path.posix.dirname(toPosix(entryFile));
473
+ if (fromDir === entryDir) return spec;
474
+ const joined = path.posix.normalize(path.posix.join(fromDir, spec));
475
+ const rel = path.posix.relative(entryDir, joined);
476
+ if (!rel) return '.';
477
+ return rel.startsWith('.') ? rel : `./${rel}`;
478
+ }
479
+
480
+ // Replaces inline `import("./rel").Member` type queries with resolved global symbols
481
+ // without modifying string literals or comments (while descending into template `${...}` expressions).
482
+ function rewriteInlineImportTypes(stmt, filePath, fileMap, resolveExportFn, diagnostics, resolveSpec, entryFile) {
483
+ if (!stmt.includes('import(')) return stmt;
484
+ const len = stmt.length;
485
+ let out = '';
486
+ let lastCopy = 0;
487
+ let i = 0;
488
+ let braceDepth = 0;
489
+ const templateBraceStack = [];
490
+ while (i < len) {
491
+ const ch = stmt[i];
492
+ if (ch === '/' && stmt[i + 1] === '/') {
493
+ i += 2;
494
+ while (i < len && stmt[i] !== '\n' && stmt[i] !== '\r') i++;
495
+ continue;
496
+ }
497
+ if (ch === '/' && stmt[i + 1] === '*') {
498
+ const end = stmt.indexOf('*/', i + 2);
499
+ i = end < 0 ? len : end + 2;
500
+ continue;
501
+ }
502
+ if (ch === '"' || ch === "'") {
503
+ const s = readQuotedString(stmt, i);
504
+ i = s ? s.end : i + 1;
505
+ continue;
506
+ }
507
+ if (ch === '`') {
508
+ i++;
509
+ let hitExpr = false;
510
+ while (i < len && stmt[i] !== '`') {
511
+ if (stmt[i] === '\\') { i += 2; continue; }
512
+ if (stmt[i] === '$' && stmt[i + 1] === '{') {
513
+ i += 2;
514
+ braceDepth++;
515
+ templateBraceStack.push(braceDepth);
516
+ hitExpr = true;
517
+ break;
518
+ }
519
+ i++;
520
+ }
521
+ if (!hitExpr && i < len && stmt[i] === '`') i++;
522
+ continue;
523
+ }
524
+ if (ch === '{') { braceDepth++; i++; continue; }
525
+ if (ch === '}') {
526
+ if (templateBraceStack.length > 0 && templateBraceStack[templateBraceStack.length - 1] === braceDepth) {
527
+ templateBraceStack.pop();
528
+ if (braceDepth > 0) braceDepth--;
529
+ i++;
530
+ let hitExpr = false;
531
+ while (i < len && stmt[i] !== '`') {
532
+ if (stmt[i] === '\\') { i += 2; continue; }
533
+ if (stmt[i] === '$' && stmt[i + 1] === '{') {
534
+ i += 2;
535
+ braceDepth++;
536
+ templateBraceStack.push(braceDepth);
537
+ hitExpr = true;
538
+ break;
539
+ }
540
+ i++;
541
+ }
542
+ if (!hitExpr && i < len && stmt[i] === '`') i++;
543
+ continue;
544
+ }
545
+ if (braceDepth > 0) braceDepth--;
546
+ i++;
547
+ continue;
548
+ }
549
+ if (ch === 'i' && stmt.startsWith('import', i)) {
550
+ const prevOk = i === 0 || !isIdPartChar(stmt.charCodeAt(i - 1));
551
+ if (prevOk) {
552
+ const tail = stmt.slice(i);
553
+ const m = /^import\(\s*(["'])([^"']+)\1\s*\)(?:\.([A-Za-z_$][\w$]*))?/.exec(tail);
554
+ if (m) {
555
+ const full = m[0];
556
+ const spec = m[2];
557
+ const member = m[3] || null;
558
+ const res = resolveSpec
559
+ ? resolveSpec(filePath, spec)
560
+ : (isRelativeSpec(spec) ? { path: resolveModuleSpec(filePath, spec, fileMap), external: false } : { path: null, external: true });
561
+ let replacement = full;
562
+ if (res.external) {
563
+ const rebased = entryFile ? rebaseExternalSpec(entryFile, filePath, spec) : spec;
564
+ if (rebased !== spec) {
565
+ replacement = member ? `import(${m[1]}${rebased}${m[1]}).${member}` : `import(${m[1]}${rebased}${m[1]})`;
566
+ }
567
+ } else if (member) {
568
+ const target = res.path;
569
+ if (!target) {
570
+ diagnostics.push({
571
+ file: filePath,
572
+ code: 'UNRESOLVED_MODULE',
573
+ severity: 'error',
574
+ message: `Cannot resolve module "${spec}"`,
575
+ start: 0,
576
+ end: 0,
577
+ });
578
+ } else {
579
+ const resolved = resolveExportFn(target, member);
580
+ if (!resolved) {
581
+ diagnostics.push({
582
+ file: filePath,
583
+ code: 'UNRESOLVED_EXPORT',
584
+ severity: 'error',
585
+ message: `Module "${target}" does not export "${member}"`,
586
+ start: 0,
587
+ end: 0,
588
+ });
589
+ } else {
590
+ replacement = resolved.globalName;
591
+ }
592
+ }
593
+ }
594
+ if (replacement !== full) {
595
+ out += stmt.slice(lastCopy, i) + replacement;
596
+ i += full.length;
597
+ lastCopy = i;
598
+ continue;
599
+ }
600
+ i += full.length;
601
+ continue;
602
+ }
603
+ }
604
+ }
605
+ i++;
606
+ }
607
+ return lastCopy === 0 ? stmt : out + stmt.slice(lastCopy);
608
+ }
609
+
610
+ function stripExportPrefix(stmt, keepDeclare) {
611
+ let s = stmt.replace(/^export\s+(?:default\s+)?/, '');
612
+ if (keepDeclare && /^(?:const|let|var|function|class|abstract\s+class|enum|const\s+enum|namespace)\b/.test(s)) {
613
+ s = `declare ${s}`;
614
+ }
615
+ return s;
616
+ }
617
+
618
+ function parseDtsModule(filePath, dtsCode, fileMap, diagnostics, resolveSpec, entryFile) {
619
+ const resolveOne = spec => {
620
+ if (resolveSpec) return resolveSpec(filePath, spec);
621
+ if (!isRelativeSpec(spec)) return { path: null, external: true };
622
+ return { path: resolveModuleSpec(filePath, spec, fileMap), external: false };
623
+ };
624
+ const rebaseExt = spec => (entryFile ? rebaseExternalSpec(entryFile, filePath, spec) : spec);
625
+ const stmts = splitDtsStatements(dtsCode);
626
+ const externalImports = []; // { spec, kind: 'named'|'ns'|'default', isType, items?, local? }
627
+ const internalImports = []; // { target, kind, isType, items?, local? }
628
+ const reExports = []; // { target, kind: 'named'|'star'|'ns', isType, items?, alias? }
629
+ const externalReExports = []; // raw `export ... from "bare"` statements
630
+ const localExports = []; // { local, exported, isType }
631
+ const decls = []; // { name, exported, isDefault, raw, kind }
632
+ let hasDefaultExportExpr = null; // e.g. `export default Foo;`
633
+
634
+ for (const stmt of stmts) {
635
+ // 1. import statements
636
+ // 1a. Combined default + named import: `import C, { A } from "..."`
637
+ const impDefNamed = /^import\s+(type\s+)?([A-Za-z_$][\w$]*)\s*,\s*\{([^{}]+)\}\s*from\s*["']([^"']+)["']\s*;?$/s.exec(stmt);
638
+ if (impDefNamed) {
639
+ const isType = !!impDefNamed[1];
640
+ const defLocal = impDefNamed[2];
641
+ const spec = impDefNamed[4];
642
+ const items = impDefNamed[3].split(',').map(s => s.trim()).filter(Boolean).map(part => {
643
+ const m = /^(type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(part);
644
+ return m ? { isType: !!m[1], imported: m[2], local: m[3] || m[2] } : null;
645
+ }).filter(Boolean);
646
+ const res = resolveOne(spec);
647
+ if (!res.external) {
648
+ if (!res.path) {
649
+ diagnostics.push({ file: filePath, code: 'UNRESOLVED_MODULE', severity: 'error', message: `Cannot resolve relative module "${spec}"`, start: 0, end: 0 });
650
+ } else {
651
+ internalImports.push({ target: res.path, kind: 'default', isType, local: defLocal });
652
+ internalImports.push({ target: res.path, kind: 'named', isType, items });
653
+ }
654
+ } else {
655
+ externalImports.push({ spec: rebaseExt(spec), kind: 'default', isType, local: defLocal });
656
+ externalImports.push({ spec: rebaseExt(spec), kind: 'named', isType, items });
657
+ }
658
+ continue;
659
+ }
660
+ const impNamed = /^import\s+(type\s+)?\{([^{}]+)\}\s*from\s*["']([^"']+)["']\s*;?$/s.exec(stmt);
661
+ if (impNamed) {
662
+ const isType = !!impNamed[1];
663
+ const spec = impNamed[3];
664
+ const items = impNamed[2].split(',').map(s => s.trim()).filter(Boolean).map(part => {
665
+ const m = /^(type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(part);
666
+ return m ? { isType: !!m[1], imported: m[2], local: m[3] || m[2] } : null;
667
+ }).filter(Boolean);
668
+ const res = resolveOne(spec);
669
+ if (!res.external) {
670
+ if (!res.path) {
671
+ diagnostics.push({ file: filePath, code: 'UNRESOLVED_MODULE', severity: 'error', message: `Cannot resolve relative module "${spec}"`, start: 0, end: 0 });
672
+ } else {
673
+ internalImports.push({ target: res.path, kind: 'named', isType, items });
674
+ }
675
+ } else {
676
+ externalImports.push({ spec: rebaseExt(spec), kind: 'named', isType, items });
677
+ }
678
+ continue;
679
+ }
680
+ const impNs = /^import\s+(type\s+)?\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s*["']([^"']+)["']\s*;?$/s.exec(stmt);
681
+ if (impNs) {
682
+ const isType = !!impNs[1];
683
+ const local = impNs[2];
684
+ const spec = impNs[3];
685
+ const res = resolveOne(spec);
686
+ if (!res.external) {
687
+ if (!res.path) {
688
+ diagnostics.push({ file: filePath, code: 'UNRESOLVED_MODULE', severity: 'error', message: `Cannot resolve relative module "${spec}"`, start: 0, end: 0 });
689
+ } else {
690
+ internalImports.push({ target: res.path, kind: 'ns', isType, local });
691
+ }
692
+ } else {
693
+ externalImports.push({ spec: rebaseExt(spec), kind: 'ns', isType, local });
694
+ }
695
+ continue;
696
+ }
697
+ const impDef = /^import\s+(type\s+)?([A-Za-z_$][\w$]*)\s+from\s*["']([^"']+)["']\s*;?$/s.exec(stmt);
698
+ if (impDef) {
699
+ const isType = !!impDef[1];
700
+ const local = impDef[2];
701
+ const spec = impDef[3];
702
+ const res = resolveOne(spec);
703
+ if (!res.external) {
704
+ if (!res.path) {
705
+ diagnostics.push({ file: filePath, code: 'UNRESOLVED_MODULE', severity: 'error', message: `Cannot resolve relative module "${spec}"`, start: 0, end: 0 });
706
+ } else {
707
+ internalImports.push({ target: res.path, kind: 'default', isType, local });
708
+ }
709
+ } else {
710
+ externalImports.push({ spec: rebaseExt(spec), kind: 'default', isType, local });
711
+ }
712
+ continue;
713
+ }
714
+
715
+ // 2. export ... from "..."
716
+ const expStarNs = /^export\s+(type\s+)?\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s*["']([^"']+)["']\s*;?$/s.exec(stmt);
717
+ if (expStarNs) {
718
+ const isType = !!expStarNs[1];
719
+ const alias = expStarNs[2];
720
+ const spec = expStarNs[3];
721
+ const res = resolveOne(spec);
722
+ if (!res.external) {
723
+ if (!res.path) {
724
+ diagnostics.push({ file: filePath, code: 'UNRESOLVED_MODULE', severity: 'error', message: `Cannot resolve relative module "${spec}"`, start: 0, end: 0 });
725
+ } else {
726
+ reExports.push({ target: res.path, kind: 'ns', isType, alias });
727
+ }
728
+ } else {
729
+ externalReExports.push({ kind: 'ns', isType, alias, spec: rebaseExt(spec) });
730
+ }
731
+ continue;
732
+ }
733
+ const expStar = /^export\s+(type\s+)?\*\s+from\s*["']([^"']+)["']\s*;?$/s.exec(stmt);
734
+ if (expStar) {
735
+ const isType = !!expStar[1];
736
+ const spec = expStar[2];
737
+ const res = resolveOne(spec);
738
+ if (!res.external) {
739
+ if (!res.path) {
740
+ diagnostics.push({ file: filePath, code: 'UNRESOLVED_MODULE', severity: 'error', message: `Cannot resolve relative module "${spec}"`, start: 0, end: 0 });
741
+ } else {
742
+ reExports.push({ target: res.path, kind: 'star', isType });
743
+ }
744
+ } else {
745
+ externalReExports.push({ kind: 'star', isType, spec: rebaseExt(spec) });
746
+ }
747
+ continue;
748
+ }
749
+ const expNamedFrom = /^export\s+(type\s+)?\{([^{}]+)\}\s*from\s*["']([^"']+)["']\s*;?$/s.exec(stmt);
750
+ if (expNamedFrom) {
751
+ const isType = !!expNamedFrom[1];
752
+ const spec = expNamedFrom[3];
753
+ const items = expNamedFrom[2].split(',').map(s => s.trim()).filter(Boolean).map(part => {
754
+ const m = /^(type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(part);
755
+ return m ? { isType: isType || !!m[1], imported: m[2], exported: m[3] || m[2] } : null;
756
+ }).filter(Boolean);
757
+ const res = resolveOne(spec);
758
+ if (!res.external) {
759
+ if (!res.path) {
760
+ diagnostics.push({ file: filePath, code: 'UNRESOLVED_MODULE', severity: 'error', message: `Cannot resolve relative module "${spec}"`, start: 0, end: 0 });
761
+ } else {
762
+ reExports.push({ target: res.path, kind: 'named', isType, items });
763
+ }
764
+ } else {
765
+ externalReExports.push({ kind: 'named', isType, spec: rebaseExt(spec), items });
766
+ }
767
+ continue;
768
+ }
769
+
770
+ // 3. export { ... }; (local re-export)
771
+ const expLocal = /^export\s+(type\s+)?\{([^{}]*)\}\s*;?$/s.exec(stmt);
772
+ if (expLocal) {
773
+ const isType = !!expLocal[1];
774
+ const inner = expLocal[2].trim();
775
+ if (inner) {
776
+ for (const part of inner.split(',')) {
777
+ const t = part.trim();
778
+ if (!t) continue;
779
+ const m = /^(type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(t);
780
+ if (m) localExports.push({ isType: isType || !!m[1], local: m[2], exported: m[3] || m[2] });
781
+ }
782
+ }
783
+ continue;
784
+ }
785
+
786
+ // 4. `export default Identifier;`
787
+ const expDefId = /^export\s+default\s+([A-Za-z_$][\w$]*)\s*;?$/.exec(stmt);
788
+ if (expDefId) {
789
+ hasDefaultExportExpr = { local: expDefId[1], raw: stmt };
790
+ continue;
791
+ }
792
+
793
+ // 5. Declaration statement (including `export default interface/class/function ...`)
794
+ const isDefault = /^export\s+default\s+/.test(stmt);
795
+ const isExported = /^export\s+/.test(stmt);
796
+ const declMatch = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:const\s+)?(const|let|var|function|class|interface|type|enum|namespace)\s+([A-Za-z_$][\w$]*)/.exec(stmt);
797
+ decls.push({
798
+ name: declMatch ? declMatch[2] : null,
799
+ exported: isExported,
800
+ isDefault,
801
+ raw: stmt,
802
+ kind: declMatch ? declMatch[1] : 'other',
803
+ });
804
+ }
805
+
806
+ return { filePath, externalImports, internalImports, reExports, externalReExports, localExports, decls, hasDefaultExportExpr };
807
+ }
808
+
809
+ function discoverGraph(entry, fileMap) {
810
+ const normalizedEntry = fileMap ? normalizeVirtualPath(entry) : toPosix(path.resolve(entry));
811
+ const visited = new Set();
812
+ const order = [];
813
+ const sources = new Map();
814
+ const diagnostics = [];
815
+
816
+ function visit(file) {
817
+ if (visited.has(file)) return;
818
+ visited.add(file);
819
+ const raw = readSource(file, fileMap);
820
+ if (raw === undefined) {
821
+ diagnostics.push({
822
+ file,
823
+ code: 'UNRESOLVED_MODULE',
824
+ severity: 'error',
825
+ message: `Cannot read module "${file}"`,
826
+ start: 0,
827
+ end: 0,
828
+ });
829
+ return;
830
+ }
831
+ sources.set(file, raw);
832
+ const text = typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf8');
833
+ const relSpecs = extractRelativeSpecifiers(text);
834
+ for (const spec of relSpecs) {
835
+ const resolved = resolveModuleSpec(file, spec, fileMap);
836
+ if (!resolved) {
837
+ diagnostics.push({
838
+ file,
839
+ code: 'UNRESOLVED_MODULE',
840
+ severity: 'error',
841
+ message: `Cannot resolve relative module "${spec}"`,
842
+ start: 0,
843
+ end: 0,
844
+ });
845
+ } else {
846
+ visit(resolved);
847
+ }
848
+ }
849
+ order.push(file);
850
+ }
851
+
852
+ visit(normalizedEntry);
853
+ return { entry: normalizedEntry, order, sources, diagnostics };
854
+ }
855
+
856
+ function assembleBundle(entry, order, dtsByFile, fileMap, resolveSpec) {
857
+ const diagnostics = [];
858
+ const modules = new Map();
859
+ for (const file of order) {
860
+ modules.set(file, parseDtsModule(file, dtsByFile.get(file), fileMap, diagnostics, resolveSpec, entry));
861
+ }
862
+ if (diagnostics.length > 0) return { code: null, diagnostics };
863
+
864
+ const usedGlobalNames = new Set();
865
+ const allocateName = preferred => {
866
+ if (!usedGlobalNames.has(preferred)) {
867
+ usedGlobalNames.add(preferred);
868
+ return preferred;
869
+ }
870
+ let idx = 1;
871
+ while (usedGlobalNames.has(`${preferred}$${idx}`)) idx++;
872
+ const chosen = `${preferred}$${idx}`;
873
+ usedGlobalNames.add(chosen);
874
+ return chosen;
875
+ };
876
+
877
+ const symbolGlobalName = new Map(); // `${file}#${declName}` -> globalName
878
+ const defaultGlobalName = new Map(); // file -> globalName
879
+ const moduleRenameMap = new Map(); // file -> Map<localName, globalName>
880
+ for (const file of order) moduleRenameMap.set(file, new Map());
881
+
882
+ // 1. Allocate globally unique names for external imports (preventing collisions across packages).
883
+ // Key: `${spec}\0${kind}\0${imported}` -> { spec, kind, imported, globalLocal, isType }
884
+ const extBindings = new Map();
885
+ for (const file of order) {
886
+ const mod = modules.get(file);
887
+ const rmap = moduleRenameMap.get(file);
888
+ for (const imp of mod.externalImports) {
889
+ if (imp.kind === 'named') {
890
+ for (const it of imp.items) {
891
+ const key = `${imp.spec}\0named\0${it.imported}`;
892
+ let entryRec = extBindings.get(key);
893
+ if (!entryRec) {
894
+ const gname = allocateName(it.local);
895
+ entryRec = { spec: imp.spec, kind: 'named', imported: it.imported, globalLocal: gname, isType: imp.isType || it.isType };
896
+ extBindings.set(key, entryRec);
897
+ } else if (!(imp.isType || it.isType)) {
898
+ entryRec.isType = false;
899
+ }
900
+ if (entryRec.globalLocal !== it.local) {
901
+ rmap.set(it.local, entryRec.globalLocal);
902
+ }
903
+ }
904
+ } else {
905
+ const key = `${imp.spec}\0${imp.kind}\0*`;
906
+ let entryRec = extBindings.get(key);
907
+ if (!entryRec) {
908
+ const gname = allocateName(imp.local);
909
+ entryRec = { spec: imp.spec, kind: imp.kind, imported: '*', globalLocal: gname, isType: imp.isType };
910
+ extBindings.set(key, entryRec);
911
+ } else if (!imp.isType) {
912
+ entryRec.isType = false;
913
+ }
914
+ if (entryRec.globalLocal !== imp.local) {
915
+ rmap.set(imp.local, entryRec.globalLocal);
916
+ }
917
+ }
918
+ }
919
+ }
920
+
921
+ // 2. Allocate globally unique names for all module declarations (entry gets name priority).
922
+ const allocOrder = [entry, ...order.filter(f => f !== entry)];
923
+ for (const file of allocOrder) {
924
+ const mod = modules.get(file);
925
+ const rmap = moduleRenameMap.get(file);
926
+ for (const d of mod.decls) {
927
+ if (d.name) {
928
+ const gname = allocateName(d.name);
929
+ symbolGlobalName.set(`${file}#${d.name}`, gname);
930
+ if (gname !== d.name) rmap.set(d.name, gname);
931
+ if (d.isDefault) defaultGlobalName.set(file, gname);
932
+ } else if (d.isDefault) {
933
+ const gname = allocateName('_default');
934
+ d.syntheticName = gname;
935
+ defaultGlobalName.set(file, gname);
936
+ }
937
+ }
938
+ }
939
+
940
+ // 3. Resolve exports recursively through declarations, localExports, internalImports, and reExports.
941
+ const resolveExportTarget = (file, exportName, seen = new Set()) => {
942
+ const visitKey = `${file}#${exportName}`;
943
+ if (seen.has(visitKey)) return null;
944
+ seen.add(visitKey);
945
+ const mod = modules.get(file);
946
+ if (!mod) return null;
947
+
948
+ if (exportName === 'default') {
949
+ if (defaultGlobalName.has(file)) {
950
+ return { globalName: defaultGlobalName.get(file), typeOnly: false };
951
+ }
952
+ if (mod.hasDefaultExportExpr) {
953
+ const loc = mod.hasDefaultExportExpr.local;
954
+ if (symbolGlobalName.has(`${file}#${loc}`)) {
955
+ return { globalName: symbolGlobalName.get(`${file}#${loc}`), typeOnly: false };
956
+ }
957
+ for (const imp of mod.internalImports) {
958
+ if (imp.kind === 'named') {
959
+ for (const it of imp.items) {
960
+ if (it.local === loc) {
961
+ const t = resolveExportTarget(imp.target, it.imported, seen);
962
+ if (t) return { globalName: t.globalName, typeOnly: t.typeOnly || imp.isType || it.isType };
963
+ }
964
+ }
965
+ } else if (imp.kind === 'default' && imp.local === loc) {
966
+ const t = resolveExportTarget(imp.target, 'default', seen);
967
+ if (t) return { globalName: t.globalName, typeOnly: t.typeOnly || imp.isType };
968
+ }
969
+ }
970
+ }
971
+ return null;
972
+ }
973
+
974
+ if (symbolGlobalName.has(visitKey)) {
975
+ const decl = mod.decls.find(d => d.name === exportName);
976
+ if (decl && decl.exported) {
977
+ return { globalName: symbolGlobalName.get(visitKey), typeOnly: decl.kind === 'type' || decl.kind === 'interface' };
978
+ }
979
+ }
980
+
981
+ for (const le of mod.localExports) {
982
+ if (le.exported === exportName) {
983
+ if (symbolGlobalName.has(`${file}#${le.local}`)) {
984
+ return { globalName: symbolGlobalName.get(`${file}#${le.local}`), typeOnly: le.isType };
985
+ }
986
+ // Check if `le.local` came from an internal import in the same module.
987
+ for (const imp of mod.internalImports) {
988
+ if (imp.kind === 'named') {
989
+ for (const it of imp.items) {
990
+ if (it.local === le.local) {
991
+ const t = resolveExportTarget(imp.target, it.imported, seen);
992
+ if (t) return { globalName: t.globalName, typeOnly: t.typeOnly || le.isType || imp.isType || it.isType };
993
+ }
994
+ }
995
+ } else if (imp.kind === 'default' && imp.local === le.local) {
996
+ const t = resolveExportTarget(imp.target, 'default', seen);
997
+ if (t) return { globalName: t.globalName, typeOnly: t.typeOnly || le.isType || imp.isType };
998
+ }
999
+ }
1000
+ }
1001
+ }
1002
+
1003
+ for (const re of mod.reExports) {
1004
+ if (re.kind === 'named') {
1005
+ for (const it of re.items) {
1006
+ if (it.exported === exportName) {
1007
+ const t = resolveExportTarget(re.target, it.imported, seen);
1008
+ if (t) return { globalName: t.globalName, typeOnly: t.typeOnly || re.isType || it.isType };
1009
+ }
1010
+ }
1011
+ } else if (re.kind === 'star') {
1012
+ const t = resolveExportTarget(re.target, exportName, seen);
1013
+ if (t) return { globalName: t.globalName, typeOnly: t.typeOnly || re.isType };
1014
+ }
1015
+ }
1016
+ return null;
1017
+ };
1018
+
1019
+ // Collect all exported bindings of any module (for `export *` and `export * as ns` / `import * as ns`).
1020
+ const collectModuleExports = (file, seen = new Set()) => {
1021
+ const out = new Map(); // exportedName -> { globalName, typeOnly }
1022
+ if (seen.has(file)) return out;
1023
+ seen.add(file);
1024
+ const mod = modules.get(file);
1025
+ if (!mod) return out;
1026
+ for (const d of mod.decls) {
1027
+ if (d.exported && !d.isDefault && d.name) {
1028
+ out.set(d.name, {
1029
+ globalName: symbolGlobalName.get(`${file}#${d.name}`),
1030
+ typeOnly: d.kind === 'type' || d.kind === 'interface',
1031
+ });
1032
+ }
1033
+ }
1034
+ for (const le of mod.localExports) {
1035
+ if (le.exported === 'default') continue;
1036
+ const t = resolveExportTarget(file, le.exported);
1037
+ if (t) out.set(le.exported, t);
1038
+ }
1039
+ for (const re of mod.reExports) {
1040
+ if (re.kind === 'named') {
1041
+ for (const it of re.items) {
1042
+ if (it.exported === 'default') continue;
1043
+ const t = resolveExportTarget(re.target, it.imported);
1044
+ if (t) out.set(it.exported, { globalName: t.globalName, typeOnly: t.typeOnly || re.isType || it.isType });
1045
+ }
1046
+ } else if (re.kind === 'star') {
1047
+ for (const [name, rec] of collectModuleExports(re.target, seen).entries()) {
1048
+ if (name === 'default') continue;
1049
+ const nextTypeOnly = rec.typeOnly || re.isType;
1050
+ const prev = out.get(name);
1051
+ if (!prev) out.set(name, { globalName: rec.globalName, typeOnly: nextTypeOnly });
1052
+ else if (prev.typeOnly && !nextTypeOnly) prev.typeOnly = false;
1053
+ }
1054
+ }
1055
+ }
1056
+ return out;
1057
+ };
1058
+
1059
+ // Helper to resolve external named/ns re-exports relayed through internal modules.
1060
+ const resolveExternalNamedExport = (targetFile, exportedName, seen = new Set()) => {
1061
+ if (seen.has(targetFile)) return null;
1062
+ seen.add(targetFile);
1063
+ const mod = modules.get(targetFile);
1064
+ if (!mod) return null;
1065
+ for (const extRec of mod.externalReExports) {
1066
+ if (extRec.kind === 'named') {
1067
+ const hit = extRec.items.find(it => it.exported === exportedName);
1068
+ if (hit) {
1069
+ return { spec: extRec.spec, imported: hit.imported, isType: extRec.isType || hit.isType };
1070
+ }
1071
+ } else if (extRec.kind === 'ns' && extRec.alias === exportedName) {
1072
+ return { kind: 'ns', spec: extRec.spec, isType: extRec.isType };
1073
+ }
1074
+ }
1075
+ for (const subRe of mod.reExports) {
1076
+ if (subRe.kind === 'named') {
1077
+ const hit = subRe.items.find(it => it.exported === exportedName);
1078
+ if (hit) {
1079
+ const found = resolveExternalNamedExport(subRe.target, hit.imported, seen);
1080
+ if (found) return { ...found, isType: found.isType || subRe.isType || hit.isType };
1081
+ }
1082
+ } else if (subRe.kind === 'star' && exportedName !== 'default') {
1083
+ const found = resolveExternalNamedExport(subRe.target, exportedName, seen);
1084
+ if (found) return { ...found, isType: found.isType || subRe.isType };
1085
+ }
1086
+ }
1087
+ return null;
1088
+ };
1089
+
1090
+ // 4. Synthesize namespace wrappers for internal `import * as D from "./d"` and `export * as M from "./a"`.
1091
+ const internalNamespaces = []; // { globalName, targetFile, exported: boolean, exportAlias?: string, typeOnly: boolean }
1092
+ const nsGlobalForTarget = new Map(); // `${targetFile}\0${preferred}` -> globalName
1093
+
1094
+ for (const file of order) {
1095
+ const mod = modules.get(file);
1096
+ const rmap = moduleRenameMap.get(file);
1097
+ for (const imp of mod.internalImports) {
1098
+ if (imp.kind === 'named') {
1099
+ for (const it of imp.items) {
1100
+ const t = resolveExportTarget(imp.target, it.imported);
1101
+ if (t) {
1102
+ if (t.globalName !== it.local) {
1103
+ rmap.set(it.local, t.globalName);
1104
+ }
1105
+ continue;
1106
+ }
1107
+ const extT = resolveExternalNamedExport(imp.target, it.imported);
1108
+ if (extT && extT.kind !== 'ns') {
1109
+ const isType = imp.isType || it.isType || extT.isType;
1110
+ const key = `${extT.spec}\0named\0${extT.imported}`;
1111
+ let rec = extBindings.get(key);
1112
+ if (!rec) {
1113
+ const globalLocal = allocateName(it.local);
1114
+ rec = { spec: extT.spec, kind: 'named', imported: extT.imported, globalLocal, isType };
1115
+ extBindings.set(key, rec);
1116
+ } else if (!isType) {
1117
+ rec.isType = false;
1118
+ }
1119
+ if (rec.globalLocal !== it.local) {
1120
+ rmap.set(it.local, rec.globalLocal);
1121
+ }
1122
+ continue;
1123
+ }
1124
+ diagnostics.push({
1125
+ file,
1126
+ code: 'UNRESOLVED_EXPORT',
1127
+ severity: 'error',
1128
+ message: `Module "${imp.target}" does not export "${it.imported}"`,
1129
+ start: 0,
1130
+ end: 0,
1131
+ });
1132
+ }
1133
+ } else if (imp.kind === 'default') {
1134
+ const t = resolveExportTarget(imp.target, 'default');
1135
+ if (!t) {
1136
+ diagnostics.push({
1137
+ file,
1138
+ code: 'UNRESOLVED_EXPORT',
1139
+ severity: 'error',
1140
+ message: `Module "${imp.target}" has no default export`,
1141
+ start: 0,
1142
+ end: 0,
1143
+ });
1144
+ } else if (t.globalName !== imp.local) {
1145
+ rmap.set(imp.local, t.globalName);
1146
+ }
1147
+ } else if (imp.kind === 'ns') {
1148
+ const key = `${imp.target}\0${imp.local}`;
1149
+ let gns = nsGlobalForTarget.get(key);
1150
+ if (!gns) {
1151
+ gns = allocateName(imp.local);
1152
+ nsGlobalForTarget.set(key, gns);
1153
+ internalNamespaces.push({ globalName: gns, targetFile: imp.target, exported: false, typeOnly: imp.isType });
1154
+ }
1155
+ if (gns !== imp.local) rmap.set(imp.local, gns);
1156
+ }
1157
+ }
1158
+ }
1159
+
1160
+ if (diagnostics.length > 0) return { code: null, diagnostics };
1161
+
1162
+ // 5. Determine public exports of the entry module.
1163
+ const entryMod = modules.get(entry);
1164
+ const entryPublicExports = new Map(); // exportedName -> { globalName, typeOnly }
1165
+ // Structured external re-export aggregators (merge value vs type-only across diamond paths to prevent TS2300).
1166
+ const extNamedReExports = new Map(); // `${spec}\0${exported}` -> { spec, imported, exported, isType }
1167
+ const extStarReExports = new Map(); // spec -> { spec, isType }
1168
+ const extNsReExports = new Map(); // `${spec}\0${alias}` -> { spec, alias, isType }
1169
+ const seenInternalNsAliases = new Set();
1170
+
1171
+ const addExtNamed = (spec, imported, exported, isType) => {
1172
+ const k = `${spec}\0${exported}`;
1173
+ const prev = extNamedReExports.get(k);
1174
+ if (!prev) {
1175
+ extNamedReExports.set(k, { spec, imported, exported, isType });
1176
+ } else if (!isType) {
1177
+ // Value export supersedes type-only export for the same symbol in diamond graphs.
1178
+ prev.isType = false;
1179
+ }
1180
+ };
1181
+ const addExtStar = (spec, isType) => {
1182
+ const prev = extStarReExports.get(spec);
1183
+ if (!prev) extStarReExports.set(spec, { spec, isType });
1184
+ else if (!isType) prev.isType = false;
1185
+ };
1186
+ const addExtNs = (spec, alias, isType) => {
1187
+ const k = `${spec}\0${alias}`;
1188
+ const prev = extNsReExports.get(k);
1189
+ if (!prev) extNsReExports.set(k, { spec, alias, isType });
1190
+ else if (!isType) prev.isType = false;
1191
+ };
1192
+
1193
+ const ingestExternalReExport = (rec, forceTypeOnly, excludeDefault) => {
1194
+ const typeFlag = rec.isType || forceTypeOnly;
1195
+ if (rec.kind === 'star') {
1196
+ addExtStar(rec.spec, typeFlag);
1197
+ return;
1198
+ }
1199
+ if (rec.kind === 'ns') {
1200
+ if (excludeDefault && rec.alias === 'default') return;
1201
+ addExtNs(rec.spec, rec.alias, typeFlag);
1202
+ return;
1203
+ }
1204
+ for (const it of rec.items) {
1205
+ if (excludeDefault && it.exported === 'default') continue;
1206
+ addExtNamed(rec.spec, it.imported, it.exported, typeFlag || it.isType);
1207
+ }
1208
+ };
1209
+
1210
+ for (const extRec of entryMod.externalReExports) {
1211
+ ingestExternalReExport(extRec, false, false);
1212
+ }
1213
+
1214
+ for (const d of entryMod.decls) {
1215
+ if (d.exported && !d.isDefault && d.name) {
1216
+ entryPublicExports.set(d.name, {
1217
+ globalName: symbolGlobalName.get(`${entry}#${d.name}`),
1218
+ typeOnly: d.kind === 'type' || d.kind === 'interface',
1219
+ });
1220
+ }
1221
+ }
1222
+ for (const le of entryMod.localExports) {
1223
+ const t = resolveExportTarget(entry, le.exported);
1224
+ if (!t) {
1225
+ diagnostics.push({ file: entry, code: 'UNRESOLVED_EXPORT', severity: 'error', message: `Cannot resolve export "${le.local}"`, start: 0, end: 0 });
1226
+ } else {
1227
+ entryPublicExports.set(le.exported, t);
1228
+ }
1229
+ }
1230
+ for (const re of entryMod.reExports) {
1231
+ if (re.kind === 'named') {
1232
+ for (const it of re.items) {
1233
+ const t = resolveExportTarget(re.target, it.imported);
1234
+ if (t) {
1235
+ entryPublicExports.set(it.exported, { globalName: t.globalName, typeOnly: t.typeOnly || re.isType || it.isType });
1236
+ continue;
1237
+ }
1238
+ const extTarget = resolveExternalNamedExport(re.target, it.imported);
1239
+ if (extTarget) {
1240
+ const forceType = extTarget.isType || re.isType || it.isType;
1241
+ if (extTarget.kind === 'ns') {
1242
+ addExtNs(extTarget.spec, it.exported, forceType);
1243
+ } else {
1244
+ addExtNamed(extTarget.spec, extTarget.imported, it.exported, forceType);
1245
+ }
1246
+ continue;
1247
+ }
1248
+ diagnostics.push({ file: entry, code: 'UNRESOLVED_EXPORT', severity: 'error', message: `Module "${re.target}" does not export "${it.imported}"`, start: 0, end: 0 });
1249
+ }
1250
+ } else if (re.kind === 'star') {
1251
+ for (const [name, rec] of collectModuleExports(re.target).entries()) {
1252
+ if (name === 'default') continue;
1253
+ const nextTypeOnly = rec.typeOnly || re.isType;
1254
+ const prev = entryPublicExports.get(name);
1255
+ if (!prev) {
1256
+ entryPublicExports.set(name, { globalName: rec.globalName, typeOnly: nextTypeOnly });
1257
+ } else if (prev.typeOnly && !nextTypeOnly) {
1258
+ prev.typeOnly = false;
1259
+ }
1260
+ }
1261
+ // Recursively propagate external re-exports, relayed named external re-exports,
1262
+ // and internal `export * as ns` along `export *` chains.
1263
+ const collectStarExternalReExports = (targetFile, inheritedTypeOnly, seen) => {
1264
+ const visitKey = `${targetFile}\x00${inheritedTypeOnly ? 1 : 0}`;
1265
+ if (seen.has(visitKey)) return;
1266
+ seen.add(visitKey);
1267
+ const subMod = modules.get(targetFile);
1268
+ if (!subMod) return;
1269
+ for (const extRec of subMod.externalReExports) {
1270
+ ingestExternalReExport(extRec, inheritedTypeOnly, true);
1271
+ }
1272
+ for (const subRe of subMod.reExports) {
1273
+ if (subRe.kind === 'star') {
1274
+ collectStarExternalReExports(subRe.target, inheritedTypeOnly || subRe.isType, seen);
1275
+ } else if (subRe.kind === 'named') {
1276
+ for (const it of subRe.items) {
1277
+ if (it.exported === 'default') continue;
1278
+ if (resolveExportTarget(subRe.target, it.imported)) continue;
1279
+ const extTarget = resolveExternalNamedExport(subRe.target, it.imported);
1280
+ if (extTarget) {
1281
+ const forceType = inheritedTypeOnly || subRe.isType || it.isType || extTarget.isType;
1282
+ if (extTarget.kind === 'ns') addExtNs(extTarget.spec, it.exported, forceType);
1283
+ else addExtNamed(extTarget.spec, extTarget.imported, it.exported, forceType);
1284
+ }
1285
+ }
1286
+ } else if (subRe.kind === 'ns' && subRe.alias !== 'default') {
1287
+ if (!seenInternalNsAliases.has(subRe.alias)) {
1288
+ seenInternalNsAliases.add(subRe.alias);
1289
+ const gns = allocateName(subRe.alias);
1290
+ internalNamespaces.push({
1291
+ globalName: gns,
1292
+ targetFile: subRe.target,
1293
+ exported: true,
1294
+ exportAlias: subRe.alias,
1295
+ typeOnly: inheritedTypeOnly || subRe.isType,
1296
+ });
1297
+ }
1298
+ }
1299
+ }
1300
+ };
1301
+ collectStarExternalReExports(re.target, re.isType, new Set([`${entry}\x000`, `${entry}\x001`]));
1302
+ } else if (re.kind === 'ns') {
1303
+ seenInternalNsAliases.add(re.alias);
1304
+ const gns = allocateName(re.alias);
1305
+ internalNamespaces.push({ globalName: gns, targetFile: re.target, exported: true, exportAlias: re.alias, typeOnly: re.isType });
1306
+ }
1307
+ }
1308
+
1309
+ // Materialize merged external re-export statements deterministically.
1310
+ const entryExternalReExports = [];
1311
+ for (const rec of extStarReExports.values()) {
1312
+ entryExternalReExports.push(`export ${rec.isType ? 'type ' : ''}* from ${JSON.stringify(rec.spec)};`);
1313
+ }
1314
+ for (const rec of extNsReExports.values()) {
1315
+ entryExternalReExports.push(`export ${rec.isType ? 'type ' : ''}* as ${rec.alias} from ${JSON.stringify(rec.spec)};`);
1316
+ }
1317
+ const namedReBySpec = new Map();
1318
+ for (const rec of extNamedReExports.values()) {
1319
+ // Explicit entry exports take precedence over star-propagated external re-exports (avoids TS2484).
1320
+ if (entryPublicExports.has(rec.exported)) continue;
1321
+ if (!namedReBySpec.has(rec.spec)) namedReBySpec.set(rec.spec, []);
1322
+ namedReBySpec.get(rec.spec).push(rec);
1323
+ }
1324
+ for (const [spec, list] of namedReBySpec.entries()) {
1325
+ const allType = list.every(it => it.isType);
1326
+ const parts = list.map(it => {
1327
+ const prefix = !allType && it.isType ? 'type ' : '';
1328
+ return it.imported === it.exported ? `${prefix}${it.imported}` : `${prefix}${it.imported} as ${it.exported}`;
1329
+ });
1330
+ entryExternalReExports.push(`export ${allType ? 'type ' : ''}{ ${parts.join(', ')} } from ${JSON.stringify(spec)};`);
1331
+ }
1332
+
1333
+ if (diagnostics.length > 0) return { code: null, diagnostics };
1334
+
1335
+ // 6. Emit final bundled `.d.ts`.
1336
+ const chunks = [];
1337
+
1338
+ // 6a. External bare imports (sorted deterministically by specifier).
1339
+ const bySpec = new Map();
1340
+ for (const rec of extBindings.values()) {
1341
+ if (!bySpec.has(rec.spec)) bySpec.set(rec.spec, { def: null, ns: null, named: [] });
1342
+ const b = bySpec.get(rec.spec);
1343
+ if (rec.kind === 'default') b.def = rec;
1344
+ else if (rec.kind === 'ns') b.ns = rec;
1345
+ else b.named.push(rec);
1346
+ }
1347
+ for (const spec of Array.from(bySpec.keys()).sort()) {
1348
+ const b = bySpec.get(spec);
1349
+ if (b.def) {
1350
+ chunks.push(`import ${b.def.isType ? 'type ' : ''}${b.def.globalLocal} from ${JSON.stringify(spec)};`);
1351
+ }
1352
+ if (b.ns) {
1353
+ chunks.push(`import ${b.ns.isType ? 'type ' : ''}* as ${b.ns.globalLocal} from ${JSON.stringify(spec)};`);
1354
+ }
1355
+ if (b.named.length > 0) {
1356
+ const allType = b.named.every(it => it.isType);
1357
+ const rendered = b.named.map(it => {
1358
+ const prefix = !allType && it.isType ? 'type ' : '';
1359
+ return it.imported === it.globalLocal ? `${prefix}${it.imported}` : `${prefix}${it.imported} as ${it.globalLocal}`;
1360
+ });
1361
+ chunks.push(`import ${allType ? 'type ' : ''}{ ${rendered.join(', ')} } from ${JSON.stringify(spec)};`);
1362
+ }
1363
+ }
1364
+
1365
+ // 6b. All module declarations in dependency order (top-level scope; non-exported unless directly public).
1366
+ const emittedDirectExports = new Set();
1367
+ let hasAnyExport = false;
1368
+
1369
+ for (const file of order) {
1370
+ const mod = modules.get(file);
1371
+ const rmap = moduleRenameMap.get(file);
1372
+ for (const d of mod.decls) {
1373
+ const gname = d.name ? symbolGlobalName.get(`${file}#${d.name}`) : (d.syntheticName || null);
1374
+ let rewritten = rewriteInlineImportTypes(d.raw, file, fileMap, resolveExportTarget, diagnostics, resolveSpec, entry);
1375
+ rewritten = rewriteDeclaration(rewritten, d.name, gname, rmap);
1376
+
1377
+ if (file === entry && d.isDefault) {
1378
+ chunks.push(rewritten);
1379
+ hasAnyExport = true;
1380
+ continue;
1381
+ }
1382
+
1383
+ const pub = gname ? entryPublicExports.get(gname) : null;
1384
+ const canInlineExport = !!(pub && pub.globalName === gname && !emittedDirectExports.has(gname) &&
1385
+ (!pub.typeOnly || d.kind === 'type' || d.kind === 'interface'));
1386
+
1387
+ if (canInlineExport) {
1388
+ let line = rewritten;
1389
+ if (!/^export\s+/.test(line)) line = `export ${line}`;
1390
+ chunks.push(line);
1391
+ emittedDirectExports.add(gname);
1392
+ hasAnyExport = true;
1393
+ } else {
1394
+ chunks.push(stripExportPrefix(rewritten, true));
1395
+ }
1396
+ }
1397
+ }
1398
+
1399
+ if (diagnostics.length > 0) return { code: null, diagnostics };
1400
+
1401
+ // 6c. Synthesized internal/exported namespaces (`declare namespace M { export { ... }; }`).
1402
+ for (const ns of internalNamespaces) {
1403
+ const subExports = collectModuleExports(ns.targetFile);
1404
+ const valueItems = [];
1405
+ const typeItems = [];
1406
+ for (const [expName, rec] of subExports.entries()) {
1407
+ const spec = expName === rec.globalName ? expName : `${rec.globalName} as ${expName}`;
1408
+ if (rec.typeOnly) typeItems.push(spec);
1409
+ else valueItems.push(spec);
1410
+ }
1411
+ const bodyLines = [];
1412
+ if (valueItems.length > 0) bodyLines.push(` export { ${valueItems.join(', ')} };`);
1413
+ if (typeItems.length > 0) bodyLines.push(` export type { ${typeItems.join(', ')} };`);
1414
+ if (ns.exported && !ns.typeOnly && ns.exportAlias === ns.globalName) {
1415
+ chunks.push(`export declare namespace ${ns.globalName} {\n${bodyLines.join('\n')}\n}`);
1416
+ hasAnyExport = true;
1417
+ } else {
1418
+ chunks.push(`declare namespace ${ns.globalName} {\n${bodyLines.join('\n')}\n}`);
1419
+ if (ns.exported) {
1420
+ const spec = ns.exportAlias === ns.globalName ? ns.globalName : `${ns.globalName} as ${ns.exportAlias}`;
1421
+ chunks.push(ns.typeOnly ? `export type { ${spec} };` : `export { ${spec} };`);
1422
+ hasAnyExport = true;
1423
+ }
1424
+ }
1425
+ }
1426
+
1427
+ // 6d. Entry default export expression (`export default Foo;`).
1428
+ if (entryMod.hasDefaultExportExpr) {
1429
+ const rmap = moduleRenameMap.get(entry);
1430
+ const loc = entryMod.hasDefaultExportExpr.local;
1431
+ const target = rmap.get(loc) || loc;
1432
+ chunks.push(`export default ${target};`);
1433
+ hasAnyExport = true;
1434
+ }
1435
+
1436
+ // 6e. Entry external re-exports (`export ... from "bare"`).
1437
+ for (const stmt of entryExternalReExports) {
1438
+ chunks.push(stmt);
1439
+ hasAnyExport = true;
1440
+ }
1441
+
1442
+ // 6f. Trailing explicit export lists (preserving value vs type-only distinction).
1443
+ const trailingValues = [];
1444
+ const trailingTypes = [];
1445
+ for (const [exportedName, rec] of entryPublicExports.entries()) {
1446
+ if (emittedDirectExports.has(exportedName)) continue;
1447
+ const spec = exportedName === rec.globalName ? exportedName : `${rec.globalName} as ${exportedName}`;
1448
+ if (rec.typeOnly) trailingTypes.push(spec);
1449
+ else trailingValues.push(spec);
1450
+ }
1451
+ if (trailingValues.length > 0) {
1452
+ chunks.push(`export { ${trailingValues.join(', ')} };`);
1453
+ hasAnyExport = true;
1454
+ }
1455
+ if (trailingTypes.length > 0) {
1456
+ chunks.push(`export type { ${trailingTypes.join(', ')} };`);
1457
+ hasAnyExport = true;
1458
+ }
1459
+
1460
+ // Always preserve module semantics so non-exported declarations never leak into global scope.
1461
+ if (!hasAnyExport) {
1462
+ chunks.push('export {};');
1463
+ }
1464
+
1465
+ return { code: chunks.join('\n') + '\n', diagnostics: [] };
1466
+ }
1467
+
1468
+ function normalizeFileMap(rawFiles) {
1469
+ if (!rawFiles) return null;
1470
+ const out = Object.create(null);
1471
+ for (const [k, v] of Object.entries(rawFiles)) {
1472
+ out[normalizeVirtualPath(k)] = v;
1473
+ }
1474
+ return out;
1475
+ }
1476
+
1477
+ module.exports = {
1478
+ assembleBundle,
1479
+ extractRelativeSpecifiers,
1480
+ normalizeVirtualPath,
1481
+ normalizeFileMap,
1482
+ isRelativeSpec,
1483
+ };