vite-plugin-dts 1.6.0 → 1.6.2

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.cjs ADDED
@@ -0,0 +1,831 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/index.ts
27
+ var src_exports = {};
28
+ __export(src_exports, {
29
+ default: () => src_default
30
+ });
31
+ module.exports = __toCommonJS(src_exports);
32
+
33
+ // src/plugin.ts
34
+ var import_node_path4 = require("path");
35
+ var import_fs_extra = __toESM(require("fs-extra"), 1);
36
+ var import_os = __toESM(require("os"), 1);
37
+ var import_chalk = __toESM(require("chalk"), 1);
38
+ var import_fast_glob = __toESM(require("fast-glob"), 1);
39
+ var import_debug = require("debug");
40
+ var import_ts_morph = require("ts-morph");
41
+ var import_vite2 = require("vite");
42
+ var import_typescript = require("typescript");
43
+
44
+ // src/transform.ts
45
+ var import_node_path2 = require("path");
46
+ var import_vite = require("vite");
47
+
48
+ // src/utils.ts
49
+ var import_node_path = require("path");
50
+ var import_node_fs = require("fs");
51
+ function isNativeObj(value) {
52
+ return Object.prototype.toString.call(value) === "[object Object]";
53
+ }
54
+ function isRegExp(value) {
55
+ return Object.prototype.toString.call(value) === "[object RegExp]";
56
+ }
57
+ function isPromise(value) {
58
+ return !!value && typeof value.then === "function" && typeof value.catch === "function";
59
+ }
60
+ function mergeObjects(sourceObj, targetObj) {
61
+ const loop = [
62
+ {
63
+ source: sourceObj,
64
+ target: targetObj
65
+ }
66
+ ];
67
+ while (loop.length) {
68
+ const { source, target } = loop.pop();
69
+ Object.keys(target).forEach((key) => {
70
+ if (isNativeObj(target[key])) {
71
+ if (!isNativeObj(source[key])) {
72
+ source[key] = {};
73
+ }
74
+ loop.push({
75
+ source: source[key],
76
+ target: target[key]
77
+ });
78
+ } else if (Array.isArray(target[key])) {
79
+ if (!Array.isArray(source[key])) {
80
+ source[key] = [];
81
+ }
82
+ loop.push({
83
+ source: source[key],
84
+ target: target[key]
85
+ });
86
+ } else {
87
+ source[key] = target[key];
88
+ }
89
+ });
90
+ }
91
+ return sourceObj;
92
+ }
93
+ function ensureAbsolute(path, root) {
94
+ return path ? (0, import_node_path.isAbsolute)(path) ? path : (0, import_node_path.resolve)(root, path) : root;
95
+ }
96
+ function ensureArray(value) {
97
+ return Array.isArray(value) ? value : value ? [value] : [];
98
+ }
99
+ async function runParallel(maxConcurrency, source, iteratorFn) {
100
+ const ret = [];
101
+ const executing = [];
102
+ for (const item of source) {
103
+ const p = Promise.resolve().then(() => iteratorFn(item, source));
104
+ ret.push(p);
105
+ if (maxConcurrency <= source.length) {
106
+ const e = p.then(() => executing.splice(executing.indexOf(e), 1));
107
+ executing.push(e);
108
+ if (executing.length >= maxConcurrency) {
109
+ await Promise.race(executing);
110
+ }
111
+ }
112
+ }
113
+ return Promise.all(ret);
114
+ }
115
+ var speRE = /[\\/]/;
116
+ function queryPublicPath(paths) {
117
+ if (paths.length === 0) {
118
+ return "";
119
+ } else if (paths.length === 1) {
120
+ return (0, import_node_path.dirname)(paths[0]);
121
+ }
122
+ let publicPath = (0, import_node_path.normalize)((0, import_node_path.dirname)(paths[0])) + import_node_path.sep;
123
+ let publicUnits = publicPath.split(speRE);
124
+ let index2 = publicUnits.length - 1;
125
+ for (const path of paths.slice(1)) {
126
+ if (!index2) {
127
+ return publicPath;
128
+ }
129
+ const dirPath = (0, import_node_path.normalize)((0, import_node_path.dirname)(path)) + import_node_path.sep;
130
+ if (dirPath.startsWith(publicPath)) {
131
+ continue;
132
+ }
133
+ const units = dirPath.split(speRE);
134
+ if (units.length < index2) {
135
+ publicPath = dirPath;
136
+ publicUnits = units;
137
+ continue;
138
+ }
139
+ for (let i = 0; i <= index2; ++i) {
140
+ if (publicUnits[i] !== units[i]) {
141
+ if (!i) {
142
+ return "";
143
+ }
144
+ index2 = i - 1;
145
+ publicUnits = publicUnits.slice(0, index2 + 1);
146
+ publicPath = publicUnits.join(import_node_path.sep) + import_node_path.sep;
147
+ break;
148
+ }
149
+ }
150
+ }
151
+ return publicPath.slice(0, -1);
152
+ }
153
+ function removeDirIfEmpty(dir) {
154
+ if (!(0, import_node_fs.existsSync)(dir)) {
155
+ return;
156
+ }
157
+ let onlyHasDir = true;
158
+ for (const file of (0, import_node_fs.readdirSync)(dir)) {
159
+ const abs = (0, import_node_path.resolve)(dir, file);
160
+ if ((0, import_node_fs.lstatSync)(abs).isDirectory()) {
161
+ if (!removeDirIfEmpty(abs)) {
162
+ onlyHasDir = false;
163
+ }
164
+ } else {
165
+ onlyHasDir = false;
166
+ }
167
+ }
168
+ if (onlyHasDir) {
169
+ (0, import_node_fs.rmdirSync)(dir);
170
+ }
171
+ return onlyHasDir;
172
+ }
173
+
174
+ // src/transform.ts
175
+ var globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
176
+ function normalizeGlob(path) {
177
+ if (/[\\/]$/.test(path)) {
178
+ return path + "**";
179
+ } else if (!globSuffixRE.test(path.split(/[\\/]/).pop())) {
180
+ return path + "/**";
181
+ }
182
+ return path;
183
+ }
184
+ var globalDynamicTypeRE = /import\(['"][^;\n]+?['"]\)\.\w+[.()[\]<>,;\n\s]/g;
185
+ var dynamicTypeRE = /import\(['"](.+)['"]\)\.(.+)([.()[\]<>,;\n\s])/;
186
+ var importTypesRE = /import\s?(?:type)?\s?\{(.+)\}\s?from\s?['"].+['"]/;
187
+ function transformDynamicImport(content) {
188
+ const importMap = /* @__PURE__ */ new Map();
189
+ content = content.replace(globalDynamicTypeRE, (str) => {
190
+ const matchResult = str.match(dynamicTypeRE);
191
+ const libName = matchResult[1];
192
+ const importSet = importMap.get(libName) ?? importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
193
+ const usedType = matchResult[2];
194
+ importSet.add(usedType);
195
+ return usedType + matchResult[3];
196
+ });
197
+ importMap.forEach((importSet, libName) => {
198
+ const importReg = new RegExp(
199
+ `import\\s?(?:type)?\\s?\\{[^;\\n]+\\}\\s?from\\s?['"]${libName}['"]`,
200
+ "g"
201
+ );
202
+ const matchResult = content.match(importReg);
203
+ if (matchResult == null ? void 0 : matchResult[0]) {
204
+ const importedTypes = matchResult[0].match(importTypesRE)[1].trim().split(",");
205
+ content = content.replace(
206
+ matchResult[0],
207
+ `import type { ${Array.from(importSet).concat(importedTypes).join(", ")} } from '${libName}'`
208
+ );
209
+ } else {
210
+ content = `import type { ${Array.from(importSet).join(", ")} } from '${libName}';
211
+ ` + content;
212
+ }
213
+ });
214
+ return content;
215
+ }
216
+ function isAliasMatch(alias, importee) {
217
+ if (isRegExp(alias.find))
218
+ return alias.find.test(importee);
219
+ if (importee.length < alias.find.length)
220
+ return false;
221
+ if (importee === alias.find)
222
+ return true;
223
+ return importee.indexOf(alias.find) === 0 && (alias.find.endsWith("/") || importee.substring(alias.find.length)[0] === "/");
224
+ }
225
+ var globalImportRE = /(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g;
226
+ var staticImportRE = /(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/;
227
+ var dynamicImportRE = /import\(['"]([^;\n]+?)['"]\)/;
228
+ var simpleStaticImportRE = /((?:import|export).+from\s?)['"](.+)['"]/;
229
+ var simpleDynamicImportRE = /(import\()['"](.+)['"]\)/;
230
+ function transformAliasImport(filePath, content, aliases, exclude = []) {
231
+ if (!aliases.length)
232
+ return content;
233
+ return content.replace(globalImportRE, (str) => {
234
+ let matchResult = str.match(staticImportRE);
235
+ let isDynamic = false;
236
+ if (!matchResult) {
237
+ matchResult = str.match(dynamicImportRE);
238
+ isDynamic = true;
239
+ }
240
+ if (matchResult == null ? void 0 : matchResult[1]) {
241
+ const matchedAlias = aliases.find((alias) => isAliasMatch(alias, matchResult[1]));
242
+ if (matchedAlias) {
243
+ if (exclude.some((e) => isRegExp(e) ? e.test(matchResult[1]) : String(e) === matchResult[1])) {
244
+ return str;
245
+ }
246
+ const truthPath = (0, import_node_path2.isAbsolute)(matchedAlias.replacement) ? (0, import_vite.normalizePath)((0, import_node_path2.relative)((0, import_node_path2.dirname)(filePath), matchedAlias.replacement)) : (0, import_vite.normalizePath)(matchedAlias.replacement);
247
+ return str.replace(
248
+ isDynamic ? simpleDynamicImportRE : simpleStaticImportRE,
249
+ `$1'${matchResult[1].replace(
250
+ matchedAlias.find,
251
+ (truthPath.startsWith(".") ? truthPath : `./${truthPath}`) + (typeof matchedAlias.find === "string" && matchedAlias.find.endsWith("/") ? "/" : "")
252
+ )}'${isDynamic ? ")" : ""}`
253
+ );
254
+ }
255
+ }
256
+ return str;
257
+ });
258
+ }
259
+ var pureImportRE = /import\s?['"][^;\n]+?['"];?\n?/g;
260
+ function removePureImport(content) {
261
+ return content.replace(pureImportRE, "");
262
+ }
263
+ var setupFunctionRE = /function setup\([\s\S]+\)\s+?\{[\s\S]+return __returned__\n\}/;
264
+ function transferSetupPosition(content) {
265
+ const match = content.match(setupFunctionRE);
266
+ if (match) {
267
+ const setupFunction = match[0];
268
+ return content.replace(setupFunction, "").replace("setup})", setupFunction.slice("function ".length) + "\n\r})");
269
+ }
270
+ return content;
271
+ }
272
+
273
+ // src/compile.ts
274
+ var exportDefaultRE = /export\s+default/;
275
+ var exportDefaultClassRE = /(?:(?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
276
+ var noScriptContent = "import { defineComponent } from 'vue'\nexport default defineComponent({})";
277
+ var index = 1;
278
+ var compileRoot = null;
279
+ var compiler;
280
+ var vue;
281
+ function requireCompiler() {
282
+ if (!compiler) {
283
+ if (compileRoot) {
284
+ try {
285
+ compiler = require(require.resolve("vue/compiler-sfc", { paths: [compileRoot] }));
286
+ } catch (e) {
287
+ }
288
+ }
289
+ if (!compiler) {
290
+ try {
291
+ compiler = require("vue/compiler-sfc");
292
+ } catch (e) {
293
+ try {
294
+ compiler = require("@vue/compiler-sfc");
295
+ } catch (e2) {
296
+ throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
297
+ }
298
+ }
299
+ }
300
+ }
301
+ return compiler;
302
+ }
303
+ function isVue3() {
304
+ if (!vue) {
305
+ if (compileRoot) {
306
+ try {
307
+ vue = require(require.resolve("vue", { paths: [compileRoot] }));
308
+ } catch (e) {
309
+ }
310
+ }
311
+ if (!vue) {
312
+ try {
313
+ vue = require("vue");
314
+ } catch (e) {
315
+ throw new Error("vue is not present in the dependency tree.\n");
316
+ }
317
+ }
318
+ }
319
+ return vue.version.startsWith("3");
320
+ }
321
+ function setCompileRoot(root) {
322
+ if (root && root !== compileRoot) {
323
+ compileRoot = root;
324
+ compiler = null;
325
+ }
326
+ }
327
+ function parseCode(code) {
328
+ const { parse } = requireCompiler();
329
+ let descriptor;
330
+ if (isVue3()) {
331
+ descriptor = parse(code).descriptor;
332
+ } else {
333
+ descriptor = parse({ source: code });
334
+ }
335
+ return descriptor;
336
+ }
337
+ function compileVueCode(code) {
338
+ const { compileScript, rewriteDefault } = requireCompiler();
339
+ const descriptor = parseCode(code);
340
+ const { script, scriptSetup } = descriptor;
341
+ let content = null;
342
+ let ext = null;
343
+ if (script || scriptSetup) {
344
+ if (scriptSetup) {
345
+ const compiled = compileScript(descriptor, {
346
+ id: `${index++}`
347
+ });
348
+ const classMatch = compiled.content.match(exportDefaultClassRE);
349
+ const plugins = scriptSetup.lang === "ts" ? ["typescript", "decorators-legacy"] : void 0;
350
+ if (classMatch) {
351
+ content = compiled.content.replace(exportDefaultClassRE, "\nclass $1") + `
352
+ const _sfc_main = ${classMatch[1]}`;
353
+ if (exportDefaultRE.test(content)) {
354
+ content = rewriteDefault(compiled.content, "_sfc_main", plugins);
355
+ }
356
+ } else {
357
+ content = rewriteDefault(compiled.content, "_sfc_main", plugins);
358
+ }
359
+ content = transferSetupPosition(content);
360
+ content = content.replace(/(const __returned__\s?=\s?\{[\s\S]+?)(props)(\s?\})/, "$1props: props as any$3").replace(
361
+ /(const __returned__\s?=\s?\{[\s\S]+?)(props,)([\s\S]+?)/,
362
+ "$1props: props as any,$3"
363
+ );
364
+ content += "\nexport default _sfc_main\n";
365
+ ext = scriptSetup.lang || "js";
366
+ } else if (script && script.content) {
367
+ content = rewriteDefault(
368
+ script.content,
369
+ "_sfc_main",
370
+ script.lang === "ts" ? ["typescript"] : void 0
371
+ );
372
+ content += "\nexport default _sfc_main\n";
373
+ ext = script.lang || "js";
374
+ }
375
+ } else {
376
+ content = noScriptContent;
377
+ ext = "ts";
378
+ }
379
+ return { content, ext };
380
+ }
381
+
382
+ // src/rollup.ts
383
+ var import_node_path3 = require("path");
384
+ var import_api_extractor = require("@microsoft/api-extractor");
385
+ var import_Collector = require("@microsoft/api-extractor/lib/collector/Collector");
386
+ var import_MessageRouter = require("@microsoft/api-extractor/lib/collector/MessageRouter");
387
+ var import_DtsRollupGenerator = require("@microsoft/api-extractor/lib/generators/DtsRollupGenerator");
388
+ var import_node_core_library = require("@rushstack/node-core-library");
389
+ var dtsRE = /\.d\.tsx?$/;
390
+ function rollupDeclarationFiles({
391
+ root,
392
+ tsConfigPath,
393
+ outputDir,
394
+ entryPath,
395
+ fileName,
396
+ compilerOptions
397
+ }) {
398
+ const configObjectFullPath = (0, import_node_path3.resolve)(root, "api-extractor.json");
399
+ const packageJsonLookup = new import_node_core_library.PackageJsonLookup();
400
+ const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
401
+ if (!dtsRE.test(fileName)) {
402
+ fileName += ".d.ts";
403
+ }
404
+ const extractorConfig = import_api_extractor.ExtractorConfig.prepare({
405
+ configObject: {
406
+ projectFolder: root,
407
+ mainEntryPointFilePath: entryPath,
408
+ compiler: {
409
+ tsconfigFilePath: tsConfigPath,
410
+ overrideTsconfig: compilerOptions
411
+ },
412
+ apiReport: {
413
+ enabled: false,
414
+ reportFileName: "<unscopedPackageName>.api.md"
415
+ },
416
+ docModel: {
417
+ enabled: false
418
+ },
419
+ dtsRollup: {
420
+ enabled: true,
421
+ publicTrimmedFilePath: (0, import_node_path3.resolve)(outputDir, fileName)
422
+ },
423
+ tsdocMetadata: {
424
+ enabled: false
425
+ },
426
+ messages: {
427
+ compilerMessageReporting: {
428
+ default: {
429
+ logLevel: "none"
430
+ }
431
+ },
432
+ extractorMessageReporting: {
433
+ default: {
434
+ logLevel: "none"
435
+ }
436
+ }
437
+ }
438
+ },
439
+ configObjectFullPath,
440
+ packageJsonFullPath
441
+ });
442
+ const compilerState = import_api_extractor.CompilerState.create(extractorConfig, {
443
+ localBuild: true,
444
+ showVerboseMessages: false
445
+ });
446
+ const messageRouter = new import_MessageRouter.MessageRouter({
447
+ workingPackageFolder: root,
448
+ messageCallback: void 0,
449
+ messagesConfig: extractorConfig.messages,
450
+ showVerboseMessages: false,
451
+ showDiagnostics: false,
452
+ tsdocConfiguration: extractorConfig.tsdocConfiguration
453
+ });
454
+ const collector = new import_Collector.Collector({
455
+ program: compilerState.program,
456
+ messageRouter,
457
+ extractorConfig
458
+ });
459
+ collector.analyze();
460
+ import_DtsRollupGenerator.DtsRollupGenerator.writeTypingsFile(
461
+ collector,
462
+ extractorConfig.publicTrimmedFilePath,
463
+ import_DtsRollupGenerator.DtsRollupKind.PublicRelease,
464
+ extractorConfig.newlineKind
465
+ );
466
+ }
467
+
468
+ // src/plugin.ts
469
+ var noneExport = "export {};\n";
470
+ var virtualPrefix = "\0";
471
+ var vueRE = /\.vue$/;
472
+ var tsRE = /\.tsx?$/;
473
+ var jsRE = /\.jsx?$/;
474
+ var dtsRE2 = /\.d\.tsx?$/;
475
+ var tjsRE = /\.(t|j)sx?$/;
476
+ var watchExtensionRE = /\.(vue|(t|j)sx?)$/;
477
+ var fullRelativeRE = /^\.\.?\//;
478
+ var defaultIndex = "index.d.ts";
479
+ var noop = () => {
480
+ };
481
+ var logPrefix = import_chalk.default.cyan("[vite:dts]");
482
+ var bundleDebug = (0, import_debug.debug)("vite-plugin-dts:bundle");
483
+ function dtsPlugin(options = {}) {
484
+ const {
485
+ tsConfigFilePath = "tsconfig.json",
486
+ aliasesExclude = [],
487
+ cleanVueFileName = false,
488
+ staticImport = false,
489
+ clearPureImport = true,
490
+ insertTypesEntry = false,
491
+ rollupTypes = false,
492
+ noEmitOnError = false,
493
+ skipDiagnostics = true,
494
+ logDiagnostics = false,
495
+ copyDtsFiles = true,
496
+ afterDiagnostic = noop,
497
+ beforeWriteFile = noop,
498
+ afterBuild = noop
499
+ } = options;
500
+ const compilerOptions = options.compilerOptions ?? {};
501
+ let root;
502
+ let entryRoot = options.entryRoot ?? "";
503
+ let libName;
504
+ let indexName;
505
+ let aliases;
506
+ let entries;
507
+ let logger;
508
+ let project;
509
+ let tsConfigPath;
510
+ let outputDirs;
511
+ let isBundle = false;
512
+ const sourceDtsFiles = /* @__PURE__ */ new Set();
513
+ let hasJsVue = false;
514
+ let allowJs = false;
515
+ return {
516
+ name: "vite:dts",
517
+ apply: "build",
518
+ enforce: "pre",
519
+ config(config) {
520
+ var _a;
521
+ if (isBundle)
522
+ return;
523
+ const aliasOptions = ((_a = config == null ? void 0 : config.resolve) == null ? void 0 : _a.alias) ?? [];
524
+ if (isNativeObj(aliasOptions)) {
525
+ aliases = Object.entries(aliasOptions).map(([key, value]) => {
526
+ return { find: key, replacement: value };
527
+ });
528
+ } else {
529
+ aliases = ensureArray(aliasOptions);
530
+ }
531
+ if (aliasesExclude.length > 0) {
532
+ aliases = aliases.filter(
533
+ ({ find }) => !aliasesExclude.some(
534
+ (alias) => {
535
+ var _a2;
536
+ return alias && (isRegExp(find) ? find.toString() === alias.toString() : isRegExp(alias) ? (_a2 = find.match(alias)) == null ? void 0 : _a2[0] : find === alias);
537
+ }
538
+ )
539
+ );
540
+ }
541
+ },
542
+ configResolved(config) {
543
+ if (isBundle)
544
+ return;
545
+ logger = config.logger;
546
+ if (!config.build.lib) {
547
+ logger.warn(
548
+ import_chalk.default.yellow(
549
+ `
550
+ ${import_chalk.default.cyan(
551
+ "[vite:dts]"
552
+ )} You building not a library that may not need to generate declaration files.
553
+ `
554
+ )
555
+ );
556
+ libName = "_default";
557
+ indexName = defaultIndex;
558
+ } else {
559
+ const filename = config.build.lib.fileName ?? defaultIndex;
560
+ libName = config.build.lib.name || "_default";
561
+ indexName = typeof filename === "string" ? filename : filename("es");
562
+ if (!dtsRE2.test(indexName)) {
563
+ indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, "") : indexName}.d.ts`;
564
+ }
565
+ }
566
+ root = ensureAbsolute(options.root ?? "", config.root);
567
+ tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
568
+ outputDirs = options.outputDir ? ensureArray(options.outputDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.build.outDir, root)];
569
+ if (!outputDirs[0]) {
570
+ logger.error(
571
+ import_chalk.default.red(
572
+ `
573
+ ${import_chalk.default.cyan(
574
+ "[vite:dts]"
575
+ )} Can not resolve declaration directory, please check your vite config and plugin options.
576
+ `
577
+ )
578
+ );
579
+ return;
580
+ }
581
+ setCompileRoot(root);
582
+ compilerOptions.rootDir || (compilerOptions.rootDir = root);
583
+ project = new import_ts_morph.Project({
584
+ compilerOptions: mergeObjects(compilerOptions, {
585
+ noEmitOnError,
586
+ outDir: ".",
587
+ declarationDir: null,
588
+ noUnusedParameters: false,
589
+ declaration: true,
590
+ noEmit: false,
591
+ emitDeclarationOnly: true
592
+ }),
593
+ tsConfigFilePath: tsConfigPath,
594
+ skipAddingFilesFromTsConfig: true
595
+ });
596
+ allowJs = project.getCompilerOptions().allowJs ?? false;
597
+ },
598
+ buildStart(inputOptions) {
599
+ if (!isBundle && (insertTypesEntry || rollupTypes)) {
600
+ entries = Array.isArray(inputOptions.input) ? inputOptions.input : Object.values(inputOptions.input);
601
+ }
602
+ },
603
+ transform(code, id) {
604
+ if (id.startsWith(virtualPrefix)) {
605
+ return null;
606
+ }
607
+ if (vueRE.test(id)) {
608
+ const { content, ext } = compileVueCode(code);
609
+ if (content) {
610
+ if (ext === "js" || ext === "jsx")
611
+ hasJsVue = true;
612
+ project.createSourceFile(`${id}.${ext || "js"}`, content, { overwrite: true });
613
+ }
614
+ } else if (!id.includes(".vue?vue") && (tsRE.test(id) || allowJs && jsRE.test(id))) {
615
+ project.addSourceFileAtPath(id);
616
+ }
617
+ return null;
618
+ },
619
+ watchChange(id) {
620
+ if (watchExtensionRE.test(id)) {
621
+ isBundle = false;
622
+ if (project) {
623
+ const sourceFile = project.getSourceFile((0, import_vite2.normalizePath)(id));
624
+ sourceFile && project.removeSourceFile(sourceFile);
625
+ }
626
+ }
627
+ },
628
+ async closeBundle() {
629
+ if (!outputDirs || !project || isBundle)
630
+ return;
631
+ logger.info(import_chalk.default.green(`
632
+ ${logPrefix} Start generate declaration files...`));
633
+ bundleDebug("start");
634
+ isBundle = true;
635
+ sourceDtsFiles.clear();
636
+ const startTime = Date.now();
637
+ const tsConfig = (0, import_typescript.readConfigFile)(tsConfigPath, project.getFileSystem().readFileSync).config ?? {};
638
+ const parentTsConfigPath = tsConfig.extends && ensureAbsolute(tsConfig.extends, root);
639
+ const parentTsConfig = parentTsConfigPath ? (0, import_typescript.readConfigFile)(parentTsConfigPath, project.getFileSystem().readFileSync).config : {};
640
+ const include = options.include ?? tsConfig.include ?? parentTsConfig.include ?? "**/*";
641
+ const exclude = options.exclude ?? tsConfig.exclude ?? parentTsConfig.exclude ?? "node_modules/**";
642
+ bundleDebug("read config");
643
+ const includedFileSet = /* @__PURE__ */ new Set();
644
+ if (include && include.length) {
645
+ const files = await (0, import_fast_glob.default)(ensureArray(include).map(normalizeGlob), {
646
+ cwd: root,
647
+ absolute: true,
648
+ ignore: ensureArray(exclude).map(normalizeGlob)
649
+ });
650
+ files.forEach((file) => {
651
+ if (dtsRE2.test(file)) {
652
+ if (!copyDtsFiles) {
653
+ return;
654
+ }
655
+ includedFileSet.add(file);
656
+ sourceDtsFiles.add(project.addSourceFileAtPath(file));
657
+ return;
658
+ }
659
+ includedFileSet.add(`${tjsRE.test(file) ? file.replace(tjsRE, "") : file}.d.ts`);
660
+ });
661
+ if (hasJsVue) {
662
+ if (!allowJs) {
663
+ logger.warn(
664
+ import_chalk.default.yellow(
665
+ `${import_chalk.default.cyan(
666
+ "[vite:dts]"
667
+ )} Some js files are referenced, but you may not enable the 'allowJs' option.`
668
+ )
669
+ );
670
+ }
671
+ project.compilerOptions.set({ allowJs: true });
672
+ }
673
+ bundleDebug("collect files");
674
+ }
675
+ project.resolveSourceFileDependencies();
676
+ bundleDebug("resolve");
677
+ if (!skipDiagnostics) {
678
+ const diagnostics = project.getPreEmitDiagnostics();
679
+ if ((diagnostics == null ? void 0 : diagnostics.length) && logDiagnostics) {
680
+ logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics));
681
+ }
682
+ if (typeof afterDiagnostic === "function") {
683
+ const result = afterDiagnostic(diagnostics);
684
+ isPromise(result) && await result;
685
+ }
686
+ bundleDebug("diagnostics");
687
+ }
688
+ const dtsOutputFiles = Array.from(sourceDtsFiles).map((sourceFile) => ({
689
+ path: sourceFile.getFilePath(),
690
+ content: sourceFile.getFullText()
691
+ }));
692
+ const service = project.getLanguageService();
693
+ const outputFiles = project.getSourceFiles().map(
694
+ (sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
695
+ path: (0, import_vite2.normalizePath)((0, import_node_path4.resolve)(root, outputFile.compilerObject.name)),
696
+ content: outputFile.getText()
697
+ }))
698
+ ).flat().concat(dtsOutputFiles);
699
+ bundleDebug("emit");
700
+ if (!entryRoot) {
701
+ entryRoot = queryPublicPath(outputFiles.map((file) => file.path));
702
+ }
703
+ entryRoot = ensureAbsolute(entryRoot, root);
704
+ const wroteFiles = /* @__PURE__ */ new Set();
705
+ const outputDir = outputDirs[0];
706
+ await runParallel(import_os.default.cpus().length, outputFiles, async (outputFile) => {
707
+ let filePath = outputFile.path;
708
+ let content = outputFile.content;
709
+ const isMapFile = filePath.endsWith(".map");
710
+ if (!includedFileSet.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport) {
711
+ return;
712
+ }
713
+ if (!isMapFile && content && content !== noneExport) {
714
+ content = clearPureImport ? removePureImport(content) : content;
715
+ content = transformAliasImport(filePath, content, aliases, aliasesExclude);
716
+ content = staticImport || rollupTypes ? transformDynamicImport(content) : content;
717
+ }
718
+ filePath = (0, import_node_path4.resolve)(
719
+ outputDir,
720
+ (0, import_node_path4.relative)(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath)
721
+ );
722
+ if (typeof beforeWriteFile === "function") {
723
+ const result = beforeWriteFile(filePath, content);
724
+ if (result === false)
725
+ return;
726
+ if (result && isNativeObj(result)) {
727
+ filePath = result.filePath ?? filePath;
728
+ content = result.content ?? content;
729
+ }
730
+ }
731
+ await import_fs_extra.default.mkdir((0, import_node_path4.dirname)(filePath), { recursive: true });
732
+ await import_fs_extra.default.writeFile(
733
+ filePath,
734
+ cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content,
735
+ "utf-8"
736
+ );
737
+ wroteFiles.add((0, import_vite2.normalizePath)(filePath));
738
+ });
739
+ bundleDebug("output");
740
+ if (insertTypesEntry || rollupTypes) {
741
+ const pkgPath = (0, import_node_path4.resolve)(root, "package.json");
742
+ const pkg = import_fs_extra.default.existsSync(pkgPath) ? JSON.parse(await import_fs_extra.default.readFile(pkgPath, "utf-8")) : {};
743
+ const types = pkg.types || pkg.typings;
744
+ let typesPath = types ? (0, import_node_path4.resolve)(root, types) : (0, import_node_path4.resolve)(outputDir, indexName);
745
+ if (!import_fs_extra.default.existsSync(typesPath)) {
746
+ const entry = entries[0];
747
+ const outputIndex = (0, import_node_path4.resolve)(outputDir, (0, import_node_path4.relative)(entryRoot, entry.replace(tsRE, ".d.ts")));
748
+ let filePath = (0, import_vite2.normalizePath)((0, import_node_path4.relative)((0, import_node_path4.dirname)(typesPath), outputIndex));
749
+ filePath = filePath.replace(dtsRE2, "");
750
+ filePath = fullRelativeRE.test(filePath) ? filePath : `./${filePath}`;
751
+ let content = `export * from '${filePath}'
752
+ `;
753
+ if (import_fs_extra.default.existsSync(outputIndex)) {
754
+ const entryCodes = await import_fs_extra.default.readFile(outputIndex, "utf-8");
755
+ if (entryCodes.includes("export default")) {
756
+ content += `import ${libName} from '${filePath}'
757
+ export default ${libName}
758
+ `;
759
+ }
760
+ }
761
+ let result;
762
+ if (typeof beforeWriteFile === "function") {
763
+ result = beforeWriteFile(typesPath, content);
764
+ if (result && isNativeObj(result)) {
765
+ typesPath = result.filePath ?? typesPath;
766
+ content = result.content ?? content;
767
+ }
768
+ }
769
+ if (result !== false) {
770
+ await import_fs_extra.default.writeFile(typesPath, content, "utf-8");
771
+ wroteFiles.add((0, import_vite2.normalizePath)(typesPath));
772
+ }
773
+ }
774
+ bundleDebug("insert index");
775
+ if (rollupTypes) {
776
+ logger.info(import_chalk.default.green(`${logPrefix} Start rollup declaration files...`));
777
+ rollupDeclarationFiles({
778
+ root,
779
+ tsConfigPath,
780
+ compilerOptions,
781
+ outputDir,
782
+ entryPath: typesPath,
783
+ fileName: (0, import_node_path4.basename)(typesPath)
784
+ });
785
+ const wroteFile = (0, import_vite2.normalizePath)(typesPath);
786
+ wroteFiles.delete(wroteFile);
787
+ await runParallel(import_os.default.cpus().length, Array.from(wroteFiles), (f) => import_fs_extra.default.unlink(f));
788
+ removeDirIfEmpty(outputDir);
789
+ wroteFiles.clear();
790
+ wroteFiles.add(wroteFile);
791
+ if (copyDtsFiles) {
792
+ await runParallel(import_os.default.cpus().length, dtsOutputFiles, async ({ path, content }) => {
793
+ const filePath = (0, import_node_path4.resolve)(outputDir, (0, import_node_path4.basename)(path));
794
+ await import_fs_extra.default.writeFile(filePath, content, "utf-8");
795
+ wroteFiles.add((0, import_vite2.normalizePath)(filePath));
796
+ });
797
+ }
798
+ bundleDebug("rollup");
799
+ }
800
+ }
801
+ if (outputDirs.length > 1) {
802
+ const dirs = outputDirs.slice(1);
803
+ await runParallel(import_os.default.cpus().length, Array.from(wroteFiles), async (wroteFile) => {
804
+ const relativePath = (0, import_node_path4.relative)(outputDir, wroteFile);
805
+ const content = await import_fs_extra.default.readFile(wroteFile, "utf-8");
806
+ await Promise.all(
807
+ dirs.map(async (dir) => {
808
+ const filePath = (0, import_node_path4.resolve)(dir, relativePath);
809
+ await import_fs_extra.default.mkdir((0, import_node_path4.dirname)(filePath), { recursive: true });
810
+ await import_fs_extra.default.writeFile(filePath, content, "utf-8");
811
+ })
812
+ );
813
+ });
814
+ }
815
+ if (typeof afterBuild === "function") {
816
+ const result = afterBuild();
817
+ isPromise(result) && await result;
818
+ }
819
+ bundleDebug("finish");
820
+ logger.info(
821
+ import_chalk.default.green(`${logPrefix} Declaration files built in ${Date.now() - startTime}ms.
822
+ `)
823
+ );
824
+ }
825
+ };
826
+ }
827
+
828
+ // src/index.ts
829
+ var src_default = dtsPlugin;
830
+ // Annotate the CommonJS export names for ESM import in node:
831
+ 0 && (module.exports = {});