vite-plugin-dts 3.1.1 → 3.3.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
@@ -11,127 +11,12 @@ const vueTsc = require('vue-tsc');
11
11
  const debug = require('debug');
12
12
  const kolorist = require('kolorist');
13
13
  const apiExtractor = require('@microsoft/api-extractor');
14
- const Collector_js = require('@microsoft/api-extractor/lib/collector/Collector.js');
15
- const MessageRouter_js = require('@microsoft/api-extractor/lib/collector/MessageRouter.js');
16
- const SourceMapper_js = require('@microsoft/api-extractor/lib/collector/SourceMapper.js');
17
- const DtsRollupGenerator_js = require('@microsoft/api-extractor/lib/generators/DtsRollupGenerator.js');
18
- const nodeCoreLibrary = require('@rushstack/node-core-library');
19
14
 
20
15
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
21
16
 
22
17
  const ts__default = /*#__PURE__*/_interopDefaultCompat(ts);
23
18
  const debug__default = /*#__PURE__*/_interopDefaultCompat(debug);
24
19
 
25
- const dtsRE$1 = /\.d\.tsx?$/;
26
- function rollupDeclarationFiles({
27
- root,
28
- configPath,
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: configPath,
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 svelteRE = /\.svelte$/;
118
- function SvelteResolver() {
119
- return {
120
- name: "svelte",
121
- supports(id) {
122
- return svelteRE.test(id);
123
- },
124
- transform({ id }) {
125
- return [
126
- {
127
- path: `${id}.d.ts`,
128
- content: "export { SvelteComponentTyped as default } from 'svelte';"
129
- }
130
- ];
131
- }
132
- };
133
- }
134
-
135
20
  const windowsSlashRE = /\\+/g;
136
21
  function slash(p) {
137
22
  return p.replace(windowsSlashRE, "/");
@@ -151,6 +36,9 @@ function isRegExp(value) {
151
36
  function isPromise(value) {
152
37
  return !!value && (typeof value === "function" || typeof value === "object") && typeof value.then === "function";
153
38
  }
39
+ async function wrapPromise(maybePromise) {
40
+ return isPromise(maybePromise) ? await maybePromise : maybePromise;
41
+ }
154
42
  function ensureAbsolute(path, root) {
155
43
  return normalizePath(path ? node_path.isAbsolute(path) ? path : resolve(root, path) : root);
156
44
  }
@@ -231,6 +119,161 @@ function removeDirIfEmpty(dir) {
231
119
  }
232
120
  return onlyHasDir;
233
121
  }
122
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
123
+ function base64Encode(number) {
124
+ if (number >= 0 && number < BASE64_ALPHABET.length) {
125
+ return BASE64_ALPHABET[number];
126
+ }
127
+ throw new TypeError("Base64 integer must be between 0 and 63: " + number);
128
+ }
129
+ const VLQ_BASE_SHIFT = 5;
130
+ const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
131
+ const VLQ_BASE_MASK = VLQ_BASE - 1;
132
+ const VLQ_CONTINUATION_BIT = VLQ_BASE;
133
+ function toVLQSigned(number) {
134
+ return number < 0 ? (-number << 1) + 1 : (number << 1) + 0;
135
+ }
136
+ function base64VLQEncode(numbers) {
137
+ let encoded = "";
138
+ for (const number of numbers) {
139
+ let vlq = toVLQSigned(number);
140
+ let digit;
141
+ do {
142
+ digit = vlq & VLQ_BASE_MASK;
143
+ vlq >>>= VLQ_BASE_SHIFT;
144
+ if (vlq > 0) {
145
+ digit |= VLQ_CONTINUATION_BIT;
146
+ }
147
+ encoded += base64Encode(digit);
148
+ } while (vlq > 0);
149
+ }
150
+ return encoded;
151
+ }
152
+ const pkgPathCache = /* @__PURE__ */ new Map();
153
+ function tryGetPkgPath(beginPath) {
154
+ beginPath = normalizePath(beginPath);
155
+ if (pkgPathCache.has(beginPath)) {
156
+ return pkgPathCache.get(beginPath);
157
+ }
158
+ const pkgPath = resolve(beginPath, "package.json");
159
+ if (node_fs.existsSync(pkgPath)) {
160
+ pkgPathCache.set(beginPath, pkgPath);
161
+ return pkgPath;
162
+ }
163
+ const parentDir = normalizePath(node_path.dirname(beginPath));
164
+ if (!parentDir || parentDir === beginPath) {
165
+ pkgPathCache.set(beginPath, void 0);
166
+ return;
167
+ }
168
+ return tryGetPkgPath(parentDir);
169
+ }
170
+
171
+ const dtsRE$1 = /\.d\.tsx?$/;
172
+ function rollupDeclarationFiles({
173
+ root,
174
+ configPath,
175
+ compilerOptions,
176
+ outDir,
177
+ entryPath,
178
+ fileName,
179
+ libFolder,
180
+ bundledPackages
181
+ }) {
182
+ const configObjectFullPath = node_path.resolve(root, "api-extractor.json");
183
+ if (!dtsRE$1.test(fileName)) {
184
+ fileName += ".d.ts";
185
+ }
186
+ const extractorConfig = apiExtractor.ExtractorConfig.prepare({
187
+ configObject: {
188
+ projectFolder: root,
189
+ mainEntryPointFilePath: entryPath,
190
+ bundledPackages,
191
+ compiler: {
192
+ tsconfigFilePath: configPath,
193
+ overrideTsconfig: {
194
+ $schema: "http://json.schemastore.org/tsconfig",
195
+ compilerOptions
196
+ }
197
+ },
198
+ apiReport: {
199
+ enabled: false
200
+ },
201
+ docModel: {
202
+ enabled: false
203
+ },
204
+ dtsRollup: {
205
+ enabled: true,
206
+ publicTrimmedFilePath: node_path.resolve(outDir, fileName)
207
+ },
208
+ tsdocMetadata: {
209
+ enabled: false
210
+ },
211
+ messages: {
212
+ compilerMessageReporting: {
213
+ default: {
214
+ logLevel: "none"
215
+ }
216
+ },
217
+ extractorMessageReporting: {
218
+ default: {
219
+ logLevel: "none"
220
+ }
221
+ }
222
+ }
223
+ },
224
+ configObjectFullPath,
225
+ packageJsonFullPath: tryGetPkgPath(configObjectFullPath)
226
+ });
227
+ const result = apiExtractor.Extractor.invoke(extractorConfig, {
228
+ localBuild: false,
229
+ showVerboseMessages: false,
230
+ showDiagnostics: false,
231
+ typescriptCompilerFolder: libFolder ? node_path.resolve(libFolder) : void 0
232
+ });
233
+ return result.succeeded;
234
+ }
235
+
236
+ const jsonRE = /\.json$/;
237
+ function JsonResolver() {
238
+ return {
239
+ name: "json",
240
+ supports(id) {
241
+ return jsonRE.test(id);
242
+ },
243
+ transform({ id, root, program }) {
244
+ const sourceFile = program.getSourceFile(id);
245
+ if (!sourceFile)
246
+ return [];
247
+ return [
248
+ {
249
+ path: node_path.relative(root, `${id}.d.ts`),
250
+ content: `declare const _default: ${sourceFile.text};
251
+
252
+ export default _default;
253
+ `
254
+ }
255
+ ];
256
+ }
257
+ };
258
+ }
259
+
260
+ const svelteRE = /\.svelte$/;
261
+ function SvelteResolver() {
262
+ return {
263
+ name: "svelte",
264
+ supports(id) {
265
+ return svelteRE.test(id);
266
+ },
267
+ transform({ id, root }) {
268
+ return [
269
+ {
270
+ path: node_path.relative(root, `${id}.d.ts`),
271
+ content: "export { SvelteComponentTyped as default } from 'svelte';\n"
272
+ }
273
+ ];
274
+ }
275
+ };
276
+ }
234
277
 
235
278
  const vueRE = /\.vue$/;
236
279
  function VueResolver() {
@@ -239,19 +282,36 @@ function VueResolver() {
239
282
  supports(id) {
240
283
  return vueRE.test(id);
241
284
  },
242
- transform({ id, root, program, service }) {
243
- let sourceFile = program.getSourceFile(id);
244
- if (!sourceFile && vueRE.test(id)) {
245
- sourceFile = program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
246
- }
285
+ transform({ id, code, program, service }) {
286
+ const sourceFile = program.getSourceFile(id) || program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
247
287
  if (!sourceFile)
248
288
  return [];
249
- return service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
289
+ const outputs = service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
250
290
  return {
251
- path: resolve(root, file.name),
291
+ path: file.name,
252
292
  content: file.text
253
293
  };
254
294
  });
295
+ if (!program.getCompilerOptions().declarationMap)
296
+ return outputs;
297
+ const [beforeScript] = code.split(/\s*<script.*>/);
298
+ const beforeLines = beforeScript.split("\n").length;
299
+ for (const output of outputs) {
300
+ if (output.path.endsWith(".map")) {
301
+ try {
302
+ const sourceMap = JSON.parse(output.content);
303
+ sourceMap.sources = sourceMap.sources.map(
304
+ (source) => source.replace(/\.vue\.ts$/, ".vue")
305
+ );
306
+ if (beforeScript && beforeScript !== code && beforeLines) {
307
+ sourceMap.mappings = `${base64VLQEncode([0, 0, beforeLines, 0])};${sourceMap.mappings}`;
308
+ }
309
+ output.content = JSON.stringify(sourceMap);
310
+ } catch (e) {
311
+ }
312
+ }
313
+ }
314
+ return outputs;
255
315
  }
256
316
  };
257
317
  }
@@ -396,6 +456,7 @@ function dtsPlugin(options = {}) {
396
456
  insertTypesEntry = false,
397
457
  rollupTypes = false,
398
458
  bundledPackages = [],
459
+ pathsToAliases = true,
399
460
  aliasesExclude = [],
400
461
  copyDtsFiles = false,
401
462
  strictOutput = true,
@@ -422,7 +483,12 @@ function dtsPlugin(options = {}) {
422
483
  let filter;
423
484
  let bundled = false;
424
485
  let timeRecord = 0;
425
- const resolvers = parseResolvers([VueResolver(), SvelteResolver(), ...options.resolvers || []]);
486
+ const resolvers = parseResolvers([
487
+ JsonResolver(),
488
+ VueResolver(),
489
+ SvelteResolver(),
490
+ ...options.resolvers || []
491
+ ]);
426
492
  const rootFiles = /* @__PURE__ */ new Set();
427
493
  const outputFiles = /* @__PURE__ */ new Map();
428
494
  return {
@@ -441,7 +507,7 @@ function dtsPlugin(options = {}) {
441
507
  if (aliasesExclude.length > 0) {
442
508
  aliases = aliases.filter(
443
509
  ({ find }) => !aliasesExclude.some(
444
- (alias) => alias && (isRegExp(find) ? find.toString() === alias.toString() : isRegExp(alias) ? find.match(alias)?.[0] : find === alias)
510
+ (aliasExclude) => aliasExclude && (isRegExp(find) ? find.toString() === aliasExclude.toString() : isRegExp(aliasExclude) ? find.match(aliasExclude)?.[0] : find === aliasExclude)
445
511
  )
446
512
  );
447
513
  }
@@ -520,12 +586,28 @@ ${kolorist.cyan(
520
586
  if (!outDirs) {
521
587
  outDirs = options.outDir ? ensureArray(options.outDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(content?.raw.compilerOptions?.outDir || "dist", root)];
522
588
  }
589
+ const { baseUrl, paths } = compilerOptions;
590
+ if (pathsToAliases && baseUrl && paths) {
591
+ const basePath = ensureAbsolute(baseUrl, configPath ? node_path.dirname(configPath) : root);
592
+ const existsFinds = new Set(
593
+ aliases.map((alias) => alias.find).filter((find) => typeof find === "string")
594
+ );
595
+ for (const [findWithAsterisk, replacements] of Object.entries(paths)) {
596
+ const find = findWithAsterisk.replace("/*", "");
597
+ if (!replacements.length || existsFinds.has(find))
598
+ continue;
599
+ aliases.push({
600
+ find,
601
+ replacement: ensureAbsolute(replacements[0].replace("/*", ""), basePath)
602
+ });
603
+ }
604
+ }
523
605
  include = ensureArray(options.include ?? content?.raw.include ?? "**/*").map(normalizeGlob);
524
606
  exclude = ensureArray(options.exclude ?? content?.raw.exclude ?? "node_modules/**").map(
525
607
  normalizeGlob
526
608
  );
527
609
  filter = pluginutils.createFilter(include, exclude, { resolve: root });
528
- const rootNames = Object.values(entries).concat(content?.fileNames.filter(filter) || []).map(normalizePath);
610
+ const rootNames = Object.values(entries).map((entry) => ensureAbsolute(entry, root)).concat(content?.fileNames.filter(filter) || []).map(normalizePath);
529
611
  host = ts__default.createCompilerHost(compilerOptions, true);
530
612
  program = vueTsc.createProgram({ host, rootNames, options: compilerOptions });
531
613
  libName = libName || "_default";
@@ -544,8 +626,7 @@ ${kolorist.cyan(
544
626
  logger.error(ts__default.formatDiagnostics(diagnostics, host));
545
627
  }
546
628
  if (typeof afterDiagnostic === "function") {
547
- const result = afterDiagnostic(diagnostics);
548
- isPromise(result) && await result;
629
+ await wrapPromise(afterDiagnostic(diagnostics));
549
630
  }
550
631
  rootNames.forEach((file) => {
551
632
  this.addWatchFile(file);
@@ -556,30 +637,39 @@ ${kolorist.cyan(
556
637
  },
557
638
  async transform(code, id) {
558
639
  let resolver;
559
- id = normalizePath(id).split("?")[0];
640
+ id = normalizePath(id);
560
641
  if (!host || !program || !filter(id) || !(resolver = resolvers.find((r) => r.supports(id))) && !tjsRE.test(id)) {
561
642
  return;
562
643
  }
563
644
  const startTime = Date.now();
645
+ const outDir = outDirs[0];
564
646
  const service = program.__vue.languageService;
647
+ id = id.split("?")[0];
565
648
  rootFiles.delete(id);
566
649
  if (resolver) {
567
650
  const result = await resolver.transform({
568
651
  id,
569
652
  code,
570
653
  root: publicRoot,
654
+ outDir,
571
655
  host,
572
656
  program,
573
657
  service
574
658
  });
575
659
  for (const { path, content } of result) {
576
- outputFiles.set(ensureAbsolute(path, publicRoot), content);
660
+ outputFiles.set(
661
+ resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(path, outDir))),
662
+ content
663
+ );
577
664
  }
578
665
  } else {
579
666
  const sourceFile = program.getSourceFile(id);
580
667
  if (sourceFile) {
581
668
  for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
582
- outputFiles.set(resolve(publicRoot, outputFile.name), outputFile.text);
669
+ outputFiles.set(
670
+ resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(outputFile.name, outDir))),
671
+ outputFile.text
672
+ );
583
673
  }
584
674
  }
585
675
  }
@@ -589,11 +679,12 @@ ${kolorist.cyan(
589
679
  timeRecord += Date.now() - startTime;
590
680
  },
591
681
  watchChange(id) {
592
- id = normalizePath(id).split("?")[0];
682
+ id = normalizePath(id);
593
683
  if (!host || !program || !filter(id) || !resolvers.find((r) => r.supports(id)) && !tjsRE.test(id)) {
594
684
  return;
595
685
  }
596
- const sourceFile = host.getSourceFile(normalizePath(id), ts__default.ScriptTarget.ESNext);
686
+ id = id.split("?")[0];
687
+ const sourceFile = host.getSourceFile(id, ts__default.ScriptTarget.ESNext);
597
688
  if (sourceFile) {
598
689
  rootFiles.add(sourceFile.fileName);
599
690
  program.__vue.projectVersion++;
@@ -611,7 +702,16 @@ ${logPrefix} Start generate declaration files...`));
611
702
  const startTime = Date.now();
612
703
  const outDir = outDirs[0];
613
704
  const emittedFiles = /* @__PURE__ */ new Map();
614
- const writeOutput = async (path, content, outDir2) => {
705
+ const writeOutput = async (path, content, outDir2, record = true) => {
706
+ if (typeof beforeWriteFile === "function") {
707
+ const result = await wrapPromise(beforeWriteFile(path, content));
708
+ if (result === false)
709
+ return;
710
+ if (result) {
711
+ path = result.filePath || path;
712
+ content = result.content ?? content;
713
+ }
714
+ }
615
715
  path = normalizePath(path);
616
716
  const dir = normalizePath(node_path.dirname(path));
617
717
  if (strictOutput && !dir.startsWith(normalizePath(outDir2))) {
@@ -622,7 +722,7 @@ ${logPrefix} Start generate declaration files...`));
622
722
  await promises.mkdir(dir, { recursive: true });
623
723
  }
624
724
  await promises.writeFile(path, content, "utf-8");
625
- emittedFiles.set(path, content);
725
+ record && emittedFiles.set(path, content);
626
726
  };
627
727
  const service = program.__vue.languageService;
628
728
  const sourceFiles = program.getSourceFiles();
@@ -634,7 +734,10 @@ ${logPrefix} Start generate declaration files...`));
634
734
  }
635
735
  if (rootFiles.has(sourceFile.fileName)) {
636
736
  for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
637
- outputFiles.set(resolve(publicRoot, outputFile.name), outputFile.text);
737
+ outputFiles.set(
738
+ resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(outputFile.name, outDir))),
739
+ outputFile.text
740
+ );
638
741
  }
639
742
  rootFiles.delete(sourceFile.fileName);
640
743
  }
@@ -645,6 +748,7 @@ ${logPrefix} Start generate declaration files...`));
645
748
  Array.from(outputFiles.entries()),
646
749
  async ([path, content]) => {
647
750
  const isMapFile = path.endsWith(".map");
751
+ const baseDir = node_path.dirname(path);
648
752
  if (!isMapFile && content) {
649
753
  content = clearPureImport ? removePureImport(content) : content;
650
754
  content = transformAliasImport(path, content, aliases, aliasesExclude);
@@ -655,13 +759,15 @@ ${logPrefix} Start generate declaration files...`));
655
759
  node_path.relative(entryRoot, cleanVueFileName ? path.replace(".vue.d.ts", ".d.ts") : path)
656
760
  );
657
761
  content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
658
- if (typeof beforeWriteFile === "function") {
659
- const result = beforeWriteFile(path, content);
660
- if (result === false)
661
- return;
662
- if (result && isNativeObj(result)) {
663
- path = result.filePath || path;
664
- content = result.content ?? content;
762
+ if (isMapFile) {
763
+ try {
764
+ const sourceMap = JSON.parse(content);
765
+ sourceMap.sources = sourceMap.sources.map((source) => {
766
+ return normalizePath(node_path.relative(node_path.dirname(path), resolve(baseDir, source)));
767
+ });
768
+ content = JSON.stringify(sourceMap);
769
+ } catch (e) {
770
+ logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${path}`);
665
771
  }
666
772
  }
667
773
  await writeOutput(path, content, outDir);
@@ -669,14 +775,18 @@ ${logPrefix} Start generate declaration files...`));
669
775
  );
670
776
  bundleDebug("write output");
671
777
  if (insertTypesEntry || rollupTypes) {
672
- const pkgPath = resolve(root, "package.json");
673
- const pkg = node_fs.existsSync(pkgPath) ? JSON.parse(await promises.readFile(pkgPath, "utf-8")) : {};
778
+ const pkgPath = tryGetPkgPath(root);
779
+ let pkg;
780
+ try {
781
+ pkg = pkgPath && node_fs.existsSync(pkgPath) ? JSON.parse(await promises.readFile(pkgPath, "utf-8")) : {};
782
+ } catch (e) {
783
+ }
674
784
  const entryNames = Object.keys(entries);
675
785
  const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings || (pkg.exports?.["."] || pkg.exports?.["./"])?.types;
676
786
  const multiple = entryNames.length > 1;
677
787
  const typesPath = types ? resolve(root, types) : resolve(outDir, indexName);
678
788
  for (const name of entryNames) {
679
- let path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
789
+ const path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
680
790
  if (node_fs.existsSync(path))
681
791
  continue;
682
792
  const index = resolve(
@@ -696,15 +806,6 @@ export default ${libName}
696
806
  `;
697
807
  }
698
808
  }
699
- if (typeof beforeWriteFile === "function") {
700
- const result = beforeWriteFile(path, content);
701
- if (result === false)
702
- return;
703
- if (result && isNativeObj(result)) {
704
- path = result.filePath ?? path;
705
- content = result.content ?? content;
706
- }
707
- }
708
809
  await writeOutput(path, content, outDir);
709
810
  }
710
811
  bundleDebug("insert index");
@@ -764,15 +865,29 @@ export default ${libName}
764
865
  await runParallel(node_os.cpus().length, Array.from(emittedFiles), async ([wroteFile, content]) => {
765
866
  const relativePath = node_path.relative(outDir, wroteFile);
766
867
  await Promise.all(
767
- extraOutDirs.map(async (outDir2) => {
768
- await writeOutput(resolve(outDir2, relativePath), content, outDir2);
868
+ extraOutDirs.map(async (targetOutDir) => {
869
+ const path = resolve(targetOutDir, relativePath);
870
+ if (wroteFile.endsWith(".map")) {
871
+ const relativeOutDir = node_path.relative(outDir, targetOutDir);
872
+ if (relativeOutDir) {
873
+ try {
874
+ const sourceMap = JSON.parse(content);
875
+ sourceMap.sources = sourceMap.sources.map((source) => {
876
+ return normalizePath(node_path.relative(relativeOutDir, source));
877
+ });
878
+ content = JSON.stringify(sourceMap);
879
+ } catch (e) {
880
+ logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${path}`);
881
+ }
882
+ }
883
+ }
884
+ await writeOutput(path, content, targetOutDir, false);
769
885
  })
770
886
  );
771
887
  });
772
888
  }
773
889
  if (typeof afterBuild === "function") {
774
- const result = afterBuild();
775
- isPromise(result) && await result;
890
+ await wrapPromise(afterBuild());
776
891
  }
777
892
  bundleDebug("finish");
778
893
  logger.info(
package/dist/index.d.ts CHANGED
@@ -16,11 +16,14 @@ interface Resolver {
16
16
  supports: (id: string) => void | boolean;
17
17
  /**
18
18
  * Transform source to declaration files
19
+ *
20
+ * Note that the path of the returns should base on `outDir`, or relative path to `root`
19
21
  */
20
22
  transform: (payload: {
21
23
  id: string;
22
24
  code: string;
23
25
  root: string;
26
+ outDir: string;
24
27
  host: ts.CompilerHost;
25
28
  program: ts.Program;
26
29
  service: ts.LanguageService;
@@ -80,6 +83,15 @@ interface PluginOptions {
80
83
  * @default []
81
84
  */
82
85
  resolvers?: Resolver[];
86
+ /**
87
+ * Parsing `paths` of tsconfig.json to aliases
88
+ *
89
+ * Note that these aliases only use for declaration files
90
+ *
91
+ * @default true
92
+ * @remarks Only use first replacement of each path
93
+ */
94
+ pathsToAliases?: boolean;
83
95
  /**
84
96
  * Set which paths should be excluded when transforming aliases
85
97
  *
@@ -169,14 +181,14 @@ interface PluginOptions {
169
181
  *
170
182
  * This allows you to transform the path or content
171
183
  *
172
- * The file will be skipped when the return value `false`
184
+ * The file will be skipped when the return value `false` or `Promise<false>`
173
185
  *
174
186
  * @default () => {}
175
187
  */
176
- beforeWriteFile?: (filePath: string, content: string) => void | false | {
188
+ beforeWriteFile?: (filePath: string, content: string) => MaybePromise<void | false | {
177
189
  filePath?: string;
178
190
  content?: string;
179
- };
191
+ }>;
180
192
  /**
181
193
  * Hook called after all declaration files are written
182
194
  *