bunup 0.8.2 → 0.8.3

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 CHANGED
@@ -1,16 +1,588 @@
1
1
  // @bun
2
- var j=Object.create;var{getPrototypeOf:H,defineProperty:_,getOwnPropertyNames:U}=Object;var X=Object.prototype.hasOwnProperty;var L=(t,r,n)=>{n=t!=null?j(H(t)):{};let e=r||!t||!t.__esModule?_(n,"default",{value:t,enumerable:!0}):n;for(let g of U(t))if(!X.call(e,g))_(e,g,{get:()=>t[g],enumerable:!0});return e};var D=(t,r)=>()=>(r||t((r={exports:{}}).exports,r),r.exports);var B=D((z,I)=>{var w=process||{},W=w.argv||[],M=w.env||{},q=!(!!M.NO_COLOR||W.includes("--no-color"))&&(!!M.FORCE_COLOR||W.includes("--color")||w.platform==="win32"||(w.stdout||{}).isTTY&&M.TERM!=="dumb"||!!M.CI),K=(t,r,n=t)=>(e)=>{let g=""+e,s=g.indexOf(r,t.length);return~s?t+Q(g,r,n,s)+r:t+g+r},Q=(t,r,n,e)=>{let g="",s=0;do g+=t.substring(s,e)+n,s=e+r.length,e=t.indexOf(r,s);while(~e);return g+t.substring(s)},Y=(t=q)=>{let r=t?K:()=>String;return{isColorSupported:t,reset:r("\x1B[0m","\x1B[0m"),bold:r("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:r("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:r("\x1B[3m","\x1B[23m"),underline:r("\x1B[4m","\x1B[24m"),inverse:r("\x1B[7m","\x1B[27m"),hidden:r("\x1B[8m","\x1B[28m"),strikethrough:r("\x1B[9m","\x1B[29m"),black:r("\x1B[30m","\x1B[39m"),red:r("\x1B[31m","\x1B[39m"),green:r("\x1B[32m","\x1B[39m"),yellow:r("\x1B[33m","\x1B[39m"),blue:r("\x1B[34m","\x1B[39m"),magenta:r("\x1B[35m","\x1B[39m"),cyan:r("\x1B[36m","\x1B[39m"),white:r("\x1B[37m","\x1B[39m"),gray:r("\x1B[90m","\x1B[39m"),bgBlack:r("\x1B[40m","\x1B[49m"),bgRed:r("\x1B[41m","\x1B[49m"),bgGreen:r("\x1B[42m","\x1B[49m"),bgYellow:r("\x1B[43m","\x1B[49m"),bgBlue:r("\x1B[44m","\x1B[49m"),bgMagenta:r("\x1B[45m","\x1B[49m"),bgCyan:r("\x1B[46m","\x1B[49m"),bgWhite:r("\x1B[47m","\x1B[49m"),blackBright:r("\x1B[90m","\x1B[39m"),redBright:r("\x1B[91m","\x1B[39m"),greenBright:r("\x1B[92m","\x1B[39m"),yellowBright:r("\x1B[93m","\x1B[39m"),blueBright:r("\x1B[94m","\x1B[39m"),magentaBright:r("\x1B[95m","\x1B[39m"),cyanBright:r("\x1B[96m","\x1B[39m"),whiteBright:r("\x1B[97m","\x1B[39m"),bgBlackBright:r("\x1B[100m","\x1B[49m"),bgRedBright:r("\x1B[101m","\x1B[49m"),bgGreenBright:r("\x1B[102m","\x1B[49m"),bgYellowBright:r("\x1B[103m","\x1B[49m"),bgBlueBright:r("\x1B[104m","\x1B[49m"),bgMagentaBright:r("\x1B[105m","\x1B[49m"),bgCyanBright:r("\x1B[106m","\x1B[49m"),bgWhiteBright:r("\x1B[107m","\x1B[49m")}};I.exports=Y();I.exports.createColors=Y});function P(){return{type:"bun",name:"shims",plugin:{name:"bunup:shims",setup(t){let r=t.config.target==="node"||t.config.target==="bun",n=t.config.format==="esm",e=t.config.format==="cjs";if(!r||!n&&!e)return;t.config.define={...t.config.define,...e&&{"import.meta.url":"importMetaUrl"}},t.onLoad({filter:/\.(js|ts|jsx|tsx|mts|cts)$/},async({path:g})=>{let s=await Bun.file(g).text(),c="";if(n&&(/\b__dirname\b/.test(s)||/\b__filename\b/.test(s)))c=`import { fileURLToPath } from 'url';
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';
3
123
  import { dirname } from 'path';
4
124
 
5
125
  const __filename = fileURLToPath(import.meta.url);
6
126
  const __dirname = dirname(__filename);
7
127
 
8
- `;if(e&&/\bimport\.meta\.url\b/.test(s))c=`import { pathToFileURL } from 'url';
128
+ `;
129
+ }
130
+ if (isCjs && /\bimport\.meta\.url\b/.test(content)) {
131
+ shimCode = `import { pathToFileURL } from 'url';
9
132
 
10
133
  const importMetaUrl = pathToFileURL(__filename).href;
11
134
 
12
- `;if(!c)return;let o=s.split(`
13
- `),x=o[0],i=o.slice(1);return{contents:[x,c,...i].join(`
14
- `)}})}}}}var b=L(B(),1),V=!1;class l{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;cliColor=b.default.blue;mutedColor=b.default.dim;infoColor=b.default.cyan;warnColor=b.default.yellow;errorColor=b.default.red;defaultColor=b.default.white;progressFgColorMap={ESM:b.default.yellow,CJS:b.default.green,IIFE:b.default.magenta,DTS:b.default.blue};progressIdentifierBgColorMap={ESM:b.default.bgYellow,CJS:b.default.bgGreen,IIFE:b.default.bgMagenta,DTS:b.default.bgBlue};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(t){if(!t?.once)return!0;if(this.loggedOnceMessages.has(t.once))return!1;return this.loggedOnceMessages.add(t.once),!0}formatMessage({fgColor:t,bgColor:r,label:n,message:e,identifier:g,muted:s}){let c=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-n.length)),o=s?this.mutedColor(e):e,x=g?` ${r(b.default.black(` ${g} `))}`:"";return`${t(n)} ${c}${o}${x}`}output(t,r={},n=console.log){if(V||!this.shouldLog(r))return;if(r.verticalSpace)n("");if(n(t),r.verticalSpace)n("")}cli(t,r={}){let n=this.formatMessage({fgColor:this.cliColor,bgColor:b.default.bgBlue,label:this.labels.cli,message:t,identifier:r.identifier,muted:r.muted});this.output(n,r)}info(t,r={}){let n=this.formatMessage({fgColor:this.infoColor,bgColor:b.default.bgCyan,label:this.labels.info,message:t,identifier:r.identifier,muted:r.muted});this.output(n,r)}warn(t,r={}){let n=this.formatMessage({fgColor:this.warnColor,bgColor:b.default.bgYellow,label:this.labels.warn,message:t,identifier:r.identifier,muted:r.muted});this.output(n,r,console.warn)}error(t,r={}){let n=this.formatMessage({fgColor:this.errorColor,bgColor:b.default.bgRed,label:this.labels.error,message:t,identifier:r.identifier,muted:r.muted});this.output(n,r,console.error)}getProgressFgColor(t){for(let[r,n]of Object.entries(this.progressFgColorMap))if(t.includes(r))return n;return this.defaultColor}getProgressBgColor(t){for(let[r,n]of Object.entries(this.progressIdentifierBgColorMap))if(t.includes(r))return n;return b.default.bgWhite}progress(t,r,n={}){let e=this.getProgressFgColor(t),g=this.getProgressBgColor(t),s=this.formatMessage({fgColor:e,bgColor:g,label:t,message:r,identifier:n.identifier,muted:n.muted});this.output(s,n)}}function A(t,r,n){let e={};for(let o of t){let x=o.header.length,i=r.map((m)=>m[o.header]?.length||0),h=n?n[o.header]?.length||0:0;e[o.header]=Math.max(x,...i,h)}let g=(o,x,i)=>{return i==="left"?o.padEnd(x):o.padStart(x)},s=t.map((o)=>g(o.header,e[o.header],o.align)).join(b.default.gray(" | "));console.log(b.default.gray(s));let c=t.map((o)=>"-".repeat(e[o.header])).join(" | ");console.log(b.default.gray(c));for(let o of r){let x=t.map((i)=>{let h=o[i.header]||"",m=g(h,e[i.header],i.align);return i.color?i.color(m):m}).join(b.default.gray(" | "));console.log(x)}if(console.log(b.default.gray(c)),n){let o=t.map((x)=>{let i=n[x.header]||"";return g(i,e[x.header],x.align)}).join(b.default.gray(" | "));console.log(o)}}var v=l.getInstance();import or,{normalize as y}from"path";var Z=L(B(),1);function S(t){let r=t.match(/{\n(\s+)/);if(!r)return 2;return r[1].length}function R(t){if(t===0)return"0 B";let r=["B","KB","MB","GB"],n=Math.floor(Math.log(t)/Math.log(1024));if(n===0)return`${t} ${r[n]}`;return`${(t/1024**n).toFixed(2)} ${r[n]}`}function N(t){let r=y(t).replace(/\\/g,"/");return r=r.replace(/^[a-zA-Z]:\//,""),r=r.replace(/^\/+/,""),r=r.replace(/\/+/g,"/"),r}function a(t,r){let n=t.endsWith(`
15
- `);return JSON.stringify(r,null,S(t))+(n?`
16
- `:"")}function cr(){return{type:"bunup",name:"exports",hooks:{onBuildDone:async({output:t,options:r,meta:n})=>{if(!n.packageJson.path||!n.packageJson.data)return;try{let e=await Bun.file(n.packageJson.path).text(),g=JSON.parse(e),{exportsField:s,entryPoints:c}=T(t.files),o=Array.isArray(g.files)?[...new Set([...g.files,r.outDir])]:[r.outDir],i={...g.exports||{}};for(let[m,O]of Object.entries(s))i[m]={...i[m]||{},...O};let h={name:g.name,description:g.description,version:g.version,type:g.type,private:g.private,files:o,...c,exports:i};for(let m in g)if(Object.prototype.hasOwnProperty.call(g,m)&&!Object.prototype.hasOwnProperty.call(h,m))h[m]=g[m];await Bun.write(n.packageJson.path,a(e,h)),v.cli("Updated package.json with exports")}catch(e){v.error("Failed to update package.json")}}}}}function T(t){let r={},n={};for(let e of t){let g=p(e.format,e.dts),s=`./${N(e.relativePathToRootDir)}`,c=G(e.outputBasePath);r[c]={...r[c],[g]:s};for(let o of Object.keys(r["."]??{}))n[F(o,e.dts)]=r["."][o]}return{exportsField:r,entryPoints:n}}function G(t){let r=t.split("/");if(r.length===1&&r[0]==="index")return".";return`./${r.filter((n)=>n!=="index").join("/")}`}function F(t,r){return r?"types":t==="require"?"main":"module"}function p(t,r){return r?"types":t==="esm"?"import":"require"}var C=L(B(),1);function dr(t={}){let{maxBundleSize:r,gzip:n=!0}=t;return{type:"bunup",name:"report",hooks:{onBuildDone:async({options:e,output:g})=>{if(e.watch)return;let s=await Promise.all(g.files.map(async(u)=>{let d=u.relativePathToRootDir,f=Bun.file(u.fullPath).size,E,$;if(n)E=Bun.gzipSync(new Uint8Array(await Bun.file(u.fullPath).arrayBuffer())).length,$=R(E);return{name:d,size:f,formattedSize:R(f),gzipSize:E,formattedGzipSize:$}})),c=s.reduce((u,d)=>u+d.size,0),o=R(c),x,i;if(n)x=s.reduce((u,d)=>u+(d.gzipSize||0),0),i=R(x);let h=[{header:"File",align:"left",color:C.default.blue},{header:"Size",align:"right",color:C.default.green}];if(n)h.push({header:"Gzip",align:"right",color:C.default.magenta});let m=s.map((u)=>{let d={File:u.name,Size:u.formattedSize};if(n&&u.formattedGzipSize)d.Gzip=u.formattedGzipSize;return d}),O={File:"Total",Size:o};if(n&&i)O.Gzip=i;if(console.log(""),A(h,m,O),r&&c>r)console.log(""),console.log(C.default.red(`Your bundle size of ${o} exceeds the configured limit of ${R(r)}`));console.log("")}}}}export{P as shims,dr as report,cr as exports};
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
+ getProgressFgColor(label) {
268
+ for (const [key, colorFn] of Object.entries(this.progressFgColorMap)) {
269
+ if (label.includes(key))
270
+ return colorFn;
271
+ }
272
+ return this.defaultColor;
273
+ }
274
+ getProgressBgColor(label) {
275
+ for (const [key, colorFn] of Object.entries(this.progressIdentifierBgColorMap)) {
276
+ if (label.includes(key))
277
+ return colorFn;
278
+ }
279
+ return import_picocolors.default.bgWhite;
280
+ }
281
+ progress(label, message, options = {}) {
282
+ const fgColor = this.getProgressFgColor(label);
283
+ const bgColor = this.getProgressBgColor(label);
284
+ const formattedMessage = this.formatMessage({
285
+ fgColor,
286
+ bgColor,
287
+ label,
288
+ message,
289
+ identifier: options.identifier,
290
+ muted: options.muted
291
+ });
292
+ this.output(formattedMessage, options);
293
+ }
294
+ }
295
+ function logTable(columns, data, footer) {
296
+ const widths = {};
297
+ for (const col of columns) {
298
+ const headerLength = col.header.length;
299
+ const dataLengths = data.map((row) => row[col.header]?.length || 0);
300
+ const footerLength = footer ? footer[col.header]?.length || 0 : 0;
301
+ widths[col.header] = Math.max(headerLength, ...dataLengths, footerLength);
302
+ }
303
+ const pad = (str, width, align) => {
304
+ return align === "left" ? str.padEnd(width) : str.padStart(width);
305
+ };
306
+ const headerRow = columns.map((col) => pad(col.header, widths[col.header], col.align)).join(import_picocolors.default.gray(" | "));
307
+ console.log(import_picocolors.default.gray(headerRow));
308
+ const separator = columns.map((col) => "-".repeat(widths[col.header])).join(" | ");
309
+ console.log(import_picocolors.default.gray(separator));
310
+ for (const row of data) {
311
+ const rowStr = columns.map((col) => {
312
+ const value = row[col.header] || "";
313
+ const padded = pad(value, widths[col.header], col.align);
314
+ return col.color ? col.color(padded) : padded;
315
+ }).join(import_picocolors.default.gray(" | "));
316
+ console.log(rowStr);
317
+ }
318
+ console.log(import_picocolors.default.gray(separator));
319
+ if (footer) {
320
+ const footerRow = columns.map((col) => {
321
+ const value = footer[col.header] || "";
322
+ const padded = pad(value, widths[col.header], col.align);
323
+ return padded;
324
+ }).join(import_picocolors.default.gray(" | "));
325
+ console.log(footerRow);
326
+ }
327
+ }
328
+ var logger = Logger.getInstance();
329
+
330
+ // src/utils.ts
331
+ import path, { normalize } from "path";
332
+
333
+ // src/errors.ts
334
+ var import_picocolors2 = __toESM(require_picocolors(), 1);
335
+
336
+ // src/utils.ts
337
+ function getJsonSpaceCount(fileContent) {
338
+ const match = fileContent.match(/{\n(\s+)/);
339
+ if (!match)
340
+ return 2;
341
+ return match[1].length;
342
+ }
343
+ function formatFileSize(bytes) {
344
+ if (bytes === 0)
345
+ return "0 B";
346
+ const units = ["B", "KB", "MB", "GB"];
347
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
348
+ if (i === 0)
349
+ return `${bytes} ${units[i]}`;
350
+ return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
351
+ }
352
+ function makePortablePath(path2) {
353
+ let cleaned = normalize(path2).replace(/\\/g, "/");
354
+ cleaned = cleaned.replace(/^[a-zA-Z]:\//, "");
355
+ cleaned = cleaned.replace(/^\/+/, "");
356
+ cleaned = cleaned.replace(/\/+/g, "/");
357
+ return cleaned;
358
+ }
359
+ function getUpdatedPackageJson(oldPackageJson, newPackageJson) {
360
+ const hasTrailingNewline = oldPackageJson.endsWith(`
361
+ `);
362
+ return JSON.stringify(newPackageJson, null, getJsonSpaceCount(oldPackageJson)) + (hasTrailingNewline ? `
363
+ ` : "");
364
+ }
365
+
366
+ // src/plugins/built-in/productivity/exports.ts
367
+ function exports() {
368
+ return {
369
+ type: "bunup",
370
+ name: "exports",
371
+ hooks: {
372
+ onBuildDone: async ({ output, options, meta }) => {
373
+ if (!meta.packageJson.path || !meta.packageJson.data) {
374
+ return;
375
+ }
376
+ try {
377
+ const packageJsonContent = await Bun.file(meta.packageJson.path).text();
378
+ const packageJson = JSON.parse(packageJsonContent);
379
+ const { exportsField, entryPoints } = generateExportsFields(output.files);
380
+ const files = Array.isArray(packageJson.files) ? [...new Set([...packageJson.files, options.outDir])] : [options.outDir];
381
+ const existingExports = packageJson.exports || {};
382
+ const mergedExports = { ...existingExports };
383
+ for (const [key, value] of Object.entries(exportsField)) {
384
+ mergedExports[key] = {
385
+ ...mergedExports[key] || {},
386
+ ...value
387
+ };
388
+ }
389
+ const newPackageJson = {
390
+ name: packageJson.name,
391
+ description: packageJson.description,
392
+ version: packageJson.version,
393
+ type: packageJson.type,
394
+ private: packageJson.private,
395
+ files,
396
+ ...entryPoints,
397
+ exports: mergedExports
398
+ };
399
+ for (const key in packageJson) {
400
+ if (Object.prototype.hasOwnProperty.call(packageJson, key) && !Object.prototype.hasOwnProperty.call(newPackageJson, key)) {
401
+ newPackageJson[key] = packageJson[key];
402
+ }
403
+ }
404
+ await Bun.write(meta.packageJson.path, getUpdatedPackageJson(packageJsonContent, newPackageJson));
405
+ logger.cli("Updated package.json with exports");
406
+ } catch (error) {
407
+ logger.error("Failed to update package.json");
408
+ }
409
+ }
410
+ }
411
+ };
412
+ }
413
+ function generateExportsFields(files) {
414
+ const exportsField = {};
415
+ const entryPoints = {};
416
+ for (const file of filterJsDtsFiles(files)) {
417
+ const exportType = formatToExportField(file.format, file.dts);
418
+ const relativePath = `./${makePortablePath(file.relativePathToRootDir)}`;
419
+ const exportKey = getExportKey(file.outputBasePath);
420
+ exportsField[exportKey] = {
421
+ ...exportsField[exportKey],
422
+ [exportType]: relativePath
423
+ };
424
+ for (const field of Object.keys(exportsField["."] ?? {})) {
425
+ entryPoints[exportFieldToEntryPoint(field, file.dts)] = exportsField["."][field];
426
+ }
427
+ }
428
+ return { exportsField, entryPoints };
429
+ }
430
+ function filterJsDtsFiles(files) {
431
+ return files.filter((file) => JS_DTS_RE.test(file.fullPath));
432
+ }
433
+ function getExportKey(outputBasePath) {
434
+ const pathSegments = outputBasePath.split("/");
435
+ if (pathSegments.length === 1 && pathSegments[0] === "index") {
436
+ return ".";
437
+ }
438
+ return `./${pathSegments.filter((p) => p !== "index").join("/")}`;
439
+ }
440
+ function exportFieldToEntryPoint(exportField, dts) {
441
+ return dts ? "types" : exportField === "require" ? "main" : "module";
442
+ }
443
+ function formatToExportField(format, dts) {
444
+ return dts ? "types" : format === "esm" ? "import" : "require";
445
+ }
446
+ // src/plugins/built-in/productivity/report.ts
447
+ var import_picocolors3 = __toESM(require_picocolors(), 1);
448
+ function report(options = {}) {
449
+ const { maxBundleSize, gzip = true } = options;
450
+ return {
451
+ type: "bunup",
452
+ name: "report",
453
+ hooks: {
454
+ onBuildDone: async ({ options: options2, output }) => {
455
+ if (options2.watch)
456
+ return;
457
+ const files = await Promise.all(output.files.map(async (file) => {
458
+ const name = file.relativePathToRootDir;
459
+ const size = Bun.file(file.fullPath).size;
460
+ let gzipSize;
461
+ let formattedGzipSize;
462
+ if (gzip) {
463
+ gzipSize = Bun.gzipSync(new Uint8Array(await Bun.file(file.fullPath).arrayBuffer())).length;
464
+ formattedGzipSize = formatFileSize(gzipSize);
465
+ }
466
+ return {
467
+ name,
468
+ size,
469
+ formattedSize: formatFileSize(size),
470
+ gzipSize,
471
+ formattedGzipSize
472
+ };
473
+ }));
474
+ const totalSize = files.reduce((sum, file) => sum + file.size, 0);
475
+ const formattedTotalSize = formatFileSize(totalSize);
476
+ let totalGzipSize;
477
+ let formattedTotalGzipSize;
478
+ if (gzip) {
479
+ totalGzipSize = files.reduce((sum, file) => sum + (file.gzipSize || 0), 0);
480
+ formattedTotalGzipSize = formatFileSize(totalGzipSize);
481
+ }
482
+ const columns = [
483
+ { header: "File", align: "left", color: import_picocolors3.default.blue },
484
+ { header: "Size", align: "right", color: import_picocolors3.default.green }
485
+ ];
486
+ if (gzip) {
487
+ columns.push({
488
+ header: "Gzip",
489
+ align: "right",
490
+ color: import_picocolors3.default.magenta
491
+ });
492
+ }
493
+ const data = files.map((file) => {
494
+ const row = {
495
+ File: file.name,
496
+ Size: file.formattedSize
497
+ };
498
+ if (gzip && file.formattedGzipSize) {
499
+ row.Gzip = file.formattedGzipSize;
500
+ }
501
+ return row;
502
+ });
503
+ const footer = {
504
+ File: "Total",
505
+ Size: formattedTotalSize
506
+ };
507
+ if (gzip && formattedTotalGzipSize) {
508
+ footer.Gzip = formattedTotalGzipSize;
509
+ }
510
+ console.log("");
511
+ logTable(columns, data, footer);
512
+ if (maxBundleSize && totalSize > maxBundleSize) {
513
+ console.log("");
514
+ console.log(import_picocolors3.default.red(`Your bundle size of ${formattedTotalSize} exceeds the configured limit of ${formatFileSize(maxBundleSize)}`));
515
+ }
516
+ console.log("");
517
+ }
518
+ }
519
+ };
520
+ }
521
+ // src/plugins/built-in/css/inject-styles.ts
522
+ import path2 from "path";
523
+ import {
524
+ transform
525
+ } from "lightningcss";
526
+ function injectStyles(options) {
527
+ const { inject, ...transformOptions } = options ?? {};
528
+ return {
529
+ type: "bun",
530
+ name: "inject-styles",
531
+ plugin: {
532
+ name: "bunup:inject-styles",
533
+ setup(build) {
534
+ build.onResolve({ filter: /^__inject-style$/ }, () => {
535
+ return {
536
+ path: "__inject-style",
537
+ namespace: "__inject-style"
538
+ };
539
+ });
540
+ build.onLoad({ filter: /^__inject-style$/, namespace: "__inject-style" }, () => {
541
+ return {
542
+ contents: `
543
+ export default function injectStyle(css) {
544
+ if (!css || typeof document === 'undefined') return
545
+
546
+ const head = document.head || document.getElementsByTagName('head')[0]
547
+ const style = document.createElement('style')
548
+ head.appendChild(style)
549
+
550
+ if (style.styleSheet) {
551
+ style.styleSheet.cssText = css
552
+ } else {
553
+ style.appendChild(document.createTextNode(css))
554
+ }
555
+ }
556
+ `,
557
+ loader: "js"
558
+ };
559
+ });
560
+ build.onLoad({ filter: CSS_RE }, async (args) => {
561
+ const source = await Bun.file(args.path).text();
562
+ const { code, warnings } = transform({
563
+ ...transformOptions,
564
+ filename: path2.basename(args.path),
565
+ code: Buffer.from(source),
566
+ minify: transformOptions.minify ?? (build.config.minify === true || typeof build.config.minify === "object" && build.config.minify.whitespace)
567
+ });
568
+ for (const warning of warnings) {
569
+ logger.warn(warning.message);
570
+ }
571
+ const stringifiedCode = JSON.stringify(code.toString());
572
+ const js = inject ? await inject(stringifiedCode, args.path) : `import injectStyle from '__inject-style';injectStyle(${stringifiedCode})`;
573
+ return {
574
+ contents: js,
575
+ loader: "js"
576
+ };
577
+ });
578
+ }
579
+ }
580
+ };
581
+ }
582
+ export {
583
+ shims,
584
+ report,
585
+ injectStyles,
586
+ filterJsDtsFiles,
587
+ exports
588
+ };
package/package.json CHANGED
@@ -1,12 +1,9 @@
1
1
  {
2
2
  "name": "bunup",
3
3
  "description": "⚡ A blazing-fast build tool for your libraries built with Bun.",
4
- "version": "0.8.2",
4
+ "version": "0.8.3",
5
5
  "type": "module",
6
- "files": [
7
- "dist",
8
- "bin"
9
- ],
6
+ "files": ["dist", "bin"],
10
7
  "module": "./dist/index.js",
11
8
  "main": "./dist/index.cjs",
12
9
  "types": "./dist/index.d.cts",
@@ -37,17 +34,13 @@
37
34
  },
38
35
  "funding": "https://github.com/sponsors/arshad-yaseen",
39
36
  "homepage": "https://bunup.dev",
40
- "keywords": [
41
- "bun",
42
- "bunup",
43
- "bun-bundler"
44
- ],
37
+ "keywords": ["bun", "bunup", "bun-bundler"],
45
38
  "bin": {
46
39
  "bunup": "bin/bunup.mjs"
47
40
  },
48
41
  "dependencies": {
49
42
  "@clack/prompts": "^0.10.1",
50
- "bun-dts": "^0.1.26",
43
+ "bun-dts": "^0.1.27",
51
44
  "chokidar": "^4.0.3",
52
45
  "coffi": "^0.1.28",
53
46
  "giget": "^2.0.0",
@@ -61,14 +54,19 @@
61
54
  "bumpp": "^10.1.0",
62
55
  "husky": "^9.1.7",
63
56
  "lint-staged": "^15.5.1",
64
- "typescript": "^5.8.3"
57
+ "typescript": "^5.8.3",
58
+ "lightningcss": "^1.30.1"
65
59
  },
66
60
  "peerDependencies": {
67
- "typescript": ">=4.5.0"
61
+ "typescript": ">=4.5.0",
62
+ "lightningcss": ">=1.17.0"
68
63
  },
69
64
  "peerDependenciesMeta": {
70
65
  "typescript": {
71
66
  "optional": true
67
+ },
68
+ "lightningcss": {
69
+ "optional": true
72
70
  }
73
71
  },
74
72
  "scripts": {
@@ -91,8 +89,5 @@
91
89
  "*": "bun run format:fix && git add .",
92
90
  "src/**/*.(m|c)?(j|t)s": "bun run tsc"
93
91
  },
94
- "workspaces": [
95
- "docs",
96
- "tests"
97
- ]
92
+ "workspaces": ["docs", "tests"]
98
93
  }