@depup/vite-plugin-dts 4.5.4-depup.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/dist/index.mjs ADDED
@@ -0,0 +1,1341 @@
1
+
2
+ import __cjs_url__ from 'url';
3
+ import __cjs_path__ from 'path';
4
+ import __cjs_mod__ from 'module';
5
+ const __filename = __cjs_url__.fileURLToPath(import.meta.url);
6
+ const __dirname = __cjs_path__.dirname(__filename);
7
+ const require = __cjs_mod__.createRequire(import.meta.url);
8
+ import { relative, posix, resolve as resolve$1, isAbsolute, dirname, normalize, sep, basename } from 'node:path';
9
+ import { existsSync, readdirSync, lstatSync, rmdirSync } from 'node:fs';
10
+ import { readFile, mkdir, writeFile, unlink } from 'node:fs/promises';
11
+ import { cpus } from 'node:os';
12
+ import { createParsedCommandLine, resolveVueCompilerOptions, createVueLanguagePlugin } from '@vue/language-core';
13
+ import { proxyCreateProgram } from '@volar/typescript';
14
+ import ts from 'typescript';
15
+ import { createRequire } from 'node:module';
16
+ import { getPackageInfoSync, resolveModule } from 'local-pkg';
17
+ import { createFilter } from '@rollup/pluginutils';
18
+ import debug from 'debug';
19
+ import { cyan, yellow, green } from 'kolorist';
20
+ import { ExtractorConfig, Extractor } from '@microsoft/api-extractor';
21
+ import { compare } from 'compare-versions';
22
+ import MagicString from 'magic-string';
23
+
24
+ const windowsSlashRE = /\\+/g;
25
+ function slash(p) {
26
+ return p.replace(windowsSlashRE, "/");
27
+ }
28
+ function resolveConfigDir(path, configDir) {
29
+ return path.replace("${configDir}", configDir);
30
+ }
31
+ function normalizePath(id) {
32
+ return posix.normalize(slash(id));
33
+ }
34
+ function resolve(...paths) {
35
+ return normalizePath(resolve$1(...paths));
36
+ }
37
+ function isNativeObj(value) {
38
+ return Object.prototype.toString.call(value) === "[object Object]";
39
+ }
40
+ function isRegExp(value) {
41
+ return Object.prototype.toString.call(value) === "[object RegExp]";
42
+ }
43
+ function isPromise(value) {
44
+ return !!value && (typeof value === "function" || typeof value === "object") && typeof value.then === "function";
45
+ }
46
+ async function unwrapPromise(maybePromise) {
47
+ return isPromise(maybePromise) ? await maybePromise : maybePromise;
48
+ }
49
+ function ensureAbsolute(path, root) {
50
+ return normalizePath(path ? isAbsolute(path) ? path : resolve(root, path) : root);
51
+ }
52
+ function ensureArray(value) {
53
+ return Array.isArray(value) ? value : value ? [value] : [];
54
+ }
55
+ async function runParallel(maxConcurrency, source, iteratorFn) {
56
+ const ret = [];
57
+ const executing = [];
58
+ for (const item of source) {
59
+ const p = Promise.resolve().then(() => iteratorFn(item, source));
60
+ ret.push(p);
61
+ if (maxConcurrency <= source.length) {
62
+ const e = p.then(() => executing.splice(executing.indexOf(e), 1));
63
+ executing.push(e);
64
+ if (executing.length >= maxConcurrency) {
65
+ await Promise.race(executing);
66
+ }
67
+ }
68
+ }
69
+ return Promise.all(ret);
70
+ }
71
+ const speRE = /[\\/]/;
72
+ function queryPublicPath(paths) {
73
+ if (paths.length === 0) {
74
+ return "";
75
+ } else if (paths.length === 1) {
76
+ return dirname(paths[0]);
77
+ }
78
+ let publicPath = normalize(dirname(paths[0])) + sep;
79
+ let publicUnits = publicPath.split(speRE);
80
+ let index = publicUnits.length - 1;
81
+ for (const path of paths.slice(1)) {
82
+ if (!index) {
83
+ return publicPath;
84
+ }
85
+ const dirPath = normalize(dirname(path)) + sep;
86
+ if (dirPath.startsWith(publicPath)) {
87
+ continue;
88
+ }
89
+ const units = dirPath.split(speRE);
90
+ if (units.length < index) {
91
+ publicPath = dirPath;
92
+ publicUnits = units;
93
+ continue;
94
+ }
95
+ for (let i = 0; i <= index; ++i) {
96
+ if (publicUnits[i] !== units[i]) {
97
+ if (!i) {
98
+ return "";
99
+ }
100
+ index = i - 1;
101
+ publicUnits = publicUnits.slice(0, index + 1);
102
+ publicPath = publicUnits.join(sep) + sep;
103
+ break;
104
+ }
105
+ }
106
+ }
107
+ return publicPath.slice(0, -1);
108
+ }
109
+ function removeDirIfEmpty(dir) {
110
+ if (!existsSync(dir)) {
111
+ return;
112
+ }
113
+ let onlyHasDir = true;
114
+ for (const file of readdirSync(dir)) {
115
+ const abs = resolve(dir, file);
116
+ if (lstatSync(abs).isDirectory()) {
117
+ if (!removeDirIfEmpty(abs)) {
118
+ onlyHasDir = false;
119
+ }
120
+ } else {
121
+ onlyHasDir = false;
122
+ }
123
+ }
124
+ if (onlyHasDir) {
125
+ rmdirSync(dir);
126
+ }
127
+ return onlyHasDir;
128
+ }
129
+ function getTsConfig(tsConfigPath, readFileSync) {
130
+ const baseConfig = ts.readConfigFile(tsConfigPath, readFileSync).config ?? {};
131
+ const tsConfig = {
132
+ ...baseConfig,
133
+ compilerOptions: {}
134
+ };
135
+ if (tsConfig.extends) {
136
+ ensureArray(tsConfig.extends).forEach((configPath) => {
137
+ const config = getTsConfig(ensureAbsolute(configPath, dirname(tsConfigPath)), readFileSync);
138
+ Object.assign(tsConfig.compilerOptions, config.compilerOptions);
139
+ if (!tsConfig.include) {
140
+ tsConfig.include = config.include;
141
+ }
142
+ if (!tsConfig.exclude) {
143
+ tsConfig.exclude = config.exclude;
144
+ }
145
+ });
146
+ }
147
+ Object.assign(tsConfig.compilerOptions, baseConfig.compilerOptions);
148
+ return tsConfig;
149
+ }
150
+ function getTsLibFolder() {
151
+ const libFolder = tryGetPackageInfo("typescript")?.rootPath;
152
+ return libFolder && normalizePath(libFolder);
153
+ }
154
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
155
+ function base64Encode(number) {
156
+ if (number >= 0 && number < BASE64_ALPHABET.length) {
157
+ return BASE64_ALPHABET[number];
158
+ }
159
+ throw new TypeError("Base64 integer must be between 0 and 63: " + number);
160
+ }
161
+ const VLQ_BASE_SHIFT = 5;
162
+ const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
163
+ const VLQ_BASE_MASK = VLQ_BASE - 1;
164
+ const VLQ_CONTINUATION_BIT = VLQ_BASE;
165
+ function toVLQSigned(number) {
166
+ return number < 0 ? (-number << 1) + 1 : (number << 1) + 0;
167
+ }
168
+ function base64VLQEncode(numbers) {
169
+ let encoded = "";
170
+ for (const number of numbers) {
171
+ let vlq = toVLQSigned(number);
172
+ let digit;
173
+ do {
174
+ digit = vlq & VLQ_BASE_MASK;
175
+ vlq >>>= VLQ_BASE_SHIFT;
176
+ if (vlq > 0) {
177
+ digit |= VLQ_CONTINUATION_BIT;
178
+ }
179
+ encoded += base64Encode(digit);
180
+ } while (vlq > 0);
181
+ }
182
+ return encoded;
183
+ }
184
+ const pkgPathCache = /* @__PURE__ */ new Map();
185
+ function tryGetPkgPath(beginPath) {
186
+ beginPath = normalizePath(beginPath);
187
+ if (pkgPathCache.has(beginPath)) {
188
+ return pkgPathCache.get(beginPath);
189
+ }
190
+ const pkgPath = resolve(beginPath, "package.json");
191
+ if (existsSync(pkgPath)) {
192
+ pkgPathCache.set(beginPath, pkgPath);
193
+ return pkgPath;
194
+ }
195
+ const parentDir = normalizePath(dirname(beginPath));
196
+ if (!parentDir || parentDir === beginPath) {
197
+ pkgPathCache.set(beginPath, undefined);
198
+ return;
199
+ }
200
+ return tryGetPkgPath(parentDir);
201
+ }
202
+ function toCapitalCase(value) {
203
+ value = value.trim().replace(/\s+/g, "-");
204
+ value = value.replace(/-+(\w)/g, (_, char) => char ? char.toUpperCase() : "");
205
+ return (value.charAt(0).toLocaleUpperCase() + value.slice(1)).replace(
206
+ /[^\w]/g,
207
+ ""
208
+ );
209
+ }
210
+ function findTypesPath(...pkgs) {
211
+ let path;
212
+ for (const pkg of pkgs) {
213
+ if (typeof pkg !== "object") continue;
214
+ path = pkg.types || pkg.typings || pkg.exports?.types || pkg.exports?.["."]?.types || pkg.exports?.["./"]?.types;
215
+ if (path) return path;
216
+ }
217
+ }
218
+ function setModuleResolution(options) {
219
+ if (options.moduleResolution) return;
220
+ const module = typeof options.module === "number" ? options.module : options.target ?? ts.ScriptTarget.ES5 >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
221
+ let moduleResolution;
222
+ switch (module) {
223
+ case ts.ModuleKind.CommonJS:
224
+ moduleResolution = ts.ModuleResolutionKind.Node10;
225
+ break;
226
+ case ts.ModuleKind.Node16:
227
+ moduleResolution = ts.ModuleResolutionKind.Node16;
228
+ break;
229
+ case ts.ModuleKind.NodeNext:
230
+ moduleResolution = ts.ModuleResolutionKind.NodeNext;
231
+ break;
232
+ default:
233
+ moduleResolution = ts.version.startsWith("5") ? ts.ModuleResolutionKind.Bundler : ts.ModuleResolutionKind.Classic;
234
+ break;
235
+ }
236
+ options.moduleResolution = moduleResolution;
237
+ }
238
+ function editSourceMapDir(content, fromDir, toDir) {
239
+ const relativeOutDir = relative(fromDir, toDir);
240
+ if (relativeOutDir) {
241
+ try {
242
+ const sourceMap = JSON.parse(content);
243
+ sourceMap.sources = sourceMap.sources.map((source) => {
244
+ return normalizePath(relative(relativeOutDir, source));
245
+ });
246
+ return JSON.stringify(sourceMap);
247
+ } catch (e) {
248
+ return false;
249
+ }
250
+ }
251
+ return true;
252
+ }
253
+ const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g;
254
+ const asteriskRE = /[*]+/g;
255
+ function parseTsAliases(basePath, paths) {
256
+ const result = [];
257
+ for (const [pathWithAsterisk, replacements] of Object.entries(paths)) {
258
+ const find = new RegExp(
259
+ `^${pathWithAsterisk.replace(regexpSymbolRE, "\\$1").replace(asteriskRE, "(?!\\.{1,2}\\/)([^*]+)")}$`
260
+ );
261
+ let index = 1;
262
+ result.push({
263
+ find,
264
+ replacement: ensureAbsolute(
265
+ replacements[0].replace(asteriskRE, () => `$${index++}`),
266
+ basePath
267
+ )
268
+ });
269
+ }
270
+ return result;
271
+ }
272
+ const rootAsteriskImportRE = /^(?!\.{1,2}\/)([^*]+)$/;
273
+ function isAliasGlobal(alias) {
274
+ return alias.find.toString() === rootAsteriskImportRE.toString();
275
+ }
276
+ function importResolves(path) {
277
+ const files = [
278
+ // js
279
+ ".js",
280
+ ".jsx",
281
+ ".mjs",
282
+ ".cjs",
283
+ // ts
284
+ ".ts",
285
+ ".tsx",
286
+ ".mts",
287
+ ".cts",
288
+ ".d.ts",
289
+ // json
290
+ ".json",
291
+ // vue
292
+ ".vue",
293
+ ".vue.d.ts",
294
+ // svelte
295
+ ".svelte"
296
+ ];
297
+ for (const ext of files) {
298
+ if (existsSync(path + ext)) {
299
+ return true;
300
+ }
301
+ }
302
+ return false;
303
+ }
304
+ function tryGetPackageInfo(name) {
305
+ if (process.versions.pnp) {
306
+ const targetRequire = createRequire(import.meta.url);
307
+ try {
308
+ return getPackageInfoSync(
309
+ targetRequire.resolve(`${name}/package.json`, { paths: [process.cwd()] })
310
+ );
311
+ } catch (e) {
312
+ }
313
+ }
314
+ try {
315
+ return getPackageInfoSync(name) ?? getPackageInfoSync(name, { paths: [resolveModule(name) || process.cwd()] });
316
+ } catch (e) {
317
+ }
318
+ }
319
+
320
+ const hasVue = !!tryGetPackageInfo("vue");
321
+ const createProgram = !hasVue ? ts.createProgram : proxyCreateProgram(ts, ts.createProgram, (ts2, options) => {
322
+ const { configFilePath } = options.options;
323
+ const vueOptions = typeof configFilePath === "string" ? createParsedCommandLine(ts2, ts2.sys, configFilePath.replace(/\\/g, "/")).vueOptions : resolveVueCompilerOptions({});
324
+ const vueLanguagePlugin = createVueLanguagePlugin(
325
+ ts2,
326
+ options.options,
327
+ vueOptions,
328
+ (id) => id
329
+ );
330
+ return [vueLanguagePlugin];
331
+ });
332
+
333
+ const dtsRE$1 = /\.d\.(m|c)?tsx?$/;
334
+ function rollupDeclarationFiles({
335
+ root,
336
+ configPath,
337
+ compilerOptions,
338
+ outDir,
339
+ entryPath,
340
+ fileName,
341
+ libFolder,
342
+ rollupConfig = {},
343
+ rollupOptions = {}
344
+ }) {
345
+ const configObjectFullPath = resolve(root, "api-extractor.json");
346
+ if (!dtsRE$1.test(fileName)) {
347
+ fileName += ".d.ts";
348
+ }
349
+ if (/preserve/i.test(compilerOptions.module)) {
350
+ compilerOptions = { ...compilerOptions, module: "ESNext" };
351
+ }
352
+ const extractorConfig = ExtractorConfig.prepare({
353
+ configObject: {
354
+ ...rollupConfig,
355
+ projectFolder: root,
356
+ mainEntryPointFilePath: entryPath,
357
+ compiler: {
358
+ tsconfigFilePath: configPath,
359
+ overrideTsconfig: {
360
+ $schema: "http://json.schemastore.org/tsconfig",
361
+ compilerOptions
362
+ }
363
+ },
364
+ apiReport: {
365
+ enabled: false,
366
+ reportFileName: "<unscopedPackageName>.api.md",
367
+ ...rollupConfig.apiReport
368
+ },
369
+ docModel: {
370
+ enabled: false,
371
+ ...rollupConfig.docModel
372
+ },
373
+ dtsRollup: {
374
+ enabled: true,
375
+ publicTrimmedFilePath: resolve(outDir, fileName)
376
+ },
377
+ tsdocMetadata: {
378
+ enabled: false,
379
+ ...rollupConfig.tsdocMetadata
380
+ },
381
+ messages: {
382
+ compilerMessageReporting: {
383
+ default: {
384
+ logLevel: "none"
385
+ }
386
+ },
387
+ extractorMessageReporting: {
388
+ default: {
389
+ logLevel: "none"
390
+ }
391
+ },
392
+ ...rollupConfig.messages
393
+ }
394
+ },
395
+ configObjectFullPath,
396
+ packageJsonFullPath: tryGetPkgPath(configObjectFullPath)
397
+ });
398
+ return Extractor.invoke(extractorConfig, {
399
+ localBuild: false,
400
+ showVerboseMessages: false,
401
+ showDiagnostics: false,
402
+ typescriptCompilerFolder: libFolder,
403
+ ...rollupOptions
404
+ });
405
+ }
406
+
407
+ const jsonRE = /\.json$/;
408
+ function JsonResolver() {
409
+ return {
410
+ name: "json",
411
+ supports(id) {
412
+ return jsonRE.test(id);
413
+ },
414
+ transform({ id, root, program }) {
415
+ const sourceFile = program.getSourceFile(id);
416
+ if (!sourceFile) return [];
417
+ return [
418
+ {
419
+ path: relative(root, `${id}.d.ts`),
420
+ content: `declare const _default: ${sourceFile.text};
421
+
422
+ export default _default;
423
+ `
424
+ }
425
+ ];
426
+ }
427
+ };
428
+ }
429
+
430
+ const svelteRE = /\.svelte$/;
431
+ let lowerVersion;
432
+ function querySvelteVersion() {
433
+ if (typeof lowerVersion === "boolean") return;
434
+ try {
435
+ const version = tryGetPackageInfo("svelte")?.version;
436
+ lowerVersion = version ? compare(version, "4.0.0", "<") : false;
437
+ } catch (e) {
438
+ lowerVersion = false;
439
+ }
440
+ }
441
+ function SvelteResolver() {
442
+ return {
443
+ name: "svelte",
444
+ supports(id) {
445
+ return svelteRE.test(id);
446
+ },
447
+ transform({ id, root }) {
448
+ querySvelteVersion();
449
+ return [
450
+ {
451
+ path: relative(root, `${id}.d.ts`),
452
+ content: `export { ${lowerVersion ? "SvelteComponentTyped" : "SvelteComponent"} as default } from 'svelte';
453
+ `
454
+ }
455
+ ];
456
+ }
457
+ };
458
+ }
459
+
460
+ const vueRE = /\.vue$/;
461
+ function VueResolver() {
462
+ return {
463
+ name: "vue",
464
+ supports(id) {
465
+ return vueRE.test(id);
466
+ },
467
+ transform({ id, code, program }) {
468
+ const sourceFile = program.getSourceFile(id) || program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
469
+ if (!sourceFile) return [];
470
+ const outputs = [];
471
+ const { emitSkipped, diagnostics } = program.emit(
472
+ sourceFile,
473
+ (path, content) => {
474
+ outputs.push({ path, content });
475
+ },
476
+ undefined,
477
+ true
478
+ );
479
+ if (!program.getCompilerOptions().declarationMap) {
480
+ return {
481
+ outputs,
482
+ emitSkipped,
483
+ diagnostics
484
+ };
485
+ }
486
+ const [beforeScript] = code.split(/\s*<script.*>/);
487
+ const beforeLines = beforeScript.split("\n").length;
488
+ for (const output of outputs) {
489
+ if (output.path.endsWith(".map")) {
490
+ try {
491
+ const sourceMap = JSON.parse(output.content);
492
+ sourceMap.sources = sourceMap.sources.map(
493
+ (source) => source.replace(/\.vue\.ts$/, ".vue")
494
+ );
495
+ if (beforeScript && beforeScript !== code && beforeLines) {
496
+ sourceMap.mappings = `${base64VLQEncode([0, 0, beforeLines, 0])};${sourceMap.mappings}`;
497
+ }
498
+ output.content = JSON.stringify(sourceMap);
499
+ } catch (e) {
500
+ }
501
+ }
502
+ }
503
+ return {
504
+ outputs,
505
+ emitSkipped,
506
+ diagnostics
507
+ };
508
+ }
509
+ };
510
+ }
511
+
512
+ function parseResolvers(resolvers) {
513
+ const nameMap = /* @__PURE__ */ new Map();
514
+ for (const resolver of resolvers) {
515
+ resolver.name && nameMap.set(resolver.name, resolver);
516
+ }
517
+ return Array.from(nameMap.values());
518
+ }
519
+
520
+ const globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
521
+ function normalizeGlob(path) {
522
+ if (/[\\/]$/.test(path)) {
523
+ return path + "**";
524
+ } else if (!globSuffixRE.test(path.split(/[\\/]/).pop())) {
525
+ return path + "/**";
526
+ }
527
+ return path;
528
+ }
529
+ function walkSourceFile(sourceFile, callback) {
530
+ function walkNode(node, parent, callback2) {
531
+ if (callback2(node, parent) !== false) {
532
+ node.forEachChild((child) => walkNode(child, node, callback2));
533
+ }
534
+ }
535
+ sourceFile.forEachChild((child) => walkNode(child, sourceFile, callback));
536
+ }
537
+ function isAliasMatch(alias, importer) {
538
+ if (isRegExp(alias.find)) return alias.find.test(importer);
539
+ if (importer.length < alias.find.length) return false;
540
+ if (importer === alias.find) return true;
541
+ return importer.indexOf(alias.find) === 0 && (alias.find.endsWith("/") || importer.substring(alias.find.length)[0] === "/");
542
+ }
543
+ function transformAlias(importer, dir, aliases, aliasesExclude) {
544
+ if (aliases?.length && !aliasesExclude.some((e) => isRegExp(e) ? e.test(importer) : String(e) === importer)) {
545
+ const matchedAlias = aliases.find((alias) => isAliasMatch(alias, importer));
546
+ if (matchedAlias) {
547
+ const replacement = isAbsolute(matchedAlias.replacement) ? normalizePath(relative(dir, matchedAlias.replacement)) : normalizePath(matchedAlias.replacement);
548
+ const endsWithSlash = typeof matchedAlias.find === "string" ? matchedAlias.find.endsWith("/") : importer.match(matchedAlias.find)[0].endsWith("/");
549
+ const truthPath = importer.replace(
550
+ matchedAlias.find,
551
+ replacement + (endsWithSlash ? "/" : "")
552
+ );
553
+ const absolutePath = resolve$1(dir, truthPath);
554
+ const normalizedPath = normalizePath(relative(dir, absolutePath));
555
+ const resultPath = normalizedPath.startsWith(".") ? normalizedPath : `./${normalizedPath}`;
556
+ if (!isAliasGlobal(matchedAlias)) return resultPath;
557
+ if (importResolves(absolutePath)) return resultPath;
558
+ }
559
+ }
560
+ return importer;
561
+ }
562
+ const vlsRE = /^_?__VLS_/;
563
+ function isVLSNode(node) {
564
+ if (ts.isVariableStatement(node)) {
565
+ return node.declarationList.declarations.some(
566
+ (d) => ts.isIdentifier(d.name) && vlsRE.test(`${d.name.escapedText}`)
567
+ );
568
+ }
569
+ if (ts.isTypeAliasDeclaration(node)) {
570
+ return vlsRE.test(`${node.name.escapedText}`);
571
+ }
572
+ if (ts.isFunctionDeclaration(node)) {
573
+ return !!node.name && vlsRE.test(`${node.name.escapedText}`);
574
+ }
575
+ return false;
576
+ }
577
+ function transformCode(options) {
578
+ const s = new MagicString(options.content);
579
+ const ast = ts.createSourceFile("a.ts", options.content, ts.ScriptTarget.Latest);
580
+ const dir = dirname(options.filePath);
581
+ const importMap = /* @__PURE__ */ new Map();
582
+ const usedDefault = /* @__PURE__ */ new Map();
583
+ const declareModules = [];
584
+ const toLibName = (origin) => {
585
+ const name = transformAlias(origin, dir, options.aliases, options.aliasesExclude);
586
+ return options.cleanVueFileName ? name.replace(/\.vue$/, "") : name;
587
+ };
588
+ let indexCount = 0;
589
+ let importCount = 0;
590
+ walkSourceFile(ast, (node, parent) => {
591
+ if (ts.isImportDeclaration(node)) {
592
+ if (!node.importClause) {
593
+ options.clearPureImport && s.remove(node.pos, node.end);
594
+ ++importCount;
595
+ } else if (ts.isStringLiteral(node.moduleSpecifier) && (node.importClause.name || node.importClause.namedBindings && ts.isNamedImports(node.importClause.namedBindings))) {
596
+ const libName = toLibName(node.moduleSpecifier.text);
597
+ const importSet = importMap.get(libName) ?? importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
598
+ if (node.importClause.name && !usedDefault.has(libName)) {
599
+ const usedType = node.importClause.name.escapedText;
600
+ usedDefault.set(libName, usedType);
601
+ importSet.add(`default as ${usedType}`);
602
+ }
603
+ if (node.importClause.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) {
604
+ node.importClause.namedBindings.elements.forEach((element) => {
605
+ if (element.propertyName) {
606
+ importSet.add(`${element.propertyName.getText(ast)} as ${element.name.escapedText}`);
607
+ } else {
608
+ importSet.add(element.name.escapedText);
609
+ }
610
+ });
611
+ }
612
+ s.remove(node.pos, node.end);
613
+ ++importCount;
614
+ }
615
+ return false;
616
+ }
617
+ if (ts.isImportTypeNode(node) && node.qualifier && ts.isLiteralTypeNode(node.argument) && ts.isIdentifier(node.qualifier) && ts.isStringLiteral(node.argument.literal)) {
618
+ const libName = toLibName(node.argument.literal.text);
619
+ if (!options.staticImport) {
620
+ s.update(node.argument.literal.pos, node.argument.literal.end, `'${libName}'`);
621
+ return !!node.typeArguments;
622
+ }
623
+ const importSet = importMap.get(libName) ?? importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
624
+ let usedType = node.qualifier.escapedText;
625
+ if (usedType === "default") {
626
+ usedType = usedDefault.get(libName) ?? usedDefault.set(libName, `__DTS_DEFAULT_${indexCount++}__`).get(libName);
627
+ importSet.add(`default as ${usedType}`);
628
+ s.update(node.qualifier.pos, node.qualifier.end, usedType);
629
+ } else {
630
+ importSet.add(usedType);
631
+ }
632
+ if (ts.isImportTypeNode(parent) && parent.typeArguments && parent.typeArguments[0] === node) {
633
+ s.remove(node.pos, node.argument.end + 2);
634
+ } else {
635
+ s.update(node.pos, node.argument.end + 2, " ");
636
+ }
637
+ return !!node.typeArguments;
638
+ }
639
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && ts.isStringLiteral(node.arguments[0])) {
640
+ s.update(
641
+ node.arguments[0].pos,
642
+ node.arguments[0].end,
643
+ `'${toLibName(node.arguments[0].text)}'`
644
+ );
645
+ return false;
646
+ }
647
+ if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
648
+ s.update(
649
+ node.moduleSpecifier.pos,
650
+ node.moduleSpecifier.end,
651
+ ` '${toLibName(node.moduleSpecifier.text)}'`
652
+ );
653
+ return false;
654
+ }
655
+ if (ts.isModuleDeclaration(node) && node.body && ts.isModuleBlock(node.body)) {
656
+ if (ts.isIdentifier(node.name) && node.name.escapedText === "global" && node.body.statements.some(isVLSNode)) {
657
+ s.remove(node.pos, node.end);
658
+ } else if (ts.isStringLiteral(node.name)) {
659
+ const libName = toLibName(node.name.text);
660
+ if (libName !== node.name.text) {
661
+ s.update(node.name.pos, node.name.end, ` '${libName}'`);
662
+ }
663
+ if (!libName.startsWith(".") && node.modifiers?.[0] && node.modifiers[0].kind === ts.SyntaxKind.DeclareKeyword && !node.body.statements.some(
664
+ (s2) => ts.isExportAssignment(s2) || ts.isExportDeclaration(s2) || ts.isImportDeclaration(s2)
665
+ )) {
666
+ declareModules.push(s.slice(node.pos, node.end + 1));
667
+ }
668
+ }
669
+ return false;
670
+ }
671
+ });
672
+ let prependImports = "";
673
+ importMap.forEach((importSet, libName) => {
674
+ prependImports += `import { ${Array.from(importSet).join(", ")} } from '${libName}';
675
+ `;
676
+ });
677
+ s.trimStart("\n").prepend(prependImports);
678
+ return {
679
+ content: s.toString(),
680
+ declareModules,
681
+ diffLineCount: importMap.size && importCount < importMap.size ? importMap.size - importCount : null
682
+ };
683
+ }
684
+ function hasNormalExport(content) {
685
+ const ast = ts.createSourceFile("a.ts", content, ts.ScriptTarget.Latest);
686
+ let has = false;
687
+ walkSourceFile(ast, (node) => {
688
+ if (ts.isExportDeclaration(node)) {
689
+ if (node.exportClause && ts.isNamedExports(node.exportClause)) {
690
+ for (const element of node.exportClause.elements) {
691
+ if (element.name.getText(ast) !== "default") {
692
+ has = true;
693
+ break;
694
+ }
695
+ }
696
+ } else {
697
+ has = true;
698
+ }
699
+ } else if ("modifiers" in node && Array.isArray(node.modifiers) && node.modifiers.length > 1) {
700
+ for (let i = 0, len = node.modifiers.length; i < len; ++i) {
701
+ if (node.modifiers[i].kind === ts.SyntaxKind.ExportKeyword && node.modifiers[i + 1]?.kind !== ts.SyntaxKind.DefaultKeyword) {
702
+ has = true;
703
+ break;
704
+ }
705
+ }
706
+ }
707
+ return false;
708
+ });
709
+ return has;
710
+ }
711
+ function hasExportDefault(content) {
712
+ const ast = ts.createSourceFile("a.ts", content, ts.ScriptTarget.Latest);
713
+ let has = false;
714
+ walkSourceFile(ast, (node) => {
715
+ if (ts.isExportAssignment(node)) {
716
+ has = true;
717
+ } else if (ts.isExportDeclaration(node) && node.exportClause && ts.isNamedExports(node.exportClause)) {
718
+ for (const element of node.exportClause.elements) {
719
+ if (element.name.getText(ast) === "default") {
720
+ has = true;
721
+ break;
722
+ }
723
+ }
724
+ } else if ("modifiers" in node && Array.isArray(node.modifiers) && node.modifiers.length > 1) {
725
+ for (let i = 0, len = node.modifiers.length; i < len; ++i) {
726
+ if (node.modifiers[i].kind === ts.SyntaxKind.ExportKeyword && node.modifiers[i + 1]?.kind === ts.SyntaxKind.DefaultKeyword) {
727
+ has = true;
728
+ break;
729
+ }
730
+ }
731
+ }
732
+ return false;
733
+ });
734
+ return has;
735
+ }
736
+
737
+ const jsRE = /\.(m|c)?jsx?$/;
738
+ const tsRE = /\.(m|c)?tsx?$/;
739
+ const dtsRE = /\.d\.(m|c)?tsx?$/;
740
+ const tjsRE = /\.(m|c)?(t|j)sx?$/;
741
+ const mtjsRE = /\.m(t|j)sx?$/;
742
+ const ctjsRE = /\.c(t|j)sx?$/;
743
+ const fullRelativeRE = /^\.\.?\//;
744
+ const defaultIndex = "index.d.ts";
745
+ const pluginName = "vite:dts";
746
+ const logPrefix = cyan(`[${pluginName}]`);
747
+ const bundleDebug = debug("vite-plugin-dts:bundle");
748
+ const fixedCompilerOptions = {
749
+ noEmit: false,
750
+ declaration: true,
751
+ emitDeclarationOnly: true,
752
+ checkJs: false,
753
+ skipLibCheck: true,
754
+ preserveSymlinks: false,
755
+ noEmitOnError: undefined,
756
+ target: ts.ScriptTarget.ESNext
757
+ };
758
+ const noop = () => {
759
+ };
760
+ const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
761
+ const tsToDts = (path) => `${path.replace(tsRE, "")}.d.ts`;
762
+ function dtsPlugin(options = {}) {
763
+ const {
764
+ tsconfigPath,
765
+ logLevel,
766
+ staticImport = false,
767
+ clearPureImport = true,
768
+ cleanVueFileName = false,
769
+ insertTypesEntry = false,
770
+ rollupTypes = false,
771
+ pathsToAliases = true,
772
+ aliasesExclude = [],
773
+ rollupOptions = {},
774
+ copyDtsFiles = false,
775
+ declarationOnly = false,
776
+ strictOutput = true,
777
+ afterDiagnostic = noop,
778
+ beforeWriteFile = noop,
779
+ afterRollup = noop,
780
+ afterBuild = noop
781
+ } = options;
782
+ let root = ensureAbsolute(options.root ?? "", process.cwd());
783
+ let publicRoot = "";
784
+ let entryRoot = options.entryRoot ?? "";
785
+ let configPath;
786
+ let compilerOptions;
787
+ let rawCompilerOptions;
788
+ let outDirs;
789
+ let entries;
790
+ let include;
791
+ let exclude;
792
+ let aliases;
793
+ let libName;
794
+ let indexName;
795
+ let logger;
796
+ let host;
797
+ let program;
798
+ let filter;
799
+ let rootNames = [];
800
+ let rebuildProgram;
801
+ let bundled = false;
802
+ let timeRecord = 0;
803
+ const resolvers = parseResolvers([
804
+ JsonResolver(),
805
+ VueResolver(),
806
+ SvelteResolver(),
807
+ ...options.resolvers || []
808
+ ]);
809
+ const rootFiles = /* @__PURE__ */ new Set();
810
+ const outputFiles = /* @__PURE__ */ new Map();
811
+ const transformedFiles = /* @__PURE__ */ new Set();
812
+ const diagnostics = [];
813
+ const setOutputFile = (path, content) => {
814
+ outputFiles.set(path, content);
815
+ };
816
+ const rollupConfig = { ...options.rollupConfig || {} };
817
+ rollupConfig.bundledPackages = rollupConfig.bundledPackages || options.bundledPackages || [];
818
+ const cleanPath = (path, emittedFiles) => {
819
+ const newPath = path.replace(".vue.d.ts", ".d.ts");
820
+ return !emittedFiles.has(newPath) && cleanVueFileName ? newPath : path;
821
+ };
822
+ return {
823
+ name: pluginName,
824
+ apply: "build",
825
+ enforce: "pre",
826
+ config(config) {
827
+ const aliasOptions = config?.resolve?.alias ?? [];
828
+ if (isNativeObj(aliasOptions)) {
829
+ aliases = Object.entries(aliasOptions).map(([key, value]) => {
830
+ return { find: key, replacement: value };
831
+ });
832
+ } else {
833
+ aliases = ensureArray(aliasOptions).map((alias) => ({ ...alias }));
834
+ }
835
+ if (aliasesExclude.length > 0) {
836
+ aliases = aliases.filter(
837
+ ({ find }) => !aliasesExclude.some(
838
+ (aliasExclude) => aliasExclude && (isRegExp(find) ? find.toString() === aliasExclude.toString() : isRegExp(aliasExclude) ? find.match(aliasExclude)?.[0] : find === aliasExclude)
839
+ )
840
+ );
841
+ }
842
+ for (const alias of aliases) {
843
+ alias.replacement = resolve(alias.replacement);
844
+ }
845
+ },
846
+ async configResolved(config) {
847
+ logger = logLevel ? (await import('vite')).createLogger(logLevel, { allowClearScreen: config.clearScreen }) : config.logger;
848
+ root = ensureAbsolute(options.root ?? "", config.root);
849
+ if (config.build.lib) {
850
+ const input = typeof config.build.lib.entry === "string" ? [config.build.lib.entry] : config.build.lib.entry;
851
+ if (Array.isArray(input)) {
852
+ entries = input.reduce(
853
+ (prev, current) => {
854
+ prev[basename(current)] = current;
855
+ return prev;
856
+ },
857
+ {}
858
+ );
859
+ } else {
860
+ entries = { ...input };
861
+ }
862
+ const filename = config.build.lib.fileName ?? defaultIndex;
863
+ const entry = typeof config.build.lib.entry === "string" ? config.build.lib.entry : Object.keys(config.build.lib.entry)[0];
864
+ libName = config.build.lib.name || "_default";
865
+ indexName = typeof filename === "string" ? filename : filename("es", entry);
866
+ if (!dtsRE.test(indexName)) {
867
+ indexName = `${indexName.replace(tjsRE, "")}.d.${extPrefix(indexName)}ts`;
868
+ }
869
+ } else {
870
+ logger.warn(
871
+ `
872
+ ${logPrefix} ${yellow(
873
+ "You are building a library that may not need to generate declaration files."
874
+ )}
875
+ `
876
+ );
877
+ libName = "_default";
878
+ indexName = defaultIndex;
879
+ }
880
+ if (!options.outDir) {
881
+ outDirs = [ensureAbsolute(config.build.outDir, root)];
882
+ }
883
+ bundleDebug("parse vite config");
884
+ },
885
+ options(options2) {
886
+ if (entries) return;
887
+ const input = typeof options2.input === "string" ? [options2.input] : options2.input;
888
+ if (Array.isArray(input)) {
889
+ entries = input.reduce(
890
+ (prev, current) => {
891
+ prev[basename(current)] = current;
892
+ return prev;
893
+ },
894
+ {}
895
+ );
896
+ } else {
897
+ entries = { ...input };
898
+ }
899
+ logger = logger || console;
900
+ aliases = aliases || [];
901
+ libName = "_default";
902
+ indexName = defaultIndex;
903
+ bundleDebug("parse options");
904
+ },
905
+ async buildStart() {
906
+ if (program) return;
907
+ bundleDebug("begin buildStart");
908
+ timeRecord = 0;
909
+ const startTime = Date.now();
910
+ configPath = tsconfigPath ? ensureAbsolute(tsconfigPath, root) : ts.findConfigFile(root, ts.sys.fileExists);
911
+ const content = configPath ? createParsedCommandLine(ts, ts.sys, configPath) : undefined;
912
+ compilerOptions = {
913
+ ...content?.options || {},
914
+ ...options.compilerOptions || {},
915
+ ...fixedCompilerOptions,
916
+ outDir: ".",
917
+ declarationDir: "."
918
+ };
919
+ rawCompilerOptions = content?.raw.compilerOptions || {};
920
+ if (content?.fileNames.find((name) => name.endsWith(".vue"))) {
921
+ setModuleResolution(compilerOptions);
922
+ }
923
+ if (!outDirs) {
924
+ outDirs = options.outDir ? ensureArray(options.outDir).map((d) => ensureAbsolute(d, root)) : [
925
+ ensureAbsolute(
926
+ content?.raw.compilerOptions?.outDir ? resolveConfigDir(content.raw.compilerOptions.outDir, root) : "dist",
927
+ root
928
+ )
929
+ ];
930
+ }
931
+ const {
932
+ // Here we are using the default value to set the `baseUrl` to the current directory if no value exists. This is
933
+ // the same behavior as the TS Compiler. See TS source:
934
+ // https://github.com/microsoft/TypeScript/blob/3386e943215613c40f68ba0b108cda1ddb7faee1/src/compiler/utilities.ts#L6493-L6501
935
+ baseUrl = compilerOptions.paths ? process.cwd() : undefined,
936
+ paths
937
+ } = compilerOptions;
938
+ if (pathsToAliases && baseUrl && paths) {
939
+ aliases.push(
940
+ ...parseTsAliases(
941
+ ensureAbsolute(
942
+ resolveConfigDir(baseUrl, root),
943
+ configPath ? dirname(configPath) : root
944
+ ),
945
+ paths
946
+ )
947
+ );
948
+ }
949
+ const computeGlobs = (rootGlobs, tsGlobs, defaultGlob) => {
950
+ if (rootGlobs?.length) {
951
+ return ensureArray(rootGlobs).map(
952
+ (glob) => normalizeGlob(ensureAbsolute(resolveConfigDir(glob, root), root))
953
+ );
954
+ }
955
+ return ensureArray(tsGlobs?.length ? tsGlobs : defaultGlob).map(
956
+ (glob) => normalizeGlob(
957
+ ensureAbsolute(resolveConfigDir(glob, root), configPath ? dirname(configPath) : root)
958
+ )
959
+ );
960
+ };
961
+ include = computeGlobs(
962
+ options.include,
963
+ [...ensureArray(content?.raw.include ?? []), ...ensureArray(content?.raw.files ?? [])],
964
+ "**/*"
965
+ );
966
+ exclude = computeGlobs(options.exclude, content?.raw.exclude, "node_modules/**");
967
+ filter = createFilter(include, exclude);
968
+ rootNames = [
969
+ ...new Set(
970
+ Object.values(entries).map((entry) => ensureAbsolute(entry, root)).concat(content?.fileNames.filter(filter) || []).map(normalizePath)
971
+ )
972
+ ];
973
+ host = ts.createCompilerHost(compilerOptions);
974
+ program = (rebuildProgram = () => createProgram({
975
+ host,
976
+ rootNames,
977
+ options: compilerOptions,
978
+ projectReferences: content?.projectReferences
979
+ }))();
980
+ libName = toCapitalCase(libName || "_default");
981
+ indexName = indexName || defaultIndex;
982
+ const maybeEmitted = (sourceFile) => {
983
+ return !(compilerOptions.noEmitForJsFiles && jsRE.test(sourceFile.fileName)) && !sourceFile.isDeclarationFile && !program.isSourceFileFromExternalLibrary(sourceFile);
984
+ };
985
+ publicRoot = compilerOptions.rootDir ? ensureAbsolute(resolveConfigDir(compilerOptions.rootDir, root), root) : compilerOptions.composite && compilerOptions.configFilePath ? dirname(compilerOptions.configFilePath) : queryPublicPath(
986
+ program.getSourceFiles().filter(maybeEmitted).map((sourceFile) => sourceFile.fileName)
987
+ );
988
+ publicRoot = normalizePath(publicRoot);
989
+ entryRoot = entryRoot || publicRoot;
990
+ entryRoot = ensureAbsolute(entryRoot, root);
991
+ diagnostics.push(
992
+ ...program.getDeclarationDiagnostics(),
993
+ ...program.getSemanticDiagnostics(),
994
+ ...program.getSyntacticDiagnostics()
995
+ );
996
+ for (const file of rootNames) {
997
+ this.addWatchFile(file);
998
+ rootFiles.add(file);
999
+ }
1000
+ bundleDebug("create ts program");
1001
+ timeRecord += Date.now() - startTime;
1002
+ },
1003
+ async transform(code, id) {
1004
+ let resolver;
1005
+ id = normalizePath(id).split("?")[0];
1006
+ if (!host || !program || !filter(id) || !(resolver = resolvers.find((r) => r.supports(id))) && !tjsRE.test(id) || transformedFiles.has(id)) {
1007
+ return;
1008
+ }
1009
+ const startTime = Date.now();
1010
+ const outDir = outDirs[0];
1011
+ rootFiles.delete(id);
1012
+ transformedFiles.add(id);
1013
+ if (resolver) {
1014
+ const result = await resolver.transform({
1015
+ id,
1016
+ code,
1017
+ root: publicRoot,
1018
+ outDir,
1019
+ host,
1020
+ program
1021
+ });
1022
+ let output;
1023
+ if (Array.isArray(result)) {
1024
+ output = result;
1025
+ } else {
1026
+ output = result.outputs;
1027
+ if (result.emitSkipped && result.diagnostics?.length) {
1028
+ diagnostics.push(...result.diagnostics);
1029
+ }
1030
+ }
1031
+ for (const { path, content } of output) {
1032
+ setOutputFile(
1033
+ resolve(publicRoot, relative(outDir, ensureAbsolute(path, outDir))),
1034
+ content
1035
+ );
1036
+ }
1037
+ } else {
1038
+ const sourceFile = program.getSourceFile(id);
1039
+ if (sourceFile) {
1040
+ const result = program.emit(
1041
+ sourceFile,
1042
+ (name, text) => {
1043
+ setOutputFile(
1044
+ resolve(publicRoot, relative(outDir, ensureAbsolute(name, outDir))),
1045
+ text
1046
+ );
1047
+ },
1048
+ undefined,
1049
+ true
1050
+ );
1051
+ if (result.emitSkipped && result.diagnostics.length) {
1052
+ diagnostics.push(...result.diagnostics);
1053
+ }
1054
+ }
1055
+ }
1056
+ const dtsId = id.replace(tjsRE, "") + ".d.ts";
1057
+ const dtsSourceFile = program.getSourceFile(dtsId);
1058
+ dtsSourceFile && filter(dtsSourceFile.fileName) && setOutputFile(normalizePath(dtsSourceFile.fileName), dtsSourceFile.getFullText());
1059
+ timeRecord += Date.now() - startTime;
1060
+ },
1061
+ watchChange(id) {
1062
+ id = normalizePath(id);
1063
+ if (!host || !program || !filter(id) || !resolvers.find((r) => r.supports(id)) && !tjsRE.test(id)) {
1064
+ return;
1065
+ }
1066
+ id = id.split("?")[0];
1067
+ const sourceFile = host.getSourceFile(id, ts.ScriptTarget.ESNext);
1068
+ if (sourceFile) {
1069
+ for (const file of rootNames) {
1070
+ rootFiles.add(file);
1071
+ }
1072
+ rootFiles.add(normalizePath(sourceFile.fileName));
1073
+ bundled = false;
1074
+ timeRecord = 0;
1075
+ program = rebuildProgram();
1076
+ }
1077
+ },
1078
+ async writeBundle() {
1079
+ transformedFiles.clear();
1080
+ if (!host || !program || bundled) return;
1081
+ bundled = true;
1082
+ bundleDebug("begin writeBundle");
1083
+ logger.info(green(`
1084
+ ${logPrefix} Start generate declaration files...`));
1085
+ const startTime = Date.now();
1086
+ if (diagnostics?.length) {
1087
+ logger.error(ts.formatDiagnosticsWithColorAndContext(diagnostics, host));
1088
+ }
1089
+ if (typeof afterDiagnostic === "function") {
1090
+ await unwrapPromise(afterDiagnostic(diagnostics));
1091
+ }
1092
+ const outDir = outDirs[0];
1093
+ const emittedFiles = /* @__PURE__ */ new Map();
1094
+ const declareModules = [];
1095
+ const writeOutput = async (path, content, outDir2, record = true) => {
1096
+ if (typeof beforeWriteFile === "function") {
1097
+ const result = await unwrapPromise(beforeWriteFile(path, content));
1098
+ if (result === false) return;
1099
+ if (result) {
1100
+ path = result.filePath || path;
1101
+ content = result.content ?? content;
1102
+ }
1103
+ }
1104
+ path = normalizePath(path);
1105
+ const dir = normalizePath(dirname(path));
1106
+ if (strictOutput && !dir.startsWith(normalizePath(outDir2))) {
1107
+ logger.warn(`${logPrefix} ${yellow("Outside emitted:")} ${path}`);
1108
+ return;
1109
+ }
1110
+ if (!existsSync(dir)) {
1111
+ await mkdir(dir, { recursive: true });
1112
+ }
1113
+ await writeFile(path, content, "utf-8");
1114
+ record && emittedFiles.set(path, content);
1115
+ };
1116
+ const sourceFiles = program.getSourceFiles();
1117
+ for (const sourceFile of sourceFiles) {
1118
+ if (!filter(sourceFile.fileName)) continue;
1119
+ if (copyDtsFiles && dtsRE.test(sourceFile.fileName)) {
1120
+ setOutputFile(normalizePath(sourceFile.fileName), sourceFile.getFullText());
1121
+ }
1122
+ if (rootFiles.has(sourceFile.fileName)) {
1123
+ program.emit(
1124
+ sourceFile,
1125
+ (name, text) => {
1126
+ setOutputFile(
1127
+ resolve(publicRoot, relative(outDir, ensureAbsolute(name, outDir))),
1128
+ text
1129
+ );
1130
+ },
1131
+ undefined,
1132
+ true
1133
+ );
1134
+ rootFiles.delete(sourceFile.fileName);
1135
+ }
1136
+ }
1137
+ bundleDebug("emit output patch");
1138
+ const currentDir = host.getCurrentDirectory();
1139
+ const declarationFiles = /* @__PURE__ */ new Map();
1140
+ const mapFiles = /* @__PURE__ */ new Map();
1141
+ const prependMappings = /* @__PURE__ */ new Map();
1142
+ for (const [filePath, content] of outputFiles.entries()) {
1143
+ if (filePath.endsWith(".map")) {
1144
+ mapFiles.set(filePath, content);
1145
+ } else {
1146
+ declarationFiles.set(filePath, content);
1147
+ }
1148
+ }
1149
+ await runParallel(
1150
+ cpus().length,
1151
+ Array.from(declarationFiles.entries()),
1152
+ async ([filePath, content]) => {
1153
+ const newFilePath = resolve(
1154
+ outDir,
1155
+ relative(
1156
+ entryRoot,
1157
+ cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath
1158
+ )
1159
+ );
1160
+ if (content) {
1161
+ const result = transformCode({
1162
+ filePath,
1163
+ content,
1164
+ aliases,
1165
+ aliasesExclude,
1166
+ staticImport,
1167
+ clearPureImport,
1168
+ cleanVueFileName
1169
+ });
1170
+ content = result.content;
1171
+ declareModules.push(...result.declareModules);
1172
+ if (result.diffLineCount) {
1173
+ prependMappings.set(`${newFilePath}.map`, ";".repeat(result.diffLineCount));
1174
+ }
1175
+ }
1176
+ await writeOutput(newFilePath, content, outDir);
1177
+ }
1178
+ );
1179
+ await runParallel(
1180
+ cpus().length,
1181
+ Array.from(mapFiles.entries()),
1182
+ async ([filePath, content]) => {
1183
+ const baseDir = dirname(filePath);
1184
+ filePath = resolve(
1185
+ outDir,
1186
+ relative(
1187
+ entryRoot,
1188
+ cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath
1189
+ )
1190
+ );
1191
+ try {
1192
+ const sourceMap = JSON.parse(content);
1193
+ sourceMap.sources = sourceMap.sources.map((source) => {
1194
+ return normalizePath(
1195
+ relative(
1196
+ dirname(filePath),
1197
+ resolve(currentDir, relative(publicRoot, baseDir), source)
1198
+ )
1199
+ );
1200
+ });
1201
+ if (prependMappings.has(filePath)) {
1202
+ sourceMap.mappings = `${prependMappings.get(filePath)}${sourceMap.mappings}`;
1203
+ }
1204
+ content = JSON.stringify(sourceMap);
1205
+ } catch (e) {
1206
+ logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${filePath}`);
1207
+ }
1208
+ await writeOutput(filePath, content, outDir);
1209
+ }
1210
+ );
1211
+ bundleDebug("write output");
1212
+ if (insertTypesEntry || rollupTypes) {
1213
+ const pkgPath = tryGetPkgPath(root);
1214
+ let pkg;
1215
+ try {
1216
+ pkg = pkgPath && existsSync(pkgPath) ? JSON.parse(await readFile(pkgPath, "utf-8")) : {};
1217
+ } catch (e) {
1218
+ }
1219
+ const entryNames = Object.keys(entries);
1220
+ const types = findTypesPath(pkg.publishConfig, pkg);
1221
+ const multiple = entryNames.length > 1;
1222
+ let typesPath = cleanPath(
1223
+ types ? resolve(root, types) : resolve(outDir, indexName),
1224
+ emittedFiles
1225
+ );
1226
+ if (!multiple && !dtsRE.test(typesPath)) {
1227
+ logger.warn(
1228
+ `
1229
+ ${logPrefix} ${yellow(
1230
+ "The resolved path of type entry is not ending with '.d.ts'."
1231
+ )}
1232
+ `
1233
+ );
1234
+ typesPath = `${typesPath.replace(tjsRE, "")}.d.${extPrefix(typesPath)}ts`;
1235
+ }
1236
+ for (const name of entryNames) {
1237
+ const entryDtsPath = multiple ? cleanPath(resolve(outDir, tsToDts(name)), emittedFiles) : typesPath;
1238
+ if (existsSync(entryDtsPath)) continue;
1239
+ const sourceEntry = normalizePath(
1240
+ cleanPath(resolve(outDir, relative(entryRoot, tsToDts(entries[name]))), emittedFiles)
1241
+ );
1242
+ let fromPath = normalizePath(relative(dirname(entryDtsPath), sourceEntry));
1243
+ fromPath = fromPath.replace(dtsRE, "");
1244
+ fromPath = fullRelativeRE.test(fromPath) ? fromPath : `./${fromPath}`;
1245
+ let content = "export {}\n";
1246
+ if (emittedFiles.has(sourceEntry)) {
1247
+ if (hasNormalExport(emittedFiles.get(sourceEntry))) {
1248
+ content = `export * from '${fromPath}'
1249
+ ${content}`;
1250
+ }
1251
+ if (hasExportDefault(emittedFiles.get(sourceEntry))) {
1252
+ content += `import ${libName} from '${fromPath}'
1253
+ export default ${libName}
1254
+ ${content}`;
1255
+ }
1256
+ }
1257
+ await writeOutput(cleanPath(entryDtsPath, emittedFiles), content, outDir);
1258
+ }
1259
+ bundleDebug("insert index");
1260
+ if (rollupTypes) {
1261
+ logger.info(green(`${logPrefix} Start rollup declaration files...`));
1262
+ const rollupFiles = /* @__PURE__ */ new Set();
1263
+ const compilerOptions2 = configPath ? getTsConfig(configPath, host.readFile).compilerOptions : rawCompilerOptions;
1264
+ const rollup = async (path) => {
1265
+ const result = rollupDeclarationFiles({
1266
+ root: publicRoot,
1267
+ configPath,
1268
+ compilerOptions: compilerOptions2,
1269
+ outDir,
1270
+ entryPath: path,
1271
+ fileName: basename(path),
1272
+ libFolder: getTsLibFolder(),
1273
+ rollupConfig,
1274
+ rollupOptions
1275
+ });
1276
+ emittedFiles.delete(path);
1277
+ rollupFiles.add(path);
1278
+ if (typeof afterRollup === "function") {
1279
+ await unwrapPromise(afterRollup(result));
1280
+ }
1281
+ };
1282
+ if (multiple) {
1283
+ await runParallel(cpus().length, entryNames, async (name) => {
1284
+ await rollup(cleanPath(resolve(outDir, tsToDts(name)), emittedFiles));
1285
+ });
1286
+ } else {
1287
+ await rollup(typesPath);
1288
+ }
1289
+ await runParallel(cpus().length, Array.from(emittedFiles.keys()), (f) => unlink(f));
1290
+ removeDirIfEmpty(outDir);
1291
+ emittedFiles.clear();
1292
+ const declared = declareModules.join("\n");
1293
+ await runParallel(cpus().length, [...rollupFiles], async (filePath) => {
1294
+ await writeOutput(
1295
+ filePath,
1296
+ await readFile(filePath, "utf-8") + (declared ? `
1297
+ ${declared}` : ""),
1298
+ dirname(filePath)
1299
+ );
1300
+ });
1301
+ bundleDebug("rollup output");
1302
+ }
1303
+ }
1304
+ if (outDirs.length > 1) {
1305
+ const extraOutDirs = outDirs.slice(1);
1306
+ await runParallel(cpus().length, Array.from(emittedFiles), async ([wroteFile, content]) => {
1307
+ const relativePath = relative(outDir, wroteFile);
1308
+ await Promise.all(
1309
+ extraOutDirs.map(async (targetOutDir) => {
1310
+ const path = resolve(targetOutDir, relativePath);
1311
+ if (wroteFile.endsWith(".map")) {
1312
+ if (!editSourceMapDir(content, outDir, targetOutDir)) {
1313
+ logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${path}`);
1314
+ }
1315
+ }
1316
+ await writeOutput(path, content, targetOutDir, false);
1317
+ })
1318
+ );
1319
+ });
1320
+ }
1321
+ diagnostics.length = 0;
1322
+ if (typeof afterBuild === "function") {
1323
+ await unwrapPromise(afterBuild(emittedFiles));
1324
+ }
1325
+ bundleDebug("finish");
1326
+ logger.info(
1327
+ green(`${logPrefix} Declaration files built in ${timeRecord + Date.now() - startTime}ms.
1328
+ `)
1329
+ );
1330
+ },
1331
+ generateBundle(_, bundle) {
1332
+ if (declarationOnly) {
1333
+ for (const id of Object.keys(bundle)) {
1334
+ delete bundle[id];
1335
+ }
1336
+ }
1337
+ }
1338
+ };
1339
+ }
1340
+
1341
+ export { dtsPlugin as default, editSourceMapDir };