bunup 0.8.2 → 0.8.4

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.js CHANGED
@@ -1,6 +1,655 @@
1
- "use client";
2
1
  // @bun
3
- var dr=Object.create;var{getPrototypeOf:ur,defineProperty:F,getOwnPropertyNames:lr}=Object;var Cr=Object.prototype.hasOwnProperty;var Y=(n,r,g)=>{g=n!=null?dr(ur(n)):{};let e=r||!n||!n.__esModule?F(g,"default",{value:n,enumerable:!0}):g;for(let b of lr(n))if(!Cr.call(e,b))F(e,b,{get:()=>n[b],enumerable:!0});return e};var cr=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var S=cr((Gr,O)=>{var E=process||{},G=E.argv||[],R=E.env||{},wr=!(!!R.NO_COLOR||G.includes("--no-color"))&&(!!R.FORCE_COLOR||G.includes("--color")||E.platform==="win32"||(E.stdout||{}).isTTY&&R.TERM!=="dumb"||!!R.CI),Mr=(n,r,g=n)=>(e)=>{let b=""+e,x=b.indexOf(r,n.length);return~x?n+Rr(b,r,g,x)+r:n+b+r},Rr=(n,r,g,e)=>{let b="",x=0;do b+=n.substring(x,e)+g,x=e+r.length,e=n.indexOf(r,x);while(~e);return b+n.substring(x)},N=(n=wr)=>{let r=n?Mr:()=>String;return{isColorSupported:n,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")}};O.exports=N();O.exports.createColors=N});function fr(n){return n}function Br(n){return n}import Or from"path";import{generateDts as Sr,logIsolatedDeclarationErrors as $r}from"bun-dts";var Er=Y(S(),1);var i=Y(S(),1),A=!1;function H(n){A=n??!1}class l{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;cliColor=i.default.blue;mutedColor=i.default.dim;infoColor=i.default.cyan;warnColor=i.default.yellow;errorColor=i.default.red;defaultColor=i.default.white;progressFgColorMap={ESM:i.default.yellow,CJS:i.default.green,IIFE:i.default.magenta,DTS:i.default.blue};progressIdentifierBgColorMap={ESM:i.default.bgYellow,CJS:i.default.bgGreen,IIFE:i.default.bgMagenta,DTS:i.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(n){if(!n?.once)return!0;if(this.loggedOnceMessages.has(n.once))return!1;return this.loggedOnceMessages.add(n.once),!0}formatMessage({fgColor:n,bgColor:r,label:g,message:e,identifier:b,muted:x}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-g.length)),d=x?this.mutedColor(e):e,I=b?` ${r(i.default.black(` ${b} `))}`:"";return`${n(g)} ${s}${d}${I}`}output(n,r={},g=console.log){if(A||!this.shouldLog(r))return;if(r.verticalSpace)g("");if(g(n),r.verticalSpace)g("")}cli(n,r={}){let g=this.formatMessage({fgColor:this.cliColor,bgColor:i.default.bgBlue,label:this.labels.cli,message:n,identifier:r.identifier,muted:r.muted});this.output(g,r)}info(n,r={}){let g=this.formatMessage({fgColor:this.infoColor,bgColor:i.default.bgCyan,label:this.labels.info,message:n,identifier:r.identifier,muted:r.muted});this.output(g,r)}warn(n,r={}){let g=this.formatMessage({fgColor:this.warnColor,bgColor:i.default.bgYellow,label:this.labels.warn,message:n,identifier:r.identifier,muted:r.muted});this.output(g,r,console.warn)}error(n,r={}){let g=this.formatMessage({fgColor:this.errorColor,bgColor:i.default.bgRed,label:this.labels.error,message:n,identifier:r.identifier,muted:r.muted});this.output(g,r,console.error)}getProgressFgColor(n){for(let[r,g]of Object.entries(this.progressFgColorMap))if(n.includes(r))return g;return this.defaultColor}getProgressBgColor(n){for(let[r,g]of Object.entries(this.progressIdentifierBgColorMap))if(n.includes(r))return g;return i.default.bgWhite}progress(n,r,g={}){let e=this.getProgressFgColor(n),b=this.getProgressBgColor(n),x=this.formatMessage({fgColor:e,bgColor:b,label:n,message:r,identifier:g.identifier,muted:g.muted});this.output(x,g)}}var o=l.getInstance();class K extends Error{constructor(n){super(n);this.name="BunupError"}}class B extends K{constructor(n){super(n);this.name="BunupBuildError"}}import U from"fs/promises";import X,{normalize as Xr}from"path";function _(n,r){switch(n){case"esm":return h(r)?".js":".mjs";case"cjs":return h(r)?".cjs":".js";case"iife":return".global.js"}}function j(n,r){switch(n){case"esm":return h(r)?".d.ts":".d.mts";case"cjs":return h(r)?".d.cts":".d.ts";case"iife":return".global.d.ts"}}function q(n){return n.replace(X.extname(n),"")}function Q(n){return n.replace(/\\/g,"/")}function h(n){return n==="module"}function Z(n){if(!n)return[];return Array.from(new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.peerDependencies||{})]))}function z(n,r=3){return n.split("/").slice(-r).join("/")}async function V(n,r){let g=X.join(n,r);try{await U.rm(g,{recursive:!0,force:!0})}catch(e){throw new B(`Failed to clean output directory: ${e}`)}await U.mkdir(g,{recursive:!0})}function $(n){if(typeof n==="string")return[{entry:n,outputBasePath:T(n)}];if(typeof n==="object"&&!Array.isArray(n))return Object.entries(n).map(([r,g])=>({entry:g,outputBasePath:r}));return n.map((r)=>({entry:r,outputBasePath:T(r)}))}function T(n){let r=Q(q(n)).split("/");return r.length>1?r.slice(1).join("/"):r.join("/")}function v(n,r){return{entry:`[dir]/${n}${r}`,chunk:`${n}-[hash].[ext]`,asset:`${n}-[name]-[hash].[ext]`}}import{loadConfig as hr}from"coffi";async function p(n){let{config:r,filepath:g}=await hr({name:"package",cwd:n,extensions:[".json"]});return{data:r,path:g}}function D(){return{type:"bunup",name:"use-client",hooks:{onBuildDone:async({output:n})=>{for(let r of n.files){let g=await Bun.file(r.fullPath).text();if(g.includes(''))g=g.replaceAll('',""),g=`
4
- ${g}`;await Bun.write(r.fullPath,g)}}}}}var Ir={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function k(n){let r={...Ir,...n};return{...r,plugins:[...r.plugins??[],D()]}}function J(n){let{minify:r,minifyWhitespace:g,minifyIdentifiers:e,minifySyntax:b}=n,x=r===!0;return{whitespace:g??x,identifiers:e??x,syntax:b??x}}function a(n,r){return r==="cjs"?n:void 0}function y(n){if(n===!0)return"inline";return typeof n==="string"?n:void 0}function P(n,r){return{...typeof r==="object"&&Object.keys(r).reduce((g,e)=>{let b=JSON.stringify(r[e]);return g[`process.env.${e}`]=b,g[`import.meta.env.${e}`]=b,g},{}),...n}}function rr(n,r){return n===void 0?r==="esm":n}function nr(n){return typeof n==="string"?n:void 0}function Lr(n){return Z(n).map((r)=>new RegExp(`^${r}($|\\/|\\\\)`))}function er(n,r){return typeof r==="string"?r===n:r.test(n)}function gr(n,r,g){let b=Lr(g).some((s)=>s.test(n))||r.external?.some((s)=>er(n,s)),x=r.noExternal?.some((s)=>er(n,s));return b&&!x}function br(n,r){return{name:"bunup:external-option-plugin",setup(g){g.onResolve({filter:/.*/},(e)=>{let b=e.path;if(gr(b,n,r))return{path:b,external:!0};return null})}}}function ir(n){if(!n)return[];return n.filter((r)=>r.type==="bun")}function xr(n){if(!n)return[];return n.filter((r)=>r.type==="bunup")}async function mr(n,r){if(!n)return;for(let g of n)if(g.hooks.onBuildStart)await g.hooks.onBuildStart(r)}async function sr(n,r,g,e){if(!n)return;for(let b of n)if(b.hooks.onBuildDone)await b.hooks.onBuildDone({options:r,output:g,meta:e})}async function Wr(n,r=process.cwd()){let g={files:[]},e=k(n);if(!e.entry||e.entry.length===0||!e.outDir)throw new B("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(e.clean)V(r,e.outDir);H(e.silent);let b=await p(r);if(b.data&&b.path)o.cli(`Using ${z(b.path,2)}`,{muted:!0,identifier:e.name,once:`${b.path}:${e.name}`});let x=xr(e.plugins);await mr(x,e);let s=$(e.entry),d=b.data?.type,I=[br(e,b.data),...ir(e.plugins).map((C)=>C.plugin)];if(!e.dtsOnly){let C=e.format.flatMap((t)=>s.map(async({entry:w,outputBasePath:M})=>{let c=e.outputExtension?.({format:t,packageType:d,options:e,entry:w}).js??_(t,d),f=await Bun.build({entrypoints:[`${r}/${w}`],format:t,naming:v(M,c),splitting:rr(e.splitting,t),bytecode:a(e.bytecode,t),define:P(e.define,e.env),minify:J(e),outdir:`${r}/${e.outDir}`,target:e.target,sourcemap:y(e.sourcemap),loader:e.loader,drop:e.drop,banner:e.banner,footer:e.footer,publicPath:e.publicPath,env:nr(e.env),plugins:I,throw:!1});for(let m of f.logs){if(m.level==="error")throw console.log(`
5
- `),console.log(m),console.log(`
6
- `),new Error;if(m.level==="warning")o.warn(m.message);else if(m.level==="info")o.info(m.message)}for(let m of f.outputs){let u=tr(m.path,r);if(m.kind==="entry-point")o.progress(t.toUpperCase(),u,{identifier:e.name});g.files.push({fullPath:m.path,relativePathToRootDir:u,dts:!1,entry:w,outputBasePath:M,format:t})}}));await Promise.all(C)}if(e.dts===!0||typeof e.dts==="object"||e.dtsOnly){let C=typeof e.dts==="object"&&"resolve"in e.dts?e.dts.resolve:void 0,t=typeof e.dts==="object"&&"entry"in e.dts?e.dts.entry:void 0,M=(t?$(t):s).map(async({entry:c,outputBasePath:f})=>{let m=await Sr(c,{cwd:r,preferredTsConfigPath:e.preferredTsconfigPath,resolve:C});for(let u of e.format){let or=e.outputExtension?.({format:u,packageType:d,options:e,entry:c}).dts??j(u,d),L=Or.join(r,e.outDir,`${f}${or}`),W=tr(L,r);if(g.files.push({fullPath:L,relativePathToRootDir:W,dts:!0,entry:c,outputBasePath:f,format:u}),m.errors.length>0)$r(m.errors,{warnInsteadOfError:e.watch,shouldExit:!0});await Bun.write(L,m.dts),o.progress("DTS",W,{identifier:e.name})}});await Promise.all(M)}if(await sr(x,e,g,{packageJson:b}),e.onSuccess)await e.onSuccess(e)}function tr(n,r){return n.replace(`${r}/`,"")}export{Br as defineWorkspace,fr as defineConfig,Wr as build};
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/define.ts
91
+ function defineConfig(options) {
92
+ return options;
93
+ }
94
+ function defineWorkspace(options) {
95
+ return options;
96
+ }
97
+ // src/build.ts
98
+ import path2 from "path";
99
+ import { generateDts, logIsolatedDeclarationErrors } from "bun-dts";
100
+
101
+ // src/errors.ts
102
+ var import_picocolors2 = __toESM(require_picocolors(), 1);
103
+
104
+ // src/logger.ts
105
+ var import_picocolors = __toESM(require_picocolors(), 1);
106
+ var silent = false;
107
+ function setSilent(value) {
108
+ silent = value ?? false;
109
+ }
110
+
111
+ class Logger {
112
+ static instance;
113
+ loggedOnceMessages = new Set;
114
+ MAX_LABEL_LENGTH = 3;
115
+ cliColor = import_picocolors.default.blue;
116
+ mutedColor = import_picocolors.default.dim;
117
+ infoColor = import_picocolors.default.cyan;
118
+ warnColor = import_picocolors.default.yellow;
119
+ errorColor = import_picocolors.default.red;
120
+ defaultColor = import_picocolors.default.white;
121
+ progressFgColorMap = {
122
+ ESM: import_picocolors.default.yellow,
123
+ CJS: import_picocolors.default.green,
124
+ IIFE: import_picocolors.default.magenta,
125
+ DTS: import_picocolors.default.blue
126
+ };
127
+ progressIdentifierBgColorMap = {
128
+ ESM: import_picocolors.default.bgYellow,
129
+ CJS: import_picocolors.default.bgGreen,
130
+ IIFE: import_picocolors.default.bgMagenta,
131
+ DTS: import_picocolors.default.bgBlue
132
+ };
133
+ labels = {
134
+ cli: "CLI",
135
+ info: "INFO",
136
+ warn: "WARN",
137
+ error: "ERROR"
138
+ };
139
+ constructor() {}
140
+ static getInstance() {
141
+ if (!Logger.instance) {
142
+ Logger.instance = new Logger;
143
+ }
144
+ return Logger.instance;
145
+ }
146
+ dispose() {
147
+ this.loggedOnceMessages.clear();
148
+ }
149
+ shouldLog(options) {
150
+ if (!options?.once)
151
+ return true;
152
+ if (this.loggedOnceMessages.has(options.once))
153
+ return false;
154
+ this.loggedOnceMessages.add(options.once);
155
+ return true;
156
+ }
157
+ formatMessage({
158
+ fgColor,
159
+ bgColor,
160
+ label,
161
+ message,
162
+ identifier,
163
+ muted
164
+ }) {
165
+ const padding = " ".repeat(Math.max(0, this.MAX_LABEL_LENGTH - label.length));
166
+ const formattedMessage = muted ? this.mutedColor(message) : message;
167
+ const identifierPart = identifier ? ` ${bgColor(import_picocolors.default.black(` ${identifier} `))}` : "";
168
+ return `${fgColor(label)} ${padding}${formattedMessage}${identifierPart}`;
169
+ }
170
+ output(message, options = {}, logFn = console.log) {
171
+ if (silent || !this.shouldLog(options))
172
+ return;
173
+ if (options.verticalSpace)
174
+ logFn("");
175
+ logFn(message);
176
+ if (options.verticalSpace)
177
+ logFn("");
178
+ }
179
+ cli(message, options = {}) {
180
+ const formattedMessage = this.formatMessage({
181
+ fgColor: this.cliColor,
182
+ bgColor: import_picocolors.default.bgBlue,
183
+ label: this.labels.cli,
184
+ message,
185
+ identifier: options.identifier,
186
+ muted: options.muted
187
+ });
188
+ this.output(formattedMessage, options);
189
+ }
190
+ info(message, options = {}) {
191
+ const formattedMessage = this.formatMessage({
192
+ fgColor: this.infoColor,
193
+ bgColor: import_picocolors.default.bgCyan,
194
+ label: this.labels.info,
195
+ message,
196
+ identifier: options.identifier,
197
+ muted: options.muted
198
+ });
199
+ this.output(formattedMessage, options);
200
+ }
201
+ warn(message, options = {}) {
202
+ const formattedMessage = this.formatMessage({
203
+ fgColor: this.warnColor,
204
+ bgColor: import_picocolors.default.bgYellow,
205
+ label: this.labels.warn,
206
+ message,
207
+ identifier: options.identifier,
208
+ muted: options.muted
209
+ });
210
+ this.output(formattedMessage, options, console.warn);
211
+ }
212
+ error(message, options = {}) {
213
+ const formattedMessage = this.formatMessage({
214
+ fgColor: this.errorColor,
215
+ bgColor: import_picocolors.default.bgRed,
216
+ label: this.labels.error,
217
+ message,
218
+ identifier: options.identifier,
219
+ muted: options.muted
220
+ });
221
+ this.output(formattedMessage, options, console.error);
222
+ }
223
+ getProgressFgColor(label) {
224
+ for (const [key, colorFn] of Object.entries(this.progressFgColorMap)) {
225
+ if (label.includes(key))
226
+ return colorFn;
227
+ }
228
+ return this.defaultColor;
229
+ }
230
+ getProgressBgColor(label) {
231
+ for (const [key, colorFn] of Object.entries(this.progressIdentifierBgColorMap)) {
232
+ if (label.includes(key))
233
+ return colorFn;
234
+ }
235
+ return import_picocolors.default.bgWhite;
236
+ }
237
+ progress(label, message, options = {}) {
238
+ const fgColor = this.getProgressFgColor(label);
239
+ const bgColor = this.getProgressBgColor(label);
240
+ const formattedMessage = this.formatMessage({
241
+ fgColor,
242
+ bgColor,
243
+ label,
244
+ message,
245
+ identifier: options.identifier,
246
+ muted: options.muted
247
+ });
248
+ this.output(formattedMessage, options);
249
+ }
250
+ }
251
+ var logger = Logger.getInstance();
252
+
253
+ // src/errors.ts
254
+ class BunupError extends Error {
255
+ constructor(message) {
256
+ super(message);
257
+ this.name = "BunupError";
258
+ }
259
+ }
260
+
261
+ class BunupBuildError extends BunupError {
262
+ constructor(message) {
263
+ super(message);
264
+ this.name = "BunupBuildError";
265
+ }
266
+ }
267
+
268
+ // src/utils.ts
269
+ import fs from "fs/promises";
270
+ import path, { normalize } from "path";
271
+ function getDefaultJsOutputExtension(format, packageType) {
272
+ switch (format) {
273
+ case "esm":
274
+ return isModulePackage(packageType) ? ".js" : ".mjs";
275
+ case "cjs":
276
+ return isModulePackage(packageType) ? ".cjs" : ".js";
277
+ case "iife":
278
+ return ".global.js";
279
+ }
280
+ }
281
+ function getDefaultDtsOutputExtension(format, packageType) {
282
+ switch (format) {
283
+ case "esm":
284
+ return isModulePackage(packageType) ? ".d.ts" : ".d.mts";
285
+ case "cjs":
286
+ return isModulePackage(packageType) ? ".d.cts" : ".d.ts";
287
+ case "iife":
288
+ return ".global.d.ts";
289
+ }
290
+ }
291
+ function removeExtension(filePath) {
292
+ return filePath.replace(path.extname(filePath), "");
293
+ }
294
+ function cleanPath(filePath) {
295
+ return filePath.replace(/\\/g, "/");
296
+ }
297
+ function isModulePackage(packageType) {
298
+ return packageType === "module";
299
+ }
300
+ function getPackageDeps(packageJson) {
301
+ if (!packageJson)
302
+ return [];
303
+ return Array.from(new Set([
304
+ ...Object.keys(packageJson.dependencies || {}),
305
+ ...Object.keys(packageJson.peerDependencies || {})
306
+ ]));
307
+ }
308
+ function getShortFilePath(filePath, maxLength = 3) {
309
+ const fileParts = filePath.split("/");
310
+ const shortPath = fileParts.slice(-maxLength).join("/");
311
+ return shortPath;
312
+ }
313
+ async function cleanOutDir(rootDir, outDir) {
314
+ const outDirPath = path.join(rootDir, outDir);
315
+ try {
316
+ await fs.rm(outDirPath, { recursive: true, force: true });
317
+ } catch (error) {
318
+ throw new BunupBuildError(`Failed to clean output directory: ${error}`);
319
+ }
320
+ await fs.mkdir(outDirPath, { recursive: true });
321
+ }
322
+
323
+ // src/helpers/entry.ts
324
+ function getProcessableEntries(entry) {
325
+ if (typeof entry === "string") {
326
+ return [
327
+ {
328
+ entry,
329
+ outputBasePath: getEntryOutputBasePath(entry)
330
+ }
331
+ ];
332
+ }
333
+ if (typeof entry === "object" && !Array.isArray(entry)) {
334
+ return Object.entries(entry).map(([name, path2]) => ({
335
+ entry: path2,
336
+ outputBasePath: name
337
+ }));
338
+ }
339
+ return entry.map((_entry) => ({
340
+ entry: _entry,
341
+ outputBasePath: getEntryOutputBasePath(_entry)
342
+ }));
343
+ }
344
+ function getEntryOutputBasePath(entry) {
345
+ const pathSegments = cleanPath(removeExtension(entry)).split("/");
346
+ return pathSegments.length > 1 ? pathSegments.slice(1).join("/") : pathSegments.join("/");
347
+ }
348
+ function getResolvedNaming(outputBasePath, extension) {
349
+ return {
350
+ entry: `[dir]/${outputBasePath}${extension}`,
351
+ chunk: `${outputBasePath}-[hash].[ext]`,
352
+ asset: `${outputBasePath}-[name]-[hash].[ext]`
353
+ };
354
+ }
355
+
356
+ // src/loaders.ts
357
+ import { loadConfig } from "coffi";
358
+ async function loadPackageJson(cwd) {
359
+ const { config, filepath } = await loadConfig({
360
+ name: "package",
361
+ cwd,
362
+ extensions: [".json"]
363
+ });
364
+ return {
365
+ data: config,
366
+ path: filepath
367
+ };
368
+ }
369
+
370
+ // src/plugins/internal/use-client.ts
371
+ function useClient() {
372
+ return {
373
+ type: "bunup",
374
+ name: "use-client",
375
+ hooks: {
376
+ onBuildDone: async ({ output }) => {
377
+ for (const file of output.files) {
378
+ let text = await Bun.file(file.fullPath).text();
379
+ const hasUseClient = text.split(`
380
+ `).some((line) => line.trim().startsWith(`"use client";`));
381
+ if (hasUseClient) {
382
+ text = text.replaceAll(`"use client";`, "");
383
+ text = `"use client";
384
+ ${text}`;
385
+ }
386
+ await Bun.write(file.fullPath, text);
387
+ }
388
+ }
389
+ }
390
+ };
391
+ }
392
+
393
+ // src/options.ts
394
+ var DEFAULT_OPTIONS = {
395
+ entry: [],
396
+ format: ["cjs"],
397
+ outDir: "dist",
398
+ target: "node",
399
+ clean: true
400
+ };
401
+ function createBuildOptions(partialOptions) {
402
+ const options = {
403
+ ...DEFAULT_OPTIONS,
404
+ ...partialOptions
405
+ };
406
+ return {
407
+ ...options,
408
+ plugins: [...options.plugins ?? [], useClient()]
409
+ };
410
+ }
411
+ function getResolvedMinify(options) {
412
+ const { minify, minifyWhitespace, minifyIdentifiers, minifySyntax } = options;
413
+ const defaultValue = minify === true;
414
+ return {
415
+ whitespace: minifyWhitespace ?? defaultValue,
416
+ identifiers: minifyIdentifiers ?? defaultValue,
417
+ syntax: minifySyntax ?? defaultValue
418
+ };
419
+ }
420
+ function getResolvedBytecode(bytecode, format) {
421
+ return format === "cjs" ? bytecode : undefined;
422
+ }
423
+ function getResolvedSourcemap(sourcemap) {
424
+ if (sourcemap === true) {
425
+ return "inline";
426
+ }
427
+ return typeof sourcemap === "string" ? sourcemap : undefined;
428
+ }
429
+ function getResolvedDefine(define, env) {
430
+ return {
431
+ ...typeof env === "object" && Object.keys(env).reduce((acc, key) => {
432
+ const value = JSON.stringify(env[key]);
433
+ acc[`process.env.${key}`] = value;
434
+ acc[`import.meta.env.${key}`] = value;
435
+ return acc;
436
+ }, {}),
437
+ ...define
438
+ };
439
+ }
440
+ function getResolvedSplitting(splitting, format) {
441
+ return splitting === undefined ? format === "esm" : splitting;
442
+ }
443
+ function getResolvedEnv(env) {
444
+ return typeof env === "string" ? env : undefined;
445
+ }
446
+
447
+ // src/helpers/external.ts
448
+ function getPackageDepsPatterns(packageJson) {
449
+ return getPackageDeps(packageJson).map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`));
450
+ }
451
+ function matchesPattern(path2, pattern) {
452
+ return typeof pattern === "string" ? pattern === path2 : pattern.test(path2);
453
+ }
454
+ function isExternal(path2, options, packageJson) {
455
+ const packageDepsPatterns = getPackageDepsPatterns(packageJson);
456
+ const matchesExternalPattern = packageDepsPatterns.some((pattern) => pattern.test(path2)) || options.external?.some((pattern) => matchesPattern(path2, pattern));
457
+ const isExcludedFromExternal = options.noExternal?.some((pattern) => matchesPattern(path2, pattern));
458
+ return matchesExternalPattern && !isExcludedFromExternal;
459
+ }
460
+
461
+ // src/plugins/internal/external-option.ts
462
+ function externalOptionPlugin(options, packageJson) {
463
+ return {
464
+ name: "bunup:external-option-plugin",
465
+ setup(build) {
466
+ build.onResolve({ filter: /.*/ }, (args) => {
467
+ const importPath = args.path;
468
+ if (isExternal(importPath, options, packageJson)) {
469
+ return {
470
+ path: importPath,
471
+ external: true
472
+ };
473
+ }
474
+ return null;
475
+ });
476
+ }
477
+ };
478
+ }
479
+
480
+ // src/plugins/utils.ts
481
+ function filterBunupBunPlugins(plugins) {
482
+ if (!plugins)
483
+ return [];
484
+ return plugins.filter((p) => p.type === "bun");
485
+ }
486
+ function filterBunupPlugins(plugins) {
487
+ if (!plugins)
488
+ return [];
489
+ return plugins.filter((p) => p.type === "bunup");
490
+ }
491
+ async function runPluginBuildStartHooks(bunupPlugins, options) {
492
+ if (!bunupPlugins)
493
+ return;
494
+ for (const plugin of bunupPlugins) {
495
+ if (plugin.hooks.onBuildStart) {
496
+ await plugin.hooks.onBuildStart(options);
497
+ }
498
+ }
499
+ }
500
+ async function runPluginBuildDoneHooks(bunupPlugins, options, output, meta) {
501
+ if (!bunupPlugins)
502
+ return;
503
+ for (const plugin of bunupPlugins) {
504
+ if (plugin.hooks.onBuildDone) {
505
+ await plugin.hooks.onBuildDone({ options, output, meta });
506
+ }
507
+ }
508
+ }
509
+
510
+ // src/build.ts
511
+ async function build(partialOptions, rootDir = process.cwd()) {
512
+ const buildOutput = {
513
+ files: []
514
+ };
515
+ const options = createBuildOptions(partialOptions);
516
+ if (!options.entry || options.entry.length === 0 || !options.outDir) {
517
+ throw new BunupBuildError("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");
518
+ }
519
+ if (options.clean) {
520
+ cleanOutDir(rootDir, options.outDir);
521
+ }
522
+ setSilent(options.silent);
523
+ const packageJson = await loadPackageJson(rootDir);
524
+ if (packageJson.data && packageJson.path) {
525
+ logger.cli(`Using ${getShortFilePath(packageJson.path, 2)}`, {
526
+ muted: true,
527
+ identifier: options.name,
528
+ once: `${packageJson.path}:${options.name}`
529
+ });
530
+ }
531
+ const bunupPlugins = filterBunupPlugins(options.plugins);
532
+ await runPluginBuildStartHooks(bunupPlugins, options);
533
+ const processableEntries = getProcessableEntries(options.entry);
534
+ const packageType = packageJson.data?.type;
535
+ const plugins = [
536
+ externalOptionPlugin(options, packageJson.data),
537
+ ...filterBunupBunPlugins(options.plugins).map((p) => p.plugin)
538
+ ];
539
+ if (!options.dtsOnly) {
540
+ const buildPromises = options.format.flatMap((fmt) => processableEntries.map(async ({ entry, outputBasePath }) => {
541
+ const extension = options.outputExtension?.({
542
+ format: fmt,
543
+ packageType,
544
+ options,
545
+ entry
546
+ }).js ?? getDefaultJsOutputExtension(fmt, packageType);
547
+ const result = await Bun.build({
548
+ entrypoints: [`${rootDir}/${entry}`],
549
+ format: fmt,
550
+ naming: getResolvedNaming(outputBasePath, extension),
551
+ splitting: getResolvedSplitting(options.splitting, fmt),
552
+ bytecode: getResolvedBytecode(options.bytecode, fmt),
553
+ define: getResolvedDefine(options.define, options.env),
554
+ minify: getResolvedMinify(options),
555
+ outdir: `${rootDir}/${options.outDir}`,
556
+ target: options.target,
557
+ sourcemap: getResolvedSourcemap(options.sourcemap),
558
+ loader: options.loader,
559
+ drop: options.drop,
560
+ banner: options.banner,
561
+ footer: options.footer,
562
+ publicPath: options.publicPath,
563
+ env: getResolvedEnv(options.env),
564
+ plugins,
565
+ throw: false
566
+ });
567
+ for (const log of result.logs) {
568
+ if (log.level === "error") {
569
+ console.log(`
570
+ `);
571
+ console.log(log);
572
+ console.log(`
573
+ `);
574
+ throw new Error;
575
+ }
576
+ if (log.level === "warning")
577
+ logger.warn(log.message);
578
+ else if (log.level === "info")
579
+ logger.info(log.message);
580
+ }
581
+ for (const file of result.outputs) {
582
+ const relativePathToRootDir = getRelativePathToRootDir(file.path, rootDir);
583
+ if (file.kind === "entry-point") {
584
+ logger.progress(fmt.toUpperCase(), relativePathToRootDir, {
585
+ identifier: options.name
586
+ });
587
+ }
588
+ buildOutput.files.push({
589
+ fullPath: file.path,
590
+ relativePathToRootDir,
591
+ dts: false,
592
+ entry,
593
+ outputBasePath,
594
+ format: fmt
595
+ });
596
+ }
597
+ }));
598
+ await Promise.all(buildPromises);
599
+ }
600
+ if (options.dts === true || typeof options.dts === "object" || options.dtsOnly) {
601
+ const dtsResolve = typeof options.dts === "object" && "resolve" in options.dts ? options.dts.resolve : undefined;
602
+ const dtsEntry = typeof options.dts === "object" && "entry" in options.dts ? options.dts.entry : undefined;
603
+ const processableDtsEntries = dtsEntry ? getProcessableEntries(dtsEntry) : processableEntries;
604
+ const dtsPromises = processableDtsEntries.map(async ({ entry, outputBasePath }) => {
605
+ const result = await generateDts(entry, {
606
+ cwd: rootDir,
607
+ preferredTsConfigPath: options.preferredTsconfigPath,
608
+ resolve: dtsResolve
609
+ });
610
+ for (const fmt of options.format) {
611
+ const extension = options.outputExtension?.({
612
+ format: fmt,
613
+ packageType,
614
+ options,
615
+ entry
616
+ }).dts ?? getDefaultDtsOutputExtension(fmt, packageType);
617
+ const filePath = path2.join(rootDir, options.outDir, `${outputBasePath}${extension}`);
618
+ const relativePathToRootDir = getRelativePathToRootDir(filePath, rootDir);
619
+ buildOutput.files.push({
620
+ fullPath: filePath,
621
+ relativePathToRootDir,
622
+ dts: true,
623
+ entry,
624
+ outputBasePath,
625
+ format: fmt
626
+ });
627
+ if (result.errors.length > 0) {
628
+ logIsolatedDeclarationErrors(result.errors, {
629
+ warnInsteadOfError: options.watch,
630
+ shouldExit: true
631
+ });
632
+ }
633
+ await Bun.write(filePath, result.dts);
634
+ logger.progress("DTS", relativePathToRootDir, {
635
+ identifier: options.name
636
+ });
637
+ }
638
+ });
639
+ await Promise.all(dtsPromises);
640
+ }
641
+ await runPluginBuildDoneHooks(bunupPlugins, options, buildOutput, {
642
+ packageJson
643
+ });
644
+ if (options.onSuccess) {
645
+ await options.onSuccess(options);
646
+ }
647
+ }
648
+ function getRelativePathToRootDir(filePath, rootDir) {
649
+ return filePath.replace(`${rootDir}/`, "");
650
+ }
651
+ export {
652
+ defineWorkspace,
653
+ defineConfig,
654
+ build
655
+ };