@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.
package/src/index.cjs ADDED
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ const bundler = require('./bundler.cjs');
4
+ const { loadTsconfig, parseJsonc, stripJsonc } = require('./tsconfig.cjs');
5
+ const { FastModuleResolver, extractModuleSpecifiers } = require('./resolver.cjs');
6
+
7
+ module.exports = {
8
+ ...bundler,
9
+ loadTsconfig,
10
+ parseJsonc,
11
+ stripJsonc,
12
+ FastModuleResolver,
13
+ extractModuleSpecifiers,
14
+ };
package/src/index.mjs ADDED
@@ -0,0 +1,20 @@
1
+ import dts from './index.cjs';
2
+
3
+ export const {
4
+ emitDeclaration,
5
+ emitDeclarations,
6
+ emitDeclarationsSync,
7
+ bundleDeclarations,
8
+ bundleDeclarationsSync,
9
+ bundleEntries,
10
+ emitProject,
11
+ buildDeclarations,
12
+ createDtsCache,
13
+ loadTsconfig,
14
+ parseJsonc,
15
+ stripJsonc,
16
+ FastModuleResolver,
17
+ extractModuleSpecifiers,
18
+ } = dts;
19
+
20
+ export default dts;
@@ -0,0 +1,536 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ const TS_EXTS = ['.ts', '.mts', '.cts', '.tsx', '.d.ts', '.d.mts', '.d.cts'];
7
+ const INDEX_CANDIDATES = ['index.ts', 'index.mts', 'index.cts', 'index.tsx', 'index.d.ts', 'index.d.mts', 'index.d.cts'];
8
+ const NON_TS_ASSET_RE = /\.(?:json|css|scss|sass|less|styl|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|eot|wasm|txt|md)$/i;
9
+
10
+ function isTsOrDtsFile(p) {
11
+ return /\.(?:[cm]?ts|tsx)$/i.test(p);
12
+ }
13
+
14
+ function toPosix(p) {
15
+ return p.replace(/\\/g, '/');
16
+ }
17
+
18
+ function isRelativeSpec(spec) {
19
+ return spec.startsWith('./') || spec.startsWith('../') || spec === '.' || spec === '..';
20
+ }
21
+
22
+ function normalizeVirtualPath(p) {
23
+ const posix = toPosix(p);
24
+ const norm = path.posix.normalize(posix);
25
+ return norm.startsWith('./') ? norm.slice(2) : norm;
26
+ }
27
+
28
+ function compileExternalMatcher(external) {
29
+ if (!external) return () => false;
30
+ if (typeof external === 'function') return external;
31
+ const list = Array.isArray(external) ? external : [external];
32
+ const strings = new Set();
33
+ const prefixes = [];
34
+ const regexes = [];
35
+ for (const item of list) {
36
+ if (typeof item === 'string') {
37
+ strings.add(item);
38
+ prefixes.push(item.endsWith('/') ? item : `${item}/`);
39
+ } else if (item instanceof RegExp) {
40
+ regexes.push(item);
41
+ }
42
+ }
43
+ return spec => {
44
+ if (strings.has(spec)) return true;
45
+ for (let i = 0; i < prefixes.length; i++) {
46
+ if (spec.startsWith(prefixes[i])) return true;
47
+ }
48
+ for (let i = 0; i < regexes.length; i++) {
49
+ if (regexes[i].test(spec)) return true;
50
+ }
51
+ return false;
52
+ };
53
+ }
54
+
55
+ /**
56
+ * Directory-cached filesystem file existence & resolution cache.
57
+ * Reduces up to 14 stat syscalls per import to 1 readdir per directory + O(1) Set lookups.
58
+ */
59
+ class FastModuleResolver {
60
+ constructor(options = {}) {
61
+ this.fileMap = options.fileMap || null;
62
+ this.tsconfig = options.tsconfig || null;
63
+ this.isExternal = compileExternalMatcher(options.external);
64
+ // Map<absDir, Set<entryName> | null> (null = unreadable / nonexistent)
65
+ this.dirCache = new Map();
66
+ // Map<absPath, boolean> for symlink/directory disambiguation when needed
67
+ this.fileKindCache = new Map();
68
+ // Map<`${fromFile}\0${spec}`, { path: string | null, external: boolean }>
69
+ this.resolveCache = new Map();
70
+ }
71
+
72
+ getDirEntries(dirPath) {
73
+ let entries = this.dirCache.get(dirPath);
74
+ if (entries !== undefined) return entries;
75
+ try {
76
+ const dirents = fs.readdirSync(dirPath, { withFileTypes: true });
77
+ const fileSet = new Set();
78
+ const dirSet = new Set();
79
+ for (let i = 0; i < dirents.length; i++) {
80
+ const d = dirents[i];
81
+ if (d.isFile()) fileSet.add(d.name);
82
+ else if (d.isDirectory()) dirSet.add(d.name);
83
+ else if (d.isSymbolicLink()) {
84
+ // Lazily resolve symlink kind only when hit.
85
+ fileSet.add(d.name);
86
+ dirSet.add(d.name);
87
+ }
88
+ }
89
+ entries = { files: fileSet, dirs: dirSet };
90
+ } catch {
91
+ entries = null;
92
+ }
93
+ this.dirCache.set(dirPath, entries);
94
+ return entries;
95
+ }
96
+
97
+ diskFileExists(candidatePath) {
98
+ const dir = path.dirname(candidatePath);
99
+ const base = path.basename(candidatePath);
100
+ const entries = this.getDirEntries(dir);
101
+ if (!entries || !entries.files.has(base)) return false;
102
+ // If name is in both files and dirs (symlink), verify isFile() once.
103
+ if (entries.dirs.has(base)) {
104
+ let isFile = this.fileKindCache.get(candidatePath);
105
+ if (isFile === undefined) {
106
+ try {
107
+ isFile = fs.statSync(candidatePath).isFile();
108
+ } catch {
109
+ isFile = false;
110
+ }
111
+ this.fileKindCache.set(candidatePath, isFile);
112
+ }
113
+ return isFile;
114
+ }
115
+ return true;
116
+ }
117
+
118
+ probeCandidates(basePath) {
119
+ if (NON_TS_ASSET_RE.test(basePath)) return null;
120
+ const candidates = [];
121
+ if (/\.mjs$/i.test(basePath)) {
122
+ candidates.push(basePath.replace(/\.mjs$/i, '.mts'), basePath.replace(/\.mjs$/i, '.d.mts'));
123
+ } else if (/\.cjs$/i.test(basePath)) {
124
+ candidates.push(basePath.replace(/\.cjs$/i, '.cts'), basePath.replace(/\.cjs$/i, '.d.cts'));
125
+ } else if (/\.jsx$/i.test(basePath)) {
126
+ candidates.push(basePath.replace(/\.jsx$/i, '.tsx'), basePath.replace(/\.jsx$/i, '.d.ts'));
127
+ } else if (/\.js$/i.test(basePath)) {
128
+ candidates.push(
129
+ basePath.replace(/\.js$/i, '.ts'),
130
+ basePath.replace(/\.js$/i, '.tsx'),
131
+ basePath.replace(/\.js$/i, '.d.ts'),
132
+ );
133
+ }
134
+ if (isTsOrDtsFile(basePath)) {
135
+ candidates.push(basePath);
136
+ }
137
+ for (let i = 0; i < TS_EXTS.length; i++) candidates.push(basePath + TS_EXTS[i]);
138
+
139
+ if (this.fileMap) {
140
+ for (let i = 0; i < candidates.length; i++) {
141
+ const norm = normalizeVirtualPath(candidates[i]);
142
+ if (Object.prototype.hasOwnProperty.call(this.fileMap, norm)) return norm;
143
+ }
144
+ for (let i = 0; i < INDEX_CANDIDATES.length; i++) {
145
+ const norm = normalizeVirtualPath(`${basePath}/${INDEX_CANDIDATES[i]}`);
146
+ if (Object.prototype.hasOwnProperty.call(this.fileMap, norm)) return norm;
147
+ }
148
+ return null;
149
+ }
150
+
151
+ for (let i = 0; i < candidates.length; i++) {
152
+ if (this.diskFileExists(candidates[i])) return toPosix(candidates[i]);
153
+ }
154
+ // Check directory index only if basePath itself is a directory.
155
+ const parent = path.dirname(basePath);
156
+ const name = path.basename(basePath);
157
+ const parentEntries = this.getDirEntries(parent);
158
+ if (parentEntries && parentEntries.dirs.has(name)) {
159
+ const subEntries = this.getDirEntries(basePath);
160
+ if (subEntries) {
161
+ for (let i = 0; i < INDEX_CANDIDATES.length; i++) {
162
+ const idx = INDEX_CANDIDATES[i];
163
+ if (subEntries.files.has(idx)) {
164
+ const full = path.join(basePath, idx);
165
+ if (this.diskFileExists(full)) return toPosix(full);
166
+ }
167
+ }
168
+ }
169
+ }
170
+ return null;
171
+ }
172
+
173
+ resolveTsconfigPaths(spec) {
174
+ const tc = this.tsconfig;
175
+ if (!tc) return null;
176
+
177
+ const matchers = tc.pathMatchers || [];
178
+ for (let i = 0; i < matchers.length; i++) {
179
+ const m = matchers[i];
180
+ let matchedWildcard = '';
181
+ if (!m.hasWildcard) {
182
+ if (spec !== m.prefix) continue;
183
+ } else {
184
+ if (!spec.startsWith(m.prefix) || !spec.endsWith(m.suffix)) continue;
185
+ if (spec.length < m.prefix.length + m.suffix.length) continue;
186
+ matchedWildcard = spec.slice(m.prefix.length, spec.length - m.suffix.length);
187
+ }
188
+ // TypeScript selects the single most-specific matching pattern and does not fall back to broader patterns.
189
+ for (let j = 0; j < m.targets.length; j++) {
190
+ const t = m.targets[j];
191
+ const relTarget = t.hasWildcard
192
+ ? `${t.prefix}${matchedWildcard}${t.suffix}`
193
+ : t.prefix;
194
+ const absTarget = path.resolve(t.baseDir, relTarget);
195
+ const found = this.probeCandidates(absTarget);
196
+ if (found) return found;
197
+ }
198
+ return null;
199
+ }
200
+
201
+ if (tc.baseUrl) {
202
+ const absTarget = path.resolve(tc.baseUrl, spec);
203
+ const found = this.probeCandidates(absTarget);
204
+ if (found) return found;
205
+ }
206
+ return null;
207
+ }
208
+
209
+ /**
210
+ * Resolves a module specifier from `fromFile`.
211
+ * Returns `{ path: string | null, external: boolean }`.
212
+ */
213
+ resolve(fromFile, spec) {
214
+ const key = `${fromFile}\0${spec}`;
215
+ const cached = this.resolveCache.get(key);
216
+ if (cached !== undefined) return cached;
217
+
218
+ let result;
219
+ if (this.isExternal(spec) || NON_TS_ASSET_RE.test(spec)) {
220
+ result = { path: null, external: true };
221
+ } else if (isRelativeSpec(spec)) {
222
+ if (this.fileMap) {
223
+ const fromDir = path.posix.dirname(fromFile);
224
+ const joined = normalizeVirtualPath(path.posix.join(fromDir, spec));
225
+ result = { path: this.probeCandidates(joined), external: false };
226
+ } else {
227
+ const fromDir = path.dirname(fromFile);
228
+ const joined = path.resolve(fromDir, spec);
229
+ result = { path: this.probeCandidates(joined), external: false };
230
+ }
231
+ } else {
232
+ const viaTsconfig = this.resolveTsconfigPaths(spec);
233
+ if (viaTsconfig) {
234
+ result = { path: viaTsconfig, external: false };
235
+ } else {
236
+ result = { path: null, external: true };
237
+ }
238
+ }
239
+
240
+ this.resolveCache.set(key, result);
241
+ return result;
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Fast syntactic extractor for all module specifiers (relative + bare/alias)
247
+ * in `import ... from "..."`, `export ... from "..."`, and `import("...")`.
248
+ */
249
+ function extractModuleSpecifiers(sourceText) {
250
+ const specs = [];
251
+ const len = sourceText.length;
252
+ let i = 0;
253
+ let braceDepth = 0;
254
+ let parenDepth = 0;
255
+ let bracketDepth = 0;
256
+ // Tracks braceDepth levels where a template literal `${ ... }` expression was opened.
257
+ const templateBraceStack = [];
258
+
259
+ const isIdStart = c => (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 36;
260
+ const isIdPart = c => isIdStart(c) || (c >= 48 && c <= 57);
261
+
262
+ const skipWs = pos => {
263
+ while (pos < len) {
264
+ const c = sourceText[pos];
265
+ if (c === ' ' || c === '\t' || c === '\n' || c === '\r') { pos++; continue; }
266
+ if (c === '/' && sourceText[pos + 1] === '/') {
267
+ pos += 2;
268
+ while (pos < len && sourceText[pos] !== '\n' && sourceText[pos] !== '\r') pos++;
269
+ continue;
270
+ }
271
+ if (c === '/' && sourceText[pos + 1] === '*') {
272
+ const end = sourceText.indexOf('*/', pos + 2);
273
+ pos = end < 0 ? len : end + 2;
274
+ continue;
275
+ }
276
+ break;
277
+ }
278
+ return pos;
279
+ };
280
+
281
+ const readStr = pos => {
282
+ const q = sourceText[pos];
283
+ if (q !== '"' && q !== "'") return null;
284
+ let j = pos + 1;
285
+ while (j < len && sourceText[j] !== q) {
286
+ if (sourceText[j] === '\\') j += 2;
287
+ else if (sourceText[j] === '\n' || sourceText[j] === '\r') return null;
288
+ else j++;
289
+ }
290
+ if (j >= len) return null;
291
+ return { value: sourceText.slice(pos + 1, j), end: j + 1 };
292
+ };
293
+
294
+ let prevNonWs = '';
295
+
296
+ const canStartRegex = ch => (
297
+ ch === '' || ch === '(' || ch === '[' || ch === '{' || ch === ',' || ch === ';'
298
+ || ch === ':' || ch === '=' || ch === '!' || ch === '&' || ch === '|' || ch === '?'
299
+ || ch === '+' || ch === '-' || ch === '*' || ch === '%' || ch === '^' || ch === '~'
300
+ || ch === '<' || ch === '>' || ch === '\n'
301
+ );
302
+
303
+ while (i < len) {
304
+ const c = sourceText[i];
305
+ if (c === ' ' || c === '\t' || c === '\r') { i++; continue; }
306
+ if (c === '\n') { prevNonWs = '\n'; i++; continue; }
307
+ if (c === '/' && sourceText[i + 1] === '/') {
308
+ i += 2;
309
+ while (i < len && sourceText[i] !== '\n' && sourceText[i] !== '\r') i++;
310
+ continue;
311
+ }
312
+ if (c === '/' && sourceText[i + 1] === '*') {
313
+ const end = sourceText.indexOf('*/', i + 2);
314
+ i = end < 0 ? len : end + 2;
315
+ continue;
316
+ }
317
+ if (c === '/' && canStartRegex(prevNonWs)) {
318
+ // Skip regex literal so braces/quotes inside regex do not corrupt depth tracking.
319
+ let j = i + 1;
320
+ let inClass = false;
321
+ let closed = false;
322
+ while (j < len && sourceText[j] !== '\n' && sourceText[j] !== '\r') {
323
+ const rc = sourceText[j];
324
+ if (rc === '\\') { j += 2; continue; }
325
+ if (rc === '[') inClass = true;
326
+ else if (rc === ']') inClass = false;
327
+ else if (rc === '/' && !inClass) { closed = true; j++; break; }
328
+ j++;
329
+ }
330
+ if (closed) {
331
+ while (j < len && isIdStart(sourceText.charCodeAt(j))) j++;
332
+ i = j;
333
+ prevNonWs = 'r';
334
+ continue;
335
+ }
336
+ }
337
+ if (c === '"' || c === "'") {
338
+ const s = readStr(i);
339
+ i = s ? s.end : i + 1;
340
+ prevNonWs = '"';
341
+ continue;
342
+ }
343
+ if (c === '`') {
344
+ i++;
345
+ let hitExpr = false;
346
+ while (i < len && sourceText[i] !== '`') {
347
+ if (sourceText[i] === '\\') { i += 2; continue; }
348
+ if (sourceText[i] === '$' && sourceText[i + 1] === '{') {
349
+ i += 2;
350
+ braceDepth++;
351
+ templateBraceStack.push(braceDepth);
352
+ prevNonWs = '{';
353
+ hitExpr = true;
354
+ break;
355
+ }
356
+ i++;
357
+ }
358
+ if (!hitExpr && i < len && sourceText[i] === '`') {
359
+ i++;
360
+ prevNonWs = '`';
361
+ }
362
+ continue;
363
+ }
364
+ if (c === '{') { braceDepth++; prevNonWs = '{'; i++; continue; }
365
+ if (c === '}') {
366
+ if (templateBraceStack.length > 0 && templateBraceStack[templateBraceStack.length - 1] === braceDepth) {
367
+ templateBraceStack.pop();
368
+ if (braceDepth > 0) braceDepth--;
369
+ // Resume scanning the enclosing template literal.
370
+ i++;
371
+ let hitExpr = false;
372
+ while (i < len && sourceText[i] !== '`') {
373
+ if (sourceText[i] === '\\') { i += 2; continue; }
374
+ if (sourceText[i] === '$' && sourceText[i + 1] === '{') {
375
+ i += 2;
376
+ braceDepth++;
377
+ templateBraceStack.push(braceDepth);
378
+ prevNonWs = '{';
379
+ hitExpr = true;
380
+ break;
381
+ }
382
+ i++;
383
+ }
384
+ if (!hitExpr && i < len && sourceText[i] === '`') {
385
+ i++;
386
+ prevNonWs = '`';
387
+ }
388
+ continue;
389
+ }
390
+ if (braceDepth > 0) braceDepth--;
391
+ prevNonWs = '}';
392
+ i++;
393
+ continue;
394
+ }
395
+ if (c === '(') { parenDepth++; prevNonWs = '('; i++; continue; }
396
+ if (c === ')') { if (parenDepth > 0) parenDepth--; prevNonWs = ')'; i++; continue; }
397
+ if (c === '[') { bracketDepth++; prevNonWs = '['; i++; continue; }
398
+ if (c === ']') { if (bracketDepth > 0) bracketDepth--; prevNonWs = ']'; i++; continue; }
399
+
400
+ const cc = sourceText.charCodeAt(i);
401
+ if (isIdStart(cc)) {
402
+ const isMemberAccess = prevNonWs === '.';
403
+ const start = i;
404
+ i++;
405
+ while (i < len && isIdPart(sourceText.charCodeAt(i))) i++;
406
+ const word = sourceText.slice(start, i);
407
+ prevNonWs = word === 'return' || word === 'case' || word === 'throw' || word === 'typeof' || word === 'in' || word === 'of'
408
+ ? '='
409
+ : 'a';
410
+
411
+ if (isMemberAccess) continue;
412
+
413
+ if (word === 'import') {
414
+ const next = skipWs(i);
415
+ if (sourceText[next] === '(') {
416
+ const argPos = skipWs(next + 1);
417
+ const s = readStr(argPos);
418
+ if (s) {
419
+ specs.push(s.value);
420
+ i = s.end;
421
+ continue;
422
+ }
423
+ }
424
+ if (braceDepth === 0 && parenDepth === 0 && bracketDepth === 0) {
425
+ const s = readStr(next);
426
+ if (s) {
427
+ specs.push(s.value);
428
+ i = s.end;
429
+ continue;
430
+ }
431
+ }
432
+ }
433
+
434
+ if ((word === 'import' || word === 'export') && braceDepth === 0 && parenDepth === 0 && bracketDepth === 0) {
435
+ // Only scan for `from "..."` when the syntax after `export`/`import` can actually be a module specifier clause.
436
+ // This guarantees O(N) linear scanning and avoids skipping past `export type X = import("./dep").T`.
437
+ let canHaveFrom = true;
438
+ if (word === 'export') {
439
+ let p = skipWs(i);
440
+ if (sourceText[p] !== '{' && sourceText[p] !== '*') {
441
+ if (isIdStart(sourceText.charCodeAt(p))) {
442
+ const kwStart = p;
443
+ while (p < len && isIdPart(sourceText.charCodeAt(p))) p++;
444
+ const kw = sourceText.slice(kwStart, p);
445
+ if (kw === 'type') {
446
+ const afterType = skipWs(p);
447
+ canHaveFrom = sourceText[afterType] === '{' || sourceText[afterType] === '*';
448
+ } else {
449
+ canHaveFrom = false;
450
+ }
451
+ } else {
452
+ canHaveFrom = false;
453
+ }
454
+ }
455
+ }
456
+ if (!canHaveFrom) continue;
457
+
458
+ let scan = i;
459
+ let innerBrace = 0;
460
+ let sawExportClauseClose = false;
461
+ while (scan < len) {
462
+ const ch = sourceText[scan];
463
+ if (ch === '/' && sourceText[scan + 1] === '/') {
464
+ scan += 2;
465
+ while (scan < len && sourceText[scan] !== '\n' && sourceText[scan] !== '\r') scan++;
466
+ continue;
467
+ }
468
+ if (ch === '/' && sourceText[scan + 1] === '*') {
469
+ const end = sourceText.indexOf('*/', scan + 2);
470
+ scan = end < 0 ? len : end + 2;
471
+ continue;
472
+ }
473
+ if (ch === '"' || ch === "'") {
474
+ const s = readStr(scan);
475
+ scan = s ? s.end : scan + 1;
476
+ continue;
477
+ }
478
+ if (ch === '{') { innerBrace++; scan++; continue; }
479
+ if (ch === '}') {
480
+ if (innerBrace > 0) innerBrace--;
481
+ scan++;
482
+ if (innerBrace === 0) {
483
+ // Immediately after closing `{ ... }`, a module clause MUST have `from "..."` next;
484
+ // otherwise it is a local `export { A }` without semicolon. Stop immediately (O(N)).
485
+ const afterClose = skipWs(scan);
486
+ if (
487
+ sourceText.startsWith('from', afterClose)
488
+ && (afterClose + 4 >= len || !isIdPart(sourceText.charCodeAt(afterClose + 4)))
489
+ ) {
490
+ const afterFrom = skipWs(afterClose + 4);
491
+ const s = readStr(afterFrom);
492
+ if (s) {
493
+ specs.push(s.value);
494
+ i = s.end;
495
+ }
496
+ }
497
+ sawExportClauseClose = true;
498
+ break;
499
+ }
500
+ continue;
501
+ }
502
+ if (ch === ';' && innerBrace === 0) break;
503
+ if (innerBrace === 0 && ch === 'f' && sourceText.startsWith('from', scan)) {
504
+ const prevOk = scan === 0 || !isIdPart(sourceText.charCodeAt(scan - 1));
505
+ const nextOk = scan + 4 >= len || !isIdPart(sourceText.charCodeAt(scan + 4));
506
+ if (prevOk && nextOk) {
507
+ const afterFrom = skipWs(scan + 4);
508
+ const s = readStr(afterFrom);
509
+ if (s) {
510
+ specs.push(s.value);
511
+ i = s.end;
512
+ }
513
+ break;
514
+ }
515
+ }
516
+ scan++;
517
+ }
518
+ if (sawExportClauseClose) continue;
519
+ }
520
+ continue;
521
+ }
522
+
523
+ prevNonWs = c;
524
+ i++;
525
+ }
526
+ return specs;
527
+ }
528
+
529
+ module.exports = {
530
+ FastModuleResolver,
531
+ extractModuleSpecifiers,
532
+ compileExternalMatcher,
533
+ isRelativeSpec,
534
+ normalizeVirtualPath,
535
+ toPosix,
536
+ };