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