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