vite-plugin-dts 1.5.0 → 1.6.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.js CHANGED
@@ -1,3 +1,4 @@
1
+ "use strict";
1
2
  var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -16,7 +17,10 @@ var __copyProps = (to, from, except, desc) => {
16
17
  }
17
18
  return to;
18
19
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
20
24
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
25
 
22
26
  // src/index.ts
@@ -184,20 +188,25 @@ var importTypesRE = /import\s?(?:type)?\s?\{(.+)\}\s?from\s?['"].+['"]/;
184
188
  function transformDynamicImport(content) {
185
189
  const importMap = /* @__PURE__ */ new Map();
186
190
  content = content.replace(globalDynamicTypeRE, (str) => {
187
- var _a;
188
191
  const matchResult = str.match(dynamicTypeRE);
189
192
  const libName = matchResult[1];
190
- const importSet = (_a = importMap.get(libName)) != null ? _a : importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
193
+ const importSet = importMap.get(libName) ?? importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
191
194
  const usedType = matchResult[2];
192
195
  importSet.add(usedType);
193
196
  return usedType + matchResult[3];
194
197
  });
195
198
  importMap.forEach((importSet, libName) => {
196
- const importReg = new RegExp(`import\\s?(?:type)?\\s?\\{[^;\\n]+\\}\\s?from\\s?['"]${libName}['"]`, "g");
199
+ const importReg = new RegExp(
200
+ `import\\s?(?:type)?\\s?\\{[^;\\n]+\\}\\s?from\\s?['"]${libName}['"]`,
201
+ "g"
202
+ );
197
203
  const matchResult = content.match(importReg);
198
204
  if (matchResult == null ? void 0 : matchResult[0]) {
199
205
  const importedTypes = matchResult[0].match(importTypesRE)[1].trim().split(",");
200
- content = content.replace(matchResult[0], `import type { ${Array.from(importSet).concat(importedTypes).join(", ")} } from '${libName}'`);
206
+ content = content.replace(
207
+ matchResult[0],
208
+ `import type { ${Array.from(importSet).concat(importedTypes).join(", ")} } from '${libName}'`
209
+ );
201
210
  } else {
202
211
  content = `import type { ${Array.from(importSet).join(", ")} } from '${libName}';
203
212
  ` + content;
@@ -236,7 +245,13 @@ function transformAliasImport(filePath, content, aliases, exclude = []) {
236
245
  return str;
237
246
  }
238
247
  const truthPath = (0, import_path2.isAbsolute)(matchedAlias.replacement) ? (0, import_vite.normalizePath)((0, import_path2.relative)((0, import_path2.dirname)(filePath), matchedAlias.replacement)) : (0, import_vite.normalizePath)(matchedAlias.replacement);
239
- return str.replace(isDynamic ? simpleDynamicImportRE : simpleStaticImportRE, `$1'${matchResult[1].replace(matchedAlias.find, (truthPath.startsWith(".") ? truthPath : `./${truthPath}`) + (typeof matchedAlias.find === "string" && matchedAlias.find.endsWith("/") ? "/" : ""))}'${isDynamic ? ")" : ""}`);
248
+ return str.replace(
249
+ isDynamic ? simpleDynamicImportRE : simpleStaticImportRE,
250
+ `$1'${matchResult[1].replace(
251
+ matchedAlias.find,
252
+ (truthPath.startsWith(".") ? truthPath : `./${truthPath}`) + (typeof matchedAlias.find === "string" && matchedAlias.find.endsWith("/") ? "/" : "")
253
+ )}'${isDynamic ? ")" : ""}`
254
+ );
240
255
  }
241
256
  }
242
257
  return str;
@@ -257,6 +272,8 @@ function transferSetupPosition(content) {
257
272
  }
258
273
 
259
274
  // src/compile.ts
275
+ var import_node_module = require("module");
276
+ var import_meta = {};
260
277
  var exportDefaultRE = /export\s+default/;
261
278
  var exportDefaultClassRE = /(?:(?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
262
279
  var noScriptContent = "import { defineComponent } from 'vue'\nexport default defineComponent({})";
@@ -264,20 +281,21 @@ var index = 1;
264
281
  var compileRoot = null;
265
282
  var compiler;
266
283
  var vue;
284
+ var _require = (0, import_node_module.createRequire)(import_meta.url);
267
285
  function requireCompiler() {
268
286
  if (!compiler) {
269
287
  if (compileRoot) {
270
288
  try {
271
- compiler = require(require.resolve("vue/compiler-sfc", { paths: [compileRoot] }));
289
+ compiler = _require(_require.resolve("vue/compiler-sfc", { paths: [compileRoot] }));
272
290
  } catch (e) {
273
291
  }
274
292
  }
275
293
  if (!compiler) {
276
294
  try {
277
- compiler = require("vue/compiler-sfc");
295
+ compiler = _require("vue/compiler-sfc");
278
296
  } catch (e) {
279
297
  try {
280
- compiler = require("@vue/compiler-sfc");
298
+ compiler = _require("@vue/compiler-sfc");
281
299
  } catch (e2) {
282
300
  throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
283
301
  }
@@ -290,13 +308,13 @@ function isVue3() {
290
308
  if (!vue) {
291
309
  if (compileRoot) {
292
310
  try {
293
- vue = require(require.resolve("vue", { paths: [compileRoot] }));
311
+ vue = _require(_require.resolve("vue", { paths: [compileRoot] }));
294
312
  } catch (e) {
295
313
  }
296
314
  }
297
315
  if (!vue) {
298
316
  try {
299
- vue = require("vue");
317
+ vue = _require("vue");
300
318
  } catch (e) {
301
319
  throw new Error("vue is not present in the dependency tree.\n");
302
320
  }
@@ -332,7 +350,7 @@ function compileVueCode(code) {
332
350
  id: `${index++}`
333
351
  });
334
352
  const classMatch = compiled.content.match(exportDefaultClassRE);
335
- const plugins = scriptSetup.lang === "ts" ? ["typescript"] : void 0;
353
+ const plugins = scriptSetup.lang === "ts" ? ["typescript", "decorators-legacy"] : void 0;
336
354
  if (classMatch) {
337
355
  content = compiled.content.replace(exportDefaultClassRE, "\nclass $1") + `
338
356
  const _sfc_main = ${classMatch[1]}`;
@@ -343,10 +361,18 @@ const _sfc_main = ${classMatch[1]}`;
343
361
  content = rewriteDefault(compiled.content, "_sfc_main", plugins);
344
362
  }
345
363
  content = transferSetupPosition(content);
364
+ content = content.replace(/(const __returned__\s?=\s?\{[\s\S]+?)(props)(\s?\})/, "$1props: props as any$3").replace(
365
+ /(const __returned__\s?=\s?\{[\s\S]+?)(props,)([\s\S]+?)/,
366
+ "$1props: props as any,$3"
367
+ );
346
368
  content += "\nexport default _sfc_main\n";
347
369
  ext = scriptSetup.lang || "js";
348
370
  } else if (script && script.content) {
349
- content = rewriteDefault(script.content, "_sfc_main", script.lang === "ts" ? ["typescript"] : void 0);
371
+ content = rewriteDefault(
372
+ script.content,
373
+ "_sfc_main",
374
+ script.lang === "ts" ? ["typescript"] : void 0
375
+ );
350
376
  content += "\nexport default _sfc_main\n";
351
377
  ext = script.lang || "js";
352
378
  }
@@ -435,7 +461,12 @@ function rollupDeclarationFiles({
435
461
  extractorConfig
436
462
  });
437
463
  collector.analyze();
438
- import_DtsRollupGenerator.DtsRollupGenerator.writeTypingsFile(collector, extractorConfig.publicTrimmedFilePath, import_DtsRollupGenerator.DtsRollupKind.PublicRelease, extractorConfig.newlineKind);
464
+ import_DtsRollupGenerator.DtsRollupGenerator.writeTypingsFile(
465
+ collector,
466
+ extractorConfig.publicTrimmedFilePath,
467
+ import_DtsRollupGenerator.DtsRollupKind.PublicRelease,
468
+ extractorConfig.newlineKind
469
+ );
439
470
  }
440
471
 
441
472
  // src/plugin.ts
@@ -454,7 +485,6 @@ var noop = () => {
454
485
  var logPrefix = import_chalk.default.cyan("[vite:dts]");
455
486
  var bundleDebug = (0, import_debug.debug)("vite-plugin-dts:bundle");
456
487
  function dtsPlugin(options = {}) {
457
- var _a, _b;
458
488
  const {
459
489
  tsConfigFilePath = "tsconfig.json",
460
490
  aliasesExclude = [],
@@ -471,9 +501,9 @@ function dtsPlugin(options = {}) {
471
501
  beforeWriteFile = noop,
472
502
  afterBuild = noop
473
503
  } = options;
474
- const compilerOptions = (_a = options.compilerOptions) != null ? _a : {};
504
+ const compilerOptions = options.compilerOptions ?? {};
475
505
  let root;
476
- let entryRoot = (_b = options.entryRoot) != null ? _b : "";
506
+ let entryRoot = options.entryRoot ?? "";
477
507
  let libName;
478
508
  let indexName;
479
509
  let aliases;
@@ -491,10 +521,10 @@ function dtsPlugin(options = {}) {
491
521
  apply: "build",
492
522
  enforce: "pre",
493
523
  config(config) {
494
- var _a2, _b2;
524
+ var _a;
495
525
  if (isBundle)
496
526
  return;
497
- const aliasOptions = (_b2 = (_a2 = config == null ? void 0 : config.resolve) == null ? void 0 : _a2.alias) != null ? _b2 : [];
527
+ const aliasOptions = ((_a = config == null ? void 0 : config.resolve) == null ? void 0 : _a.alias) ?? [];
498
528
  if (isNativeObj(aliasOptions)) {
499
529
  aliases = Object.entries(aliasOptions).map(([key, value]) => {
500
530
  return { find: key, replacement: value };
@@ -503,38 +533,53 @@ function dtsPlugin(options = {}) {
503
533
  aliases = ensureArray(aliasOptions);
504
534
  }
505
535
  if (aliasesExclude.length > 0) {
506
- aliases = aliases.filter(({ find }) => !aliasesExclude.some((alias) => {
507
- var _a3;
508
- return alias && (isRegExp(find) ? find.toString() === alias.toString() : isRegExp(alias) ? (_a3 = find.match(alias)) == null ? void 0 : _a3[0] : find === alias);
509
- }));
536
+ aliases = aliases.filter(
537
+ ({ find }) => !aliasesExclude.some(
538
+ (alias) => {
539
+ var _a2;
540
+ return alias && (isRegExp(find) ? find.toString() === alias.toString() : isRegExp(alias) ? (_a2 = find.match(alias)) == null ? void 0 : _a2[0] : find === alias);
541
+ }
542
+ )
543
+ );
510
544
  }
511
545
  },
512
546
  configResolved(config) {
513
- var _a2, _b2, _c;
514
547
  if (isBundle)
515
548
  return;
516
549
  logger = config.logger;
517
550
  if (!config.build.lib) {
518
- logger.warn(import_chalk.default.yellow(`
519
- ${import_chalk.default.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
520
- `));
551
+ logger.warn(
552
+ import_chalk.default.yellow(
553
+ `
554
+ ${import_chalk.default.cyan(
555
+ "[vite:dts]"
556
+ )} You building not a library that may not need to generate declaration files.
557
+ `
558
+ )
559
+ );
521
560
  libName = "_default";
522
561
  indexName = defaultIndex;
523
562
  } else {
524
- const filename = (_a2 = config.build.lib.fileName) != null ? _a2 : defaultIndex;
563
+ const filename = config.build.lib.fileName ?? defaultIndex;
525
564
  libName = config.build.lib.name || "_default";
526
565
  indexName = typeof filename === "string" ? filename : filename("es");
527
566
  if (!dtsRE2.test(indexName)) {
528
567
  indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, "") : indexName}.d.ts`;
529
568
  }
530
569
  }
531
- root = ensureAbsolute((_b2 = options.root) != null ? _b2 : "", config.root);
570
+ root = ensureAbsolute(options.root ?? "", config.root);
532
571
  tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
533
572
  outputDirs = options.outputDir ? ensureArray(options.outputDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.build.outDir, root)];
534
- if (!outputDirs) {
535
- logger.error(import_chalk.default.red(`
536
- ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory, please check your vite config and plugin options.
537
- `));
573
+ if (!outputDirs[0]) {
574
+ logger.error(
575
+ import_chalk.default.red(
576
+ `
577
+ ${import_chalk.default.cyan(
578
+ "[vite:dts]"
579
+ )} Can not resolve declaration directory, please check your vite config and plugin options.
580
+ `
581
+ )
582
+ );
538
583
  return;
539
584
  }
540
585
  setCompileRoot(root);
@@ -552,7 +597,7 @@ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory
552
597
  tsConfigFilePath: tsConfigPath,
553
598
  skipAddingFilesFromTsConfig: true
554
599
  });
555
- allowJs = (_c = project.getCompilerOptions().allowJs) != null ? _c : false;
600
+ allowJs = project.getCompilerOptions().allowJs ?? false;
556
601
  },
557
602
  buildStart(inputOptions) {
558
603
  if (!isBundle && (insertTypesEntry || rollupTypes)) {
@@ -585,7 +630,6 @@ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory
585
630
  }
586
631
  },
587
632
  async closeBundle() {
588
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
589
633
  if (!outputDirs || !project || isBundle)
590
634
  return;
591
635
  logger.info(import_chalk.default.green(`
@@ -594,11 +638,11 @@ ${logPrefix} Start generate declaration files...`));
594
638
  isBundle = true;
595
639
  sourceDtsFiles.clear();
596
640
  const startTime = Date.now();
597
- const tsConfig = (_a2 = (0, import_typescript.readConfigFile)(tsConfigPath, project.getFileSystem().readFileSync).config) != null ? _a2 : {};
641
+ const tsConfig = (0, import_typescript.readConfigFile)(tsConfigPath, project.getFileSystem().readFileSync).config ?? {};
598
642
  const parentTsConfigPath = tsConfig.extends && ensureAbsolute(tsConfig.extends, root);
599
643
  const parentTsConfig = parentTsConfigPath ? (0, import_typescript.readConfigFile)(parentTsConfigPath, project.getFileSystem().readFileSync).config : {};
600
- const include = (_d = (_c = (_b2 = options.include) != null ? _b2 : tsConfig.include) != null ? _c : parentTsConfig.include) != null ? _d : "**/*";
601
- const exclude = (_g = (_f = (_e = options.exclude) != null ? _e : tsConfig.exclude) != null ? _f : parentTsConfig.exclude) != null ? _g : "node_modules/**";
644
+ const include = options.include ?? tsConfig.include ?? parentTsConfig.include ?? "**/*";
645
+ const exclude = options.exclude ?? tsConfig.exclude ?? parentTsConfig.exclude ?? "node_modules/**";
602
646
  bundleDebug("read config");
603
647
  const includedFileSet = /* @__PURE__ */ new Set();
604
648
  if (include && include.length) {
@@ -620,13 +664,18 @@ ${logPrefix} Start generate declaration files...`));
620
664
  });
621
665
  if (hasJsVue) {
622
666
  if (!allowJs) {
623
- logger.warn(import_chalk.default.yellow(`${import_chalk.default.cyan("[vite:dts]")} Some js files are referenced, but you may not enable the 'allowJs' option.`));
667
+ logger.warn(
668
+ import_chalk.default.yellow(
669
+ `${import_chalk.default.cyan(
670
+ "[vite:dts]"
671
+ )} Some js files are referenced, but you may not enable the 'allowJs' option.`
672
+ )
673
+ );
624
674
  }
625
675
  project.compilerOptions.set({ allowJs: true });
626
676
  }
627
677
  bundleDebug("collect files");
628
678
  }
629
- project.resolveSourceFileDependencies();
630
679
  bundleDebug("resolve");
631
680
  if (!skipDiagnostics) {
632
681
  const diagnostics = project.getPreEmitDiagnostics();
@@ -644,10 +693,12 @@ ${logPrefix} Start generate declaration files...`));
644
693
  content: sourceFile.getFullText()
645
694
  }));
646
695
  const service = project.getLanguageService();
647
- const outputFiles = project.getSourceFiles().map((sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
648
- path: (0, import_vite2.normalizePath)((0, import_path4.resolve)(root, outputFile.compilerObject.name)),
649
- content: outputFile.getText()
650
- }))).flat().concat(dtsOutputFiles);
696
+ const outputFiles = project.getSourceFiles().map(
697
+ (sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
698
+ path: (0, import_vite2.normalizePath)((0, import_path4.resolve)(root, outputFile.compilerObject.name)),
699
+ content: outputFile.getText()
700
+ }))
701
+ ).flat().concat(dtsOutputFiles);
651
702
  bundleDebug("emit");
652
703
  if (!entryRoot) {
653
704
  entryRoot = queryPublicPath(outputFiles.map((file) => file.path));
@@ -656,7 +707,6 @@ ${logPrefix} Start generate declaration files...`));
656
707
  const wroteFiles = /* @__PURE__ */ new Set();
657
708
  const outputDir = outputDirs[0];
658
709
  await runParallel(import_os.default.cpus().length, outputFiles, async (outputFile) => {
659
- var _a3, _b3;
660
710
  let filePath = outputFile.path;
661
711
  let content = outputFile.content;
662
712
  const isMapFile = filePath.endsWith(".map");
@@ -668,16 +718,25 @@ ${logPrefix} Start generate declaration files...`));
668
718
  content = transformAliasImport(filePath, content, aliases, aliasesExclude);
669
719
  content = staticImport || rollupTypes ? transformDynamicImport(content) : content;
670
720
  }
671
- filePath = (0, import_path4.resolve)(outputDir, (0, import_path4.relative)(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath));
721
+ filePath = (0, import_path4.resolve)(
722
+ outputDir,
723
+ (0, import_path4.relative)(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath)
724
+ );
672
725
  if (typeof beforeWriteFile === "function") {
673
726
  const result = beforeWriteFile(filePath, content);
727
+ if (result === false)
728
+ return;
674
729
  if (result && isNativeObj(result)) {
675
- filePath = (_a3 = result.filePath) != null ? _a3 : filePath;
676
- content = (_b3 = result.content) != null ? _b3 : content;
730
+ filePath = result.filePath ?? filePath;
731
+ content = result.content ?? content;
677
732
  }
678
733
  }
679
734
  await import_fs_extra.default.mkdir((0, import_path4.dirname)(filePath), { recursive: true });
680
- await import_fs_extra.default.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf-8");
735
+ await import_fs_extra.default.writeFile(
736
+ filePath,
737
+ cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content,
738
+ "utf-8"
739
+ );
681
740
  wroteFiles.add((0, import_vite2.normalizePath)(filePath));
682
741
  });
683
742
  bundleDebug("output");
@@ -702,15 +761,18 @@ export default ${libName}
702
761
  `;
703
762
  }
704
763
  }
764
+ let result;
705
765
  if (typeof beforeWriteFile === "function") {
706
- const result = beforeWriteFile(typesPath, content);
766
+ result = beforeWriteFile(typesPath, content);
707
767
  if (result && isNativeObj(result)) {
708
- typesPath = (_h = result.filePath) != null ? _h : typesPath;
709
- content = (_i = result.content) != null ? _i : content;
768
+ typesPath = result.filePath ?? typesPath;
769
+ content = result.content ?? content;
710
770
  }
711
771
  }
712
- await import_fs_extra.default.writeFile(typesPath, content, "utf-8");
713
- wroteFiles.add((0, import_vite2.normalizePath)(typesPath));
772
+ if (result !== false) {
773
+ await import_fs_extra.default.writeFile(typesPath, content, "utf-8");
774
+ wroteFiles.add((0, import_vite2.normalizePath)(typesPath));
775
+ }
714
776
  }
715
777
  bundleDebug("insert index");
716
778
  if (rollupTypes) {
@@ -744,11 +806,13 @@ export default ${libName}
744
806
  await runParallel(import_os.default.cpus().length, Array.from(wroteFiles), async (wroteFile) => {
745
807
  const relativePath = (0, import_path4.relative)(outputDir, wroteFile);
746
808
  const content = await import_fs_extra.default.readFile(wroteFile, "utf-8");
747
- await Promise.all(dirs.map(async (dir) => {
748
- const filePath = (0, import_path4.resolve)(dir, relativePath);
749
- await import_fs_extra.default.mkdir((0, import_path4.dirname)(filePath), { recursive: true });
750
- await import_fs_extra.default.writeFile(filePath, content, "utf-8");
751
- }));
809
+ await Promise.all(
810
+ dirs.map(async (dir) => {
811
+ const filePath = (0, import_path4.resolve)(dir, relativePath);
812
+ await import_fs_extra.default.mkdir((0, import_path4.dirname)(filePath), { recursive: true });
813
+ await import_fs_extra.default.writeFile(filePath, content, "utf-8");
814
+ })
815
+ );
752
816
  });
753
817
  }
754
818
  if (typeof afterBuild === "function") {
@@ -756,8 +820,10 @@ export default ${libName}
756
820
  isPromise(result) && await result;
757
821
  }
758
822
  bundleDebug("finish");
759
- logger.info(import_chalk.default.green(`${logPrefix} Declaration files built in ${Date.now() - startTime}ms.
760
- `));
823
+ logger.info(
824
+ import_chalk.default.green(`${logPrefix} Declaration files built in ${Date.now() - startTime}ms.
825
+ `)
826
+ );
761
827
  }
762
828
  };
763
829
  }