vite-plugin-dts 2.0.0-beta.2 → 2.0.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/README.md CHANGED
@@ -232,7 +232,8 @@ export interface PluginOptions {
232
232
  /**
233
233
  * Whether copy .d.ts source files into outputDir
234
234
  *
235
- * @default true
235
+ * @default false
236
+ * @remarks Before 2.0 it defaults to true
236
237
  */
237
238
  copyDtsFiles?: boolean
238
239
 
@@ -251,6 +252,7 @@ export interface PluginOptions {
251
252
  * But for the source files with type errors will not be emitted
252
253
  *
253
254
  * @default false
255
+ * @remarks Before 1.7 it defaults to true
254
256
  */
255
257
  skipDiagnostics?: boolean
256
258
 
package/README.zh-CN.md CHANGED
@@ -231,7 +231,8 @@ export interface PluginOptions {
231
231
  /**
232
232
  * 是否将源码里的 .d.ts 文件复制到 outputDir
233
233
  *
234
- * @default true
234
+ * @default false
235
+ * @remarks 在 2.0 之前它默认为 true
235
236
  */
236
237
  copyDtsFiles?: boolean
237
238
 
@@ -250,6 +251,7 @@ export interface PluginOptions {
250
251
  * 但对于出现错误的源文件,将无法生成相应的类型文件
251
252
  *
252
253
  * @default false
254
+ * @remarks 在 1.7 之前它默认为 true
253
255
  */
254
256
  skipDiagnostics?: boolean
255
257
 
package/dist/index.cjs CHANGED
@@ -599,6 +599,7 @@ const defaultIndex = "index.d.ts";
599
599
  const noop = () => {
600
600
  };
601
601
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
602
+ const resolve = (...paths) => vite.normalizePath(node_path.resolve(...paths));
602
603
  const logPrefix = kolorist.cyan("[vite:dts]");
603
604
  const bundleDebug = debug("vite-plugin-dts:bundle");
604
605
  function dtsPlugin(options = {}) {
@@ -612,7 +613,7 @@ function dtsPlugin(options = {}) {
612
613
  rollupTypes = false,
613
614
  noEmitOnError = false,
614
615
  skipDiagnostics = false,
615
- copyDtsFiles = true,
616
+ copyDtsFiles = false,
616
617
  logLevel = void 0,
617
618
  afterDiagnostic = noop,
618
619
  beforeWriteFile = noop,
@@ -635,16 +636,17 @@ function dtsPlugin(options = {}) {
635
636
  let filter;
636
637
  let libFolderPath = options.libFolderPath;
637
638
  const sourceDtsFiles = /* @__PURE__ */ new Set();
639
+ const includedFiles = /* @__PURE__ */ new Set();
638
640
  const emittedFiles = /* @__PURE__ */ new Map();
639
641
  let hasJsVue = false;
640
642
  let allowJs = false;
641
643
  let transformError = false;
642
- function internalTransform(code, id) {
643
- if (!filter(id)) {
644
+ async function internalTransform(id) {
645
+ if (!project || !filter(id)) {
644
646
  return;
645
647
  }
646
648
  if (vueRE.test(id)) {
647
- const { error, content, ext } = compileVueCode(code);
649
+ const { error, content, ext } = compileVueCode(await fs.readFile(id, "utf-8"));
648
650
  if (!transformError && error) {
649
651
  logger.error(
650
652
  kolorist.red(
@@ -663,7 +665,7 @@ ${kolorist.cyan(
663
665
  project.createSourceFile(`${id}.${ext || "js"}`, content, { overwrite: true });
664
666
  }
665
667
  } else if (!id.includes(".vue?vue") && (tsRE.test(id) || allowJs && jsRE.test(id))) {
666
- project.createSourceFile(id, code, { overwrite: true });
668
+ project.createSourceFile(id, await fs.readFile(id, "utf-8"), { overwrite: true });
667
669
  }
668
670
  }
669
671
  return {
@@ -735,7 +737,7 @@ ${kolorist.cyan(
735
737
  compilerOptions: mergeObjects(compilerOptions, {
736
738
  rootDir: compilerOptions.rootDir || root,
737
739
  noEmitOnError,
738
- outDir: ".",
740
+ outDir: outputDirs[0],
739
741
  declarationDir: void 0,
740
742
  noUnusedParameters: false,
741
743
  declaration: true,
@@ -769,7 +771,7 @@ ${kolorist.cyan(
769
771
  filter = pluginutils.createFilter(include, exclude, { resolve: root });
770
772
  compilerOptions = tsConfig.compilerOptions;
771
773
  },
772
- buildStart(inputOptions) {
774
+ async buildStart(inputOptions) {
773
775
  if (Array.isArray(inputOptions.input)) {
774
776
  entries = inputOptions.input.reduce((prev, current) => {
775
777
  prev[node_path.basename(current)] = current;
@@ -778,49 +780,27 @@ ${kolorist.cyan(
778
780
  } else {
779
781
  entries = { ...inputOptions.input };
780
782
  }
781
- },
782
- transform(code, id) {
783
- internalTransform(code, id);
784
- return null;
785
- },
786
- async watchChange(id) {
787
- if (watchExtensionRE.test(id)) {
788
- isBundle = false;
789
- if (project) {
790
- const sourceFile = project.getSourceFile(vite.normalizePath(id));
791
- sourceFile && project.removeSourceFile(sourceFile);
792
- internalTransform(await fs.readFile(id, "utf-8"), id);
793
- }
794
- }
795
- },
796
- async closeBundle() {
797
- if (!outputDirs || !project || isBundle)
798
- return;
799
- logger.info(kolorist.green(`
800
- ${logPrefix} Start generate declaration files...`));
801
- bundleDebug("start");
802
- isBundle = true;
783
+ bundleDebug("parse entries");
803
784
  sourceDtsFiles.clear();
804
- emittedFiles.clear();
805
- const startTime = Date.now();
806
- const includedFileSet = /* @__PURE__ */ new Set();
807
- if (include && include.length) {
785
+ includedFiles.clear();
786
+ if (project && include && include.length) {
808
787
  const files = await glob(include, {
809
788
  cwd: root,
810
789
  absolute: true,
811
790
  ignore: exclude
812
791
  });
813
- files.forEach((file) => {
792
+ for (const file of files) {
793
+ this.addWatchFile(file);
814
794
  if (dtsRE.test(file)) {
815
795
  sourceDtsFiles.add(project.addSourceFileAtPath(file));
816
796
  if (!copyDtsFiles) {
817
- return;
797
+ continue;
818
798
  }
819
- includedFileSet.add(file);
820
- return;
799
+ includedFiles.add(file);
800
+ continue;
821
801
  }
822
- includedFileSet.add(`${file.replace(tjsRE, "")}.d.${extPrefix(file)}ts`);
823
- });
802
+ includedFiles.add(`${file.replace(tjsRE, "")}.d.${extPrefix(file)}ts`);
803
+ }
824
804
  if (hasJsVue) {
825
805
  if (!allowJs) {
826
806
  logger.warn(
@@ -835,6 +815,30 @@ ${logPrefix} Start generate declaration files...`));
835
815
  }
836
816
  bundleDebug("collect files");
837
817
  }
818
+ },
819
+ async transform(_, id) {
820
+ await internalTransform(id);
821
+ return null;
822
+ },
823
+ async watchChange(id) {
824
+ if (watchExtensionRE.test(id)) {
825
+ isBundle = false;
826
+ if (project) {
827
+ const sourceFile = project.getSourceFile(vite.normalizePath(id));
828
+ sourceFile && project.removeSourceFile(sourceFile);
829
+ await internalTransform(id);
830
+ }
831
+ }
832
+ },
833
+ async closeBundle() {
834
+ if (!outputDirs || !project || isBundle)
835
+ return;
836
+ logger.info(kolorist.green(`
837
+ ${logPrefix} Start generate declaration files...`));
838
+ bundleDebug("start");
839
+ isBundle = true;
840
+ emittedFiles.clear();
841
+ const startTime = Date.now();
838
842
  project.resolveSourceFileDependencies();
839
843
  bundleDebug("resolve");
840
844
  if (!skipDiagnostics) {
@@ -848,6 +852,7 @@ ${logPrefix} Start generate declaration files...`));
848
852
  }
849
853
  bundleDebug("diagnostics");
850
854
  }
855
+ const outputDir = outputDirs[0];
851
856
  const dtsOutputFiles = Array.from(sourceDtsFiles).map((sourceFile) => ({
852
857
  path: sourceFile.getFilePath(),
853
858
  content: sourceFile.getFullText()
@@ -855,21 +860,18 @@ ${logPrefix} Start generate declaration files...`));
855
860
  const service = project.getLanguageService();
856
861
  const outputFiles = project.getSourceFiles().map(
857
862
  (sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
858
- path: vite.normalizePath(node_path.resolve(root, outputFile.compilerObject.name)),
863
+ path: resolve(root, node_path.relative(outputDir, outputFile.compilerObject.name)),
859
864
  content: outputFile.getText()
860
865
  }))
861
866
  ).flat().concat(dtsOutputFiles);
862
867
  bundleDebug("emit");
863
- if (!entryRoot) {
864
- entryRoot = queryPublicPath(outputFiles.map((file) => file.path));
865
- }
868
+ entryRoot = entryRoot || queryPublicPath(outputFiles.map((file) => file.path));
866
869
  entryRoot = ensureAbsolute(entryRoot, root);
867
- const outputDir = outputDirs[0];
868
870
  await runParallel(os.cpus().length, outputFiles, async (outputFile) => {
869
871
  let filePath = outputFile.path;
870
872
  let content = outputFile.content;
871
873
  const isMapFile = filePath.endsWith(".map");
872
- if (!includedFileSet.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport) {
874
+ if (!includedFiles.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport) {
873
875
  return;
874
876
  }
875
877
  if (!isMapFile && content && content !== noneExport) {
@@ -877,43 +879,38 @@ ${logPrefix} Start generate declaration files...`));
877
879
  content = transformAliasImport(filePath, content, aliases, aliasesExclude);
878
880
  content = staticImport || rollupTypes ? transformDynamicImport(content) : content;
879
881
  }
880
- filePath = node_path.resolve(
882
+ filePath = resolve(
881
883
  outputDir,
882
884
  node_path.relative(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath)
883
885
  );
886
+ content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
884
887
  if (typeof beforeWriteFile === "function") {
885
888
  const result = beforeWriteFile(filePath, content);
886
889
  if (result === false)
887
890
  return;
888
891
  if (result && isNativeObj(result)) {
889
- filePath = result.filePath ?? filePath;
892
+ filePath = result.filePath || filePath;
890
893
  content = result.content ?? content;
891
894
  }
892
895
  }
896
+ filePath = vite.normalizePath(filePath);
893
897
  await fs.mkdir(node_path.dirname(filePath), { recursive: true });
894
- await fs.writeFile(
895
- filePath,
896
- cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content,
897
- "utf-8"
898
- );
899
- emittedFiles.set(
900
- vite.normalizePath(filePath),
901
- cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content
902
- );
898
+ await fs.writeFile(filePath, content, "utf-8");
899
+ emittedFiles.set(filePath, content);
903
900
  });
904
901
  bundleDebug("output");
905
902
  if (insertTypesEntry || rollupTypes) {
906
- const pkgPath = node_path.resolve(root, "package.json");
903
+ const pkgPath = resolve(root, "package.json");
907
904
  const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, "utf-8")) : {};
908
905
  const entryNames = Object.keys(entries);
909
- const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings;
906
+ const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings || (pkg.exports?.["."] || pkg.exports?.["./"])?.types;
910
907
  const multiple = entryNames.length > 1;
911
- const typesPath = types ? node_path.resolve(root, types) : node_path.resolve(outputDir, indexName);
908
+ const typesPath = types ? resolve(root, types) : resolve(outputDir, indexName);
912
909
  for (const name of entryNames) {
913
- let filePath = multiple ? node_path.resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
910
+ let filePath = multiple ? resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
914
911
  if (fs.existsSync(filePath))
915
912
  continue;
916
- const index = node_path.resolve(
913
+ const index = resolve(
917
914
  outputDir,
918
915
  node_path.relative(entryRoot, `${entries[name].replace(tsRE, "")}.d.ts`)
919
916
  );
@@ -938,21 +935,19 @@ export default ${libName}
938
935
  content = result.content ?? content;
939
936
  }
940
937
  }
938
+ filePath = vite.normalizePath(filePath);
941
939
  if (result !== false) {
942
940
  await fs.writeFile(filePath, content, "utf-8");
943
- emittedFiles.set(vite.normalizePath(filePath), content);
941
+ emittedFiles.set(filePath, content);
944
942
  }
945
943
  }
946
944
  bundleDebug("insert index");
947
945
  if (rollupTypes) {
948
946
  logger.info(kolorist.green(`${logPrefix} Start rollup declaration files...`));
949
947
  const rollupFiles = /* @__PURE__ */ new Set();
950
- for (const [filePath, content] of emittedFiles) {
951
- project.createSourceFile(filePath, content, { overwrite: true });
952
- }
953
948
  if (multiple) {
954
949
  for (const name of entryNames) {
955
- const path = node_path.resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`);
950
+ const path = resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`);
956
951
  rollupDeclarationFiles({
957
952
  root,
958
953
  compilerOptions,
@@ -961,9 +956,8 @@ export default ${libName}
961
956
  fileName: node_path.basename(path),
962
957
  libFolder: libFolderPath
963
958
  });
964
- const wroteFile = vite.normalizePath(path);
965
- emittedFiles.delete(wroteFile);
966
- rollupFiles.add(wroteFile);
959
+ emittedFiles.delete(path);
960
+ rollupFiles.add(path);
967
961
  }
968
962
  } else {
969
963
  rollupDeclarationFiles({
@@ -974,9 +968,8 @@ export default ${libName}
974
968
  fileName: node_path.basename(typesPath),
975
969
  libFolder: libFolderPath
976
970
  });
977
- const wroteFile = vite.normalizePath(typesPath);
978
- emittedFiles.delete(wroteFile);
979
- rollupFiles.add(wroteFile);
971
+ emittedFiles.delete(typesPath);
972
+ rollupFiles.add(typesPath);
980
973
  }
981
974
  await runParallel(os.cpus().length, Array.from(emittedFiles.keys()), (f) => fs.unlink(f));
982
975
  removeDirIfEmpty(outputDir);
@@ -984,13 +977,6 @@ export default ${libName}
984
977
  for (const file of rollupFiles) {
985
978
  emittedFiles.set(file, await fs.readFile(file, "utf-8"));
986
979
  }
987
- if (copyDtsFiles) {
988
- await runParallel(os.cpus().length, dtsOutputFiles, async ({ path, content }) => {
989
- const filePath = node_path.resolve(outputDir, node_path.basename(path));
990
- await fs.writeFile(filePath, content, "utf-8");
991
- emittedFiles.set(vite.normalizePath(filePath), content);
992
- });
993
- }
994
980
  bundleDebug("rollup");
995
981
  }
996
982
  }
@@ -1003,7 +989,7 @@ export default ${libName}
1003
989
  const relativePath = node_path.relative(outputDir, wroteFile);
1004
990
  await Promise.all(
1005
991
  dirs.map(async (dir) => {
1006
- const filePath = node_path.resolve(dir, relativePath);
992
+ const filePath = resolve(dir, relativePath);
1007
993
  await fs.mkdir(node_path.dirname(filePath), { recursive: true });
1008
994
  await fs.writeFile(filePath, content, "utf-8");
1009
995
  })
package/dist/index.d.ts CHANGED
@@ -106,7 +106,8 @@ interface PluginOptions {
106
106
  /**
107
107
  * Whether copy .d.ts source files into outputDir
108
108
  *
109
- * @default true
109
+ * @default false
110
+ * @remarks Before 2.0 it defaults to true
110
111
  */
111
112
  copyDtsFiles?: boolean;
112
113
  /**
@@ -123,6 +124,7 @@ interface PluginOptions {
123
124
  * But for the source files with type errors will not be emitted
124
125
  *
125
126
  * @default false
127
+ * @remarks Before 1.7 it defaults to true
126
128
  */
127
129
  skipDiagnostics?: boolean;
128
130
  /**
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import __cjs_mod__ from 'module';
5
5
  const __filename = __cjs_url__.fileURLToPath(import.meta.url);
6
6
  const __dirname = __cjs_path__.dirname(__filename);
7
7
  const require = __cjs_mod__.createRequire(import.meta.url);
8
- import { isAbsolute, resolve, dirname, normalize, sep, relative, basename } from 'node:path';
8
+ import { isAbsolute, resolve as resolve$1, dirname, normalize, sep, relative, basename } from 'node:path';
9
9
  import fs from 'fs-extra';
10
10
  import os from 'os';
11
11
  import { cyan, yellow, red, green } from 'kolorist';
@@ -69,7 +69,7 @@ function mergeObjects(sourceObj, targetObj) {
69
69
  return sourceObj;
70
70
  }
71
71
  function ensureAbsolute(path, root) {
72
- return path ? isAbsolute(path) ? path : resolve(root, path) : root;
72
+ return path ? isAbsolute(path) ? path : resolve$1(root, path) : root;
73
73
  }
74
74
  function ensureArray(value) {
75
75
  return Array.isArray(value) ? value : value ? [value] : [];
@@ -134,7 +134,7 @@ function removeDirIfEmpty(dir) {
134
134
  }
135
135
  let onlyHasDir = true;
136
136
  for (const file of readdirSync(dir)) {
137
- const abs = resolve(dir, file);
137
+ const abs = resolve$1(dir, file);
138
138
  if (lstatSync(abs).isDirectory()) {
139
139
  if (!removeDirIfEmpty(abs)) {
140
140
  onlyHasDir = false;
@@ -514,7 +514,7 @@ function rollupDeclarationFiles({
514
514
  fileName,
515
515
  libFolder
516
516
  }) {
517
- const configObjectFullPath = resolve(root, "api-extractor.json");
517
+ const configObjectFullPath = resolve$1(root, "api-extractor.json");
518
518
  const packageJsonLookup = new PackageJsonLookup();
519
519
  const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
520
520
  if (!dtsRE$1.test(fileName)) {
@@ -539,7 +539,7 @@ function rollupDeclarationFiles({
539
539
  },
540
540
  dtsRollup: {
541
541
  enabled: true,
542
- publicTrimmedFilePath: resolve(outputDir, fileName)
542
+ publicTrimmedFilePath: resolve$1(outputDir, fileName)
543
543
  },
544
544
  tsdocMetadata: {
545
545
  enabled: false
@@ -563,7 +563,7 @@ function rollupDeclarationFiles({
563
563
  const compilerState = CompilerState.create(extractorConfig, {
564
564
  localBuild: false,
565
565
  showVerboseMessages: false,
566
- typescriptCompilerFolder: libFolder ? resolve(libFolder, "..") : void 0
566
+ typescriptCompilerFolder: libFolder ? resolve$1(libFolder, "..") : void 0
567
567
  });
568
568
  const sourceMapper = new SourceMapper();
569
569
  const messageRouter = new MessageRouter({
@@ -604,6 +604,7 @@ const defaultIndex = "index.d.ts";
604
604
  const noop = () => {
605
605
  };
606
606
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
607
+ const resolve = (...paths) => normalizePath(resolve$1(...paths));
607
608
  const logPrefix = cyan("[vite:dts]");
608
609
  const bundleDebug = debug("vite-plugin-dts:bundle");
609
610
  function dtsPlugin(options = {}) {
@@ -617,7 +618,7 @@ function dtsPlugin(options = {}) {
617
618
  rollupTypes = false,
618
619
  noEmitOnError = false,
619
620
  skipDiagnostics = false,
620
- copyDtsFiles = true,
621
+ copyDtsFiles = false,
621
622
  logLevel = void 0,
622
623
  afterDiagnostic = noop,
623
624
  beforeWriteFile = noop,
@@ -640,16 +641,17 @@ function dtsPlugin(options = {}) {
640
641
  let filter;
641
642
  let libFolderPath = options.libFolderPath;
642
643
  const sourceDtsFiles = /* @__PURE__ */ new Set();
644
+ const includedFiles = /* @__PURE__ */ new Set();
643
645
  const emittedFiles = /* @__PURE__ */ new Map();
644
646
  let hasJsVue = false;
645
647
  let allowJs = false;
646
648
  let transformError = false;
647
- function internalTransform(code, id) {
648
- if (!filter(id)) {
649
+ async function internalTransform(id) {
650
+ if (!project || !filter(id)) {
649
651
  return;
650
652
  }
651
653
  if (vueRE.test(id)) {
652
- const { error, content, ext } = compileVueCode(code);
654
+ const { error, content, ext } = compileVueCode(await fs.readFile(id, "utf-8"));
653
655
  if (!transformError && error) {
654
656
  logger.error(
655
657
  red(
@@ -668,7 +670,7 @@ ${cyan(
668
670
  project.createSourceFile(`${id}.${ext || "js"}`, content, { overwrite: true });
669
671
  }
670
672
  } else if (!id.includes(".vue?vue") && (tsRE.test(id) || allowJs && jsRE.test(id))) {
671
- project.createSourceFile(id, code, { overwrite: true });
673
+ project.createSourceFile(id, await fs.readFile(id, "utf-8"), { overwrite: true });
672
674
  }
673
675
  }
674
676
  return {
@@ -740,7 +742,7 @@ ${cyan(
740
742
  compilerOptions: mergeObjects(compilerOptions, {
741
743
  rootDir: compilerOptions.rootDir || root,
742
744
  noEmitOnError,
743
- outDir: ".",
745
+ outDir: outputDirs[0],
744
746
  declarationDir: void 0,
745
747
  noUnusedParameters: false,
746
748
  declaration: true,
@@ -774,7 +776,7 @@ ${cyan(
774
776
  filter = createFilter(include, exclude, { resolve: root });
775
777
  compilerOptions = tsConfig.compilerOptions;
776
778
  },
777
- buildStart(inputOptions) {
779
+ async buildStart(inputOptions) {
778
780
  if (Array.isArray(inputOptions.input)) {
779
781
  entries = inputOptions.input.reduce((prev, current) => {
780
782
  prev[basename(current)] = current;
@@ -783,49 +785,27 @@ ${cyan(
783
785
  } else {
784
786
  entries = { ...inputOptions.input };
785
787
  }
786
- },
787
- transform(code, id) {
788
- internalTransform(code, id);
789
- return null;
790
- },
791
- async watchChange(id) {
792
- if (watchExtensionRE.test(id)) {
793
- isBundle = false;
794
- if (project) {
795
- const sourceFile = project.getSourceFile(normalizePath(id));
796
- sourceFile && project.removeSourceFile(sourceFile);
797
- internalTransform(await fs.readFile(id, "utf-8"), id);
798
- }
799
- }
800
- },
801
- async closeBundle() {
802
- if (!outputDirs || !project || isBundle)
803
- return;
804
- logger.info(green(`
805
- ${logPrefix} Start generate declaration files...`));
806
- bundleDebug("start");
807
- isBundle = true;
788
+ bundleDebug("parse entries");
808
789
  sourceDtsFiles.clear();
809
- emittedFiles.clear();
810
- const startTime = Date.now();
811
- const includedFileSet = /* @__PURE__ */ new Set();
812
- if (include && include.length) {
790
+ includedFiles.clear();
791
+ if (project && include && include.length) {
813
792
  const files = await glob(include, {
814
793
  cwd: root,
815
794
  absolute: true,
816
795
  ignore: exclude
817
796
  });
818
- files.forEach((file) => {
797
+ for (const file of files) {
798
+ this.addWatchFile(file);
819
799
  if (dtsRE.test(file)) {
820
800
  sourceDtsFiles.add(project.addSourceFileAtPath(file));
821
801
  if (!copyDtsFiles) {
822
- return;
802
+ continue;
823
803
  }
824
- includedFileSet.add(file);
825
- return;
804
+ includedFiles.add(file);
805
+ continue;
826
806
  }
827
- includedFileSet.add(`${file.replace(tjsRE, "")}.d.${extPrefix(file)}ts`);
828
- });
807
+ includedFiles.add(`${file.replace(tjsRE, "")}.d.${extPrefix(file)}ts`);
808
+ }
829
809
  if (hasJsVue) {
830
810
  if (!allowJs) {
831
811
  logger.warn(
@@ -840,6 +820,30 @@ ${logPrefix} Start generate declaration files...`));
840
820
  }
841
821
  bundleDebug("collect files");
842
822
  }
823
+ },
824
+ async transform(_, id) {
825
+ await internalTransform(id);
826
+ return null;
827
+ },
828
+ async watchChange(id) {
829
+ if (watchExtensionRE.test(id)) {
830
+ isBundle = false;
831
+ if (project) {
832
+ const sourceFile = project.getSourceFile(normalizePath(id));
833
+ sourceFile && project.removeSourceFile(sourceFile);
834
+ await internalTransform(id);
835
+ }
836
+ }
837
+ },
838
+ async closeBundle() {
839
+ if (!outputDirs || !project || isBundle)
840
+ return;
841
+ logger.info(green(`
842
+ ${logPrefix} Start generate declaration files...`));
843
+ bundleDebug("start");
844
+ isBundle = true;
845
+ emittedFiles.clear();
846
+ const startTime = Date.now();
843
847
  project.resolveSourceFileDependencies();
844
848
  bundleDebug("resolve");
845
849
  if (!skipDiagnostics) {
@@ -853,6 +857,7 @@ ${logPrefix} Start generate declaration files...`));
853
857
  }
854
858
  bundleDebug("diagnostics");
855
859
  }
860
+ const outputDir = outputDirs[0];
856
861
  const dtsOutputFiles = Array.from(sourceDtsFiles).map((sourceFile) => ({
857
862
  path: sourceFile.getFilePath(),
858
863
  content: sourceFile.getFullText()
@@ -860,21 +865,18 @@ ${logPrefix} Start generate declaration files...`));
860
865
  const service = project.getLanguageService();
861
866
  const outputFiles = project.getSourceFiles().map(
862
867
  (sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
863
- path: normalizePath(resolve(root, outputFile.compilerObject.name)),
868
+ path: resolve(root, relative(outputDir, outputFile.compilerObject.name)),
864
869
  content: outputFile.getText()
865
870
  }))
866
871
  ).flat().concat(dtsOutputFiles);
867
872
  bundleDebug("emit");
868
- if (!entryRoot) {
869
- entryRoot = queryPublicPath(outputFiles.map((file) => file.path));
870
- }
873
+ entryRoot = entryRoot || queryPublicPath(outputFiles.map((file) => file.path));
871
874
  entryRoot = ensureAbsolute(entryRoot, root);
872
- const outputDir = outputDirs[0];
873
875
  await runParallel(os.cpus().length, outputFiles, async (outputFile) => {
874
876
  let filePath = outputFile.path;
875
877
  let content = outputFile.content;
876
878
  const isMapFile = filePath.endsWith(".map");
877
- if (!includedFileSet.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport) {
879
+ if (!includedFiles.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport) {
878
880
  return;
879
881
  }
880
882
  if (!isMapFile && content && content !== noneExport) {
@@ -886,32 +888,27 @@ ${logPrefix} Start generate declaration files...`));
886
888
  outputDir,
887
889
  relative(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath)
888
890
  );
891
+ content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
889
892
  if (typeof beforeWriteFile === "function") {
890
893
  const result = beforeWriteFile(filePath, content);
891
894
  if (result === false)
892
895
  return;
893
896
  if (result && isNativeObj(result)) {
894
- filePath = result.filePath ?? filePath;
897
+ filePath = result.filePath || filePath;
895
898
  content = result.content ?? content;
896
899
  }
897
900
  }
901
+ filePath = normalizePath(filePath);
898
902
  await fs.mkdir(dirname(filePath), { recursive: true });
899
- await fs.writeFile(
900
- filePath,
901
- cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content,
902
- "utf-8"
903
- );
904
- emittedFiles.set(
905
- normalizePath(filePath),
906
- cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content
907
- );
903
+ await fs.writeFile(filePath, content, "utf-8");
904
+ emittedFiles.set(filePath, content);
908
905
  });
909
906
  bundleDebug("output");
910
907
  if (insertTypesEntry || rollupTypes) {
911
908
  const pkgPath = resolve(root, "package.json");
912
909
  const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, "utf-8")) : {};
913
910
  const entryNames = Object.keys(entries);
914
- const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings;
911
+ const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings || (pkg.exports?.["."] || pkg.exports?.["./"])?.types;
915
912
  const multiple = entryNames.length > 1;
916
913
  const typesPath = types ? resolve(root, types) : resolve(outputDir, indexName);
917
914
  for (const name of entryNames) {
@@ -943,18 +940,16 @@ export default ${libName}
943
940
  content = result.content ?? content;
944
941
  }
945
942
  }
943
+ filePath = normalizePath(filePath);
946
944
  if (result !== false) {
947
945
  await fs.writeFile(filePath, content, "utf-8");
948
- emittedFiles.set(normalizePath(filePath), content);
946
+ emittedFiles.set(filePath, content);
949
947
  }
950
948
  }
951
949
  bundleDebug("insert index");
952
950
  if (rollupTypes) {
953
951
  logger.info(green(`${logPrefix} Start rollup declaration files...`));
954
952
  const rollupFiles = /* @__PURE__ */ new Set();
955
- for (const [filePath, content] of emittedFiles) {
956
- project.createSourceFile(filePath, content, { overwrite: true });
957
- }
958
953
  if (multiple) {
959
954
  for (const name of entryNames) {
960
955
  const path = resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`);
@@ -966,9 +961,8 @@ export default ${libName}
966
961
  fileName: basename(path),
967
962
  libFolder: libFolderPath
968
963
  });
969
- const wroteFile = normalizePath(path);
970
- emittedFiles.delete(wroteFile);
971
- rollupFiles.add(wroteFile);
964
+ emittedFiles.delete(path);
965
+ rollupFiles.add(path);
972
966
  }
973
967
  } else {
974
968
  rollupDeclarationFiles({
@@ -979,9 +973,8 @@ export default ${libName}
979
973
  fileName: basename(typesPath),
980
974
  libFolder: libFolderPath
981
975
  });
982
- const wroteFile = normalizePath(typesPath);
983
- emittedFiles.delete(wroteFile);
984
- rollupFiles.add(wroteFile);
976
+ emittedFiles.delete(typesPath);
977
+ rollupFiles.add(typesPath);
985
978
  }
986
979
  await runParallel(os.cpus().length, Array.from(emittedFiles.keys()), (f) => fs.unlink(f));
987
980
  removeDirIfEmpty(outputDir);
@@ -989,13 +982,6 @@ export default ${libName}
989
982
  for (const file of rollupFiles) {
990
983
  emittedFiles.set(file, await fs.readFile(file, "utf-8"));
991
984
  }
992
- if (copyDtsFiles) {
993
- await runParallel(os.cpus().length, dtsOutputFiles, async ({ path, content }) => {
994
- const filePath = resolve(outputDir, basename(path));
995
- await fs.writeFile(filePath, content, "utf-8");
996
- emittedFiles.set(normalizePath(filePath), content);
997
- });
998
- }
999
985
  bundleDebug("rollup");
1000
986
  }
1001
987
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-dts",
3
- "version": "2.0.0-beta.2",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "qmhc",