bunup 0.8.28 → 0.8.29

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/plugins.js DELETED
@@ -1,610 +0,0 @@
1
- // @bun
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 __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
-
20
- // node_modules/picocolors/picocolors.js
21
- var require_picocolors = __commonJS((exports, module) => {
22
- var p = process || {};
23
- var argv = p.argv || [];
24
- var env = p.env || {};
25
- 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);
26
- var formatter = (open, close, replace = open) => (input) => {
27
- let string = "" + input, index = string.indexOf(close, open.length);
28
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
29
- };
30
- var replaceClose = (string, close, replace, index) => {
31
- let result = "", cursor = 0;
32
- do {
33
- result += string.substring(cursor, index) + replace;
34
- cursor = index + close.length;
35
- index = string.indexOf(close, cursor);
36
- } while (~index);
37
- return result + string.substring(cursor);
38
- };
39
- var createColors = (enabled = isColorSupported) => {
40
- let f = enabled ? formatter : () => String;
41
- return {
42
- isColorSupported: enabled,
43
- reset: f("\x1B[0m", "\x1B[0m"),
44
- bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
45
- dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
46
- italic: f("\x1B[3m", "\x1B[23m"),
47
- underline: f("\x1B[4m", "\x1B[24m"),
48
- inverse: f("\x1B[7m", "\x1B[27m"),
49
- hidden: f("\x1B[8m", "\x1B[28m"),
50
- strikethrough: f("\x1B[9m", "\x1B[29m"),
51
- black: f("\x1B[30m", "\x1B[39m"),
52
- red: f("\x1B[31m", "\x1B[39m"),
53
- green: f("\x1B[32m", "\x1B[39m"),
54
- yellow: f("\x1B[33m", "\x1B[39m"),
55
- blue: f("\x1B[34m", "\x1B[39m"),
56
- magenta: f("\x1B[35m", "\x1B[39m"),
57
- cyan: f("\x1B[36m", "\x1B[39m"),
58
- white: f("\x1B[37m", "\x1B[39m"),
59
- gray: f("\x1B[90m", "\x1B[39m"),
60
- bgBlack: f("\x1B[40m", "\x1B[49m"),
61
- bgRed: f("\x1B[41m", "\x1B[49m"),
62
- bgGreen: f("\x1B[42m", "\x1B[49m"),
63
- bgYellow: f("\x1B[43m", "\x1B[49m"),
64
- bgBlue: f("\x1B[44m", "\x1B[49m"),
65
- bgMagenta: f("\x1B[45m", "\x1B[49m"),
66
- bgCyan: f("\x1B[46m", "\x1B[49m"),
67
- bgWhite: f("\x1B[47m", "\x1B[49m"),
68
- blackBright: f("\x1B[90m", "\x1B[39m"),
69
- redBright: f("\x1B[91m", "\x1B[39m"),
70
- greenBright: f("\x1B[92m", "\x1B[39m"),
71
- yellowBright: f("\x1B[93m", "\x1B[39m"),
72
- blueBright: f("\x1B[94m", "\x1B[39m"),
73
- magentaBright: f("\x1B[95m", "\x1B[39m"),
74
- cyanBright: f("\x1B[96m", "\x1B[39m"),
75
- whiteBright: f("\x1B[97m", "\x1B[39m"),
76
- bgBlackBright: f("\x1B[100m", "\x1B[49m"),
77
- bgRedBright: f("\x1B[101m", "\x1B[49m"),
78
- bgGreenBright: f("\x1B[102m", "\x1B[49m"),
79
- bgYellowBright: f("\x1B[103m", "\x1B[49m"),
80
- bgBlueBright: f("\x1B[104m", "\x1B[49m"),
81
- bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
82
- bgCyanBright: f("\x1B[106m", "\x1B[49m"),
83
- bgWhiteBright: f("\x1B[107m", "\x1B[49m")
84
- };
85
- };
86
- module.exports = createColors();
87
- module.exports.createColors = createColors;
88
- });
89
-
90
- // src/constants/re.ts
91
- var JS_RE = /\.(js|jsx|cjs|mjs)$/;
92
- var TS_RE = /\.(ts|tsx|mts|cts)$/;
93
- var DTS_RE = /\.(d\.(ts|mts|cts))$/;
94
- var JS_TS_RE = new RegExp(`${JS_RE.source}|${TS_RE.source}`);
95
- var JS_DTS_RE = new RegExp(`${JS_RE.source}|${DTS_RE.source}`);
96
- var CSS_RE = /\.(css)$/;
97
-
98
- // src/plugins/built-in/node/shims.ts
99
- function shims() {
100
- return {
101
- type: "bun",
102
- name: "shims",
103
- plugin: {
104
- name: "bunup:shims",
105
- setup(build) {
106
- const isNodeCompatibleTarget = build.config.target === "node" || build.config.target === "bun";
107
- const isEsm = build.config.format === "esm";
108
- const isCjs = build.config.format === "cjs";
109
- if (!isNodeCompatibleTarget || !isEsm && !isCjs) {
110
- return;
111
- }
112
- build.config.define = {
113
- ...build.config.define,
114
- ...isCjs && {
115
- "import.meta.url": "importMetaUrl"
116
- }
117
- };
118
- build.onLoad({ filter: JS_TS_RE }, async ({ path }) => {
119
- const content = await Bun.file(path).text();
120
- let shimCode = "";
121
- if (isEsm && (/\b__dirname\b/.test(content) || /\b__filename\b/.test(content))) {
122
- shimCode = `import { fileURLToPath } from 'url';
123
- import { dirname } from 'path';
124
-
125
- const __filename = fileURLToPath(import.meta.url);
126
- const __dirname = dirname(__filename);
127
-
128
- `;
129
- }
130
- if (isCjs && /\bimport\.meta\.url\b/.test(content)) {
131
- shimCode = `import { pathToFileURL } from 'url';
132
-
133
- const importMetaUrl = pathToFileURL(__filename).href;
134
-
135
- `;
136
- }
137
- if (!shimCode)
138
- return;
139
- const lines = content.split(`
140
- `);
141
- const firstLine = lines[0];
142
- const restLines = lines.slice(1);
143
- return {
144
- contents: [firstLine, shimCode, ...restLines].join(`
145
- `)
146
- };
147
- });
148
- }
149
- }
150
- };
151
- }
152
- // src/logger.ts
153
- var import_picocolors = __toESM(require_picocolors(), 1);
154
- var silent = false;
155
- class Logger {
156
- static instance;
157
- loggedOnceMessages = new Set;
158
- MAX_LABEL_LENGTH = 3;
159
- cliColor = import_picocolors.default.blue;
160
- mutedColor = import_picocolors.default.dim;
161
- infoColor = import_picocolors.default.cyan;
162
- warnColor = import_picocolors.default.yellow;
163
- errorColor = import_picocolors.default.red;
164
- defaultColor = import_picocolors.default.white;
165
- progressFgColorMap = {
166
- ESM: import_picocolors.default.yellow,
167
- CJS: import_picocolors.default.green,
168
- IIFE: import_picocolors.default.magenta,
169
- DTS: import_picocolors.default.blue
170
- };
171
- progressIdentifierBgColorMap = {
172
- ESM: import_picocolors.default.bgYellow,
173
- CJS: import_picocolors.default.bgGreen,
174
- IIFE: import_picocolors.default.bgMagenta,
175
- DTS: import_picocolors.default.bgBlue
176
- };
177
- labels = {
178
- cli: "CLI",
179
- info: "INFO",
180
- warn: "WARN",
181
- error: "ERROR"
182
- };
183
- constructor() {}
184
- static getInstance() {
185
- if (!Logger.instance) {
186
- Logger.instance = new Logger;
187
- }
188
- return Logger.instance;
189
- }
190
- dispose() {
191
- this.loggedOnceMessages.clear();
192
- }
193
- shouldLog(options) {
194
- if (!options?.once)
195
- return true;
196
- if (this.loggedOnceMessages.has(options.once))
197
- return false;
198
- this.loggedOnceMessages.add(options.once);
199
- return true;
200
- }
201
- formatMessage({
202
- fgColor,
203
- bgColor,
204
- label,
205
- message,
206
- identifier,
207
- muted
208
- }) {
209
- const padding = " ".repeat(Math.max(0, this.MAX_LABEL_LENGTH - label.length));
210
- const formattedMessage = muted ? this.mutedColor(message) : message;
211
- const identifierPart = identifier ? ` ${bgColor(import_picocolors.default.black(` ${identifier} `))}` : "";
212
- return `${fgColor(label)} ${padding}${formattedMessage}${identifierPart}`;
213
- }
214
- output(message, options = {}, logFn = console.log) {
215
- if (silent || !this.shouldLog(options))
216
- return;
217
- if (options.verticalSpace)
218
- logFn("");
219
- logFn(message);
220
- if (options.verticalSpace)
221
- logFn("");
222
- }
223
- cli(message, options = {}) {
224
- const formattedMessage = this.formatMessage({
225
- fgColor: this.cliColor,
226
- bgColor: import_picocolors.default.bgBlue,
227
- label: this.labels.cli,
228
- message,
229
- identifier: options.identifier,
230
- muted: options.muted
231
- });
232
- this.output(formattedMessage, options);
233
- }
234
- info(message, options = {}) {
235
- const formattedMessage = this.formatMessage({
236
- fgColor: this.infoColor,
237
- bgColor: import_picocolors.default.bgCyan,
238
- label: this.labels.info,
239
- message,
240
- identifier: options.identifier,
241
- muted: options.muted
242
- });
243
- this.output(formattedMessage, options);
244
- }
245
- warn(message, options = {}) {
246
- const formattedMessage = this.formatMessage({
247
- fgColor: this.warnColor,
248
- bgColor: import_picocolors.default.bgYellow,
249
- label: this.labels.warn,
250
- message,
251
- identifier: options.identifier,
252
- muted: options.muted
253
- });
254
- this.output(formattedMessage, options, console.warn);
255
- }
256
- error(message, options = {}) {
257
- const formattedMessage = this.formatMessage({
258
- fgColor: this.errorColor,
259
- bgColor: import_picocolors.default.bgRed,
260
- label: this.labels.error,
261
- message,
262
- identifier: options.identifier,
263
- muted: options.muted
264
- });
265
- this.output(formattedMessage, options, console.error);
266
- }
267
- space() {
268
- if (silent)
269
- return;
270
- console.log("");
271
- }
272
- getProgressFgColor(label) {
273
- for (const [key, colorFn] of Object.entries(this.progressFgColorMap)) {
274
- if (label.includes(key))
275
- return colorFn;
276
- }
277
- return this.defaultColor;
278
- }
279
- getProgressBgColor(label) {
280
- for (const [key, colorFn] of Object.entries(this.progressIdentifierBgColorMap)) {
281
- if (label.includes(key))
282
- return colorFn;
283
- }
284
- return import_picocolors.default.bgWhite;
285
- }
286
- progress(label, message, options = {}) {
287
- const fgColor = this.getProgressFgColor(label);
288
- const bgColor = this.getProgressBgColor(label);
289
- const formattedMessage = this.formatMessage({
290
- fgColor,
291
- bgColor,
292
- label,
293
- message,
294
- identifier: options.identifier,
295
- muted: options.muted
296
- });
297
- this.output(formattedMessage, options);
298
- }
299
- }
300
- function logTable(columns, data, footer) {
301
- if (silent)
302
- return;
303
- const widths = {};
304
- for (const col of columns) {
305
- const headerLength = col.header.length;
306
- const dataLengths = data.map((row) => row[col.header]?.length || 0);
307
- const footerLength = footer ? footer[col.header]?.length || 0 : 0;
308
- widths[col.header] = Math.max(headerLength, ...dataLengths, footerLength);
309
- }
310
- const pad = (str, width, align) => {
311
- return align === "left" ? str.padEnd(width) : str.padStart(width);
312
- };
313
- const headerRow = columns.map((col) => pad(col.header, widths[col.header], col.align)).join(import_picocolors.default.gray(" | "));
314
- console.log(import_picocolors.default.gray(headerRow));
315
- const separator = columns.map((col) => "-".repeat(widths[col.header])).join(" | ");
316
- console.log(import_picocolors.default.gray(separator));
317
- for (const row of data) {
318
- const rowStr = columns.map((col) => {
319
- const value = row[col.header] || "";
320
- const padded = pad(value, widths[col.header], col.align);
321
- return col.color ? col.color(padded) : padded;
322
- }).join(import_picocolors.default.gray(" | "));
323
- console.log(rowStr);
324
- }
325
- console.log(import_picocolors.default.gray(separator));
326
- if (footer) {
327
- const footerRow = columns.map((col) => {
328
- const value = footer[col.header] || "";
329
- const padded = pad(value, widths[col.header], col.align);
330
- return padded;
331
- }).join(import_picocolors.default.gray(" | "));
332
- console.log(footerRow);
333
- }
334
- }
335
- var logger = Logger.getInstance();
336
-
337
- // src/utils.ts
338
- import path, { normalize } from "path";
339
-
340
- // src/errors.ts
341
- var import_picocolors2 = __toESM(require_picocolors(), 1);
342
- class BunupError extends Error {
343
- constructor(message) {
344
- super(message);
345
- this.name = "BunupError";
346
- }
347
- }
348
- class BunupPluginError extends BunupError {
349
- constructor(message) {
350
- super(message);
351
- this.name = "BunupPluginError";
352
- }
353
- }
354
-
355
- // src/utils.ts
356
- function formatFileSize(bytes) {
357
- if (bytes === 0)
358
- return "0 B";
359
- const units = ["B", "KB", "MB", "GB"];
360
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
361
- if (i === 0)
362
- return `${bytes} ${units[i]}`;
363
- return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
364
- }
365
- function makePortablePath(path2) {
366
- let cleaned = normalize(path2).replace(/\\/g, "/");
367
- cleaned = cleaned.replace(/^[a-zA-Z]:\//, "");
368
- cleaned = cleaned.replace(/^\/+/, "");
369
- cleaned = cleaned.replace(/\/+/g, "/");
370
- return cleaned;
371
- }
372
- function isDirectoryPath(filePath) {
373
- return path.extname(filePath) === "";
374
- }
375
-
376
- // src/plugins/built-in/productivity/exports.ts
377
- function exports() {
378
- return {
379
- type: "bunup",
380
- name: "exports",
381
- hooks: {
382
- onBuildDone: async ({ output, options, meta }) => {
383
- if (!meta.packageJson.path || !meta.packageJson.data) {
384
- return;
385
- }
386
- try {
387
- const { exportsField, entryPoints } = generateExportsFields(output.files);
388
- const files = Array.isArray(meta.packageJson.data.files) ? [...new Set([...meta.packageJson.data.files, options.outDir])] : [options.outDir];
389
- const existingExports = meta.packageJson.data.exports || {};
390
- const mergedExports = { ...existingExports };
391
- for (const [key, value] of Object.entries(exportsField)) {
392
- mergedExports[key] = value;
393
- }
394
- const newPackageJson = {
395
- name: meta.packageJson.data.name,
396
- description: meta.packageJson.data.description,
397
- version: meta.packageJson.data.version,
398
- type: meta.packageJson.data.type,
399
- private: meta.packageJson.data.private,
400
- files,
401
- ...entryPoints,
402
- exports: mergedExports
403
- };
404
- for (const key in meta.packageJson.data) {
405
- if (Object.prototype.hasOwnProperty.call(meta.packageJson.data, key) && !Object.prototype.hasOwnProperty.call(newPackageJson, key)) {
406
- newPackageJson[key] = meta.packageJson.data[key];
407
- }
408
- }
409
- await Bun.write(meta.packageJson.path, JSON.stringify(newPackageJson, null, 2));
410
- logger.cli("Updated package.json with exports");
411
- } catch (error) {
412
- logger.error("Failed to update package.json");
413
- }
414
- }
415
- }
416
- };
417
- }
418
- function generateExportsFields(files) {
419
- const exportsField = {};
420
- const entryPoints = {};
421
- for (const file of filterJsDtsFiles(files)) {
422
- const exportType = formatToExportField(file.format, file.dts);
423
- const relativePath = `./${makePortablePath(file.relativePathToRootDir)}`;
424
- const exportKey = getExportKey(file.outputBasePath);
425
- exportsField[exportKey] = {
426
- ...exportsField[exportKey],
427
- [exportType]: relativePath
428
- };
429
- for (const field of Object.keys(exportsField["."] ?? {})) {
430
- entryPoints[exportFieldToEntryPoint(field, file.dts)] = exportsField["."][field];
431
- }
432
- }
433
- return { exportsField, entryPoints };
434
- }
435
- function filterJsDtsFiles(files) {
436
- return files.filter((file) => JS_DTS_RE.test(file.fullPath));
437
- }
438
- function getExportKey(outputBasePath) {
439
- const pathSegments = outputBasePath.split("/");
440
- if (pathSegments.length === 1 && pathSegments[0] === "index") {
441
- return ".";
442
- }
443
- return `./${pathSegments.filter((p) => p !== "index").join("/")}`;
444
- }
445
- function exportFieldToEntryPoint(exportField, dts) {
446
- return dts ? "types" : exportField === "require" ? "main" : "module";
447
- }
448
- function formatToExportField(format, dts) {
449
- return dts ? "types" : format === "esm" ? "import" : "require";
450
- }
451
- // src/plugins/built-in/css/inject-styles.ts
452
- import path2 from "path";
453
-
454
- // src/plugins/utils.ts
455
- var import_picocolors3 = __toESM(require_picocolors(), 1);
456
- async function getPackageForPlugin(name, pluginName) {
457
- let pkg;
458
- try {
459
- pkg = await import(name);
460
- } catch {
461
- 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`)}`);
462
- }
463
- return pkg;
464
- }
465
-
466
- // src/plugins/built-in/css/inject-styles.ts
467
- function injectStyles(options) {
468
- const { inject, ...transformOptions } = options ?? {};
469
- return {
470
- type: "bun",
471
- name: "inject-styles",
472
- plugin: {
473
- name: "bunup:inject-styles",
474
- async setup(build) {
475
- const lightningcss = await getPackageForPlugin("lightningcss", "inject-styles");
476
- build.onResolve({ filter: /^__inject-style$/ }, () => {
477
- return {
478
- path: "__inject-style",
479
- namespace: "__inject-style"
480
- };
481
- });
482
- build.onLoad({ filter: /^__inject-style$/, namespace: "__inject-style" }, () => {
483
- return {
484
- contents: `
485
- export default function injectStyle(css) {
486
- if (!css || typeof document === 'undefined') return
487
-
488
- const head = document.head || document.getElementsByTagName('head')[0]
489
- const style = document.createElement('style')
490
- head.appendChild(style)
491
-
492
- if (style.styleSheet) {
493
- style.styleSheet.cssText = css
494
- } else {
495
- style.appendChild(document.createTextNode(css))
496
- }
497
- }
498
- `,
499
- loader: "js"
500
- };
501
- });
502
- build.onLoad({ filter: CSS_RE }, async (args) => {
503
- const source = await Bun.file(args.path).text();
504
- const { code, warnings } = lightningcss.transform({
505
- ...transformOptions,
506
- filename: path2.basename(args.path),
507
- code: Buffer.from(source),
508
- minify: transformOptions.minify ?? (build.config.minify === true || typeof build.config.minify === "object" && build.config.minify.whitespace)
509
- });
510
- for (const warning of warnings) {
511
- logger.warn(warning.message);
512
- }
513
- const stringifiedCode = JSON.stringify(code.toString());
514
- const js = inject ? await inject(stringifiedCode, args.path) : `import injectStyle from '__inject-style';injectStyle(${stringifiedCode})`;
515
- return {
516
- contents: js,
517
- loader: "js"
518
- };
519
- });
520
- }
521
- }
522
- };
523
- }
524
- // src/plugins/built-in/productivity/copy.ts
525
- import { join } from "path";
526
- import { basename } from "path";
527
- function copy(patterns, outPath) {
528
- return {
529
- type: "bunup",
530
- name: "copy",
531
- hooks: {
532
- onBuildDone: async ({ options, meta }) => {
533
- const destinationPath = outPath || options.outDir;
534
- for (const pattern of patterns) {
535
- const glob = new Bun.Glob(pattern);
536
- for await (const filePath of glob.scan({
537
- cwd: meta.rootDir,
538
- dot: true
539
- })) {
540
- const sourceFile = Bun.file(join(meta.rootDir, filePath));
541
- await Bun.write(outPath && isDirectoryPath(outPath) ? join(destinationPath, basename(filePath)) : destinationPath, sourceFile);
542
- }
543
- }
544
- }
545
- }
546
- };
547
- }
548
- // src/plugins/internal/report.ts
549
- var import_picocolors4 = __toESM(require_picocolors(), 1);
550
- function report() {
551
- return {
552
- type: "bunup",
553
- name: "report",
554
- hooks: {
555
- onBuildDone: async ({ options, output }) => {
556
- if (options.watch)
557
- return;
558
- const files = await Promise.all(output.files.map(async (file) => {
559
- const name = file.relativePathToRootDir;
560
- const size = Bun.file(file.fullPath).size;
561
- const gzipSize = Bun.gzipSync(new Uint8Array(await Bun.file(file.fullPath).arrayBuffer())).length;
562
- const formattedGzipSize = formatFileSize(gzipSize);
563
- return {
564
- name,
565
- size,
566
- formattedSize: formatFileSize(size),
567
- gzipSize,
568
- formattedGzipSize
569
- };
570
- }));
571
- const totalSize = files.reduce((sum, file) => sum + file.size, 0);
572
- const formattedTotalSize = formatFileSize(totalSize);
573
- const totalGzipSize = files.reduce((sum, file) => sum + (file.gzipSize || 0), 0);
574
- const formattedTotalGzipSize = formatFileSize(totalGzipSize);
575
- const columns = [
576
- { header: "File", align: "left", color: import_picocolors4.default.blue },
577
- { header: "Size", align: "right", color: import_picocolors4.default.green },
578
- {
579
- header: "Gzip",
580
- align: "right",
581
- color: import_picocolors4.default.magenta
582
- }
583
- ];
584
- const data = files.map((file) => {
585
- return {
586
- File: file.name,
587
- Size: file.formattedSize,
588
- Gzip: file.formattedGzipSize
589
- };
590
- });
591
- const footer = {
592
- File: "Total",
593
- Size: formattedTotalSize,
594
- Gzip: formattedTotalGzipSize
595
- };
596
- logger.space();
597
- logTable(columns, data, footer);
598
- logger.space();
599
- }
600
- }
601
- };
602
- }
603
- export {
604
- shims,
605
- report,
606
- injectStyles,
607
- filterJsDtsFiles,
608
- exports,
609
- copy
610
- };