bunup 0.8.40 → 0.8.42

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.
@@ -47,10 +47,4 @@ type InjectStylesPluginOptions = Pick<import("lightningcss").TransformOptions<im
47
47
  * @see https://bunup.dev/docs/plugins/inject-styles
48
48
  */
49
49
  declare function injectStyles(options?: InjectStylesPluginOptions): Plugin;
50
- /**
51
- * A plugin that logs a report of the bundle size.
52
- *
53
- * @deprecated This plugin is enabled by default. Bundle size reports are automatically logged without needing to use this plugin.
54
- */
55
- declare function report(): BunupPlugin;
56
- export { shims, report, injectStyles, exports, copy };
50
+ export { shims, injectStyles, exports, copy };
@@ -1,12 +1,380 @@
1
1
  // @bun
2
- import {
3
- BunupPluginError,
4
- cleanPath,
5
- formatFileSize,
6
- isDirectoryPath,
7
- logTable,
8
- logger
9
- } from "../chunk-c1eyecm3.js";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __export = (target, all) => {
19
+ for (var name in all)
20
+ __defProp(target, name, {
21
+ get: all[name],
22
+ enumerable: true,
23
+ configurable: true,
24
+ set: (newValue) => all[name] = () => newValue
25
+ });
26
+ };
27
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
28
+ var __require = import.meta.require;
29
+
30
+ // src/logger.ts
31
+ import pc from "picocolors";
32
+ function setSilent(value) {
33
+ silent = value ?? false;
34
+ }
35
+
36
+ class Logger {
37
+ static instance;
38
+ loggedOnceMessages = new Set;
39
+ constructor() {}
40
+ static getInstance() {
41
+ if (!Logger.instance) {
42
+ Logger.instance = new Logger;
43
+ }
44
+ return Logger.instance;
45
+ }
46
+ dispose() {
47
+ this.loggedOnceMessages.clear();
48
+ }
49
+ shouldLog(options) {
50
+ if (!options?.once) {
51
+ return true;
52
+ }
53
+ if (this.loggedOnceMessages.has(options.once)) {
54
+ return false;
55
+ }
56
+ this.loggedOnceMessages.add(options.once);
57
+ return true;
58
+ }
59
+ getIcon(type, tick) {
60
+ if (tick) {
61
+ return pc.green("\u2713");
62
+ }
63
+ const iconMap = {
64
+ info: pc.blue("i"),
65
+ warn: pc.yellow("!"),
66
+ error: pc.red("\u2715")
67
+ };
68
+ return iconMap[type];
69
+ }
70
+ formatIdentifier(identifier) {
71
+ return identifier ? ` ${pc.bgBlue(pc.black(` ${identifier} `))}` : "";
72
+ }
73
+ formatMessage(options) {
74
+ const {
75
+ message,
76
+ identifier,
77
+ muted = false,
78
+ tick = false,
79
+ type = "info"
80
+ } = options;
81
+ const icon = this.getIcon(type, tick);
82
+ const styledMessage = muted ? pc.dim(message) : type === "error" ? pc.red(message) : type === "warn" ? pc.yellow(message) : message;
83
+ const identifierPart = this.formatIdentifier(identifier);
84
+ return `${icon} ${styledMessage}${identifierPart}`;
85
+ }
86
+ output(message, options = {}, logFn = console.log) {
87
+ if (silent || !this.shouldLog(options)) {
88
+ return;
89
+ }
90
+ if (options.verticalSpace) {
91
+ logFn("");
92
+ }
93
+ logFn(message);
94
+ if (options.verticalSpace) {
95
+ logFn("");
96
+ }
97
+ }
98
+ info(message, options = {}) {
99
+ const formattedMessage = this.formatMessage({
100
+ ...options,
101
+ message,
102
+ type: "info"
103
+ });
104
+ this.output(formattedMessage, options);
105
+ }
106
+ warn(message, options = {}) {
107
+ const formattedMessage = this.formatMessage({
108
+ ...options,
109
+ message,
110
+ type: "warn"
111
+ });
112
+ this.output(formattedMessage, options);
113
+ }
114
+ error(message, options = {}) {
115
+ const formattedMessage = this.formatMessage({
116
+ ...options,
117
+ message,
118
+ type: "error"
119
+ });
120
+ this.output(formattedMessage, options);
121
+ }
122
+ success(message, options = {}) {
123
+ const formattedMessage = this.formatMessage({
124
+ ...options,
125
+ message,
126
+ tick: true
127
+ });
128
+ this.output(formattedMessage, options);
129
+ }
130
+ space() {
131
+ if (!silent) {
132
+ console.log("");
133
+ }
134
+ }
135
+ }
136
+ function logTable(columns, data, footer) {
137
+ if (silent)
138
+ return;
139
+ const widths = {};
140
+ for (const col of columns) {
141
+ const headerLength = col.header.length;
142
+ const dataLengths = data.map((row) => row[col.header]?.length || 0);
143
+ const footerLength = footer ? footer[col.header]?.length || 0 : 0;
144
+ widths[col.header] = Math.max(headerLength, ...dataLengths, footerLength);
145
+ }
146
+ const pad = (str, width, align) => {
147
+ return align === "left" ? str.padEnd(width) : str.padStart(width);
148
+ };
149
+ const headerRow = columns.map((col) => pad(col.header, widths[col.header], col.align)).join(pc.gray(" | "));
150
+ console.log(pc.gray(headerRow));
151
+ const separator = columns.map((col) => "-".repeat(widths[col.header])).join(" | ");
152
+ console.log(pc.gray(separator));
153
+ for (const row of data) {
154
+ const rowStr = columns.map((col) => {
155
+ const value = row[col.header] || "";
156
+ const padded = pad(value, widths[col.header], col.align);
157
+ return col.color ? col.color(padded) : padded;
158
+ }).join(pc.gray(" | "));
159
+ console.log(rowStr);
160
+ }
161
+ console.log(pc.gray(separator));
162
+ if (footer) {
163
+ const footerRow = columns.map((col) => {
164
+ const value = footer[col.header] || "";
165
+ const padded = pad(value, widths[col.header], col.align);
166
+ return padded;
167
+ }).join(pc.gray(" | "));
168
+ console.log(footerRow);
169
+ }
170
+ }
171
+ var silent = false, logger;
172
+ var init_logger = __esm(() => {
173
+ logger = Logger.getInstance();
174
+ });
175
+
176
+ // src/errors.ts
177
+ import pc2 from "picocolors";
178
+ var BunupError, BunupBuildError, BunupDTSBuildError, BunupCLIError, BunupWatchError, BunupPluginError, parseErrorMessage = (error) => {
179
+ if (error instanceof Error) {
180
+ return error.message;
181
+ }
182
+ return String(error);
183
+ }, KNOWN_ERRORS, handleError = (error, context) => {
184
+ const errorMessage = parseErrorMessage(error);
185
+ const contextPrefix = context ? `[${context}] ` : "";
186
+ let errorType = "UNKNOWN ERROR";
187
+ if (error instanceof BunupBuildError) {
188
+ errorType = "BUILD ERROR";
189
+ } else if (error instanceof BunupDTSBuildError) {
190
+ errorType = "DTS ERROR";
191
+ } else if (error instanceof BunupCLIError) {
192
+ errorType = "CLI ERROR";
193
+ } else if (error instanceof BunupWatchError) {
194
+ errorType = "WATCH ERROR";
195
+ } else if (error instanceof BunupPluginError) {
196
+ errorType = "PLUGIN ERROR";
197
+ } else if (error instanceof BunupError) {
198
+ errorType = "BUNUP ERROR";
199
+ }
200
+ const knownError = KNOWN_ERRORS.find((error2) => error2.pattern.test(errorMessage) && (error2.errorType === errorType || !error2.errorType));
201
+ if (!knownError && errorType) {
202
+ console.error(`${pc2.red(errorType)} ${contextPrefix}${errorMessage}`);
203
+ }
204
+ if (knownError) {
205
+ console.log(`
206
+ `);
207
+ knownError.logSolution(errorMessage);
208
+ console.log(`
209
+ `);
210
+ } else {
211
+ console.error(pc2.dim(pc2.white("If you think this is a bug, please open an issue at: ") + pc2.cyan("https://github.com/arshad-yaseen/bunup/issues/new")));
212
+ }
213
+ }, handleErrorAndExit = (error, context) => {
214
+ handleError(error, context);
215
+ process.exit(1);
216
+ };
217
+ var init_errors = __esm(() => {
218
+ init_logger();
219
+ BunupError = class BunupError extends Error {
220
+ constructor(message) {
221
+ super(message);
222
+ this.name = "BunupError";
223
+ }
224
+ };
225
+ BunupBuildError = class BunupBuildError extends BunupError {
226
+ constructor(message) {
227
+ super(message);
228
+ this.name = "BunupBuildError";
229
+ }
230
+ };
231
+ BunupDTSBuildError = class BunupDTSBuildError extends BunupError {
232
+ constructor(message) {
233
+ super(message);
234
+ this.name = "BunupDTSBuildError";
235
+ }
236
+ };
237
+ BunupCLIError = class BunupCLIError extends BunupError {
238
+ constructor(message) {
239
+ super(message);
240
+ this.name = "BunupCLIError";
241
+ }
242
+ };
243
+ BunupWatchError = class BunupWatchError extends BunupError {
244
+ constructor(message) {
245
+ super(message);
246
+ this.name = "BunupWatchError";
247
+ }
248
+ };
249
+ BunupPluginError = class BunupPluginError extends BunupError {
250
+ constructor(message) {
251
+ super(message);
252
+ this.name = "BunupPluginError";
253
+ }
254
+ };
255
+ KNOWN_ERRORS = [
256
+ {
257
+ pattern: /Could not resolve: "bun"/i,
258
+ errorType: "BUILD ERROR",
259
+ logSolution: () => {
260
+ logger.info(pc2.white("You're trying to build a project that uses Bun. ") + pc2.white("Please set the target option to ") + pc2.cyan("`bun`") + pc2.white(`.
261
+ `) + pc2.white("Example: ") + pc2.green("`bunup --target bun`") + pc2.white(" or in config: ") + pc2.green("{ target: 'bun' }"));
262
+ }
263
+ }
264
+ ];
265
+ });
266
+
267
+ // src/utils.ts
268
+ import fsSync from "fs";
269
+ import fs from "fs/promises";
270
+ import path, { normalize } from "path";
271
+ function ensureArray(value) {
272
+ return Array.isArray(value) ? value : [value];
273
+ }
274
+ function getDefaultOutputExtension(format, packageType) {
275
+ switch (format) {
276
+ case "esm":
277
+ return isModulePackage(packageType) ? ".js" : ".mjs";
278
+ case "cjs":
279
+ return isModulePackage(packageType) ? ".cjs" : ".js";
280
+ case "iife":
281
+ return ".global.js";
282
+ }
283
+ }
284
+ function getDefaultDtsExtention(format, packageType) {
285
+ switch (format) {
286
+ case "esm":
287
+ return isModulePackage(packageType) ? ".d.ts" : ".d.mts";
288
+ case "cjs":
289
+ return isModulePackage(packageType) ? ".d.cts" : ".d.ts";
290
+ case "iife":
291
+ return ".global.d.ts";
292
+ }
293
+ }
294
+ function isModulePackage(packageType) {
295
+ return packageType === "module";
296
+ }
297
+ function formatTime(ms) {
298
+ return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`;
299
+ }
300
+ function getPackageDeps(packageJson) {
301
+ if (!packageJson)
302
+ return [];
303
+ return Array.from(new Set([
304
+ ...Object.keys(packageJson.dependencies || {}),
305
+ ...Object.keys(packageJson.peerDependencies || {})
306
+ ]));
307
+ }
308
+ function formatFileSize(bytes) {
309
+ if (bytes === 0)
310
+ return "0 B";
311
+ const units = ["B", "KB", "MB", "GB"];
312
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
313
+ if (i === 0)
314
+ return `${bytes} ${units[i]}`;
315
+ return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
316
+ }
317
+ function getShortFilePath(filePath, maxLength = 3) {
318
+ const fileParts = filePath.split("/");
319
+ const shortPath = fileParts.slice(-maxLength).join("/");
320
+ return shortPath;
321
+ }
322
+ async function cleanOutDir(rootDir, outDir) {
323
+ const outDirPath = path.join(rootDir, outDir);
324
+ try {
325
+ await fs.rm(outDirPath, { recursive: true, force: true });
326
+ } catch (error) {
327
+ throw new BunupBuildError(`Failed to clean output directory: ${error}`);
328
+ }
329
+ await fs.mkdir(outDirPath, { recursive: true });
330
+ }
331
+ function cleanPath(path2) {
332
+ let cleaned = normalize(path2).replace(/\\/g, "/");
333
+ cleaned = cleaned.replace(/^[a-zA-Z]:\//, "");
334
+ cleaned = cleaned.replace(/^\/+/, "");
335
+ cleaned = cleaned.replace(/\/+/g, "/");
336
+ return cleaned;
337
+ }
338
+ function isDirectoryPath(filePath) {
339
+ return path.extname(filePath) === "";
340
+ }
341
+ function pathExistsSync(filePath) {
342
+ try {
343
+ fsSync.accessSync(filePath);
344
+ return true;
345
+ } catch (error) {
346
+ return false;
347
+ }
348
+ }
349
+ function formatListWithAnd(arr) {
350
+ return new Intl.ListFormat("en", {
351
+ style: "long",
352
+ type: "conjunction"
353
+ }).format(arr);
354
+ }
355
+ async function getFilesFromGlobs(patterns, cwd) {
356
+ const includePatterns = patterns.filter((p) => !p.startsWith("!"));
357
+ const excludePatterns = patterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
358
+ const includedFiles = new Set;
359
+ for (const pattern of includePatterns) {
360
+ const glob = new Bun.Glob(pattern);
361
+ for await (const file of glob.scan(cwd)) {
362
+ includedFiles.add(file);
363
+ }
364
+ }
365
+ if (excludePatterns.length > 0) {
366
+ for (const pattern of excludePatterns) {
367
+ const glob = new Bun.Glob(pattern);
368
+ for await (const file of glob.scan(cwd)) {
369
+ includedFiles.delete(file);
370
+ }
371
+ }
372
+ }
373
+ return Array.from(includedFiles);
374
+ }
375
+ var init_utils = __esm(() => {
376
+ init_errors();
377
+ });
10
378
 
11
379
  // src/constants/re.ts
12
380
  var JS_RE = /\.(js|jsx|cjs|mjs)$/;
@@ -71,7 +439,9 @@ const importMetaUrl = pathToFileURL(__filename).href;
71
439
  };
72
440
  }
73
441
  // src/plugins/exports.ts
74
- import path from "path";
442
+ import path2 from "path";
443
+ init_logger();
444
+ init_utils();
75
445
  function exports(options = {}) {
76
446
  return {
77
447
  type: "bunup",
@@ -168,16 +538,17 @@ function formatToExportField(format, dts) {
168
538
  return dts ? "types" : format === "esm" ? "import" : "require";
169
539
  }
170
540
  function removeExtension(filePath) {
171
- const basename = path.basename(filePath);
541
+ const basename = path2.basename(filePath);
172
542
  const firstDotIndex = basename.indexOf(".");
173
543
  if (firstDotIndex === -1) {
174
544
  return filePath;
175
545
  }
176
546
  const nameWithoutExtensions = basename.slice(0, firstDotIndex);
177
- const directory = path.dirname(filePath);
178
- return directory === "." ? nameWithoutExtensions : path.join(directory, nameWithoutExtensions);
547
+ const directory = path2.dirname(filePath);
548
+ return directory === "." ? nameWithoutExtensions : path2.join(directory, nameWithoutExtensions);
179
549
  }
180
550
  // src/plugins/copy.ts
551
+ init_utils();
181
552
  import { join } from "path";
182
553
  import { basename } from "path";
183
554
  function copy(patterns, outPath) {
@@ -202,10 +573,12 @@ function copy(patterns, outPath) {
202
573
  };
203
574
  }
204
575
  // src/plugins/inject-styles.ts
205
- import path2 from "path";
576
+ import path3 from "path";
577
+ init_logger();
206
578
 
207
579
  // src/plugins/utils.ts
208
- import pc from "picocolors";
580
+ init_errors();
581
+ import pc3 from "picocolors";
209
582
  function filterBunupBunPlugins(plugins) {
210
583
  if (!plugins)
211
584
  return [];
@@ -239,7 +612,7 @@ async function getPackageForPlugin(name, pluginName) {
239
612
  try {
240
613
  pkg = await import(name);
241
614
  } catch {
242
- throw new BunupPluginError(`[${pc.cyan(name)}] is required for the ${pluginName} plugin. Please install it with: ${pc.blue(`bun add ${name} --dev`)}`);
615
+ throw new BunupPluginError(`[${pc3.cyan(name)}] is required for the ${pluginName} plugin. Please install it with: ${pc3.blue(`bun add ${name} --dev`)}`);
243
616
  }
244
617
  return pkg;
245
618
  }
@@ -284,7 +657,7 @@ function injectStyles(options) {
284
657
  const source = await Bun.file(args.path).text();
285
658
  const { code, warnings } = lightningcss.transform({
286
659
  ...transformOptions,
287
- filename: path2.basename(args.path),
660
+ filename: path3.basename(args.path),
288
661
  code: Buffer.from(source),
289
662
  minify: transformOptions.minify ?? (build.config.minify === true || typeof build.config.minify === "object" && build.config.minify.whitespace)
290
663
  });
@@ -302,66 +675,9 @@ function injectStyles(options) {
302
675
  }
303
676
  };
304
677
  }
305
- // src/plugins/internal/report.ts
306
- import pc2 from "picocolors";
307
- function report() {
308
- return {
309
- type: "bunup",
310
- name: "report",
311
- hooks: {
312
- onBuildDone: async ({ options, output }) => {
313
- if (options.watch)
314
- return;
315
- const files = await Promise.all(output.files.map(async (file) => {
316
- const name = file.relativePathToRootDir;
317
- const size = Bun.file(file.fullPath).size;
318
- const gzipSize = Bun.gzipSync(new Uint8Array(await Bun.file(file.fullPath).arrayBuffer())).length;
319
- const formattedGzipSize = formatFileSize(gzipSize);
320
- return {
321
- name,
322
- size,
323
- formattedSize: formatFileSize(size),
324
- gzipSize,
325
- formattedGzipSize
326
- };
327
- }));
328
- const totalSize = files.reduce((sum, file) => sum + file.size, 0);
329
- const formattedTotalSize = formatFileSize(totalSize);
330
- const totalGzipSize = files.reduce((sum, file) => sum + (file.gzipSize || 0), 0);
331
- const formattedTotalGzipSize = formatFileSize(totalGzipSize);
332
- const columns = [
333
- { header: "File", align: "left", color: pc2.blue },
334
- { header: "Size", align: "right", color: pc2.green },
335
- {
336
- header: "Gzip",
337
- align: "right",
338
- color: pc2.magenta
339
- }
340
- ];
341
- const data = files.map((file) => {
342
- return {
343
- File: file.name,
344
- Size: file.formattedSize,
345
- Gzip: file.formattedGzipSize
346
- };
347
- });
348
- const footer = {
349
- File: "Total",
350
- Size: formattedTotalSize,
351
- Gzip: formattedTotalGzipSize
352
- };
353
- logger.space();
354
- logTable(columns, data, footer);
355
- logger.space();
356
- }
357
- }
358
- };
359
- }
360
678
  export {
361
679
  shims,
362
- report,
363
680
  injectStyles,
364
681
  exports,
365
682
  copy
366
683
  };
367
- export { filterBunupBunPlugins, filterBunupPlugins, runPluginBuildStartHooks, runPluginBuildDoneHooks, report };