dtsroll 1.7.1 → 1.7.2

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.
@@ -1,905 +0,0 @@
1
- import path from 'node:path';
2
- import fs from 'node:fs/promises';
3
- import { rollup } from 'rollup';
4
- import { dts } from 'rollup-plugin-dts';
5
- import nodeResolve from '@rollup/plugin-node-resolve';
6
- import fs$1 from 'node:fs';
7
- import convert from 'convert-source-map';
8
- import { up } from 'empathic/find';
9
- import { resolveImports } from 'resolve-pkg-maps';
10
- import byteSize from 'byte-size';
11
-
12
- let enabled = true;
13
- const globalVar = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
14
- let supportLevel = 0;
15
- if (globalVar.process && globalVar.process.env && globalVar.process.stdout) {
16
- const { FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, COLORTERM } = globalVar.process.env;
17
- if (NODE_DISABLE_COLORS || NO_COLOR || FORCE_COLOR === "0") {
18
- enabled = false;
19
- } else if (FORCE_COLOR === "1" || FORCE_COLOR === "2" || FORCE_COLOR === "3") {
20
- enabled = true;
21
- } else if (TERM === "dumb") {
22
- enabled = false;
23
- } else if ("CI" in globalVar.process.env && [
24
- "TRAVIS",
25
- "CIRCLECI",
26
- "APPVEYOR",
27
- "GITLAB_CI",
28
- "GITHUB_ACTIONS",
29
- "BUILDKITE",
30
- "DRONE"
31
- ].some((vendor) => vendor in globalVar.process.env)) {
32
- enabled = true;
33
- } else {
34
- enabled = process.stdout.isTTY;
35
- }
36
- if (enabled) {
37
- if (process.platform === "win32") {
38
- supportLevel = 3;
39
- } else {
40
- if (COLORTERM && (COLORTERM === "truecolor" || COLORTERM === "24bit")) {
41
- supportLevel = 3;
42
- } else if (TERM && (TERM.endsWith("-256color") || TERM.endsWith("256"))) {
43
- supportLevel = 2;
44
- } else {
45
- supportLevel = 1;
46
- }
47
- }
48
- }
49
- }
50
- let options = {
51
- enabled,
52
- supportLevel
53
- };
54
- function kolorist(start, end, level = 1) {
55
- const open = `\x1B[${start}m`;
56
- const close = `\x1B[${end}m`;
57
- const regex = new RegExp(`\\x1b\\[${end}m`, "g");
58
- return (str) => {
59
- return options.enabled && options.supportLevel >= level ? open + ("" + str).replace(regex, open) + close : "" + str;
60
- };
61
- }
62
- const bold = kolorist(1, 22);
63
- const dim = kolorist(2, 22);
64
- const underline = kolorist(4, 24);
65
- const black = kolorist(30, 39);
66
- const red = kolorist(31, 39);
67
- const green = kolorist(32, 39);
68
- const yellow = kolorist(33, 39);
69
- const magenta = kolorist(35, 39);
70
- const lightYellow = kolorist(93, 39);
71
- const bgYellow = kolorist(43, 49);
72
-
73
- const cwd = process.cwd();
74
-
75
- const isPath = (filePath) => filePath[0] === "." || path.isAbsolute(filePath);
76
- const normalizePath = (filepath) => filepath.replaceAll("\\", "/");
77
- const getDisplayPath = (fullPath) => {
78
- const relativePath = path.relative(cwd, fullPath);
79
- return normalizePath(
80
- relativePath.length < fullPath.length ? relativePath : fullPath
81
- );
82
- };
83
-
84
- const warningSignUnicode = "\u26A0";
85
- const warningPrefix = yellow("Warning:");
86
- const logOutput = (dtsOutput) => {
87
- console.log(underline("dtsroll"));
88
- const { inputs } = dtsOutput;
89
- const isCliInput = inputs[0]?.[1] === void 0;
90
- console.log(bold(`
91
- \u{1F4E5} Entry points${isCliInput ? "" : " in package.json"}`));
92
- console.log(
93
- inputs.map(([inputFile, inputSource, error]) => {
94
- const logPath2 = getDisplayPath(inputFile);
95
- if (error) {
96
- return ` ${lightYellow(`${warningSignUnicode} ${logPath2} ${dim(error)}`)}`;
97
- }
98
- return ` \u2192 ${green(logPath2)}${inputSource ? ` ${dim(`from ${inputSource}`)}` : ""}`;
99
- }).join("\n")
100
- );
101
- if ("error" in dtsOutput) {
102
- console.error(`${red("Error:")} ${dtsOutput.error}`);
103
- return;
104
- }
105
- const {
106
- outputDirectory,
107
- output: {
108
- entries: outputEntries,
109
- chunks: outputChunks
110
- },
111
- size,
112
- externals
113
- } = dtsOutput;
114
- const logPath = `${getDisplayPath(outputDirectory)}/`;
115
- const logChunk = ({
116
- file,
117
- indent,
118
- bullet,
119
- color
120
- }) => {
121
- const sizeFormatted = byteSize(file.size).toString();
122
- let log = `${indent}${bullet} ${dim(color(logPath))}${color(file.fileName)} ${sizeFormatted}`;
123
- const { moduleIds, moduleToPackage } = file;
124
- log += `
125
- ${moduleIds.sort().map((moduleId, index) => {
126
- const isLast = index === moduleIds.length - 1;
127
- const prefix = `${indent} ${isLast ? "\u2514\u2500 " : "\u251C\u2500 "}`;
128
- const logModuleId = getDisplayPath(moduleId);
129
- const bareSpecifier = moduleToPackage[moduleId];
130
- if (bareSpecifier) {
131
- return `${prefix}${dim(`${magenta(bareSpecifier)} (${logModuleId})`)}`;
132
- }
133
- return `${prefix}${dim(logModuleId)}`;
134
- }).join("\n")}`;
135
- return log;
136
- };
137
- console.log(bold("\n\u{1F4A0} Bundled output"));
138
- console.log(
139
- outputEntries.map((file) => logChunk({
140
- file,
141
- indent: " ",
142
- bullet: "\u25CF",
143
- color: green
144
- })).join("\n\n")
145
- );
146
- if (outputChunks.length > 0) {
147
- console.log(bold("\n Chunks"));
148
- console.log(
149
- outputChunks.map((file) => logChunk({
150
- file,
151
- indent: " ",
152
- bullet: "\u25A0",
153
- color: yellow
154
- })).join("\n\n")
155
- );
156
- }
157
- console.log(bold("\n\u2696\uFE0F Size savings"));
158
- const difference = size.input - size.output;
159
- const direction = difference > 0 ? "decrease" : "increase";
160
- const percentage = (Math.abs(difference / size.input) * 100).toFixed(0);
161
- console.log(` Input source size: ${byteSize(size.input).toString()}`);
162
- console.log(` Bundled output size: ${byteSize(size.output).toString()}${difference === 0 ? "" : ` (${percentage}% ${direction})`}`);
163
- if (externals.length > 0) {
164
- console.log(bold("\n\u{1F4E6} External packages"));
165
- console.log(
166
- externals.map(([packageName, reason, devTypePackage]) => {
167
- let stdout = ` \u2500 ${magenta(packageName)} ${dim(`externalized ${reason}`)}`;
168
- if (devTypePackage) {
169
- stdout += `
170
- ${warningPrefix} ${magenta(devTypePackage)} should not be in devDependencies if ${magenta(packageName)} is externalized`;
171
- }
172
- return stdout;
173
- }).sort().join("\n")
174
- );
175
- }
176
- };
177
-
178
- class DtsrollBuildError extends Error {
179
- id;
180
- importChain;
181
- constructor(message, id, importChain) {
182
- super(message);
183
- this.name = "DtsrollBuildError";
184
- this.id = id;
185
- this.importChain = importChain;
186
- }
187
- }
188
-
189
- const dtsExtensions = [".d.ts", ".d.cts", ".d.mts"];
190
- const isDts = (fileName) => dtsExtensions.some((extension) => fileName.endsWith(extension));
191
-
192
- const isValidIdentifier = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
193
- const reservedWords = /* @__PURE__ */ new Set([
194
- "do",
195
- "if",
196
- "in",
197
- "for",
198
- "int",
199
- "new",
200
- "try",
201
- "var",
202
- "byte",
203
- "case",
204
- "char",
205
- "else",
206
- "enum",
207
- "goto",
208
- "long",
209
- "null",
210
- "this",
211
- "true",
212
- "void",
213
- "with",
214
- "break",
215
- "catch",
216
- "class",
217
- "const",
218
- "false",
219
- "final",
220
- "float",
221
- "short",
222
- "super",
223
- "throw",
224
- "while",
225
- "delete",
226
- "double",
227
- "export",
228
- "import",
229
- "native",
230
- "public",
231
- "return",
232
- "static",
233
- "switch",
234
- "throws",
235
- "typeof",
236
- "boolean",
237
- "default",
238
- "extends",
239
- "finally",
240
- "package",
241
- "private",
242
- "abstract",
243
- "continue",
244
- "debugger",
245
- "function",
246
- "volatile",
247
- "interface",
248
- "protected",
249
- "transient",
250
- "implements",
251
- "instanceof",
252
- "synchronized"
253
- ]);
254
- const propertyNeedsQuotes = (property) => !isValidIdentifier.test(property) || reservedWords.has(property);
255
-
256
- const pathExists = async (filePath) => fs.access(filePath).then(() => true, () => false);
257
-
258
- const typesPrefix = "@types/";
259
- const getOriginalPackageName = (typePackageName) => {
260
- let originalPackageName = typePackageName.slice(typesPrefix.length);
261
- if (originalPackageName.includes("__")) {
262
- originalPackageName = `@${originalPackageName.replace("__", "/")}`;
263
- }
264
- return originalPackageName;
265
- };
266
- const getPackageName = (id) => {
267
- let indexOfSlash = id.indexOf("/");
268
- if (indexOfSlash === -1) {
269
- return id;
270
- }
271
- if (id[0] === "@") {
272
- const secondSlash = id.indexOf("/", indexOfSlash + 1);
273
- if (secondSlash === -1) {
274
- return id;
275
- }
276
- indexOfSlash = secondSlash;
277
- }
278
- return id.slice(0, indexOfSlash);
279
- };
280
-
281
- const getAllFiles = async (directoryPath, dontShortenPath) => {
282
- const directoryFiles = await fs.readdir(directoryPath, { withFileTypes: true });
283
- const fileTree = await Promise.all(
284
- directoryFiles.map(async (entry) => {
285
- const filePath = path.join(directoryPath, entry.name);
286
- if (entry.isDirectory()) {
287
- const files = await getAllFiles(filePath, true);
288
- return dontShortenPath ? files : files.map((file) => `./${normalizePath(path.relative(directoryPath, file))}`);
289
- }
290
- return dontShortenPath ? filePath : `./${normalizePath(path.relative(directoryPath, filePath))}`;
291
- })
292
- );
293
- return fileTree.flat();
294
- };
295
-
296
- const readPackageJson = async (filePath) => {
297
- const packageJsonString = await fs.readFile(filePath, "utf8");
298
- return JSON.parse(packageJsonString);
299
- };
300
- const traverseExports = (exportValue, propertyPath) => {
301
- if (typeof exportValue === "string") {
302
- return [[exportValue, propertyPath]];
303
- }
304
- if (Array.isArray(exportValue)) {
305
- return exportValue.flatMap((value, index) => traverseExports(value, `${propertyPath}[${index}]`));
306
- }
307
- if (typeof exportValue === "object" && exportValue !== null) {
308
- return Object.entries(exportValue).flatMap(([property, value]) => {
309
- const newProperty = propertyNeedsQuotes(property) ? `["${property}"]` : `.${property}`;
310
- return traverseExports(value, propertyPath + newProperty);
311
- });
312
- }
313
- return [];
314
- };
315
- const getDtsEntryPoints = async (packageJson, packageJsonDirectory) => {
316
- const entryPoints = {};
317
- const addEntry = (subpath, from) => {
318
- if (!isDts(subpath)) {
319
- return;
320
- }
321
- const entryPath = path.join(packageJsonDirectory, subpath);
322
- if (!entryPoints[entryPath]) {
323
- entryPoints[entryPath] = from;
324
- }
325
- };
326
- if (packageJson.types) {
327
- addEntry(packageJson.types, "types");
328
- }
329
- if (packageJson.typings) {
330
- addEntry(packageJson.typings, "typings");
331
- }
332
- if (packageJson.exports) {
333
- const subpaths = traverseExports(packageJson.exports, "exports");
334
- let packageFiles;
335
- for (const [subpath, fromProperty] of subpaths) {
336
- if (!subpath.includes("*")) {
337
- addEntry(subpath, fromProperty);
338
- continue;
339
- }
340
- if (!packageFiles) {
341
- packageFiles = await getAllFiles(packageJsonDirectory);
342
- }
343
- const [prefix, suffix] = subpath.split("*", 2);
344
- for (const file of packageFiles) {
345
- if (file.startsWith(prefix) && file.endsWith(suffix)) {
346
- addEntry(file, fromProperty);
347
- }
348
- }
349
- }
350
- }
351
- return entryPoints;
352
- };
353
- const externalizedDependencies = [
354
- "dependencies",
355
- "peerDependencies",
356
- "optionalDependencies"
357
- ];
358
- const getExternals = (packageJson) => {
359
- const external = /* @__PURE__ */ new Map();
360
- for (const dependencyType of externalizedDependencies) {
361
- const dependencyObject = packageJson[dependencyType];
362
- if (dependencyObject) {
363
- const dependencyNames = Object.keys(dependencyObject);
364
- for (const dependencyName of dependencyNames) {
365
- external.set(dependencyName, `by package.json ${dependencyType}`);
366
- }
367
- }
368
- }
369
- return external;
370
- };
371
- const getPackageJson = async (cwd) => {
372
- const packageJsonPath = path.resolve(cwd, "package.json");
373
- const exists = await pathExists(packageJsonPath);
374
- if (!exists) {
375
- return;
376
- }
377
- let packageJson;
378
- try {
379
- packageJson = await readPackageJson(packageJsonPath);
380
- } catch (error) {
381
- throw new Error(`Failed to parse package.json at ${packageJsonPath}: ${error.message}`);
382
- }
383
- return {
384
- getExternals: () => getExternals(packageJson),
385
- getDtsEntryPoints: () => getDtsEntryPoints(packageJson, path.dirname(packageJsonPath)),
386
- devTypePackages: !packageJson.private && packageJson.devDependencies ? Object.fromEntries(
387
- Object.keys(packageJson.devDependencies).filter((dep) => dep.startsWith(typesPrefix)).map((dep) => [getOriginalPackageName(dep), dep])
388
- ) : {}
389
- };
390
- };
391
-
392
- const getCommonDirectory = (filePaths) => {
393
- const splitPaths = filePaths.map((filePath) => filePath.split(path.sep).slice(0, -1));
394
- const commonPath = [];
395
- const [firstPath] = splitPaths;
396
- for (let i = 0; i < firstPath.length; i += 1) {
397
- const segment = firstPath[i];
398
- const segmentIsCommon = splitPaths.every((pathParts) => pathParts[i] === segment);
399
- if (!segmentIsCommon) {
400
- break;
401
- }
402
- commonPath.push(segment);
403
- }
404
- return commonPath.join(path.sep);
405
- };
406
-
407
- const validateInput = async (inputFiles) => {
408
- if (!inputFiles) {
409
- throw new Error("No input files");
410
- }
411
- const isCliInput = Array.isArray(inputFiles);
412
- const inputNormalized = isCliInput ? inputFiles.map((i) => [i]) : Object.entries(inputFiles);
413
- return await Promise.all(inputNormalized.map(
414
- async ([inputFile, inputSource]) => {
415
- if (!isDts(inputFile)) {
416
- return [inputFile, inputSource, "Ignoring non-d.ts input"];
417
- }
418
- const exists = await pathExists(inputFile);
419
- if (!exists) {
420
- return [inputFile, inputSource, "File not found"];
421
- }
422
- return [inputFile, inputSource];
423
- }
424
- ));
425
- };
426
-
427
- const createExternalizePlugin = (configuredExternals) => {
428
- const resolvedBareSpecifiers = /* @__PURE__ */ new Map();
429
- const importPath = /* @__PURE__ */ new Map();
430
- const externalized = /* @__PURE__ */ new Map();
431
- const externalizePlugin = {
432
- name: "externalize",
433
- async resolveId(id, importer, options) {
434
- const packageName = !isPath(id) && getPackageName(id);
435
- if (packageName) {
436
- const externalReason = configuredExternals.get(packageName);
437
- if (externalReason) {
438
- externalized.set(packageName, externalReason);
439
- return {
440
- id,
441
- external: true
442
- };
443
- }
444
- }
445
- const resolved = await this.resolve(id, importer, options);
446
- if (resolved) {
447
- if (packageName) {
448
- resolvedBareSpecifiers.set(resolved.id, id);
449
- }
450
- if (
451
- // Self imports happen
452
- importer && resolved.id !== importer && importPath.get(importer) !== resolved.id
453
- ) {
454
- importPath.set(resolved.id, importer);
455
- }
456
- return resolved;
457
- }
458
- if (packageName) {
459
- externalized.set(packageName, "because unresolvable");
460
- return {
461
- id,
462
- external: true
463
- };
464
- }
465
- }
466
- };
467
- const getPackageEntryPoint = (subpackagePath) => {
468
- let i = 0;
469
- let lastEntry = subpackagePath;
470
- do {
471
- if (resolvedBareSpecifiers.has(lastEntry)) {
472
- return resolvedBareSpecifiers.get(lastEntry);
473
- }
474
- lastEntry = importPath.get(lastEntry);
475
- i += 1;
476
- } while (lastEntry && i < 100);
477
- };
478
- return {
479
- externalizePlugin,
480
- externalized,
481
- getPackageEntryPoint
482
- };
483
- };
484
-
485
- const createImportChainPlugin = () => {
486
- const importerMap = /* @__PURE__ */ new Map();
487
- const plugin = {
488
- name: "import-chain-tracker",
489
- buildStart: () => {
490
- importerMap.clear();
491
- },
492
- async resolveId(source, importer) {
493
- if (!importer) {
494
- return null;
495
- }
496
- const resolved = await this.resolve(source, importer, { skipSelf: true });
497
- if (resolved && !resolved.external && !importerMap.has(resolved.id)) {
498
- importerMap.set(resolved.id, importer);
499
- }
500
- return null;
501
- }
502
- };
503
- const getImportChain = (errorFileId) => {
504
- const chain = [];
505
- let current = errorFileId;
506
- while (current) {
507
- chain.unshift(current);
508
- current = importerMap.get(current);
509
- }
510
- return chain;
511
- };
512
- return {
513
- plugin,
514
- getImportChain
515
- };
516
- };
517
-
518
- const tryReadFile = async (filePath) => {
519
- try {
520
- return await fs$1.promises.readFile(filePath, "utf8");
521
- } catch {
522
- return null;
523
- }
524
- };
525
- const loadSourceMap = async (codePath, code) => {
526
- const adjacentMapPath = `${codePath}.map`;
527
- const adjacentMapContent = await tryReadFile(adjacentMapPath);
528
- if (adjacentMapContent) {
529
- try {
530
- const converter = convert.fromJSON(adjacentMapContent);
531
- return {
532
- map: converter.toObject(),
533
- mapPath: adjacentMapPath
534
- };
535
- } catch {
536
- }
537
- }
538
- try {
539
- const inlineConverter = convert.fromSource(code);
540
- if (inlineConverter) {
541
- return {
542
- map: inlineConverter.toObject(),
543
- mapPath: codePath
544
- };
545
- }
546
- } catch {
547
- }
548
- try {
549
- const regex = new RegExp(convert.mapFileCommentRegex.source);
550
- const commentMatch = regex.exec(code);
551
- const referencedPath = commentMatch?.[1] ?? commentMatch?.[2];
552
- if (!referencedPath) {
553
- return;
554
- }
555
- const mapFilePath = path.join(path.dirname(codePath), referencedPath);
556
- const mapContent = await tryReadFile(mapFilePath);
557
- if (!mapContent) {
558
- return;
559
- }
560
- const converter = convert.fromJSON(mapContent);
561
- return {
562
- map: converter.toObject(),
563
- mapPath: mapFilePath
564
- };
565
- } catch {
566
- }
567
- };
568
- const loadInputSourcemapsPlugin = () => {
569
- const inputSourcemaps = /* @__PURE__ */ new Map();
570
- return {
571
- name: "load-input-sourcemaps",
572
- async load(id) {
573
- const isDts = dtsExtensions.some((extension) => id.endsWith(extension));
574
- if (!isDts) {
575
- return null;
576
- }
577
- const code = await tryReadFile(id);
578
- if (!code) {
579
- return null;
580
- }
581
- const result = await loadSourceMap(id, code);
582
- if (!result) {
583
- return { code };
584
- }
585
- const { map: inputMap, mapPath } = result;
586
- const sourceRoot = path.resolve(path.dirname(mapPath), inputMap.sourceRoot ?? ".");
587
- const sources = inputMap.sources.map(
588
- (source) => path.isAbsolute(source) ? source : path.resolve(sourceRoot, source)
589
- );
590
- const sourcesContentRaw = await Promise.all(
591
- sources.map(
592
- async (source, index) => inputMap.sourcesContent?.[index] ?? tryReadFile(source)
593
- )
594
- );
595
- const sourcesContent = sourcesContentRaw.filter(
596
- (content) => content !== null
597
- );
598
- inputSourcemaps.set(id, {
599
- sources,
600
- sourcesContent
601
- });
602
- return {
603
- code,
604
- map: {
605
- version: inputMap.version,
606
- names: inputMap.names,
607
- sources,
608
- mappings: inputMap.mappings,
609
- ...sourcesContent.length > 0 ? { sourcesContent } : {},
610
- ...inputMap.file ? { file: inputMap.file } : {}
611
- }
612
- };
613
- },
614
- async writeBundle(options, bundle) {
615
- const outputDir = options.dir ?? path.dirname(options.file ?? "");
616
- if (!outputDir) {
617
- return;
618
- }
619
- for (const [fileName, chunk] of Object.entries(bundle)) {
620
- if (chunk.type !== "chunk" || !chunk.map) {
621
- continue;
622
- }
623
- if (chunk.map.sources.length > 0) {
624
- continue;
625
- }
626
- const entryModule = chunk.facadeModuleId;
627
- if (!entryModule) {
628
- continue;
629
- }
630
- const inputSourcemap = inputSourcemaps.get(entryModule);
631
- if (!inputSourcemap || inputSourcemap.sources.length === 0) {
632
- continue;
633
- }
634
- const mapFileName = `${fileName}.map`;
635
- const mapPath = path.join(outputDir, mapFileName);
636
- const outputFileDir = path.dirname(path.join(outputDir, fileName));
637
- const relativeSources = inputSourcemap.sources.map(
638
- (source) => normalizePath(path.relative(outputFileDir, source))
639
- );
640
- const fixedMap = {
641
- ...chunk.map,
642
- sources: relativeSources,
643
- sourcesContent: inputSourcemap.sourcesContent.length > 0 ? inputSourcemap.sourcesContent : void 0
644
- };
645
- await fs$1.promises.writeFile(mapPath, JSON.stringify(fixedMap));
646
- }
647
- }
648
- };
649
- };
650
-
651
- const nodeModules = `${path.sep}node_modules${path.sep}`;
652
- const removeBundledModulesPlugin = (outputDirectory, sizeRef) => {
653
- let deleteFiles = [];
654
- return {
655
- name: "remove-bundled-modules",
656
- transform: {
657
- // Get size of raw code before other transformations
658
- order: "pre",
659
- handler: (code) => ({
660
- meta: {
661
- size: Buffer.byteLength(code)
662
- }
663
- })
664
- },
665
- async generateBundle(options, bundle) {
666
- const modules = Object.values(bundle);
667
- const bundledFiles = Array.from(new Set(modules.flatMap(({ moduleIds }) => moduleIds)));
668
- let totalSize = 0;
669
- for (const moduleId of bundledFiles) {
670
- const moduleInfo = this.getModuleInfo(moduleId);
671
- const size = moduleInfo?.meta?.size;
672
- if (typeof size === "number") {
673
- totalSize += size;
674
- }
675
- }
676
- sizeRef.value = totalSize;
677
- const outputFiles = new Set(modules.map(({ fileName }) => path.join(options.dir, fileName)));
678
- deleteFiles = bundledFiles.filter((moduleId) => moduleId && moduleId.startsWith(outputDirectory) && !moduleId.includes(nodeModules) && !outputFiles.has(moduleId));
679
- },
680
- writeBundle: async () => {
681
- await Promise.all(
682
- deleteFiles.flatMap((moduleId) => [
683
- fs.rm(moduleId),
684
- // Also delete orphaned sourcemap files
685
- fs.rm(`${moduleId}.map`, { force: true })
686
- ])
687
- );
688
- }
689
- };
690
- };
691
-
692
- const packageJsonCache = /* @__PURE__ */ new Map();
693
- const findPackageJsonUp = async (cwd) => {
694
- const packageJsonPath = up("package.json", { cwd });
695
- if (!packageJsonPath) {
696
- return void 0;
697
- }
698
- const packageRoot = path.dirname(packageJsonPath);
699
- let packageJson = packageJsonCache.get(packageRoot);
700
- if (!packageJson) {
701
- try {
702
- const content = await fs.readFile(packageJsonPath, "utf8");
703
- packageJson = JSON.parse(content);
704
- packageJsonCache.set(packageRoot, packageJson);
705
- } catch {
706
- return void 0;
707
- }
708
- }
709
- if (packageJson.imports) {
710
- return {
711
- imports: packageJson.imports,
712
- packageRoot
713
- };
714
- }
715
- };
716
- const resolveSubpathImportsPlugin = () => ({
717
- name: "resolve-subpath-imports",
718
- async resolveId(id, importer) {
719
- if (id[0] !== "#" || !importer) {
720
- return null;
721
- }
722
- const result = await findPackageJsonUp(path.dirname(importer));
723
- if (!result) {
724
- return null;
725
- }
726
- const { imports, packageRoot } = result;
727
- let resolvedPaths;
728
- try {
729
- resolvedPaths = resolveImports(imports, id, ["types", "import"]);
730
- } catch {
731
- return null;
732
- }
733
- if (resolvedPaths.length === 0) {
734
- return null;
735
- }
736
- return this.resolve(
737
- path.join(packageRoot, resolvedPaths[0]),
738
- importer,
739
- { skipSelf: true }
740
- );
741
- }
742
- });
743
-
744
- const createInputMap = (input, outputDirectory) => Object.fromEntries(
745
- input.map((inputFile) => [
746
- inputFile.slice(outputDirectory.length + 1),
747
- inputFile
748
- ])
749
- );
750
- const build = async (input, outputDirectory, externals, mode, conditions, sourcemap) => {
751
- const {
752
- externalizePlugin,
753
- externalized,
754
- getPackageEntryPoint
755
- } = createExternalizePlugin(externals);
756
- const { plugin: importChainPlugin, getImportChain } = createImportChainPlugin();
757
- const sizeRef = {};
758
- const rollupConfig = {
759
- input: createInputMap(input, outputDirectory),
760
- output: {
761
- sourcemap,
762
- dir: outputDirectory,
763
- entryFileNames: "[name]",
764
- chunkFileNames: "_dtsroll-chunks/[hash]-[name].ts"
765
- },
766
- plugins: [
767
- importChainPlugin,
768
- externalizePlugin,
769
- removeBundledModulesPlugin(outputDirectory, sizeRef),
770
- resolveSubpathImportsPlugin(),
771
- // Load existing .d.ts.map files to chain sourcemaps back to original .ts sources
772
- sourcemap && loadInputSourcemapsPlugin(),
773
- nodeResolve({
774
- extensions: [".ts", ...dtsExtensions],
775
- exportConditions: conditions
776
- }),
777
- dts({
778
- respectExternal: true
779
- /**
780
- * Setting a tsconfig or compilerOptions shouldn't be necessary since
781
- * we're dealing with pre-compiled d.ts files
782
- *
783
- * But may be something we need to support if we want to support
784
- * aliases in the future
785
- */
786
- })
787
- ]
788
- };
789
- try {
790
- const rollupBuild = await rollup(rollupConfig);
791
- const built = await rollupBuild[mode](rollupConfig.output);
792
- await rollupBuild.close();
793
- return {
794
- built,
795
- externalized,
796
- getPackageEntryPoint,
797
- sourceSize: sizeRef.value ?? 0
798
- };
799
- } catch (error) {
800
- if (error instanceof Error && "id" in error && typeof error.id === "string") {
801
- throw new DtsrollBuildError(
802
- error.message,
803
- error.id,
804
- getImportChain(error.id)
805
- );
806
- }
807
- throw error;
808
- }
809
- };
810
-
811
- const dtsroll = async ({
812
- cwd = process.cwd(),
813
- inputs,
814
- external,
815
- conditions,
816
- dryRun,
817
- sourcemap
818
- } = {}) => {
819
- const pkgJson = await getPackageJson(cwd);
820
- const externals = pkgJson ? pkgJson.getExternals() : /* @__PURE__ */ new Map();
821
- if (external && external.length > 0) {
822
- if (pkgJson) {
823
- console.warn(`${warningPrefix} The --external flag is only supported when there is no package.json`);
824
- } else {
825
- for (const externalDependency of external) {
826
- externals.set(externalDependency, "by --external flag");
827
- }
828
- }
829
- }
830
- const manualInput = inputs && inputs.length > 0;
831
- const validatedInputs = await validateInput(
832
- manualInput ? inputs.map((file) => path.resolve(file)) : await pkgJson?.getDtsEntryPoints()
833
- );
834
- const inputFiles = validatedInputs.filter((input) => !input[2]).map(([file]) => file);
835
- if (inputFiles.length === 0) {
836
- return {
837
- inputs: validatedInputs,
838
- error: "No input files"
839
- };
840
- }
841
- const outputDirectory = getCommonDirectory(inputFiles);
842
- const {
843
- built,
844
- externalized,
845
- getPackageEntryPoint,
846
- sourceSize
847
- } = await build(
848
- inputFiles,
849
- outputDirectory,
850
- externals,
851
- dryRun ? "generate" : "write",
852
- conditions,
853
- sourcemap
854
- );
855
- let outputSize = 0;
856
- const outputEntries = [];
857
- const outputChunks = [];
858
- const moduleImports = /* @__PURE__ */ new Set();
859
- const chunks = built.output.filter((file) => file.type === "chunk");
860
- for (const file of chunks) {
861
- const size = Buffer.byteLength(file.code);
862
- outputSize += size;
863
- const moduleToPackage = Object.fromEntries(
864
- file.moduleIds.map((moduleId) => [moduleId, getPackageEntryPoint(moduleId)])
865
- );
866
- const chunkWithSize = Object.assign(file, {
867
- size,
868
- moduleToPackage
869
- });
870
- if (chunkWithSize.isEntry) {
871
- outputEntries.push(chunkWithSize);
872
- } else {
873
- outputChunks.push(chunkWithSize);
874
- }
875
- for (const id of file.imports) {
876
- moduleImports.add(getPackageName(id));
877
- }
878
- }
879
- const externalPackages = [];
880
- moduleImports.forEach((importedSpecifier) => {
881
- const reason = externalized.get(importedSpecifier);
882
- if (reason) {
883
- externalPackages.push([
884
- importedSpecifier,
885
- reason,
886
- pkgJson?.devTypePackages?.[importedSpecifier]
887
- ]);
888
- }
889
- });
890
- return {
891
- inputs: validatedInputs,
892
- outputDirectory,
893
- output: {
894
- entries: outputEntries,
895
- chunks: outputChunks
896
- },
897
- size: {
898
- input: sourceSize,
899
- output: outputSize
900
- },
901
- externals: externalPackages
902
- };
903
- };
904
-
905
- export { DtsrollBuildError as D, black as a, bgYellow as b, dtsroll as d, logOutput as l };