vite-plugin-dts 3.9.0 → 4.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7,6 +7,7 @@ const node_fs = require('node:fs');
7
7
  const promises = require('node:fs/promises');
8
8
  const node_os = require('node:os');
9
9
  const languageCore = require('@vue/language-core');
10
+ const typescript = require('@volar/typescript');
10
11
  const ts = require('typescript');
11
12
  const pluginutils = require('@rollup/pluginutils');
12
13
  const vueTsc = require('vue-tsc');
@@ -124,9 +125,10 @@ function removeDirIfEmpty(dir) {
124
125
  return onlyHasDir;
125
126
  }
126
127
  function getTsConfig(tsConfigPath, readFileSync) {
128
+ const baseConfig = ts__default.readConfigFile(tsConfigPath, readFileSync).config ?? {};
127
129
  const tsConfig = {
128
- compilerOptions: {},
129
- ...ts__default.readConfigFile(tsConfigPath, readFileSync).config ?? {}
130
+ ...baseConfig,
131
+ compilerOptions: {}
130
132
  };
131
133
  if (tsConfig.extends) {
132
134
  ensureArray(tsConfig.extends).forEach((configPath) => {
@@ -140,6 +142,7 @@ function getTsConfig(tsConfigPath, readFileSync) {
140
142
  }
141
143
  });
142
144
  }
145
+ Object.assign(tsConfig.compilerOptions, baseConfig.compilerOptions);
143
146
  return tsConfig;
144
147
  }
145
148
  const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
@@ -203,7 +206,7 @@ function findTypesPath(...pkgs) {
203
206
  for (const pkg of pkgs) {
204
207
  if (typeof pkg !== "object")
205
208
  continue;
206
- path = pkg.types || pkg.typings || pkg.exports?.["."]?.types || pkg.exports?.["./"]?.types;
209
+ path = pkg.types || pkg.typings || pkg.exports?.types || pkg.exports?.["."]?.types || pkg.exports?.["./"]?.types;
207
210
  if (path)
208
211
  return path;
209
212
  }
@@ -244,8 +247,27 @@ function editSourceMapDir(content, fromDir, toDir) {
244
247
  }
245
248
  return true;
246
249
  }
250
+ const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g;
251
+ const asteriskRE = /[*]+/g;
252
+ function parseTsAliases(basePath, paths) {
253
+ const result = [];
254
+ for (const [pathWithAsterisk, replacements] of Object.entries(paths)) {
255
+ const find = new RegExp(
256
+ `^${pathWithAsterisk.replace(regexpSymbolRE, "\\$1").replace(asteriskRE, "([^\\/]+)")}$`
257
+ );
258
+ let index = 1;
259
+ result.push({
260
+ find,
261
+ replacement: ensureAbsolute(
262
+ replacements[0].replace(asteriskRE, () => `$${index++}`),
263
+ basePath
264
+ )
265
+ });
266
+ }
267
+ return result;
268
+ }
247
269
 
248
- const dtsRE$1 = /\.d\.tsx?$/;
270
+ const dtsRE$1 = /\.d\.(m|c)?tsx?$/;
249
271
  function rollupDeclarationFiles({
250
272
  root,
251
273
  configPath,
@@ -365,16 +387,19 @@ function VueResolver() {
365
387
  supports(id) {
366
388
  return vueRE.test(id);
367
389
  },
368
- transform({ id, code, program, service }) {
390
+ transform({ id, code, program }) {
369
391
  const sourceFile = program.getSourceFile(id) || program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
370
392
  if (!sourceFile)
371
393
  return [];
372
- const outputs = service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
373
- return {
374
- path: file.name,
375
- content: file.text
376
- };
377
- });
394
+ const outputs = [];
395
+ program.emit(
396
+ sourceFile,
397
+ (path, content) => {
398
+ outputs.push({ path, content });
399
+ },
400
+ void 0,
401
+ true
402
+ );
378
403
  if (!program.getCompilerOptions().declarationMap)
379
404
  return outputs;
380
405
  const [beforeScript] = code.split(/\s*<script.*>/);
@@ -456,18 +481,17 @@ function transformCode(options) {
456
481
  const importMap = /* @__PURE__ */ new Map();
457
482
  const usedDefault = /* @__PURE__ */ new Map();
458
483
  const declareModules = [];
484
+ const toLibName = (origin) => {
485
+ const name = transformAlias(origin, dir, options.aliases, options.aliasesExclude);
486
+ return options.cleanVueFileName ? name.replace(/\.vue$/, "") : name;
487
+ };
459
488
  let indexCount = 0;
460
489
  walkSourceFile(ast, (node, parent) => {
461
490
  if (ts__default.isImportDeclaration(node)) {
462
491
  if (!node.importClause) {
463
492
  options.clearPureImport && s.remove(node.pos, node.end);
464
493
  } else if (ts__default.isStringLiteral(node.moduleSpecifier) && (node.importClause.name || node.importClause.namedBindings && ts__default.isNamedImports(node.importClause.namedBindings))) {
465
- const libName = transformAlias(
466
- node.moduleSpecifier.text,
467
- dir,
468
- options.aliases,
469
- options.aliasesExclude
470
- );
494
+ const libName = toLibName(node.moduleSpecifier.text);
471
495
  const importSet = importMap.get(libName) ?? importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
472
496
  if (node.importClause.name && !usedDefault.has(libName)) {
473
497
  const usedType = node.importClause.name.escapedText;
@@ -488,12 +512,7 @@ function transformCode(options) {
488
512
  return false;
489
513
  }
490
514
  if (ts__default.isImportTypeNode(node) && node.qualifier && ts__default.isLiteralTypeNode(node.argument) && ts__default.isIdentifier(node.qualifier) && ts__default.isStringLiteral(node.argument.literal)) {
491
- const libName = transformAlias(
492
- node.argument.literal.text,
493
- dir,
494
- options.aliases,
495
- options.aliasesExclude
496
- );
515
+ const libName = toLibName(node.argument.literal.text);
497
516
  if (!options.staticImport) {
498
517
  s.update(node.argument.literal.pos, node.argument.literal.end, `'${libName}'`);
499
518
  return !!node.typeArguments;
@@ -515,23 +534,19 @@ function transformCode(options) {
515
534
  return !!node.typeArguments;
516
535
  }
517
536
  if (ts__default.isCallExpression(node) && node.expression.kind === ts__default.SyntaxKind.ImportKeyword && ts__default.isStringLiteral(node.arguments[0])) {
518
- const libName = transformAlias(
519
- node.arguments[0].text,
520
- dir,
521
- options.aliases,
522
- options.aliasesExclude
537
+ s.update(
538
+ node.arguments[0].pos,
539
+ node.arguments[0].end,
540
+ `'${toLibName(node.arguments[0].text)}'`
523
541
  );
524
- s.update(node.arguments[0].pos, node.arguments[0].end, `'${libName}'`);
525
542
  return false;
526
543
  }
527
544
  if (ts__default.isExportDeclaration(node) && node.moduleSpecifier && ts__default.isStringLiteral(node.moduleSpecifier)) {
528
- const libName = transformAlias(
529
- node.moduleSpecifier.text,
530
- dir,
531
- options.aliases,
532
- options.aliasesExclude
545
+ s.update(
546
+ node.moduleSpecifier.pos,
547
+ node.moduleSpecifier.end,
548
+ ` '${toLibName(node.moduleSpecifier.text)}'`
533
549
  );
534
- s.update(node.moduleSpecifier.pos, node.moduleSpecifier.end, ` '${libName}'`);
535
550
  return false;
536
551
  }
537
552
  if (ts__default.isModuleDeclaration(node)) {
@@ -543,10 +558,12 @@ function transformCode(options) {
543
558
  return false;
544
559
  }
545
560
  });
561
+ let prependImports = "";
546
562
  importMap.forEach((importSet, libName) => {
547
- s.prepend(`import { ${Array.from(importSet).join(", ")} } from '${libName}';
548
- `);
563
+ prependImports += `import { ${Array.from(importSet).join(", ")} } from '${libName}';
564
+ `;
549
565
  });
566
+ s.prepend(prependImports);
550
567
  return {
551
568
  content: s.toString(),
552
569
  declareModules
@@ -578,6 +595,26 @@ function hasExportDefault(content) {
578
595
  return has;
579
596
  }
580
597
 
598
+ const createProgram = typescript.proxyCreateProgram(ts__default, ts__default.createProgram, (ts2, options) => {
599
+ const { configFilePath } = options.options;
600
+ const vueOptions = typeof configFilePath === "string" ? languageCore.createParsedCommandLine(ts2, ts2.sys, configFilePath.replace(/\\/g, "/")).vueOptions : languageCore.resolveVueCompilerOptions({});
601
+ if (options.host) {
602
+ const writeFile2 = options.host.writeFile.bind(options.host);
603
+ options.host.writeFile = (fileName, contents, ...args) => {
604
+ return writeFile2(fileName, vueTsc.removeEmitGlobalTypes(contents), ...args);
605
+ };
606
+ }
607
+ const vueLanguagePlugin = languageCore.createVueLanguagePlugin(
608
+ ts2,
609
+ (id) => id,
610
+ options.host?.useCaseSensitiveFileNames?.() ?? false,
611
+ () => "",
612
+ () => options.rootNames.map((rootName) => rootName.replace(/\\/g, "/")),
613
+ options.options,
614
+ vueOptions
615
+ );
616
+ return [vueLanguagePlugin];
617
+ });
581
618
  const jsRE = /\.(m|c)?jsx?$/;
582
619
  const tsRE = /\.(m|c)?tsx?$/;
583
620
  const dtsRE = /\.d\.(m|c)?tsx?$/;
@@ -604,8 +641,6 @@ const noop = () => {
604
641
  };
605
642
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
606
643
  const tsToDts = (path) => `${path.replace(tsRE, "")}.d.ts`;
607
- const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g;
608
- const asteriskRE = /[*]+/g;
609
644
  function dtsPlugin(options = {}) {
610
645
  const {
611
646
  tsconfigPath,
@@ -643,6 +678,7 @@ function dtsPlugin(options = {}) {
643
678
  let host;
644
679
  let program;
645
680
  let filter;
681
+ let rebuildProgram;
646
682
  let bundled = false;
647
683
  let timeRecord = 0;
648
684
  const resolvers = parseResolvers([
@@ -653,6 +689,9 @@ function dtsPlugin(options = {}) {
653
689
  ]);
654
690
  const rootFiles = /* @__PURE__ */ new Set();
655
691
  const outputFiles = /* @__PURE__ */ new Map();
692
+ const setOutputFile = (path, content) => {
693
+ outputFiles.set(path, content);
694
+ };
656
695
  const rollupConfig = { ...options.rollupConfig || {} };
657
696
  rollupConfig.bundledPackages = rollupConfig.bundledPackages || options.bundledPackages || [];
658
697
  const cleanPath = (path) => {
@@ -766,20 +805,9 @@ ${logPrefix} ${kolorist.yellow(
766
805
  }
767
806
  const { baseUrl, paths } = compilerOptions;
768
807
  if (pathsToAliases && baseUrl && paths) {
769
- const basePath = ensureAbsolute(baseUrl, configPath ? node_path.dirname(configPath) : root);
770
- for (const [pathWithAsterisk, replacements] of Object.entries(paths)) {
771
- const find = new RegExp(
772
- `^${pathWithAsterisk.replace(regexpSymbolRE, "\\$1").replace(asteriskRE, "(.+)")}$`
773
- );
774
- let index = 1;
775
- aliases.push({
776
- find,
777
- replacement: ensureAbsolute(
778
- replacements[0].replace(asteriskRE, () => `$${index++}`),
779
- basePath
780
- )
781
- });
782
- }
808
+ aliases.push(
809
+ ...parseTsAliases(ensureAbsolute(baseUrl, configPath ? node_path.dirname(configPath) : root), paths)
810
+ );
783
811
  }
784
812
  const computeGlobs = (rootGlobs, tsGlobs, defaultGlob) => {
785
813
  if (rootGlobs?.length) {
@@ -798,11 +826,12 @@ ${logPrefix} ${kolorist.yellow(
798
826
  )
799
827
  ];
800
828
  host = ts__default.createCompilerHost(compilerOptions);
801
- program = vueTsc.createProgram({
829
+ program = (rebuildProgram = () => createProgram({
802
830
  host,
803
831
  rootNames,
804
- options: compilerOptions
805
- });
832
+ options: compilerOptions,
833
+ projectReferences: content?.projectReferences
834
+ }))();
806
835
  libName = toCapitalCase(libName || "_default");
807
836
  indexName = indexName || defaultIndex;
808
837
  const maybeEmitted = (sourceFile) => {
@@ -840,7 +869,6 @@ ${logPrefix} ${kolorist.yellow(
840
869
  }
841
870
  const startTime = Date.now();
842
871
  const outDir = outDirs[0];
843
- const service = program.__vue.languageService;
844
872
  id = id.split("?")[0];
845
873
  rootFiles.delete(id);
846
874
  if (resolver) {
@@ -850,11 +878,10 @@ ${logPrefix} ${kolorist.yellow(
850
878
  root: publicRoot,
851
879
  outDir,
852
880
  host,
853
- program,
854
- service
881
+ program
855
882
  });
856
883
  for (const { path, content } of result) {
857
- outputFiles.set(
884
+ setOutputFile(
858
885
  resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(path, outDir))),
859
886
  content
860
887
  );
@@ -862,17 +889,22 @@ ${logPrefix} ${kolorist.yellow(
862
889
  } else {
863
890
  const sourceFile = program.getSourceFile(id);
864
891
  if (sourceFile) {
865
- for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
866
- outputFiles.set(
867
- resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(outputFile.name, outDir))),
868
- outputFile.text
869
- );
870
- }
892
+ program.emit(
893
+ sourceFile,
894
+ (name, text) => {
895
+ setOutputFile(
896
+ resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(name, outDir))),
897
+ text
898
+ );
899
+ },
900
+ void 0,
901
+ true
902
+ );
871
903
  }
872
904
  }
873
905
  const dtsId = id.replace(tjsRE, "") + ".d.ts";
874
906
  const dtsSourceFile = program.getSourceFile(dtsId);
875
- dtsSourceFile && filter(dtsSourceFile.fileName) && outputFiles.set(normalizePath(dtsSourceFile.fileName), dtsSourceFile.getFullText());
907
+ dtsSourceFile && filter(dtsSourceFile.fileName) && setOutputFile(normalizePath(dtsSourceFile.fileName), dtsSourceFile.getFullText());
876
908
  timeRecord += Date.now() - startTime;
877
909
  },
878
910
  watchChange(id) {
@@ -884,9 +916,9 @@ ${logPrefix} ${kolorist.yellow(
884
916
  const sourceFile = host.getSourceFile(id, ts__default.ScriptTarget.ESNext);
885
917
  if (sourceFile) {
886
918
  rootFiles.add(sourceFile.fileName);
887
- program.__vue.projectVersion++;
888
919
  bundled = false;
889
920
  timeRecord = 0;
921
+ program = rebuildProgram();
890
922
  }
891
923
  },
892
924
  async writeBundle() {
@@ -922,27 +954,30 @@ ${logPrefix} Start generate declaration files...`));
922
954
  await promises.writeFile(path, content, "utf-8");
923
955
  record && emittedFiles.set(path, content);
924
956
  };
925
- const service = program.__vue.languageService;
926
957
  const sourceFiles = program.getSourceFiles();
927
958
  for (const sourceFile of sourceFiles) {
928
959
  if (!filter(sourceFile.fileName))
929
960
  continue;
930
961
  if (copyDtsFiles && dtsRE.test(sourceFile.fileName)) {
931
- outputFiles.set(normalizePath(sourceFile.fileName), sourceFile.getFullText());
962
+ setOutputFile(normalizePath(sourceFile.fileName), sourceFile.getFullText());
932
963
  }
933
964
  if (rootFiles.has(sourceFile.fileName)) {
934
- for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
935
- outputFiles.set(
936
- resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(outputFile.name, outDir))),
937
- outputFile.text
938
- );
939
- }
965
+ program.emit(
966
+ sourceFile,
967
+ (name, text) => {
968
+ setOutputFile(
969
+ resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(name, outDir))),
970
+ text
971
+ );
972
+ },
973
+ void 0,
974
+ true
975
+ );
940
976
  rootFiles.delete(sourceFile.fileName);
941
977
  }
942
978
  }
943
979
  bundleDebug("emit output patch");
944
980
  const currentDir = host.getCurrentDirectory();
945
- const vuePathRE = /['"](.+)\.vue['"]/g;
946
981
  await runParallel(
947
982
  node_os.cpus().length,
948
983
  Array.from(outputFiles.entries()),
@@ -956,7 +991,8 @@ ${logPrefix} Start generate declaration files...`));
956
991
  aliases,
957
992
  aliasesExclude,
958
993
  staticImport,
959
- clearPureImport
994
+ clearPureImport,
995
+ cleanVueFileName
960
996
  });
961
997
  content = result.content;
962
998
  declareModules.push(...result.declareModules);
@@ -968,7 +1004,6 @@ ${logPrefix} Start generate declaration files...`));
968
1004
  cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath
969
1005
  )
970
1006
  );
971
- content = cleanVueFileName ? content.replace(vuePathRE, '"$1"') : content;
972
1007
  if (isMapFile) {
973
1008
  try {
974
1009
  const sourceMap = JSON.parse(content);
package/dist/index.d.cts CHANGED
@@ -28,7 +28,6 @@ interface Resolver {
28
28
  outDir: string;
29
29
  host: ts.CompilerHost;
30
30
  program: ts.Program;
31
- service: ts.LanguageService;
32
31
  }) => MaybePromise<{
33
32
  path: string;
34
33
  content: string;
package/dist/index.d.mts CHANGED
@@ -28,7 +28,6 @@ interface Resolver {
28
28
  outDir: string;
29
29
  host: ts.CompilerHost;
30
30
  program: ts.Program;
31
- service: ts.LanguageService;
32
31
  }) => MaybePromise<{
33
32
  path: string;
34
33
  content: string;
package/dist/index.d.ts CHANGED
@@ -28,7 +28,6 @@ interface Resolver {
28
28
  outDir: string;
29
29
  host: ts.CompilerHost;
30
30
  program: ts.Program;
31
- service: ts.LanguageService;
32
31
  }) => MaybePromise<{
33
32
  path: string;
34
33
  content: string;