bunup 0.8.30 → 0.8.32

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 DELETED
@@ -1,1168 +0,0 @@
1
- // @bun @bun-cjs
2
- (function(exports, require, module, __filename, __dirname) {var __create = Object.create;
3
- var __getProtoOf = Object.getPrototypeOf;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __toESM = (mod, isNodeMode, target) => {
9
- target = mod != null ? __create(__getProtoOf(mod)) : {};
10
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
- for (let key of __getOwnPropNames(mod))
12
- if (!__hasOwnProp.call(to, key))
13
- __defProp(to, key, {
14
- get: () => mod[key],
15
- enumerable: true
16
- });
17
- return to;
18
- };
19
- var __moduleCache = /* @__PURE__ */ new WeakMap;
20
- var __toCommonJS = (from) => {
21
- var entry = __moduleCache.get(from), desc;
22
- if (entry)
23
- return entry;
24
- entry = __defProp({}, "__esModule", { value: true });
25
- if (from && typeof from === "object" || typeof from === "function")
26
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
27
- get: () => from[key],
28
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
29
- }));
30
- __moduleCache.set(from, entry);
31
- return entry;
32
- };
33
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
34
- var __export = (target, all) => {
35
- for (var name in all)
36
- __defProp(target, name, {
37
- get: all[name],
38
- enumerable: true,
39
- configurable: true,
40
- set: (newValue) => all[name] = () => newValue
41
- });
42
- };
43
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
44
-
45
- // node_modules/picocolors/picocolors.js
46
- var require_picocolors = __commonJS((exports2, module2) => {
47
- var p = process || {};
48
- var argv = p.argv || [];
49
- var env = p.env || {};
50
- var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
51
- var formatter = (open, close, replace = open) => (input) => {
52
- let string = "" + input, index = string.indexOf(close, open.length);
53
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
54
- };
55
- var replaceClose = (string, close, replace, index) => {
56
- let result = "", cursor = 0;
57
- do {
58
- result += string.substring(cursor, index) + replace;
59
- cursor = index + close.length;
60
- index = string.indexOf(close, cursor);
61
- } while (~index);
62
- return result + string.substring(cursor);
63
- };
64
- var createColors = (enabled = isColorSupported) => {
65
- let f = enabled ? formatter : () => String;
66
- return {
67
- isColorSupported: enabled,
68
- reset: f("\x1B[0m", "\x1B[0m"),
69
- bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
70
- dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
71
- italic: f("\x1B[3m", "\x1B[23m"),
72
- underline: f("\x1B[4m", "\x1B[24m"),
73
- inverse: f("\x1B[7m", "\x1B[27m"),
74
- hidden: f("\x1B[8m", "\x1B[28m"),
75
- strikethrough: f("\x1B[9m", "\x1B[29m"),
76
- black: f("\x1B[30m", "\x1B[39m"),
77
- red: f("\x1B[31m", "\x1B[39m"),
78
- green: f("\x1B[32m", "\x1B[39m"),
79
- yellow: f("\x1B[33m", "\x1B[39m"),
80
- blue: f("\x1B[34m", "\x1B[39m"),
81
- magenta: f("\x1B[35m", "\x1B[39m"),
82
- cyan: f("\x1B[36m", "\x1B[39m"),
83
- white: f("\x1B[37m", "\x1B[39m"),
84
- gray: f("\x1B[90m", "\x1B[39m"),
85
- bgBlack: f("\x1B[40m", "\x1B[49m"),
86
- bgRed: f("\x1B[41m", "\x1B[49m"),
87
- bgGreen: f("\x1B[42m", "\x1B[49m"),
88
- bgYellow: f("\x1B[43m", "\x1B[49m"),
89
- bgBlue: f("\x1B[44m", "\x1B[49m"),
90
- bgMagenta: f("\x1B[45m", "\x1B[49m"),
91
- bgCyan: f("\x1B[46m", "\x1B[49m"),
92
- bgWhite: f("\x1B[47m", "\x1B[49m"),
93
- blackBright: f("\x1B[90m", "\x1B[39m"),
94
- redBright: f("\x1B[91m", "\x1B[39m"),
95
- greenBright: f("\x1B[92m", "\x1B[39m"),
96
- yellowBright: f("\x1B[93m", "\x1B[39m"),
97
- blueBright: f("\x1B[94m", "\x1B[39m"),
98
- magentaBright: f("\x1B[95m", "\x1B[39m"),
99
- cyanBright: f("\x1B[96m", "\x1B[39m"),
100
- whiteBright: f("\x1B[97m", "\x1B[39m"),
101
- bgBlackBright: f("\x1B[100m", "\x1B[49m"),
102
- bgRedBright: f("\x1B[101m", "\x1B[49m"),
103
- bgGreenBright: f("\x1B[102m", "\x1B[49m"),
104
- bgYellowBright: f("\x1B[103m", "\x1B[49m"),
105
- bgBlueBright: f("\x1B[104m", "\x1B[49m"),
106
- bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
107
- bgCyanBright: f("\x1B[106m", "\x1B[49m"),
108
- bgWhiteBright: f("\x1B[107m", "\x1B[49m")
109
- };
110
- };
111
- module2.exports = createColors();
112
- module2.exports.createColors = createColors;
113
- });
114
-
115
- // src/logger.ts
116
- function setSilent(value) {
117
- silent = value ?? false;
118
- }
119
-
120
- class Logger {
121
- static instance;
122
- loggedOnceMessages = new Set;
123
- MAX_LABEL_LENGTH = 3;
124
- cliColor = import_picocolors.default.blue;
125
- mutedColor = import_picocolors.default.dim;
126
- infoColor = import_picocolors.default.cyan;
127
- warnColor = import_picocolors.default.yellow;
128
- errorColor = import_picocolors.default.red;
129
- defaultColor = import_picocolors.default.white;
130
- progressFgColorMap = {
131
- ESM: import_picocolors.default.yellow,
132
- CJS: import_picocolors.default.green,
133
- IIFE: import_picocolors.default.magenta,
134
- DTS: import_picocolors.default.blue
135
- };
136
- progressIdentifierBgColorMap = {
137
- ESM: import_picocolors.default.bgYellow,
138
- CJS: import_picocolors.default.bgGreen,
139
- IIFE: import_picocolors.default.bgMagenta,
140
- DTS: import_picocolors.default.bgBlue
141
- };
142
- labels = {
143
- cli: "CLI",
144
- info: "INFO",
145
- warn: "WARN",
146
- error: "ERROR"
147
- };
148
- constructor() {}
149
- static getInstance() {
150
- if (!Logger.instance) {
151
- Logger.instance = new Logger;
152
- }
153
- return Logger.instance;
154
- }
155
- dispose() {
156
- this.loggedOnceMessages.clear();
157
- }
158
- shouldLog(options) {
159
- if (!options?.once)
160
- return true;
161
- if (this.loggedOnceMessages.has(options.once))
162
- return false;
163
- this.loggedOnceMessages.add(options.once);
164
- return true;
165
- }
166
- formatMessage({
167
- fgColor,
168
- bgColor,
169
- label,
170
- message,
171
- identifier,
172
- muted
173
- }) {
174
- const padding = " ".repeat(Math.max(0, this.MAX_LABEL_LENGTH - label.length));
175
- const formattedMessage = muted ? this.mutedColor(message) : message;
176
- const identifierPart = identifier ? ` ${bgColor(import_picocolors.default.black(` ${identifier} `))}` : "";
177
- return `${fgColor(label)} ${padding}${formattedMessage}${identifierPart}`;
178
- }
179
- output(message, options = {}, logFn = console.log) {
180
- if (silent || !this.shouldLog(options))
181
- return;
182
- if (options.verticalSpace)
183
- logFn("");
184
- logFn(message);
185
- if (options.verticalSpace)
186
- logFn("");
187
- }
188
- cli(message, options = {}) {
189
- const formattedMessage = this.formatMessage({
190
- fgColor: this.cliColor,
191
- bgColor: import_picocolors.default.bgBlue,
192
- label: this.labels.cli,
193
- message,
194
- identifier: options.identifier,
195
- muted: options.muted
196
- });
197
- this.output(formattedMessage, options);
198
- }
199
- info(message, options = {}) {
200
- const formattedMessage = this.formatMessage({
201
- fgColor: this.infoColor,
202
- bgColor: import_picocolors.default.bgCyan,
203
- label: this.labels.info,
204
- message,
205
- identifier: options.identifier,
206
- muted: options.muted
207
- });
208
- this.output(formattedMessage, options);
209
- }
210
- warn(message, options = {}) {
211
- const formattedMessage = this.formatMessage({
212
- fgColor: this.warnColor,
213
- bgColor: import_picocolors.default.bgYellow,
214
- label: this.labels.warn,
215
- message,
216
- identifier: options.identifier,
217
- muted: options.muted
218
- });
219
- this.output(formattedMessage, options, console.warn);
220
- }
221
- error(message, options = {}) {
222
- const formattedMessage = this.formatMessage({
223
- fgColor: this.errorColor,
224
- bgColor: import_picocolors.default.bgRed,
225
- label: this.labels.error,
226
- message,
227
- identifier: options.identifier,
228
- muted: options.muted
229
- });
230
- this.output(formattedMessage, options, console.error);
231
- }
232
- space() {
233
- if (silent)
234
- return;
235
- console.log("");
236
- }
237
- getProgressFgColor(label) {
238
- for (const [key, colorFn] of Object.entries(this.progressFgColorMap)) {
239
- if (label.includes(key))
240
- return colorFn;
241
- }
242
- return this.defaultColor;
243
- }
244
- getProgressBgColor(label) {
245
- for (const [key, colorFn] of Object.entries(this.progressIdentifierBgColorMap)) {
246
- if (label.includes(key))
247
- return colorFn;
248
- }
249
- return import_picocolors.default.bgWhite;
250
- }
251
- progress(label, message, options = {}) {
252
- const fgColor = this.getProgressFgColor(label);
253
- const bgColor = this.getProgressBgColor(label);
254
- const formattedMessage = this.formatMessage({
255
- fgColor,
256
- bgColor,
257
- label,
258
- message,
259
- identifier: options.identifier,
260
- muted: options.muted
261
- });
262
- this.output(formattedMessage, options);
263
- }
264
- }
265
- function logTable(columns, data, footer) {
266
- if (silent)
267
- return;
268
- const widths = {};
269
- for (const col of columns) {
270
- const headerLength = col.header.length;
271
- const dataLengths = data.map((row) => row[col.header]?.length || 0);
272
- const footerLength = footer ? footer[col.header]?.length || 0 : 0;
273
- widths[col.header] = Math.max(headerLength, ...dataLengths, footerLength);
274
- }
275
- const pad = (str, width, align) => {
276
- return align === "left" ? str.padEnd(width) : str.padStart(width);
277
- };
278
- const headerRow = columns.map((col) => pad(col.header, widths[col.header], col.align)).join(import_picocolors.default.gray(" | "));
279
- console.log(import_picocolors.default.gray(headerRow));
280
- const separator = columns.map((col) => "-".repeat(widths[col.header])).join(" | ");
281
- console.log(import_picocolors.default.gray(separator));
282
- for (const row of data) {
283
- const rowStr = columns.map((col) => {
284
- const value = row[col.header] || "";
285
- const padded = pad(value, widths[col.header], col.align);
286
- return col.color ? col.color(padded) : padded;
287
- }).join(import_picocolors.default.gray(" | "));
288
- console.log(rowStr);
289
- }
290
- console.log(import_picocolors.default.gray(separator));
291
- if (footer) {
292
- const footerRow = columns.map((col) => {
293
- const value = footer[col.header] || "";
294
- const padded = pad(value, widths[col.header], col.align);
295
- return padded;
296
- }).join(import_picocolors.default.gray(" | "));
297
- console.log(footerRow);
298
- }
299
- }
300
- var import_picocolors, silent = false, logger;
301
- var init_logger = __esm(() => {
302
- import_picocolors = __toESM(require_picocolors());
303
- logger = Logger.getInstance();
304
- });
305
-
306
- // src/errors.ts
307
- var import_picocolors2, BunupError, BunupBuildError, BunupDTSBuildError, BunupCLIError, BunupWatchError, BunupPluginError, parseErrorMessage = (error) => {
308
- if (error instanceof Error) {
309
- return error.message;
310
- }
311
- return String(error);
312
- }, KNOWN_ERRORS, handleError = (error, context) => {
313
- const errorMessage = parseErrorMessage(error);
314
- const contextPrefix = context ? `[${context}] ` : "";
315
- let errorType = "UNKNOWN ERROR";
316
- if (error instanceof BunupBuildError) {
317
- errorType = "BUILD ERROR";
318
- } else if (error instanceof BunupDTSBuildError) {
319
- errorType = "DTS ERROR";
320
- } else if (error instanceof BunupCLIError) {
321
- errorType = "CLI ERROR";
322
- } else if (error instanceof BunupWatchError) {
323
- errorType = "WATCH ERROR";
324
- } else if (error instanceof BunupPluginError) {
325
- errorType = "PLUGIN ERROR";
326
- } else if (error instanceof BunupError) {
327
- errorType = "BUNUP ERROR";
328
- }
329
- const knownError = KNOWN_ERRORS.find((error2) => error2.pattern.test(errorMessage) && (error2.errorType === errorType || !error2.errorType));
330
- if (!knownError && errorType) {
331
- console.error(`${import_picocolors2.default.red(errorType)} ${contextPrefix}${errorMessage}`);
332
- }
333
- if (knownError) {
334
- console.log(`
335
- `);
336
- knownError.logSolution(errorMessage);
337
- console.log(`
338
- `);
339
- } else {
340
- console.error(import_picocolors2.default.dim(import_picocolors2.default.white("If you think this is a bug, please open an issue at: ") + import_picocolors2.default.cyan("https://github.com/arshad-yaseen/bunup/issues/new")));
341
- }
342
- }, handleErrorAndExit = (error, context) => {
343
- handleError(error, context);
344
- process.exit(1);
345
- };
346
- var init_errors = __esm(() => {
347
- import_picocolors2 = __toESM(require_picocolors());
348
- init_logger();
349
- BunupError = class BunupError extends Error {
350
- constructor(message) {
351
- super(message);
352
- this.name = "BunupError";
353
- }
354
- };
355
- BunupBuildError = class BunupBuildError extends BunupError {
356
- constructor(message) {
357
- super(message);
358
- this.name = "BunupBuildError";
359
- }
360
- };
361
- BunupDTSBuildError = class BunupDTSBuildError extends BunupError {
362
- constructor(message) {
363
- super(message);
364
- this.name = "BunupDTSBuildError";
365
- }
366
- };
367
- BunupCLIError = class BunupCLIError extends BunupError {
368
- constructor(message) {
369
- super(message);
370
- this.name = "BunupCLIError";
371
- }
372
- };
373
- BunupWatchError = class BunupWatchError extends BunupError {
374
- constructor(message) {
375
- super(message);
376
- this.name = "BunupWatchError";
377
- }
378
- };
379
- BunupPluginError = class BunupPluginError extends BunupError {
380
- constructor(message) {
381
- super(message);
382
- this.name = "BunupPluginError";
383
- }
384
- };
385
- KNOWN_ERRORS = [
386
- {
387
- pattern: /Could not resolve: "bun"/i,
388
- errorType: "BUILD ERROR",
389
- logSolution: () => {
390
- logger.error(import_picocolors2.default.white("You're trying to build a project that uses Bun. ") + import_picocolors2.default.white("Please set the target option to ") + import_picocolors2.default.cyan("`bun`") + import_picocolors2.default.white(`.
391
- `) + import_picocolors2.default.white("Example: ") + import_picocolors2.default.green("`bunup --target bun`") + import_picocolors2.default.white(" or in config: ") + import_picocolors2.default.green("{ target: 'bun' }"));
392
- }
393
- }
394
- ];
395
- });
396
-
397
- // src/loaders.ts
398
- async function processLoadedConfigs(config, cwd, filter) {
399
- return Array.isArray(config) && "root" in config[0] ? config.filter((c) => filter ? filter.includes(c.name) : true).map((c) => ({
400
- rootDir: import_node_path.default.resolve(cwd, c.root),
401
- options: addField(c.config, "name", c.name)
402
- })) : [
403
- {
404
- rootDir: cwd,
405
- options: config
406
- }
407
- ];
408
- }
409
- function addField(objectOrArray, field, value) {
410
- return Array.isArray(objectOrArray) ? objectOrArray.map((o) => ({ ...o, [field]: value })) : { ...objectOrArray, [field]: value };
411
- }
412
- async function loadPackageJson(cwd = process.cwd()) {
413
- const { config, filepath } = await import_coffi.loadConfig({
414
- name: "package",
415
- cwd,
416
- extensions: [".json"]
417
- });
418
- return {
419
- data: config,
420
- path: filepath
421
- };
422
- }
423
- var import_node_path, import_coffi;
424
- var init_loaders = __esm(() => {
425
- import_node_path = __toESM(require("path"));
426
- import_coffi = require("coffi");
427
- });
428
-
429
- // src/utils.ts
430
- function ensureArray(value) {
431
- return Array.isArray(value) ? value : [value];
432
- }
433
- function getDefaultJsOutputExtension(format, packageType) {
434
- switch (format) {
435
- case "esm":
436
- return isModulePackage(packageType) ? ".js" : ".mjs";
437
- case "cjs":
438
- return isModulePackage(packageType) ? ".cjs" : ".js";
439
- case "iife":
440
- return ".global.js";
441
- }
442
- }
443
- function removeExtension(filePath) {
444
- const basename = import_node_path2.default.basename(filePath);
445
- const firstDotIndex = basename.indexOf(".");
446
- if (firstDotIndex === -1) {
447
- return filePath;
448
- }
449
- const nameWithoutExtensions = basename.slice(0, firstDotIndex);
450
- const directory = import_node_path2.default.dirname(filePath);
451
- return directory === "." ? nameWithoutExtensions : import_node_path2.default.join(directory, nameWithoutExtensions);
452
- }
453
- function isModulePackage(packageType) {
454
- return packageType === "module";
455
- }
456
- function formatTime(ms) {
457
- return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`;
458
- }
459
- function getPackageDeps(packageJson) {
460
- if (!packageJson)
461
- return [];
462
- return Array.from(new Set([
463
- ...Object.keys(packageJson.dependencies || {}),
464
- ...Object.keys(packageJson.peerDependencies || {})
465
- ]));
466
- }
467
- function formatFileSize(bytes) {
468
- if (bytes === 0)
469
- return "0 B";
470
- const units = ["B", "KB", "MB", "GB"];
471
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
472
- if (i === 0)
473
- return `${bytes} ${units[i]}`;
474
- return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
475
- }
476
- function getShortFilePath(filePath, maxLength = 3) {
477
- const fileParts = filePath.split("/");
478
- const shortPath = fileParts.slice(-maxLength).join("/");
479
- return shortPath;
480
- }
481
- async function cleanOutDir(rootDir, outDir) {
482
- const outDirPath = import_node_path2.default.join(rootDir, outDir);
483
- try {
484
- await import_promises.default.rm(outDirPath, { recursive: true, force: true });
485
- } catch (error) {
486
- throw new BunupBuildError(`Failed to clean output directory: ${error}`);
487
- }
488
- await import_promises.default.mkdir(outDirPath, { recursive: true });
489
- }
490
- function cleanPath(path3) {
491
- let cleaned = import_node_path2.normalize(path3).replace(/\\/g, "/");
492
- cleaned = cleaned.replace(/^[a-zA-Z]:\//, "");
493
- cleaned = cleaned.replace(/^\/+/, "");
494
- cleaned = cleaned.replace(/\/+/g, "/");
495
- return cleaned;
496
- }
497
- function isDirectoryPath(filePath) {
498
- return import_node_path2.default.extname(filePath) === "";
499
- }
500
- function pathExistsSync(filePath) {
501
- try {
502
- import_node_fs.default.accessSync(filePath);
503
- return true;
504
- } catch (error) {
505
- return false;
506
- }
507
- }
508
- function formatListWithAnd(arr) {
509
- return new Intl.ListFormat("en", {
510
- style: "long",
511
- type: "conjunction"
512
- }).format(arr);
513
- }
514
- async function getFilesFromGlobs(patterns, cwd) {
515
- const includePatterns = patterns.filter((p) => !p.startsWith("!"));
516
- const excludePatterns = patterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
517
- const includedFiles = new Set;
518
- for (const pattern of includePatterns) {
519
- const glob = new Bun.Glob(pattern);
520
- for await (const file of glob.scan(cwd)) {
521
- includedFiles.add(file);
522
- }
523
- }
524
- if (excludePatterns.length > 0) {
525
- for (const pattern of excludePatterns) {
526
- const glob = new Bun.Glob(pattern);
527
- for await (const file of glob.scan(cwd)) {
528
- includedFiles.delete(file);
529
- }
530
- }
531
- }
532
- return Array.from(includedFiles);
533
- }
534
- var import_node_fs, import_promises, import_node_path2;
535
- var init_utils = __esm(() => {
536
- import_node_fs = __toESM(require("fs"));
537
- import_promises = __toESM(require("fs/promises"));
538
- import_node_path2 = __toESM(require("path"));
539
- init_errors();
540
- });
541
-
542
- // src/index.ts
543
- var exports_src = {};
544
- __export(exports_src, {
545
- defineWorkspace: () => defineWorkspace,
546
- defineConfig: () => defineConfig,
547
- build: () => build
548
- });
549
- module.exports = __toCommonJS(exports_src);
550
-
551
- // src/define.ts
552
- function defineConfig(options) {
553
- return options;
554
- }
555
- function defineWorkspace(options) {
556
- return options;
557
- }
558
- // src/build.ts
559
- var import_node_path6 = __toESM(require("path"));
560
- var import_bun_dts = require("bun-dts");
561
- init_errors();
562
- init_loaders();
563
- init_logger();
564
-
565
- // src/constants/re.ts
566
- var JS_RE = /\.(js|jsx|cjs|mjs)$/;
567
- var TS_RE = /\.(ts|tsx|mts|cts)$/;
568
- var DTS_RE = /\.(d\.(ts|mts|cts))$/;
569
- var JS_TS_RE = new RegExp(`${JS_RE.source}|${TS_RE.source}`);
570
- var JS_DTS_RE = new RegExp(`${JS_RE.source}|${DTS_RE.source}`);
571
- var CSS_RE = /\.(css)$/;
572
-
573
- // src/plugins/built-in/node/shims.ts
574
- function shims() {
575
- return {
576
- type: "bun",
577
- name: "shims",
578
- plugin: {
579
- name: "bunup:shims",
580
- setup(build) {
581
- const isNodeCompatibleTarget = build.config.target === "node" || build.config.target === "bun";
582
- const isEsm = build.config.format === "esm";
583
- const isCjs = build.config.format === "cjs";
584
- if (!isNodeCompatibleTarget || !isEsm && !isCjs) {
585
- return;
586
- }
587
- build.config.define = {
588
- ...build.config.define,
589
- ...isCjs && {
590
- "import.meta.url": "importMetaUrl"
591
- }
592
- };
593
- build.onLoad({ filter: JS_TS_RE }, async ({ path: path2 }) => {
594
- const content = await Bun.file(path2).text();
595
- let shimCode = "";
596
- if (isEsm && (/\b__dirname\b/.test(content) || /\b__filename\b/.test(content))) {
597
- shimCode = `import { fileURLToPath } from 'url';
598
- import { dirname } from 'path';
599
-
600
- const __filename = fileURLToPath(import.meta.url);
601
- const __dirname = dirname(__filename);
602
-
603
- `;
604
- }
605
- if (isCjs && /\bimport\.meta\.url\b/.test(content)) {
606
- shimCode = `import { pathToFileURL } from 'url';
607
-
608
- const importMetaUrl = pathToFileURL(__filename).href;
609
-
610
- `;
611
- }
612
- if (!shimCode)
613
- return;
614
- const lines = content.split(`
615
- `);
616
- const firstLine = lines[0];
617
- const restLines = lines.slice(1);
618
- return {
619
- contents: [firstLine, shimCode, ...restLines].join(`
620
- `)
621
- };
622
- });
623
- }
624
- }
625
- };
626
- }
627
- // src/plugins/built-in/productivity/exports.ts
628
- init_logger();
629
- init_utils();
630
- function exports2(options = {}) {
631
- return {
632
- type: "bunup",
633
- name: "exports",
634
- hooks: {
635
- onBuildDone: async ({ output, options: buildOptions, meta }) => {
636
- if (!meta.packageJson.path || !meta.packageJson.data) {
637
- return;
638
- }
639
- try {
640
- const { exportsField, entryPoints } = generateExportsFields(output.files);
641
- const files = Array.isArray(meta.packageJson.data.files) ? [
642
- ...new Set([
643
- ...meta.packageJson.data.files,
644
- buildOptions.outDir
645
- ])
646
- ] : [buildOptions.outDir];
647
- const mergedExports = { ...exportsField };
648
- if (options.extraExports) {
649
- for (const [key, value] of Object.entries(options.extraExports)) {
650
- if (typeof value === "string") {
651
- mergedExports[key] = value;
652
- } else {
653
- const existingExport = mergedExports[key];
654
- if (typeof existingExport === "object" && existingExport !== null) {
655
- mergedExports[key] = {
656
- ...existingExport,
657
- ...value
658
- };
659
- } else {
660
- mergedExports[key] = value;
661
- }
662
- }
663
- }
664
- }
665
- const newPackageJson = {
666
- name: meta.packageJson.data.name,
667
- description: meta.packageJson.data.description,
668
- version: meta.packageJson.data.version,
669
- type: meta.packageJson.data.type,
670
- private: meta.packageJson.data.private,
671
- files,
672
- ...entryPoints,
673
- exports: mergedExports
674
- };
675
- for (const key in meta.packageJson.data) {
676
- if (Object.prototype.hasOwnProperty.call(meta.packageJson.data, key) && !Object.prototype.hasOwnProperty.call(newPackageJson, key)) {
677
- newPackageJson[key] = meta.packageJson.data[key];
678
- }
679
- }
680
- await Bun.write(meta.packageJson.path, JSON.stringify(newPackageJson, null, 2));
681
- logger.cli("Updated package.json with exports");
682
- } catch {
683
- logger.error("Failed to update package.json");
684
- }
685
- }
686
- }
687
- };
688
- }
689
- function generateExportsFields(files) {
690
- const exportsField = {};
691
- const entryPoints = {};
692
- const filteredFiles = filterFiles(files);
693
- for (const file of filteredFiles) {
694
- const exportType = formatToExportField(file.format, file.dts);
695
- const relativePath = `./${cleanPath(file.relativePathToRootDir)}`;
696
- const exportKey = getExportKey(cleanPath(file.relativePathToOutputDir));
697
- exportsField[exportKey] = {
698
- ...exportsField[exportKey],
699
- [exportType]: relativePath
700
- };
701
- }
702
- for (const field of Object.keys(exportsField["."] ?? {})) {
703
- const entryPoint = exportFieldToEntryPoint(field);
704
- entryPoints[entryPoint] = exportsField["."][field];
705
- }
706
- return { exportsField, entryPoints };
707
- }
708
- function filterFiles(files) {
709
- return files.filter((file) => JS_DTS_RE.test(file.fullPath) && file.kind === "entry-point");
710
- }
711
- function getExportKey(relativePathToOutputDir) {
712
- const pathSegments = cleanPath(removeExtension(relativePathToOutputDir)).split("/");
713
- if (pathSegments.length === 1 && pathSegments[0].startsWith("index")) {
714
- return ".";
715
- }
716
- return `./${pathSegments.filter((p) => !p.startsWith("index")).join("/")}`;
717
- }
718
- function exportFieldToEntryPoint(exportField) {
719
- return exportField === "types" ? "types" : exportField === "require" ? "main" : "module";
720
- }
721
- function formatToExportField(format, dts) {
722
- return dts ? "types" : format === "esm" ? "import" : "require";
723
- }
724
- // src/plugins/built-in/css/inject-styles.ts
725
- var import_node_path3 = __toESM(require("path"));
726
- init_logger();
727
-
728
- // src/plugins/utils.ts
729
- var import_picocolors3 = __toESM(require_picocolors());
730
- init_errors();
731
- function filterBunupBunPlugins(plugins) {
732
- if (!plugins)
733
- return [];
734
- return plugins.filter((p) => p.type === "bun");
735
- }
736
- function filterBunupPlugins(plugins) {
737
- if (!plugins)
738
- return [];
739
- return plugins.filter((p) => p.type === "bunup");
740
- }
741
- async function runPluginBuildStartHooks(bunupPlugins, options) {
742
- if (!bunupPlugins)
743
- return;
744
- for (const plugin of bunupPlugins) {
745
- if (plugin.hooks.onBuildStart) {
746
- await plugin.hooks.onBuildStart(options);
747
- }
748
- }
749
- }
750
- async function runPluginBuildDoneHooks(bunupPlugins, options, output, meta) {
751
- if (!bunupPlugins)
752
- return;
753
- for (const plugin of bunupPlugins) {
754
- if (plugin.hooks.onBuildDone) {
755
- await plugin.hooks.onBuildDone({ options, output, meta });
756
- }
757
- }
758
- }
759
- async function getPackageForPlugin(name, pluginName) {
760
- let pkg;
761
- try {
762
- pkg = await import(name);
763
- } catch {
764
- throw new BunupPluginError(`[${import_picocolors3.default.cyan(name)}] is required for the ${pluginName} plugin. Please install it with: ${import_picocolors3.default.blue(`bun add ${name} --dev`)}`);
765
- }
766
- return pkg;
767
- }
768
-
769
- // src/plugins/built-in/css/inject-styles.ts
770
- function injectStyles(options) {
771
- const { inject, ...transformOptions } = options ?? {};
772
- return {
773
- type: "bun",
774
- name: "inject-styles",
775
- plugin: {
776
- name: "bunup:inject-styles",
777
- async setup(build) {
778
- const lightningcss = await getPackageForPlugin("lightningcss", "inject-styles");
779
- build.onResolve({ filter: /^__inject-style$/ }, () => {
780
- return {
781
- path: "__inject-style",
782
- namespace: "__inject-style"
783
- };
784
- });
785
- build.onLoad({ filter: /^__inject-style$/, namespace: "__inject-style" }, () => {
786
- return {
787
- contents: `
788
- export default function injectStyle(css) {
789
- if (!css || typeof document === 'undefined') return
790
-
791
- const head = document.head || document.getElementsByTagName('head')[0]
792
- const style = document.createElement('style')
793
- head.appendChild(style)
794
-
795
- if (style.styleSheet) {
796
- style.styleSheet.cssText = css
797
- } else {
798
- style.appendChild(document.createTextNode(css))
799
- }
800
- }
801
- `,
802
- loader: "js"
803
- };
804
- });
805
- build.onLoad({ filter: CSS_RE }, async (args) => {
806
- const source = await Bun.file(args.path).text();
807
- const { code, warnings } = lightningcss.transform({
808
- ...transformOptions,
809
- filename: import_node_path3.default.basename(args.path),
810
- code: Buffer.from(source),
811
- minify: transformOptions.minify ?? (build.config.minify === true || typeof build.config.minify === "object" && build.config.minify.whitespace)
812
- });
813
- for (const warning of warnings) {
814
- logger.warn(warning.message);
815
- }
816
- const stringifiedCode = JSON.stringify(code.toString());
817
- const js = inject ? await inject(stringifiedCode, args.path) : `import injectStyle from '__inject-style';injectStyle(${stringifiedCode})`;
818
- return {
819
- contents: js,
820
- loader: "js"
821
- };
822
- });
823
- }
824
- }
825
- };
826
- }
827
- // src/plugins/built-in/productivity/copy.ts
828
- var import_node_path4 = require("path");
829
- var import_node_path5 = require("path");
830
- init_utils();
831
- function copy(patterns, outPath) {
832
- return {
833
- type: "bunup",
834
- name: "copy",
835
- hooks: {
836
- onBuildDone: async ({ options, meta }) => {
837
- const destinationPath = outPath || options.outDir;
838
- for (const pattern of patterns) {
839
- const glob = new Bun.Glob(pattern);
840
- for await (const filePath of glob.scan({
841
- cwd: meta.rootDir,
842
- dot: true
843
- })) {
844
- const sourceFile = Bun.file(import_node_path4.join(meta.rootDir, filePath));
845
- await Bun.write(outPath && isDirectoryPath(outPath) ? import_node_path4.join(destinationPath, import_node_path5.basename(filePath)) : destinationPath, sourceFile);
846
- }
847
- }
848
- }
849
- }
850
- };
851
- }
852
- // src/plugins/internal/report.ts
853
- var import_picocolors4 = __toESM(require_picocolors());
854
- init_logger();
855
- init_logger();
856
- init_utils();
857
- function report() {
858
- return {
859
- type: "bunup",
860
- name: "report",
861
- hooks: {
862
- onBuildDone: async ({ options, output }) => {
863
- if (options.watch)
864
- return;
865
- const files = await Promise.all(output.files.map(async (file) => {
866
- const name = file.relativePathToRootDir;
867
- const size = Bun.file(file.fullPath).size;
868
- const gzipSize = Bun.gzipSync(new Uint8Array(await Bun.file(file.fullPath).arrayBuffer())).length;
869
- const formattedGzipSize = formatFileSize(gzipSize);
870
- return {
871
- name,
872
- size,
873
- formattedSize: formatFileSize(size),
874
- gzipSize,
875
- formattedGzipSize
876
- };
877
- }));
878
- const totalSize = files.reduce((sum, file) => sum + file.size, 0);
879
- const formattedTotalSize = formatFileSize(totalSize);
880
- const totalGzipSize = files.reduce((sum, file) => sum + (file.gzipSize || 0), 0);
881
- const formattedTotalGzipSize = formatFileSize(totalGzipSize);
882
- const columns = [
883
- { header: "File", align: "left", color: import_picocolors4.default.blue },
884
- { header: "Size", align: "right", color: import_picocolors4.default.green },
885
- {
886
- header: "Gzip",
887
- align: "right",
888
- color: import_picocolors4.default.magenta
889
- }
890
- ];
891
- const data = files.map((file) => {
892
- return {
893
- File: file.name,
894
- Size: file.formattedSize,
895
- Gzip: file.formattedGzipSize
896
- };
897
- });
898
- const footer = {
899
- File: "Total",
900
- Size: formattedTotalSize,
901
- Gzip: formattedTotalGzipSize
902
- };
903
- logger.space();
904
- logTable(columns, data, footer);
905
- logger.space();
906
- }
907
- }
908
- };
909
- }
910
- // src/plugins/internal/use-client.ts
911
- function useClient() {
912
- return {
913
- type: "bunup",
914
- name: "use-client",
915
- hooks: {
916
- onBuildDone: async ({ output }) => {
917
- for (const file of output.files) {
918
- let text = await Bun.file(file.fullPath).text();
919
- const hasUseClient = text.split(`
920
- `).some((line) => line.trim().startsWith(`"use client";`));
921
- if (hasUseClient) {
922
- text = text.replaceAll(`"use client";`, "");
923
- text = `"use client";
924
- ${text}`;
925
- }
926
- await Bun.write(file.fullPath, text);
927
- }
928
- }
929
- }
930
- };
931
- }
932
-
933
- // src/options.ts
934
- init_utils();
935
- var DEFAULT_OPTIONS = {
936
- entry: [],
937
- format: ["cjs"],
938
- outDir: "dist",
939
- target: "node",
940
- clean: true
941
- };
942
- function createBuildOptions(partialOptions) {
943
- const options = {
944
- ...DEFAULT_OPTIONS,
945
- ...partialOptions
946
- };
947
- return {
948
- ...options,
949
- plugins: [
950
- ...options.plugins?.filter((p) => p.name !== "report") ?? [],
951
- useClient(),
952
- report()
953
- ]
954
- };
955
- }
956
- function getResolvedMinify(options) {
957
- const { minify, minifyWhitespace, minifyIdentifiers, minifySyntax } = options;
958
- const defaultValue = minify === true;
959
- return {
960
- whitespace: minifyWhitespace ?? defaultValue,
961
- identifiers: minifyIdentifiers ?? defaultValue,
962
- syntax: minifySyntax ?? defaultValue
963
- };
964
- }
965
- function getResolvedBytecode(bytecode, format) {
966
- return format === "cjs" ? bytecode : undefined;
967
- }
968
- function getResolvedSourcemap(sourcemap) {
969
- if (sourcemap === true) {
970
- return "inline";
971
- }
972
- return typeof sourcemap === "string" ? sourcemap : undefined;
973
- }
974
- function getResolvedDefine(define, env) {
975
- return {
976
- ...typeof env === "object" && Object.keys(env).reduce((acc, key) => {
977
- const value = JSON.stringify(env[key]);
978
- acc[`process.env.${key}`] = value;
979
- acc[`import.meta.env.${key}`] = value;
980
- return acc;
981
- }, {}),
982
- ...define
983
- };
984
- }
985
- function getResolvedSplitting(splitting, format) {
986
- return splitting === undefined ? format === "esm" : splitting;
987
- }
988
- var DEFAULT_ENTRY_NAMING = "[dir]/[name].[ext]";
989
- function getResolvedNaming(naming, fmt, packageType) {
990
- const resolvedNaming = typeof naming === "object" ? { entry: DEFAULT_ENTRY_NAMING, ...naming } : naming ?? DEFAULT_ENTRY_NAMING;
991
- const replaceExt = (pattern) => pattern.replace(".[ext]", getDefaultJsOutputExtension(fmt, packageType));
992
- if (typeof resolvedNaming === "string") {
993
- return replaceExt(resolvedNaming);
994
- }
995
- return {
996
- ...resolvedNaming,
997
- entry: replaceExt(resolvedNaming.entry)
998
- };
999
- }
1000
- function getResolvedEnv(env) {
1001
- return typeof env === "string" ? env : undefined;
1002
- }
1003
-
1004
- // src/helpers/external.ts
1005
- init_utils();
1006
- function getPackageDepsPatterns(packageJson) {
1007
- return getPackageDeps(packageJson).map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`));
1008
- }
1009
- function matchesPattern(path4, pattern) {
1010
- return typeof pattern === "string" ? pattern === path4 : pattern.test(path4);
1011
- }
1012
- function isExternal(path4, options, packageJson) {
1013
- const packageDepsPatterns = getPackageDepsPatterns(packageJson);
1014
- const matchesExternalPattern = packageDepsPatterns.some((pattern) => pattern.test(path4)) || options.external?.some((pattern) => matchesPattern(path4, pattern));
1015
- const isExcludedFromExternal = options.noExternal?.some((pattern) => matchesPattern(path4, pattern));
1016
- return matchesExternalPattern && !isExcludedFromExternal;
1017
- }
1018
-
1019
- // src/plugins/internal/external-option.ts
1020
- function externalOptionPlugin(options, packageJson) {
1021
- return {
1022
- name: "bunup:external-option-plugin",
1023
- setup(build) {
1024
- build.onResolve({ filter: /.*/ }, (args) => {
1025
- const importPath = args.path;
1026
- if (isExternal(importPath, options, packageJson)) {
1027
- return {
1028
- path: importPath,
1029
- external: true
1030
- };
1031
- }
1032
- return null;
1033
- });
1034
- }
1035
- };
1036
- }
1037
-
1038
- // src/build.ts
1039
- init_utils();
1040
- async function build(partialOptions, rootDir = process.cwd()) {
1041
- const buildOutput = {
1042
- files: []
1043
- };
1044
- const options = createBuildOptions(partialOptions);
1045
- if (!options.entry || options.entry.length === 0 || !options.outDir) {
1046
- throw new BunupBuildError("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");
1047
- }
1048
- if (options.clean) {
1049
- cleanOutDir(rootDir, options.outDir);
1050
- }
1051
- setSilent(options.silent);
1052
- const packageJson = await loadPackageJson(rootDir);
1053
- if (packageJson.data && packageJson.path) {
1054
- logger.cli(`Using ${getShortFilePath(packageJson.path, 2)}`, {
1055
- muted: true,
1056
- identifier: options.name,
1057
- once: `${packageJson.path}:${options.name}`
1058
- });
1059
- }
1060
- const bunupPlugins = filterBunupPlugins(options.plugins);
1061
- await runPluginBuildStartHooks(bunupPlugins, options);
1062
- const packageType = packageJson.data?.type;
1063
- const plugins = [
1064
- externalOptionPlugin(options, packageJson.data),
1065
- ...filterBunupBunPlugins(options.plugins).map((p) => p.plugin)
1066
- ];
1067
- if (options.dts) {
1068
- const { resolve, entry, splitting } = typeof options.dts === "object" ? options.dts : {};
1069
- let entrypoints2;
1070
- if (entry) {
1071
- entrypoints2 = await getFilesFromGlobs(ensureArray(entry), rootDir);
1072
- }
1073
- if (Array.isArray(entrypoints2) && !entrypoints2.length) {
1074
- throw new BunupDTSBuildError("The dts entrypoints you provided do not exist. Please make sure the entrypoints point to valid files.");
1075
- }
1076
- plugins.push(import_bun_dts.dts({
1077
- resolve,
1078
- preferredTsConfigPath: options.preferredTsconfigPath,
1079
- entry: entrypoints2,
1080
- cwd: rootDir,
1081
- splitting,
1082
- onDeclarationsGenerated({ results, buildConfig }) {
1083
- for (const result of results) {
1084
- logger.progress("DTS", `${options.outDir}/${result.outputPath}`, {
1085
- identifier: options.name
1086
- });
1087
- const fullPath = import_node_path6.default.join(rootDir, options.outDir, result.outputPath);
1088
- if (buildConfig.format) {
1089
- buildOutput.files.push({
1090
- fullPath,
1091
- relativePathToRootDir: getRelativePathToRootDir(fullPath, rootDir),
1092
- relativePathToOutputDir: result.outputPath,
1093
- dts: true,
1094
- format: buildConfig.format,
1095
- kind: result.kind
1096
- });
1097
- }
1098
- }
1099
- }
1100
- }));
1101
- }
1102
- const entrypoints = await getFilesFromGlobs(ensureArray(options.entry), rootDir);
1103
- if (!entrypoints.length) {
1104
- throw new BunupBuildError("The entrypoints you provided do not exist. Please make sure the entrypoints point to valid files.");
1105
- }
1106
- const buildPromises = options.format.flatMap(async (fmt) => {
1107
- const result = await Bun.build({
1108
- entrypoints: entrypoints.map((file) => `${rootDir}/${file}`),
1109
- format: fmt,
1110
- naming: getResolvedNaming(options.naming, fmt, packageType),
1111
- splitting: getResolvedSplitting(options.splitting, fmt),
1112
- bytecode: getResolvedBytecode(options.bytecode, fmt),
1113
- define: getResolvedDefine(options.define, options.env),
1114
- minify: getResolvedMinify(options),
1115
- outdir: `${rootDir}/${options.outDir}`,
1116
- target: options.target,
1117
- sourcemap: getResolvedSourcemap(options.sourcemap),
1118
- loader: options.loader,
1119
- drop: options.drop,
1120
- banner: options.banner,
1121
- footer: options.footer,
1122
- publicPath: options.publicPath,
1123
- env: getResolvedEnv(options.env),
1124
- plugins,
1125
- throw: false
1126
- });
1127
- for (const log of result.logs) {
1128
- if (log.level === "error") {
1129
- throw new BunupBuildError(log.message);
1130
- }
1131
- if (log.level === "warning")
1132
- logger.warn(log.message);
1133
- else if (log.level === "info")
1134
- logger.info(log.message);
1135
- }
1136
- for (const file of result.outputs) {
1137
- const relativePathToRootDir = getRelativePathToRootDir(file.path, rootDir);
1138
- if (file.kind === "entry-point") {
1139
- logger.progress(fmt.toUpperCase(), relativePathToRootDir, {
1140
- identifier: options.name
1141
- });
1142
- }
1143
- buildOutput.files.push({
1144
- fullPath: file.path,
1145
- relativePathToRootDir,
1146
- relativePathToOutputDir: getRelativePathToOutputDir(relativePathToRootDir, options.outDir),
1147
- dts: false,
1148
- format: fmt,
1149
- kind: file.kind
1150
- });
1151
- }
1152
- });
1153
- await Promise.all(buildPromises);
1154
- await runPluginBuildDoneHooks(bunupPlugins, options, buildOutput, {
1155
- packageJson,
1156
- rootDir
1157
- });
1158
- if (options.onSuccess) {
1159
- await options.onSuccess(options);
1160
- }
1161
- }
1162
- function getRelativePathToRootDir(filePath, rootDir) {
1163
- return cleanPath(filePath).replace(`${cleanPath(rootDir)}/`, "");
1164
- }
1165
- function getRelativePathToOutputDir(relativePathToRootDir, outDir) {
1166
- return cleanPath(relativePathToRootDir).replace(`${cleanPath(outDir)}/`, "");
1167
- }
1168
- })