vite-plugin-dts 2.2.0 → 3.0.0-beta.1

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 CHANGED
@@ -1,19 +1,16 @@
1
1
  'use strict';
2
2
 
3
3
  const node_path = require('node:path');
4
- const fs = require('fs-extra');
4
+ const node_fs = require('node:fs');
5
+ const promises = require('node:fs/promises');
5
6
  const os = require('os');
6
- const kolorist = require('kolorist');
7
- const glob = require('fast-glob');
8
- const debug = require('debug');
9
- const tsMorph = require('ts-morph');
7
+ const ts = require('typescript');
10
8
  const vite = require('vite');
11
- const typescript = require('typescript');
12
9
  const pluginutils = require('@rollup/pluginutils');
13
- const node_fs = require('node:fs');
14
- const node_module = require('node:module');
15
- const parser = require('@babel/parser');
16
- const MagicString = require('magic-string');
10
+ const languageCore = require('@vue/language-core');
11
+ const vueTsc = require('vue-tsc');
12
+ const debug = require('debug');
13
+ const kolorist = require('kolorist');
17
14
  const apiExtractor = require('@microsoft/api-extractor');
18
15
  const Collector_js = require('@microsoft/api-extractor/lib/collector/Collector.js');
19
16
  const MessageRouter_js = require('@microsoft/api-extractor/lib/collector/MessageRouter.js');
@@ -21,6 +18,110 @@ const SourceMapper_js = require('@microsoft/api-extractor/lib/collector/SourceMa
21
18
  const DtsRollupGenerator_js = require('@microsoft/api-extractor/lib/generators/DtsRollupGenerator.js');
22
19
  const nodeCoreLibrary = require('@rushstack/node-core-library');
23
20
 
21
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
22
+
23
+ const ts__default = /*#__PURE__*/_interopDefaultCompat(ts);
24
+ const debug__default = /*#__PURE__*/_interopDefaultCompat(debug);
25
+
26
+ const dtsRE$1 = /\.d\.tsx?$/;
27
+ function rollupDeclarationFiles({
28
+ root,
29
+ compilerOptions,
30
+ outDir,
31
+ entryPath,
32
+ fileName,
33
+ libFolder,
34
+ bundledPackages
35
+ }) {
36
+ const configObjectFullPath = node_path.resolve(root, "api-extractor.json");
37
+ const packageJsonLookup = new nodeCoreLibrary.PackageJsonLookup();
38
+ const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
39
+ if (!dtsRE$1.test(fileName)) {
40
+ fileName += ".d.ts";
41
+ }
42
+ const extractorConfig = apiExtractor.ExtractorConfig.prepare({
43
+ configObject: {
44
+ projectFolder: root,
45
+ mainEntryPointFilePath: entryPath,
46
+ bundledPackages,
47
+ compiler: {
48
+ // tsconfigFilePath: tsConfigPath,
49
+ overrideTsconfig: {
50
+ $schema: "http://json.schemastore.org/tsconfig",
51
+ compilerOptions: {
52
+ ...compilerOptions,
53
+ target: "ESNext"
54
+ }
55
+ }
56
+ },
57
+ apiReport: {
58
+ enabled: false,
59
+ reportFileName: "<unscopedPackageName>.api.md"
60
+ },
61
+ docModel: {
62
+ enabled: false
63
+ },
64
+ dtsRollup: {
65
+ enabled: true,
66
+ publicTrimmedFilePath: node_path.resolve(outDir, fileName)
67
+ },
68
+ tsdocMetadata: {
69
+ enabled: false
70
+ },
71
+ messages: {
72
+ compilerMessageReporting: {
73
+ default: {
74
+ logLevel: "none"
75
+ }
76
+ },
77
+ extractorMessageReporting: {
78
+ default: {
79
+ logLevel: "none"
80
+ }
81
+ }
82
+ }
83
+ },
84
+ configObjectFullPath,
85
+ packageJsonFullPath
86
+ });
87
+ const compilerState = apiExtractor.CompilerState.create(extractorConfig, {
88
+ localBuild: false,
89
+ showVerboseMessages: false,
90
+ typescriptCompilerFolder: libFolder ? node_path.resolve(libFolder, "..") : void 0
91
+ });
92
+ const sourceMapper = new SourceMapper_js.SourceMapper();
93
+ const messageRouter = new MessageRouter_js.MessageRouter({
94
+ workingPackageFolder: root,
95
+ messageCallback: void 0,
96
+ messagesConfig: extractorConfig.messages,
97
+ showVerboseMessages: false,
98
+ showDiagnostics: false,
99
+ tsdocConfiguration: extractorConfig.tsdocConfiguration,
100
+ sourceMapper
101
+ });
102
+ const collector = new Collector_js.Collector({
103
+ program: compilerState.program,
104
+ messageRouter,
105
+ extractorConfig,
106
+ sourceMapper
107
+ });
108
+ collector.analyze();
109
+ DtsRollupGenerator_js.DtsRollupGenerator.writeTypingsFile(
110
+ collector,
111
+ extractorConfig.publicTrimmedFilePath,
112
+ DtsRollupGenerator_js.DtsRollupKind.PublicRelease,
113
+ extractorConfig.newlineKind
114
+ );
115
+ }
116
+
117
+ const windowsSlashRE = /\\/g;
118
+ function slash(p) {
119
+ return p.replace(windowsSlashRE, "/");
120
+ }
121
+ const isWindows = os.platform() === "win32";
122
+ function normalizePath(id) {
123
+ return node_path.posix.normalize(isWindows ? slash(id) : id);
124
+ }
24
125
  function isNativeObj(value) {
25
126
  return Object.prototype.toString.call(value) === "[object Object]";
26
127
  }
@@ -30,39 +131,6 @@ function isRegExp(value) {
30
131
  function isPromise(value) {
31
132
  return !!value && typeof value.then === "function" && typeof value.catch === "function";
32
133
  }
33
- function mergeObjects(sourceObj, targetObj) {
34
- const loop = [
35
- {
36
- source: sourceObj,
37
- target: targetObj
38
- }
39
- ];
40
- while (loop.length) {
41
- const { source, target } = loop.pop();
42
- Object.keys(target).forEach((key) => {
43
- if (isNativeObj(target[key])) {
44
- if (!isNativeObj(source[key])) {
45
- source[key] = {};
46
- }
47
- loop.push({
48
- source: source[key],
49
- target: target[key]
50
- });
51
- } else if (Array.isArray(target[key])) {
52
- if (!Array.isArray(source[key])) {
53
- source[key] = [];
54
- }
55
- loop.push({
56
- source: source[key],
57
- target: target[key]
58
- });
59
- } else {
60
- source[key] = target[key];
61
- }
62
- });
63
- }
64
- return sourceObj;
65
- }
66
134
  function ensureAbsolute(path, root) {
67
135
  return path ? node_path.isAbsolute(path) ? path : node_path.resolve(root, path) : root;
68
136
  }
@@ -232,456 +300,67 @@ const pureImportRE = /import\s?['"][^;\n]+?['"];?\n?/g;
232
300
  function removePureImport(content) {
233
301
  return content.replace(pureImportRE, "");
234
302
  }
235
- const setupFunctionRE = /function setup\([\s\S]+\)\s+?\{[\s\S]+return __returned__\n\}/;
236
- function transferSetupPosition(content) {
237
- const match = content.match(setupFunctionRE);
238
- if (match) {
239
- const setupFunction = match[0];
240
- return content.replace(setupFunction, "").replace("setup})", setupFunction.slice("function ".length) + "\n\r})");
241
- }
242
- return content;
243
- }
244
303
 
245
- const noScriptContent = "import { defineComponent } from 'vue'\nexport default defineComponent({})";
246
- const _require = node_module.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)));
247
- let index = 1;
248
- let compileRoot = null;
249
- let compiler;
250
- let vue;
251
- function requireCompiler() {
252
- if (!compiler) {
253
- if (compileRoot) {
254
- try {
255
- compiler = _require(_require.resolve("vue/compiler-sfc", { paths: [compileRoot] }));
256
- } catch (e) {
257
- try {
258
- compiler = _require(_require.resolve("@vue/compiler-sfc", { paths: [compileRoot] }));
259
- } catch (e2) {
260
- }
261
- }
262
- }
263
- if (!compiler) {
264
- try {
265
- compiler = _require("vue/compiler-sfc");
266
- } catch (e) {
267
- try {
268
- compiler = _require("@vue/compiler-sfc");
269
- } catch (e2) {
270
- throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
271
- }
272
- }
273
- }
274
- }
275
- return compiler;
276
- }
277
- function isVue3() {
278
- if (!vue) {
279
- if (compileRoot) {
280
- try {
281
- vue = _require(_require.resolve("vue", { paths: [compileRoot] }));
282
- } catch (e) {
283
- }
284
- }
285
- if (!vue) {
286
- try {
287
- vue = _require("vue");
288
- } catch (e) {
289
- throw new Error("vue is not present in the dependency tree.\n");
290
- }
291
- }
292
- }
293
- return vue.version.startsWith("3");
294
- }
295
- function setCompileRoot(root) {
296
- if (root && root !== compileRoot) {
297
- compileRoot = root;
298
- compiler = null;
299
- }
300
- }
301
- function parseCode(code) {
302
- const { parse: parseVueCode } = requireCompiler();
303
- let descriptor;
304
- if (isVue3()) {
305
- descriptor = parseVueCode(code).descriptor;
306
- } else {
307
- descriptor = parseVueCode({ source: code });
308
- }
309
- return descriptor;
310
- }
311
- function transformJsToTs(script) {
312
- if (!script)
313
- return script;
314
- const lang = !script.lang || script.lang === "js" ? "ts" : script.lang === "jsx" ? "tsx" : script.lang;
315
- return { ...script, lang };
316
- }
317
- function preprocessVueCode(code, setupScript) {
318
- const plugins = ["typescript", "decorators-legacy", "jsx"];
319
- const scriptAst = parser.parse(code, { sourceType: "module", plugins }).program.body;
320
- const source = new MagicString(code);
321
- let propsTypeName;
322
- let propsTypeLiteral;
323
- if (setupScript) {
324
- let processDefineProps = function(node) {
325
- if (node.type === "CallExpression" && node.callee.type === "Identifier") {
326
- if (node.callee.name === "defineProps") {
327
- defineProps = node;
328
- return true;
329
- } else if (node.callee.name === "withDefaults") {
330
- const propsDef = node.arguments[0];
331
- if (propsDef.type === "CallExpression" && propsDef.callee.type === "Identifier" && propsDef.callee.name === "defineProps") {
332
- defineProps = propsDef;
333
- return true;
334
- }
335
- }
336
- }
337
- return false;
338
- };
339
- const setupAst = parser.parse(setupScript.content, { sourceType: "module", plugins }).program.body;
340
- let defineProps;
341
- for (const node of setupAst) {
342
- if (node.type === "ExpressionStatement") {
343
- processDefineProps(node.expression);
344
- } else if (node.type === "VariableDeclaration" && !node.declare) {
345
- for (const decl of node.declarations) {
346
- if (decl.init && processDefineProps(decl.init)) {
347
- break;
348
- }
349
- }
350
- }
351
- if (defineProps) {
352
- const type = defineProps.typeParameters?.params[0];
353
- if (type && type.type === "TSTypeReference" && type.typeName.type === "Identifier") {
354
- propsTypeName = type.typeName.name;
355
- } else if (type?.type === "TSTypeLiteral") {
356
- propsTypeName = "__DTS_Props__";
357
- propsTypeLiteral = setupScript.content.substring(type.start, type.end);
358
- }
359
- break;
360
- }
361
- }
362
- }
363
- const declRecord = /* @__PURE__ */ new Map();
364
- let defaultExport;
365
- let options;
366
- for (const node of scriptAst) {
367
- if (node.type === "VariableDeclaration") {
368
- for (const decl of node.declarations) {
369
- if (decl.id.type === "Identifier" && decl.init) {
370
- let properties;
371
- if (decl.init.type === "ObjectExpression") {
372
- properties = decl.init.properties;
373
- } else if (decl.init.type === "CallExpression" && decl.init.arguments[0]?.type === "ObjectExpression") {
374
- properties = decl.init.arguments[0].properties;
375
- }
376
- if (!properties)
377
- continue;
378
- if (defaultExport && decl.id.name === defaultExport) {
379
- options = properties;
380
- break;
381
- } else {
382
- declRecord.set(decl.id.name, properties);
383
- }
384
- }
385
- }
386
- }
387
- if (node.type === "ExportDefaultDeclaration") {
388
- if (node.declaration.type === "ObjectExpression") {
389
- options = node.declaration.properties;
390
- } else if (node.declaration.type === "CallExpression" && node.declaration.arguments[0]?.type === "ObjectExpression") {
391
- options = node.declaration.arguments[0].properties;
392
- } else if (node.declaration.type === "Identifier") {
393
- if (declRecord.has(node.declaration.name)) {
394
- options = declRecord.get(node.declaration.name);
395
- } else {
396
- defaultExport = node.declaration.name;
397
- }
398
- }
399
- }
400
- if (options) {
401
- for (const option of options) {
402
- if (propsTypeName && option.type === "ObjectProperty" && option.key.type === "Identifier" && option.key.name === "props" && option.value.type === "ObjectExpression") {
403
- for (const prop of option.value.properties) {
404
- if (prop.type === "ObjectProperty" && prop.key.type === "Identifier") {
405
- if (prop.value.type === "ObjectExpression") {
406
- for (const propDef of prop.value.properties) {
407
- if (propDef.type === "ObjectProperty" && propDef.key.type === "Identifier" && propDef.key.name === "type") {
408
- source.prependLeft(
409
- propDef.end,
410
- ` as unknown as __PropType<${propsTypeName}['${prop.key.name}']>`
411
- );
412
- }
413
- }
414
- } else {
415
- source.prependLeft(
416
- prop.end,
417
- ` as unknown as __PropType<${propsTypeName}['${prop.key.name}']>`
418
- );
419
- }
420
- }
421
- }
422
- }
423
- if (option.type === "ObjectProperty" && option.key.type === "Identifier" && option.key.name === "components") {
424
- source.overwrite(option.value.start, option.value.end, "undefined");
425
- }
426
- if (option.type === "ObjectMethod" && option.key.type === "Identifier" && option.key.name === "setup") {
427
- let exposed;
428
- let returned;
429
- for (const node2 of option.body.body) {
430
- if (!exposed && node2.type === "ExpressionStatement" && node2.expression.type === "CallExpression" && node2.expression.callee.type === "Identifier" && node2.expression.callee.name === "expose") {
431
- exposed = node2.expression.arguments[0];
432
- continue;
433
- }
434
- if (node2.type === "ReturnStatement") {
435
- returned = node2;
436
- break;
437
- }
438
- }
439
- const newReturned = exposed && exposed.type === "ObjectExpression" ? `return ${code.substring(exposed.start, exposed.end)}` : setupScript ? "return {}" : "";
440
- if (newReturned) {
441
- if (returned) {
442
- source.overwrite(returned.start, returned.end, newReturned);
443
- } else if (option.body.body.length) {
444
- source.appendRight(option.body.body.at(-1).end, `
445
- ${newReturned}
446
- `);
447
- }
448
- }
449
- }
450
- }
451
- break;
452
- }
453
- }
454
- if (propsTypeName) {
455
- if (propsTypeLiteral) {
456
- source.prepend(`
457
- type ${propsTypeName} = ${propsTypeLiteral}
458
-
459
- `);
460
- }
461
- source.prepend("import type { PropType as __PropType } from 'vue'\n");
462
- }
463
- return source.toString();
464
- }
465
- function compileVueCode(code) {
466
- const { compileScript, rewriteDefault } = requireCompiler();
467
- const descriptor = parseCode(code);
468
- const { script, scriptSetup } = descriptor;
469
- let error;
470
- let content;
471
- let ext = "js";
472
- if (script || scriptSetup) {
473
- const compiled = compileScript(
474
- {
475
- ...descriptor,
476
- script: transformJsToTs(script),
477
- scriptSetup: transformJsToTs(scriptSetup),
478
- cssVars: []
479
- },
480
- { id: `${index++}` }
481
- );
482
- try {
483
- content = preprocessVueCode(compiled.content, scriptSetup);
484
- } catch (e) {
485
- error = e;
486
- content = compiled.content;
487
- }
488
- content = rewriteDefault(content, "_sfc_main", ["typescript", "decorators-legacy"]);
489
- if (scriptSetup) {
490
- content = transferSetupPosition(content);
491
- ext = scriptSetup.lang || "js";
492
- } else if (script && script.content) {
493
- ext = script.lang || "js";
494
- }
495
- content += "\nexport default _sfc_main\n";
496
- } else {
497
- content = noScriptContent;
498
- ext = "ts";
499
- }
500
- return { error, content, ext };
501
- }
502
-
503
- const dtsRE$1 = /\.d\.tsx?$/;
504
- function rollupDeclarationFiles({
505
- root,
506
- compilerOptions,
507
- outputDir,
508
- entryPath,
509
- fileName,
510
- libFolder,
511
- bundledPackages
512
- }) {
513
- const configObjectFullPath = node_path.resolve(root, "api-extractor.json");
514
- const packageJsonLookup = new nodeCoreLibrary.PackageJsonLookup();
515
- const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
516
- if (!dtsRE$1.test(fileName)) {
517
- fileName += ".d.ts";
518
- }
519
- const extractorConfig = apiExtractor.ExtractorConfig.prepare({
520
- configObject: {
521
- projectFolder: root,
522
- mainEntryPointFilePath: entryPath,
523
- bundledPackages,
524
- compiler: {
525
- overrideTsconfig: {
526
- $schema: "http://json.schemastore.org/tsconfig",
527
- compilerOptions
528
- }
529
- },
530
- apiReport: {
531
- enabled: false,
532
- reportFileName: "<unscopedPackageName>.api.md"
533
- },
534
- docModel: {
535
- enabled: false
536
- },
537
- dtsRollup: {
538
- enabled: true,
539
- publicTrimmedFilePath: node_path.resolve(outputDir, fileName)
540
- },
541
- tsdocMetadata: {
542
- enabled: false
543
- },
544
- messages: {
545
- compilerMessageReporting: {
546
- default: {
547
- logLevel: "none"
548
- }
549
- },
550
- extractorMessageReporting: {
551
- default: {
552
- logLevel: "none"
553
- }
554
- }
555
- }
556
- },
557
- configObjectFullPath,
558
- packageJsonFullPath
559
- });
560
- const compilerState = apiExtractor.CompilerState.create(extractorConfig, {
561
- localBuild: false,
562
- showVerboseMessages: false,
563
- typescriptCompilerFolder: libFolder ? node_path.resolve(libFolder, "..") : void 0
564
- });
565
- const sourceMapper = new SourceMapper_js.SourceMapper();
566
- const messageRouter = new MessageRouter_js.MessageRouter({
567
- workingPackageFolder: root,
568
- messageCallback: void 0,
569
- messagesConfig: extractorConfig.messages,
570
- showVerboseMessages: false,
571
- showDiagnostics: false,
572
- tsdocConfiguration: extractorConfig.tsdocConfiguration,
573
- sourceMapper
574
- });
575
- const collector = new Collector_js.Collector({
576
- program: compilerState.program,
577
- messageRouter,
578
- extractorConfig,
579
- sourceMapper
580
- });
581
- collector.analyze();
582
- DtsRollupGenerator_js.DtsRollupGenerator.writeTypingsFile(
583
- collector,
584
- extractorConfig.publicTrimmedFilePath,
585
- DtsRollupGenerator_js.DtsRollupKind.PublicRelease,
586
- extractorConfig.newlineKind
587
- );
588
- }
589
-
590
- const noneExport = "export {};\n";
591
- const vueRE = /\.vue$/;
592
- const svelteRE = /\.svelte$/;
593
304
  const tsRE = /\.(m|c)?tsx?$/;
594
- const jsRE = /\.(m|c)?jsx?$/;
595
305
  const dtsRE = /\.d\.(m|c)?tsx?$/;
596
306
  const tjsRE = /\.(m|c)?(t|j)sx?$/;
597
307
  const mtjsRE = /\.m(t|j)sx?$/;
598
308
  const ctjsRE = /\.c(t|j)sx?$/;
599
- const watchExtensionRE = /\.(vue|(m|c)?(t|j)sx?)$/;
600
309
  const fullRelativeRE = /^\.\.?\//;
310
+ const watchExtensionRE = /\.(vue|(m|c)?(t|j)sx?)$/;
601
311
  const defaultIndex = "index.d.ts";
312
+ const logPrefix = kolorist.cyan("[vite:dts]");
313
+ const bundleDebug = debug__default("vite-plugin-dts:bundle");
314
+ const fixedCompilerOptions = {
315
+ noEmit: false,
316
+ declaration: true,
317
+ emitDeclarationOnly: true,
318
+ noUnusedParameters: false,
319
+ checkJs: false,
320
+ skipLibCheck: true,
321
+ preserveSymlinks: false,
322
+ noEmitOnError: void 0,
323
+ target: ts__default.ScriptTarget.ESNext
324
+ };
602
325
  const noop = () => {
603
326
  };
604
327
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
605
- const resolve = (...paths) => vite.normalizePath(node_path.resolve(...paths));
606
- const logPrefix = kolorist.cyan("[vite:dts]");
607
- const bundleDebug = debug("vite-plugin-dts:bundle");
328
+ const resolve = (...paths) => normalizePath(node_path.resolve(...paths));
608
329
  function dtsPlugin(options = {}) {
609
330
  const {
610
- tsConfigFilePath = "tsconfig.json",
611
- aliasesExclude = [],
612
- cleanVueFileName = false,
331
+ tsconfigPath,
613
332
  staticImport = false,
614
333
  clearPureImport = true,
334
+ cleanVueFileName = false,
615
335
  insertTypesEntry = false,
616
336
  rollupTypes = false,
617
337
  bundledPackages = [],
618
- noEmitOnError = false,
619
- skipDiagnostics = false,
338
+ aliasesExclude = [],
339
+ logLevel,
620
340
  copyDtsFiles = false,
621
- logLevel = void 0,
622
341
  afterDiagnostic = noop,
623
342
  beforeWriteFile = noop,
624
343
  afterBuild = noop
625
344
  } = options;
626
- let compilerOptions = options.compilerOptions ?? {};
627
- let root;
345
+ let compilerOptions;
346
+ let rawCompilerOptions;
347
+ let root = ensureAbsolute(options.root ?? "", process.cwd());
628
348
  let entryRoot = options.entryRoot ?? "";
629
- let libName;
630
- let indexName;
631
- let aliases;
632
349
  let entries;
633
- let logger;
634
- let project;
635
- let tsConfigPath;
636
- let outputDirs;
637
- let isBundle = false;
638
350
  let include;
639
351
  let exclude;
640
- let filter;
641
- let libFolderPath = options.libFolderPath;
642
- const sourceDtsFiles = /* @__PURE__ */ new Set();
643
- const includedFiles = /* @__PURE__ */ new Set();
644
- const emittedFiles = /* @__PURE__ */ new Map();
645
- let hasJsVue = false;
646
- let allowJs = false;
647
- let transformError = false;
648
- async function internalTransform(id) {
649
- if (!project || !filter(id)) {
650
- return;
651
- }
652
- if (vueRE.test(id)) {
653
- const { error, content, ext } = compileVueCode(await fs.readFile(id, "utf-8"));
654
- if (!transformError && error) {
655
- logger.error(
656
- kolorist.red(
657
- `
658
- ${kolorist.cyan(
659
- "[vite:dts]"
660
- )} A error occurred when transform code, maybe there are some inertnal bugs.
661
- `
662
- )
663
- );
664
- transformError = true;
665
- }
666
- if (content) {
667
- if (ext === "js" || ext === "jsx")
668
- hasJsVue = true;
669
- project.createSourceFile(`${id}.${ext || "js"}`, content, { overwrite: true });
670
- }
671
- } else if (!id.includes(".vue?vue") && (tsRE.test(id) || allowJs && jsRE.test(id))) {
672
- project.createSourceFile(id, await fs.readFile(id, "utf-8"), { overwrite: true });
673
- } else if (svelteRE.test(id)) {
674
- const content = "export { SvelteComponentTyped as default } from 'svelte/internal';";
675
- project.createSourceFile(`${id}.ts`, content, { overwrite: true });
676
- }
677
- }
352
+ let outDirs;
353
+ let aliases;
354
+ let libName;
355
+ let indexName;
356
+ let logger;
357
+ let bundled = false;
358
+ let program;
678
359
  return {
679
360
  name: "vite:dts",
680
361
  apply: "build",
681
362
  enforce: "pre",
682
363
  config(config) {
683
- if (isBundle)
684
- return;
685
364
  const aliasOptions = config?.resolve?.alias ?? [];
686
365
  if (isNativeObj(aliasOptions)) {
687
366
  aliases = Object.entries(aliasOptions).map(([key, value]) => {
@@ -699,22 +378,18 @@ ${kolorist.cyan(
699
378
  }
700
379
  },
701
380
  configResolved(config) {
702
- if (isBundle)
703
- return;
704
381
  logger = logLevel ? vite.createLogger(logLevel, { allowClearScreen: config.clearScreen }) : config.logger;
705
- if (!config.build.lib) {
706
- logger.warn(
707
- kolorist.yellow(
708
- `
709
- ${kolorist.cyan(
710
- "[vite:dts]"
711
- )} You are building a library that may not need to generate declaration files.
712
- `
713
- )
714
- );
715
- libName = "_default";
716
- indexName = defaultIndex;
717
- } else {
382
+ root = ensureAbsolute(options.root ?? "", config.root);
383
+ if (config.build.lib) {
384
+ const input = typeof config.build.lib.entry === "string" ? [config.build.lib.entry] : config.build.lib.entry;
385
+ if (Array.isArray(input)) {
386
+ entries = input.reduce((prev, current) => {
387
+ prev[node_path.basename(current)] = current;
388
+ return prev;
389
+ }, {});
390
+ } else {
391
+ entries = { ...input };
392
+ }
718
393
  const filename = config.build.lib.fileName ?? defaultIndex;
719
394
  const entry = typeof config.build.lib.entry === "string" ? config.build.lib.entry : Object.values(config.build.lib.entry)[0];
720
395
  libName = config.build.lib.name || "_default";
@@ -722,212 +397,177 @@ ${kolorist.cyan(
722
397
  if (!dtsRE.test(indexName)) {
723
398
  indexName = `${indexName.replace(tjsRE, "")}.d.${extPrefix(indexName)}ts`;
724
399
  }
725
- }
726
- root = ensureAbsolute(options.root ?? "", config.root);
727
- tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
728
- libFolderPath = libFolderPath && ensureAbsolute(libFolderPath, root);
729
- outputDirs = options.outputDir ? ensureArray(options.outputDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.build.outDir, root)];
730
- if (!outputDirs[0]) {
731
- logger.error(
732
- kolorist.red(
400
+ } else {
401
+ logger.warn(
402
+ kolorist.yellow(
733
403
  `
734
404
  ${kolorist.cyan(
735
405
  "[vite:dts]"
736
- )} Can not resolve declaration directory. Please check your vite config and plugin options.
406
+ )} You are building a library that may not need to generate declaration files.
737
407
  `
738
408
  )
739
409
  );
740
- return;
410
+ libName = "_default";
411
+ indexName = defaultIndex;
741
412
  }
742
- setCompileRoot(root);
743
- project = new tsMorph.Project({
744
- compilerOptions: mergeObjects(compilerOptions, {
745
- rootDir: compilerOptions.rootDir || root,
746
- noEmitOnError,
747
- outDir: outputDirs[0],
748
- declarationDir: void 0,
749
- noUnusedParameters: false,
750
- declaration: true,
751
- noEmit: false,
752
- emitDeclarationOnly: true,
753
- composite: false
754
- }),
755
- tsConfigFilePath: tsConfigPath,
756
- skipAddingFilesFromTsConfig: true,
757
- libFolderPath
758
- });
759
- allowJs = project.getCompilerOptions().allowJs ?? false;
760
- const tsConfig = { compilerOptions: {} };
761
- const readFile = project.getFileSystem().readFileSync;
762
- let currentConfigPath = tsConfigPath;
763
- while (currentConfigPath) {
764
- const currentConfig = typescript.readConfigFile(currentConfigPath, readFile).config ?? {};
765
- Object.assign(tsConfig.compilerOptions, currentConfig.compilerOptions || {});
766
- if (!tsConfig.include) {
767
- tsConfig.include = currentConfig.include;
768
- }
769
- if (!tsConfig.exclude) {
770
- tsConfig.exclude = currentConfig.exclude;
771
- }
772
- currentConfigPath = currentConfig.extends && ensureAbsolute(currentConfig.extends, node_path.dirname(currentConfigPath));
413
+ if (!options.outDir) {
414
+ outDirs = [ensureAbsolute(config.build.outDir, root)];
773
415
  }
774
- include = ensureArray(options.include ?? tsConfig.include ?? "**/*").map(normalizeGlob);
775
- exclude = ensureArray(options.exclude ?? tsConfig.exclude ?? "node_modules/**").map(
776
- normalizeGlob
777
- );
778
- filter = pluginutils.createFilter(include, exclude, { resolve: root });
779
- compilerOptions = tsConfig.compilerOptions;
416
+ bundleDebug("parse vite config");
780
417
  },
781
- async buildStart(inputOptions) {
782
- if (Array.isArray(inputOptions.input)) {
783
- entries = inputOptions.input.reduce((prev, current) => {
418
+ options(options2) {
419
+ if (entries)
420
+ return;
421
+ const input = typeof options2.input === "string" ? [options2.input] : options2.input;
422
+ if (Array.isArray(input)) {
423
+ entries = input.reduce((prev, current) => {
784
424
  prev[node_path.basename(current)] = current;
785
425
  return prev;
786
426
  }, {});
787
427
  } else {
788
- entries = { ...inputOptions.input };
428
+ entries = { ...input };
789
429
  }
790
- bundleDebug("parse entries");
791
- sourceDtsFiles.clear();
792
- includedFiles.clear();
793
- if (project && include && include.length) {
794
- const files = await glob(include, {
795
- cwd: root,
796
- absolute: true,
797
- ignore: exclude
798
- });
799
- for (const file of files) {
800
- this.addWatchFile(file);
801
- if (dtsRE.test(file)) {
802
- sourceDtsFiles.add(project.addSourceFileAtPath(file));
803
- if (!copyDtsFiles) {
804
- continue;
805
- }
806
- includedFiles.add(file);
807
- continue;
808
- }
809
- includedFiles.add(`${file.replace(tjsRE, "")}.d.${extPrefix(file)}ts`);
810
- }
811
- if (hasJsVue) {
812
- if (!allowJs) {
813
- logger.warn(
814
- kolorist.yellow(
815
- `${kolorist.cyan(
816
- "[vite:dts]"
817
- )} Some js files are referenced, but you may not enable the 'allowJs' option.`
818
- )
819
- );
820
- }
821
- project.compilerOptions.set({ allowJs: true });
822
- }
823
- bundleDebug("collect files");
824
- }
825
- },
826
- async transform(_, id) {
827
- await internalTransform(id);
828
- return null;
430
+ logger = logger || console;
431
+ libName = "_default";
432
+ indexName = defaultIndex;
433
+ bundleDebug("parse options");
829
434
  },
830
- async watchChange(id) {
435
+ watchChange(id) {
831
436
  if (watchExtensionRE.test(id)) {
832
- isBundle = false;
833
- if (project) {
834
- const sourceFile = project.getSourceFile(vite.normalizePath(id));
835
- sourceFile && project.removeSourceFile(sourceFile);
836
- await internalTransform(id);
437
+ bundled = false;
438
+ program?.getSourceFile(normalizePath(id));
439
+ }
440
+ },
441
+ async buildStart() {
442
+ if (program)
443
+ return;
444
+ const configPath = tsconfigPath ? ensureAbsolute(tsconfigPath, root) : ts__default.findConfigFile(root, ts__default.sys.fileExists);
445
+ const content = configPath && languageCore.createParsedCommandLine(ts__default, ts__default.sys, configPath);
446
+ const config = content ? {
447
+ include: content.raw.include,
448
+ exclude: content.raw.exclude,
449
+ fileNames: content.fileNames,
450
+ raw: content.raw,
451
+ options: {
452
+ ...content.options,
453
+ ...options.compilerOptions || {},
454
+ ...fixedCompilerOptions
837
455
  }
456
+ } : { options: { ...options.compilerOptions || {}, ...fixedCompilerOptions } };
457
+ if (!outDirs) {
458
+ outDirs = options.outDir ? ensureArray(options.outDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.raw?.compilerOptions?.outDir || "dist", root)];
838
459
  }
460
+ include = ensureArray(options.include ?? config.include ?? "**/*").map(normalizeGlob);
461
+ exclude = ensureArray(options.exclude ?? config.exclude ?? "node_modules/**").map(
462
+ normalizeGlob
463
+ );
464
+ compilerOptions = { ...config.options, outDir: outDirs[0] };
465
+ rawCompilerOptions = config.raw?.compilerOptions || {};
466
+ const host = ts__default.createCompilerHost(compilerOptions, true);
467
+ program = vueTsc.createProgram({
468
+ host,
469
+ rootNames: Object.values(entries).concat(
470
+ config.fileNames?.filter((name) => dtsRE.test(name)) || []
471
+ ),
472
+ options: compilerOptions
473
+ });
474
+ libName = libName || "_default";
475
+ indexName = indexName || defaultIndex;
476
+ const diagnostics = program.getDeclarationDiagnostics();
477
+ if (diagnostics?.length) {
478
+ logger.error(ts__default.formatDiagnostics(diagnostics, host));
479
+ }
480
+ if (typeof afterDiagnostic === "function") {
481
+ const result = afterDiagnostic(diagnostics);
482
+ isPromise(result) && await result;
483
+ }
484
+ bundleDebug("create ts program");
839
485
  },
840
- async closeBundle() {
841
- if (!outputDirs || !project || isBundle)
486
+ async writeBundle() {
487
+ if (!outDirs || !program || bundled)
842
488
  return;
843
489
  logger.info(kolorist.green(`
844
490
  ${logPrefix} Start generate declaration files...`));
845
- bundleDebug("start");
846
- isBundle = true;
847
- emittedFiles.clear();
848
- const startTime = Date.now();
849
- project.resolveSourceFileDependencies();
850
- bundleDebug("resolve");
851
- if (!skipDiagnostics) {
852
- const diagnostics = project.getPreEmitDiagnostics();
853
- if (diagnostics?.length) {
854
- logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics));
491
+ bundled = true;
492
+ const outDir = outDirs[0];
493
+ const emittedFiles = /* @__PURE__ */ new Map();
494
+ const filter = pluginutils.createFilter(include, exclude, { resolve: root });
495
+ const service = program.__vue.languageService;
496
+ const sourceFiles = program.getSourceFiles();
497
+ const outputFiles = sourceFiles.map((sourceFile) => {
498
+ if (!filter(sourceFile.fileName))
499
+ return [];
500
+ const output = [];
501
+ if (copyDtsFiles && dtsRE.test(sourceFile.fileName)) {
502
+ output.push({
503
+ path: sourceFile.fileName,
504
+ content: sourceFile.getFullText()
505
+ });
855
506
  }
856
- if (typeof afterDiagnostic === "function") {
857
- const result = afterDiagnostic(diagnostics);
858
- isPromise(result) && await result;
859
- }
860
- bundleDebug("diagnostics");
861
- }
862
- const outputDir = outputDirs[0];
863
- const dtsOutputFiles = Array.from(sourceDtsFiles).map((sourceFile) => ({
864
- path: sourceFile.getFilePath(),
865
- content: sourceFile.getFullText()
866
- }));
867
- const service = project.getLanguageService();
868
- const outputFiles = project.getSourceFiles().map(
869
- (sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
870
- path: resolve(root, node_path.relative(outputDir, outputFile.compilerObject.name)),
871
- content: outputFile.getText()
872
- }))
873
- ).flat().concat(dtsOutputFiles);
874
- bundleDebug("emit");
507
+ return output.concat(
508
+ service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((outputFile) => {
509
+ return {
510
+ path: resolve(root, node_path.relative(outDir, outputFile.name)),
511
+ content: outputFile.text
512
+ };
513
+ })
514
+ );
515
+ }).flat();
516
+ bundleDebug("emit output");
875
517
  entryRoot = entryRoot || queryPublicPath(outputFiles.map((file) => file.path));
876
518
  entryRoot = ensureAbsolute(entryRoot, root);
877
- await runParallel(os.cpus().length, outputFiles, async (outputFile) => {
878
- let filePath = outputFile.path;
879
- let content = outputFile.content;
880
- const isMapFile = filePath.endsWith(".map");
881
- if (!includedFiles.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport) {
882
- return;
883
- }
884
- if (!isMapFile && content && content !== noneExport) {
519
+ await runParallel(os.cpus().length, outputFiles, async ({ path, content }) => {
520
+ const isMapFile = path.endsWith(".map");
521
+ if (!isMapFile && content) {
885
522
  content = clearPureImport ? removePureImport(content) : content;
886
- content = transformAliasImport(filePath, content, aliases, aliasesExclude);
523
+ content = transformAliasImport(path, content, aliases, aliasesExclude);
887
524
  content = staticImport || rollupTypes ? transformDynamicImport(content) : content;
888
525
  }
889
- filePath = resolve(
890
- outputDir,
891
- node_path.relative(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath)
526
+ path = resolve(
527
+ outDir,
528
+ node_path.relative(entryRoot, cleanVueFileName ? path.replace(".vue.d.ts", ".d.ts") : path)
892
529
  );
893
530
  content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
894
531
  if (typeof beforeWriteFile === "function") {
895
- const result = beforeWriteFile(filePath, content);
532
+ const result = beforeWriteFile(path, content);
896
533
  if (result === false)
897
534
  return;
898
535
  if (result && isNativeObj(result)) {
899
- filePath = result.filePath || filePath;
536
+ path = result.filePath || path;
900
537
  content = result.content ?? content;
901
538
  }
902
539
  }
903
- filePath = vite.normalizePath(filePath);
904
- await fs.mkdir(node_path.dirname(filePath), { recursive: true });
905
- await fs.writeFile(filePath, content, "utf-8");
906
- emittedFiles.set(filePath, content);
540
+ path = normalizePath(path);
541
+ const dir = node_path.dirname(path);
542
+ if (!node_fs.existsSync(dir)) {
543
+ await promises.mkdir(dir, { recursive: true });
544
+ }
545
+ await promises.writeFile(path, content, "utf-8");
546
+ emittedFiles.set(path, content);
907
547
  });
908
- bundleDebug("output");
548
+ bundleDebug("write output");
909
549
  if (insertTypesEntry || rollupTypes) {
910
550
  const pkgPath = resolve(root, "package.json");
911
- const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, "utf-8")) : {};
551
+ const pkg = node_fs.existsSync(pkgPath) ? JSON.parse(await promises.readFile(pkgPath, "utf-8")) : {};
912
552
  const entryNames = Object.keys(entries);
913
553
  const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings || (pkg.exports?.["."] || pkg.exports?.["./"])?.types;
914
554
  const multiple = entryNames.length > 1;
915
- const typesPath = types ? resolve(root, types) : resolve(outputDir, indexName);
555
+ const typesPath = types ? resolve(root, types) : resolve(outDir, indexName);
916
556
  for (const name of entryNames) {
917
- let filePath = multiple ? resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
918
- if (fs.existsSync(filePath))
557
+ let path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
558
+ if (node_fs.existsSync(path))
919
559
  continue;
920
560
  const index = resolve(
921
- outputDir,
561
+ outDir,
922
562
  node_path.relative(entryRoot, `${entries[name].replace(tsRE, "")}.d.ts`)
923
563
  );
924
- let fromPath = vite.normalizePath(node_path.relative(node_path.dirname(filePath), index));
564
+ let fromPath = normalizePath(node_path.relative(node_path.dirname(path), index));
925
565
  fromPath = fromPath.replace(dtsRE, "");
926
566
  fromPath = fullRelativeRE.test(fromPath) ? fromPath : `./${fromPath}`;
927
567
  let content = `export * from '${fromPath}'
928
568
  `;
929
- if (fs.existsSync(index)) {
930
- const entryCodes = await fs.readFile(index, "utf-8");
569
+ if (node_fs.existsSync(index)) {
570
+ const entryCodes = await promises.readFile(index, "utf-8");
931
571
  if (entryCodes.includes("export default")) {
932
572
  content += `import ${libName} from '${fromPath}'
933
573
  export default ${libName}
@@ -936,32 +576,41 @@ export default ${libName}
936
576
  }
937
577
  let result;
938
578
  if (typeof beforeWriteFile === "function") {
939
- result = beforeWriteFile(filePath, content);
579
+ result = beforeWriteFile(path, content);
940
580
  if (result && isNativeObj(result)) {
941
- filePath = result.filePath ?? filePath;
581
+ path = result.filePath ?? path;
942
582
  content = result.content ?? content;
943
583
  }
944
584
  }
945
- filePath = vite.normalizePath(filePath);
585
+ path = normalizePath(path);
946
586
  if (result !== false) {
947
- await fs.writeFile(filePath, content, "utf-8");
948
- emittedFiles.set(filePath, content);
587
+ await promises.writeFile(path, content, "utf-8");
588
+ emittedFiles.set(path, content);
949
589
  }
950
590
  }
951
591
  bundleDebug("insert index");
952
592
  if (rollupTypes) {
953
593
  logger.info(kolorist.green(`${logPrefix} Start rollup declaration files...`));
594
+ let libFolder = resolve(root, "node_modules/typescript");
595
+ if (!node_fs.existsSync(libFolder)) {
596
+ if (root !== entryRoot) {
597
+ libFolder = resolve(entryRoot, "node_modules/typescript");
598
+ if (!node_fs.existsSync(libFolder))
599
+ libFolder = void 0;
600
+ }
601
+ libFolder = void 0;
602
+ }
954
603
  const rollupFiles = /* @__PURE__ */ new Set();
955
604
  if (multiple) {
956
605
  for (const name of entryNames) {
957
- const path = resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`);
606
+ const path = resolve(outDir, `${name.replace(tsRE, "")}.d.ts`);
958
607
  rollupDeclarationFiles({
959
608
  root,
960
- compilerOptions,
961
- outputDir,
609
+ compilerOptions: rawCompilerOptions,
610
+ outDir,
962
611
  entryPath: path,
963
612
  fileName: node_path.basename(path),
964
- libFolder: libFolderPath,
613
+ libFolder,
965
614
  bundledPackages
966
615
  });
967
616
  emittedFiles.delete(path);
@@ -970,48 +619,47 @@ export default ${libName}
970
619
  } else {
971
620
  rollupDeclarationFiles({
972
621
  root,
973
- compilerOptions,
974
- outputDir,
622
+ compilerOptions: rawCompilerOptions,
623
+ outDir,
975
624
  entryPath: typesPath,
976
625
  fileName: node_path.basename(typesPath),
977
- libFolder: libFolderPath,
626
+ libFolder,
978
627
  bundledPackages
979
628
  });
980
629
  emittedFiles.delete(typesPath);
981
630
  rollupFiles.add(typesPath);
982
631
  }
983
- await runParallel(os.cpus().length, Array.from(emittedFiles.keys()), (f) => fs.unlink(f));
984
- removeDirIfEmpty(outputDir);
632
+ await runParallel(os.cpus().length, Array.from(emittedFiles.keys()), (f) => promises.unlink(f));
633
+ removeDirIfEmpty(outDir);
985
634
  emittedFiles.clear();
986
635
  for (const file of rollupFiles) {
987
- emittedFiles.set(file, await fs.readFile(file, "utf-8"));
636
+ emittedFiles.set(file, await promises.readFile(file, "utf-8"));
988
637
  }
989
- bundleDebug("rollup");
638
+ bundleDebug("rollup output");
990
639
  }
991
640
  }
992
- if (outputDirs.length > 1) {
993
- const dirs = outputDirs.slice(1);
994
- await runParallel(
995
- os.cpus().length,
996
- Array.from(emittedFiles),
997
- async ([wroteFile, content]) => {
998
- const relativePath = node_path.relative(outputDir, wroteFile);
999
- await Promise.all(
1000
- dirs.map(async (dir) => {
1001
- const filePath = resolve(dir, relativePath);
1002
- await fs.mkdir(node_path.dirname(filePath), { recursive: true });
1003
- await fs.writeFile(filePath, content, "utf-8");
1004
- })
1005
- );
1006
- }
1007
- );
641
+ if (outDirs.length > 1) {
642
+ const dirs = outDirs.slice(1);
643
+ await runParallel(os.cpus().length, Array.from(emittedFiles), async ([wroteFile, content]) => {
644
+ const relativePath = node_path.relative(outDir, wroteFile);
645
+ await Promise.all(
646
+ dirs.map(async (dir) => {
647
+ const path = resolve(dir, relativePath);
648
+ const dirPath = node_path.dirname(path);
649
+ if (!node_fs.existsSync(dirPath)) {
650
+ await promises.mkdir(dirPath, { recursive: true });
651
+ }
652
+ await promises.writeFile(path, content, "utf-8");
653
+ })
654
+ );
655
+ });
1008
656
  }
1009
657
  if (typeof afterBuild === "function") {
1010
658
  const result = afterBuild();
1011
659
  isPromise(result) && await result;
1012
660
  }
1013
661
  bundleDebug("finish");
1014
- logger.info(kolorist.green(`${logPrefix} Declaration files built in ${Date.now() - startTime}ms.
662
+ logger.info(kolorist.green(`${logPrefix} Declaration files built.
1015
663
  `));
1016
664
  }
1017
665
  };