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/cli.js CHANGED
@@ -1,23 +1,1300 @@
1
- "use client";
2
1
  #!/usr/bin/env bun
3
2
  // @bun
4
- var ci=Object.create;var{getPrototypeOf:mi,defineProperty:H,getOwnPropertyNames:gi}=Object;var xi=Object.prototype.hasOwnProperty;var Y=(i,r,s)=>{s=i!=null?ci(mi(i)):{};let n=r||!i||!i.__esModule?H(s,"default",{value:i,enumerable:!0}):s;for(let t of gi(i))if(!xi.call(n,t))H(n,t,{get:()=>i[t],enumerable:!0});return n};var ui=(i,r)=>()=>(r||i((r={exports:{}}).exports,r),r.exports);var xr=(i,r)=>{for(var s in r)H(i,s,{get:r[s],enumerable:!0,configurable:!0,set:(n)=>r[s]=()=>n})};var S=(i,r)=>()=>(i&&(r=i(i=0)),r);var fi=import.meta.require;var O=ui((ki,v)=>{var K=process||{},ur=K.argv||[],z=K.env||{},wi=!(!!z.NO_COLOR||ur.includes("--no-color"))&&(!!z.FORCE_COLOR||ur.includes("--color")||K.platform==="win32"||(K.stdout||{}).isTTY&&z.TERM!=="dumb"||!!z.CI),hi=(i,r,s=i)=>(n)=>{let t=""+n,d=t.indexOf(r,i.length);return~d?i+Bi(t,r,s,d)+r:i+t+r},Bi=(i,r,s,n)=>{let t="",d=0;do t+=i.substring(d,n)+s,d=n+r.length,n=i.indexOf(r,d);while(~n);return t+i.substring(d)},fr=(i=wi)=>{let r=i?hi:()=>String;return{isColorSupported:i,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")}};v.exports=fr();v.exports.createColors=fr});function G(i){or=i??!1}class q{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;cliColor=c.default.blue;mutedColor=c.default.dim;infoColor=c.default.cyan;warnColor=c.default.yellow;errorColor=c.default.red;defaultColor=c.default.white;progressFgColorMap={ESM:c.default.yellow,CJS:c.default.green,IIFE:c.default.magenta,DTS:c.default.blue};progressIdentifierBgColorMap={ESM:c.default.bgYellow,CJS:c.default.bgGreen,IIFE:c.default.bgMagenta,DTS:c.default.bgBlue};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!q.instance)q.instance=new q;return q.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(i){if(!i?.once)return!0;if(this.loggedOnceMessages.has(i.once))return!1;return this.loggedOnceMessages.add(i.once),!0}formatMessage({fgColor:i,bgColor:r,label:s,message:n,identifier:t,muted:d}){let e=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-s.length)),g=d?this.mutedColor(n):n,B=t?` ${r(c.default.black(` ${t} `))}`:"";return`${i(s)} ${e}${g}${B}`}output(i,r={},s=console.log){if(or||!this.shouldLog(r))return;if(r.verticalSpace)s("");if(s(i),r.verticalSpace)s("")}cli(i,r={}){let s=this.formatMessage({fgColor:this.cliColor,bgColor:c.default.bgBlue,label:this.labels.cli,message:i,identifier:r.identifier,muted:r.muted});this.output(s,r)}info(i,r={}){let s=this.formatMessage({fgColor:this.infoColor,bgColor:c.default.bgCyan,label:this.labels.info,message:i,identifier:r.identifier,muted:r.muted});this.output(s,r)}warn(i,r={}){let s=this.formatMessage({fgColor:this.warnColor,bgColor:c.default.bgYellow,label:this.labels.warn,message:i,identifier:r.identifier,muted:r.muted});this.output(s,r,console.warn)}error(i,r={}){let s=this.formatMessage({fgColor:this.errorColor,bgColor:c.default.bgRed,label:this.labels.error,message:i,identifier:r.identifier,muted:r.muted});this.output(s,r,console.error)}getProgressFgColor(i){for(let[r,s]of Object.entries(this.progressFgColorMap))if(i.includes(r))return s;return this.defaultColor}getProgressBgColor(i){for(let[r,s]of Object.entries(this.progressIdentifierBgColorMap))if(i.includes(r))return s;return c.default.bgWhite}progress(i,r,s={}){let n=this.getProgressFgColor(i),t=this.getProgressBgColor(i),d=this.formatMessage({fgColor:n,bgColor:t,label:i,message:r,identifier:s.identifier,muted:s.muted});this.output(d,s)}}var c,or=!1,m;var I=S(()=>{c=Y(O(),1);m=q.getInstance()});var o,L,X,wr,M,V,P=(i)=>{if(i instanceof Error)return i.message;return String(i)},Ci,a=(i,r)=>{let s=P(i),n=r?`[${r}] `:"",t="";if(i instanceof X)t="BUILD ERROR";else if(i instanceof wr)t="DTS ERROR";else if(i instanceof M)t="CLI ERROR";else if(i instanceof V)t="WATCH ERROR";else if(i instanceof L)t="BUNUP ERROR";let d=Ci.find((e)=>e.pattern.test(s)&&(e.errorType===t||!e.errorType));if(!d&&t)console.error(`${o.default.red(t)} ${n}${s}`);if(d)console.log(`
5
- `),d.logSolution(s),console.log(`
6
- `);else console.error(o.default.dim(o.default.white("If you think this is a bug, please open an issue at: ")+o.default.cyan("https://github.com/arshad-yaseen/bunup/issues/new")))},hr=(i,r)=>{a(i,r),process.exit(1)};var F=S(()=>{o=Y(O(),1);I();L=class L extends Error{constructor(i){super(i);this.name="BunupError"}};X=class X extends L{constructor(i){super(i);this.name="BunupBuildError"}};wr=class wr extends L{constructor(i){super(i);this.name="BunupDTSBuildError"}};M=class M extends L{constructor(i){super(i);this.name="BunupCLIError"}};V=class V extends L{constructor(i){super(i);this.name="BunupWatchError"}};Ci=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",logSolution:()=>{m.error(o.default.white("You're trying to build a project that uses Bun. ")+o.default.white("Please set the target option to ")+o.default.cyan("`bun`")+o.default.white(`.
7
- `)+o.default.white("Example: ")+o.default.green("`bunup --target bun`")+o.default.white(" or in config: ")+o.default.green("{ target: 'bun' }"))}}]});import li from"fs";import Cr from"fs/promises";import y,{normalize as sn}from"path";function lr(i){return Array.isArray(i)?i:[i]}function Sr(i,r){switch(i){case"esm":return E(r)?".js":".mjs";case"cjs":return E(r)?".cjs":".js";case"iife":return".global.js"}}function Mr(i,r){switch(i){case"esm":return E(r)?".d.ts":".d.mts";case"cjs":return E(r)?".d.cts":".d.ts";case"iife":return".global.d.ts"}}function $r(i){let r=y.basename(i),s=y.extname(r);return s?r.slice(0,-s.length):r}function Rr(i){return i.replace(y.extname(i),"")}function Wr(i){return i.replace(/\\/g,"/")}function E(i){return i==="module"}function p(i){return i>=1000?`${(i/1000).toFixed(2)}s`:`${Math.round(i)}ms`}function Yr(i){if(!i)return[];return Array.from(new Set([...Object.keys(i.dependencies||{}),...Object.keys(i.peerDependencies||{})]))}function A(i,r=3){return i.split("/").slice(-r).join("/")}async function Or(i,r){let s=y.join(i,r);try{await Cr.rm(s,{recursive:!0,force:!0})}catch(n){throw new X(`Failed to clean output directory: ${n}`)}await Cr.mkdir(s,{recursive:!0})}function jr(i){try{return li.accessSync(i),!0}catch(r){return!1}}var W=S(()=>{F()});import Ri from"path";import{loadConfig as Wi}from"coffi";async function Lr(i,r,s){return Array.isArray(i)&&"root"in i[0]?i.filter((n)=>s?s.includes(n.name):!0).map((n)=>({rootDir:Ri.resolve(r,n.root),options:Yi(n.config,"name",n.name)})):[{rootDir:r,options:i}]}function Yi(i,r,s){return Array.isArray(i)?i.map((n)=>({...n,[r]:s})):{...i,[r]:s}}async function Xr(i){let{config:r,filepath:s}=await Wi({name:"package",cwd:i,extensions:[".json"]});return{data:r,path:s}}var ir=()=>{};function U(i){if(typeof i==="string")return[{entry:i,outputBasePath:Fr(i)}];if(typeof i==="object"&&!Array.isArray(i))return Object.entries(i).map(([r,s])=>({entry:s,outputBasePath:r}));return i.map((r)=>({entry:r,outputBasePath:Fr(r)}))}function Fr(i){let r=Wr(Rr(i)).split("/");return r.length>1?r.slice(1).join("/"):r.join("/")}function Ur(i,r){return{entry:`[dir]/${i}${r}`,chunk:`${i}-[hash].[ext]`,asset:`${i}-[name]-[hash].[ext]`}}var nr=S(()=>{W()});function Qr(){return{type:"bunup",name:"use-client",hooks:{onBuildDone:async({output:i})=>{for(let r of i.files){let s=await Bun.file(r.fullPath).text();if(s.includes(''))s=s.replaceAll('',""),s=`
8
- ${s}`;await Bun.write(r.fullPath,s)}}}}}function _(i){let r={...Oi,...i};return{...r,plugins:[...r.plugins??[],Qr()]}}function Zr(i){let{minify:r,minifyWhitespace:s,minifyIdentifiers:n,minifySyntax:t}=i,d=r===!0;return{whitespace:s??d,identifiers:n??d,syntax:t??d}}function zr(i,r){return r==="cjs"?i:void 0}function Kr(i){if(i===!0)return"inline";return typeof i==="string"?i:void 0}function Gr(i,r){return{...typeof r==="object"&&Object.keys(r).reduce((s,n)=>{let t=JSON.stringify(r[n]);return s[`process.env.${n}`]=t,s[`import.meta.env.${n}`]=t,s},{}),...i}}function Vr(i,r){return i===void 0?r==="esm":i}function yr(i){return typeof i==="string"?i:void 0}var Oi;var tr=S(()=>{Oi={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0}});function ji(i){return Yr(i).map((r)=>new RegExp(`^${r}($|\\/|\\\\)`))}function Er(i,r){return typeof r==="string"?r===i:r.test(i)}function pr(i,r,s){let t=ji(s).some((e)=>e.test(i))||r.external?.some((e)=>Er(i,e)),d=r.noExternal?.some((e)=>Er(i,e));return t&&!d}var Ar=S(()=>{W()});function Tr(i,r){return{name:"bunup:external-option-plugin",setup(s){s.onResolve({filter:/.*/},(n)=>{let t=n.path;if(pr(t,i,r))return{path:t,external:!0};return null})}}}var Jr=S(()=>{Ar()});function _r(i){if(!i)return[];return i.filter((r)=>r.type==="bun")}function Dr(i){if(!i)return[];return i.filter((r)=>r.type==="bunup")}async function kr(i,r){if(!i)return;for(let s of i)if(s.hooks.onBuildStart)await s.hooks.onBuildStart(r)}async function Nr(i,r,s,n){if(!i)return;for(let t of i)if(t.hooks.onBuildDone)await t.hooks.onBuildDone({options:r,output:s,meta:n})}var vr={};xr(vr,{build:()=>dr});import qi from"path";import{generateDts as Ii,logIsolatedDeclarationErrors as Li}from"bun-dts";async function dr(i,r=process.cwd()){let s={files:[]},n=_(i);if(!n.entry||n.entry.length===0||!n.outDir)throw new X("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(n.clean)Or(r,n.outDir);G(n.silent);let t=await Xr(r);if(t.data&&t.path)m.cli(`Using ${A(t.path,2)}`,{muted:!0,identifier:n.name,once:`${t.path}:${n.name}`});let d=Dr(n.plugins);await kr(d,n);let e=U(n.entry),g=t.data?.type,B=[Tr(n,t.data),..._r(n.plugins).map((w)=>w.plugin)];if(!n.dtsOnly){let w=n.format.flatMap((b)=>e.map(async({entry:l,outputBasePath:x})=>{let u=n.outputExtension?.({format:b,packageType:g,options:n,entry:l}).js??Sr(b,g),C=await Bun.build({entrypoints:[`${r}/${l}`],format:b,naming:Ur(x,u),splitting:Vr(n.splitting,b),bytecode:zr(n.bytecode,b),define:Gr(n.define,n.env),minify:Zr(n),outdir:`${r}/${n.outDir}`,target:n.target,sourcemap:Kr(n.sourcemap),loader:n.loader,drop:n.drop,banner:n.banner,footer:n.footer,publicPath:n.publicPath,env:yr(n.env),plugins:B,throw:!1});for(let f of C.logs){if(f.level==="error")throw console.log(`
9
- `),console.log(f),console.log(`
10
- `),new Error;if(f.level==="warning")m.warn(f.message);else if(f.level==="info")m.info(f.message)}for(let f of C.outputs){let j=Hr(f.path,r);if(f.kind==="entry-point")m.progress(b.toUpperCase(),j,{identifier:n.name});s.files.push({fullPath:f.path,relativePathToRootDir:j,dts:!1,entry:l,outputBasePath:x,format:b})}}));await Promise.all(w)}if(n.dts===!0||typeof n.dts==="object"||n.dtsOnly){let w=typeof n.dts==="object"&&"resolve"in n.dts?n.dts.resolve:void 0,b=typeof n.dts==="object"&&"entry"in n.dts?n.dts.entry:void 0,x=(b?U(b):e).map(async({entry:u,outputBasePath:C})=>{let f=await Ii(u,{cwd:r,preferredTsConfigPath:n.preferredTsconfigPath,resolve:w});for(let j of n.format){let bi=n.outputExtension?.({format:j,packageType:g,options:n,entry:u}).dts??Mr(j,g),N=qi.join(r,n.outDir,`${C}${bi}`),gr=Hr(N,r);if(s.files.push({fullPath:N,relativePathToRootDir:gr,dts:!0,entry:u,outputBasePath:C,format:j}),f.errors.length>0)Li(f.errors,{warnInsteadOfError:n.watch,shouldExit:!0});await Bun.write(N,f.dts),m.progress("DTS",gr,{identifier:n.name})}});await Promise.all(x)}if(await Nr(d,n,s,{packageJson:t}),n.onSuccess)await n.onSuccess(n)}function Hr(i,r){return i.replace(`${r}/`,"")}var er=S(()=>{F();nr();ir();I();tr();Jr();W()});var ti={};xr(ti,{newProject:()=>Ei});import{renameSync as Xi}from"fs";import Q from"path";import{cancel as Fi,confirm as Ui,intro as Qi,outro as Zi,select as zi,tasks as Ki,text as br}from"@clack/prompts";import{downloadTemplate as Gi}from"giget";import{replaceInFile as ri}from"replace-in-file";async function Ei(){Qi(R.default.bgCyan(R.default.black(" Scaffold a new project with Bunup ")));let i=await zi({message:"Select a template",options:ni.map((b)=>({value:b.dir,label:R.default.blue(b.name)}))}),r=ni.find((b)=>b.dir===i);if(!r)Fi("Invalid template"),process.exit(1);let s=r.monorepoDir!==void 0,n=await br({message:"Enter the project name",placeholder:r.defaultName,defaultValue:r.defaultName,validate:(b)=>{if(!b)return"Project name is required";if(b.includes(" "))return"Project name cannot contain spaces";if(jr(si(b)))return"Project already exists"}}),t=si(n),d=!1,e;if(s){if(d=await Ui({message:"Do you want to create a monorepo?",initialValue:!1}),d)e=await br({message:"Enter the name of the first package",placeholder:k,defaultValue:k})}let g=await br({message:"GitHub username and repo name (username/repo):",placeholder:`${cr}/${mr}`,defaultValue:`${cr}/${mr}`}),[B,w]=g.split("/");await Ki([{title:"Downloading template",task:async()=>{let b=d?r.monorepoDir:r.dir;return await Gi(`github:${Vi}/${yi}/${b}`,{dir:t}),"Template downloaded"}},{title:"Making the project yours",task:async()=>{if(await ri({files:Q.join(t,"**/*"),from:[new RegExp(mr,"g"),new RegExp(cr,"g"),new RegExp(r.defaultName,"g")],to:[w,B,n],ignore:["node_modules","dist","bun.lock"]}),d&&e)await ri({files:Q.join(t,"**/*"),from:[new RegExp(k,"g")],to:[e],ignore:["node_modules","dist","bun.lock"]}),Xi(Q.join(t,ii,k),Q.join(t,ii,e))}}]),Zi(`
11
- ${R.default.green("\u2728 Project scaffolded successfully! \u2728")}
12
-
13
- ${R.default.bold("Ready to launch your awesome new project?")}
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
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 __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, {
23
+ get: all[name],
24
+ enumerable: true,
25
+ configurable: true,
26
+ set: (newValue) => all[name] = () => newValue
27
+ });
28
+ };
29
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
30
+ var __require = import.meta.require;
31
+
32
+ // node_modules/picocolors/picocolors.js
33
+ var require_picocolors = __commonJS((exports, module) => {
34
+ var p = process || {};
35
+ var argv = p.argv || [];
36
+ var env = p.env || {};
37
+ 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);
38
+ var formatter = (open, close, replace = open) => (input) => {
39
+ let string = "" + input, index = string.indexOf(close, open.length);
40
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
41
+ };
42
+ var replaceClose = (string, close, replace, index) => {
43
+ let result = "", cursor = 0;
44
+ do {
45
+ result += string.substring(cursor, index) + replace;
46
+ cursor = index + close.length;
47
+ index = string.indexOf(close, cursor);
48
+ } while (~index);
49
+ return result + string.substring(cursor);
50
+ };
51
+ var createColors = (enabled = isColorSupported) => {
52
+ let f = enabled ? formatter : () => String;
53
+ return {
54
+ isColorSupported: enabled,
55
+ reset: f("\x1B[0m", "\x1B[0m"),
56
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
57
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
58
+ italic: f("\x1B[3m", "\x1B[23m"),
59
+ underline: f("\x1B[4m", "\x1B[24m"),
60
+ inverse: f("\x1B[7m", "\x1B[27m"),
61
+ hidden: f("\x1B[8m", "\x1B[28m"),
62
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
63
+ black: f("\x1B[30m", "\x1B[39m"),
64
+ red: f("\x1B[31m", "\x1B[39m"),
65
+ green: f("\x1B[32m", "\x1B[39m"),
66
+ yellow: f("\x1B[33m", "\x1B[39m"),
67
+ blue: f("\x1B[34m", "\x1B[39m"),
68
+ magenta: f("\x1B[35m", "\x1B[39m"),
69
+ cyan: f("\x1B[36m", "\x1B[39m"),
70
+ white: f("\x1B[37m", "\x1B[39m"),
71
+ gray: f("\x1B[90m", "\x1B[39m"),
72
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
73
+ bgRed: f("\x1B[41m", "\x1B[49m"),
74
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
75
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
76
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
77
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
78
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
79
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
80
+ blackBright: f("\x1B[90m", "\x1B[39m"),
81
+ redBright: f("\x1B[91m", "\x1B[39m"),
82
+ greenBright: f("\x1B[92m", "\x1B[39m"),
83
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
84
+ blueBright: f("\x1B[94m", "\x1B[39m"),
85
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
86
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
87
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
88
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
89
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
90
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
91
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
92
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
93
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
94
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
95
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
96
+ };
97
+ };
98
+ module.exports = createColors();
99
+ module.exports.createColors = createColors;
100
+ });
101
+
102
+ // src/logger.ts
103
+ function setSilent(value) {
104
+ silent = value ?? false;
105
+ }
106
+
107
+ class Logger {
108
+ static instance;
109
+ loggedOnceMessages = new Set;
110
+ MAX_LABEL_LENGTH = 3;
111
+ cliColor = import_picocolors.default.blue;
112
+ mutedColor = import_picocolors.default.dim;
113
+ infoColor = import_picocolors.default.cyan;
114
+ warnColor = import_picocolors.default.yellow;
115
+ errorColor = import_picocolors.default.red;
116
+ defaultColor = import_picocolors.default.white;
117
+ progressFgColorMap = {
118
+ ESM: import_picocolors.default.yellow,
119
+ CJS: import_picocolors.default.green,
120
+ IIFE: import_picocolors.default.magenta,
121
+ DTS: import_picocolors.default.blue
122
+ };
123
+ progressIdentifierBgColorMap = {
124
+ ESM: import_picocolors.default.bgYellow,
125
+ CJS: import_picocolors.default.bgGreen,
126
+ IIFE: import_picocolors.default.bgMagenta,
127
+ DTS: import_picocolors.default.bgBlue
128
+ };
129
+ labels = {
130
+ cli: "CLI",
131
+ info: "INFO",
132
+ warn: "WARN",
133
+ error: "ERROR"
134
+ };
135
+ constructor() {}
136
+ static getInstance() {
137
+ if (!Logger.instance) {
138
+ Logger.instance = new Logger;
139
+ }
140
+ return Logger.instance;
141
+ }
142
+ dispose() {
143
+ this.loggedOnceMessages.clear();
144
+ }
145
+ shouldLog(options) {
146
+ if (!options?.once)
147
+ return true;
148
+ if (this.loggedOnceMessages.has(options.once))
149
+ return false;
150
+ this.loggedOnceMessages.add(options.once);
151
+ return true;
152
+ }
153
+ formatMessage({
154
+ fgColor,
155
+ bgColor,
156
+ label,
157
+ message,
158
+ identifier,
159
+ muted
160
+ }) {
161
+ const padding = " ".repeat(Math.max(0, this.MAX_LABEL_LENGTH - label.length));
162
+ const formattedMessage = muted ? this.mutedColor(message) : message;
163
+ const identifierPart = identifier ? ` ${bgColor(import_picocolors.default.black(` ${identifier} `))}` : "";
164
+ return `${fgColor(label)} ${padding}${formattedMessage}${identifierPart}`;
165
+ }
166
+ output(message, options = {}, logFn = console.log) {
167
+ if (silent || !this.shouldLog(options))
168
+ return;
169
+ if (options.verticalSpace)
170
+ logFn("");
171
+ logFn(message);
172
+ if (options.verticalSpace)
173
+ logFn("");
174
+ }
175
+ cli(message, options = {}) {
176
+ const formattedMessage = this.formatMessage({
177
+ fgColor: this.cliColor,
178
+ bgColor: import_picocolors.default.bgBlue,
179
+ label: this.labels.cli,
180
+ message,
181
+ identifier: options.identifier,
182
+ muted: options.muted
183
+ });
184
+ this.output(formattedMessage, options);
185
+ }
186
+ info(message, options = {}) {
187
+ const formattedMessage = this.formatMessage({
188
+ fgColor: this.infoColor,
189
+ bgColor: import_picocolors.default.bgCyan,
190
+ label: this.labels.info,
191
+ message,
192
+ identifier: options.identifier,
193
+ muted: options.muted
194
+ });
195
+ this.output(formattedMessage, options);
196
+ }
197
+ warn(message, options = {}) {
198
+ const formattedMessage = this.formatMessage({
199
+ fgColor: this.warnColor,
200
+ bgColor: import_picocolors.default.bgYellow,
201
+ label: this.labels.warn,
202
+ message,
203
+ identifier: options.identifier,
204
+ muted: options.muted
205
+ });
206
+ this.output(formattedMessage, options, console.warn);
207
+ }
208
+ error(message, options = {}) {
209
+ const formattedMessage = this.formatMessage({
210
+ fgColor: this.errorColor,
211
+ bgColor: import_picocolors.default.bgRed,
212
+ label: this.labels.error,
213
+ message,
214
+ identifier: options.identifier,
215
+ muted: options.muted
216
+ });
217
+ this.output(formattedMessage, options, console.error);
218
+ }
219
+ getProgressFgColor(label) {
220
+ for (const [key, colorFn] of Object.entries(this.progressFgColorMap)) {
221
+ if (label.includes(key))
222
+ return colorFn;
223
+ }
224
+ return this.defaultColor;
225
+ }
226
+ getProgressBgColor(label) {
227
+ for (const [key, colorFn] of Object.entries(this.progressIdentifierBgColorMap)) {
228
+ if (label.includes(key))
229
+ return colorFn;
230
+ }
231
+ return import_picocolors.default.bgWhite;
232
+ }
233
+ progress(label, message, options = {}) {
234
+ const fgColor = this.getProgressFgColor(label);
235
+ const bgColor = this.getProgressBgColor(label);
236
+ const formattedMessage = this.formatMessage({
237
+ fgColor,
238
+ bgColor,
239
+ label,
240
+ message,
241
+ identifier: options.identifier,
242
+ muted: options.muted
243
+ });
244
+ this.output(formattedMessage, options);
245
+ }
246
+ }
247
+ var import_picocolors, silent = false, logger;
248
+ var init_logger = __esm(() => {
249
+ import_picocolors = __toESM(require_picocolors(), 1);
250
+ logger = Logger.getInstance();
251
+ });
252
+
253
+ // src/errors.ts
254
+ var import_picocolors2, BunupError, BunupBuildError, BunupDTSBuildError, BunupCLIError, BunupWatchError, parseErrorMessage = (error) => {
255
+ if (error instanceof Error) {
256
+ return error.message;
257
+ }
258
+ return String(error);
259
+ }, KNOWN_ERRORS, handleError = (error, context) => {
260
+ const errorMessage = parseErrorMessage(error);
261
+ const contextPrefix = context ? `[${context}] ` : "";
262
+ let errorType = "";
263
+ if (error instanceof BunupBuildError) {
264
+ errorType = "BUILD ERROR";
265
+ } else if (error instanceof BunupDTSBuildError) {
266
+ errorType = "DTS ERROR";
267
+ } else if (error instanceof BunupCLIError) {
268
+ errorType = "CLI ERROR";
269
+ } else if (error instanceof BunupWatchError) {
270
+ errorType = "WATCH ERROR";
271
+ } else if (error instanceof BunupError) {
272
+ errorType = "BUNUP ERROR";
273
+ }
274
+ const knownError = KNOWN_ERRORS.find((error2) => error2.pattern.test(errorMessage) && (error2.errorType === errorType || !error2.errorType));
275
+ if (!knownError && errorType) {
276
+ console.error(`${import_picocolors2.default.red(errorType)} ${contextPrefix}${errorMessage}`);
277
+ }
278
+ if (knownError) {
279
+ console.log(`
280
+ `);
281
+ knownError.logSolution(errorMessage);
282
+ console.log(`
283
+ `);
284
+ } else {
285
+ console.error(import_picocolors2.default.dim(import_picocolors2.default.white("If you think this is a bug, please open an issue at: ") + import_picocolors2.default.cyan("https://github.com/arshad-yaseen/bunup/issues/new")));
286
+ }
287
+ }, handleErrorAndExit = (error, context) => {
288
+ handleError(error, context);
289
+ process.exit(1);
290
+ };
291
+ var init_errors = __esm(() => {
292
+ import_picocolors2 = __toESM(require_picocolors(), 1);
293
+ init_logger();
294
+ BunupError = class BunupError extends Error {
295
+ constructor(message) {
296
+ super(message);
297
+ this.name = "BunupError";
298
+ }
299
+ };
300
+ BunupBuildError = class BunupBuildError extends BunupError {
301
+ constructor(message) {
302
+ super(message);
303
+ this.name = "BunupBuildError";
304
+ }
305
+ };
306
+ BunupDTSBuildError = class BunupDTSBuildError extends BunupError {
307
+ constructor(message) {
308
+ super(message);
309
+ this.name = "BunupDTSBuildError";
310
+ }
311
+ };
312
+ BunupCLIError = class BunupCLIError extends BunupError {
313
+ constructor(message) {
314
+ super(message);
315
+ this.name = "BunupCLIError";
316
+ }
317
+ };
318
+ BunupWatchError = class BunupWatchError extends BunupError {
319
+ constructor(message) {
320
+ super(message);
321
+ this.name = "BunupWatchError";
322
+ }
323
+ };
324
+ KNOWN_ERRORS = [
325
+ {
326
+ pattern: /Could not resolve: "bun"/i,
327
+ errorType: "BUILD ERROR",
328
+ logSolution: () => {
329
+ logger.error(import_picocolors2.default.white("You're trying to build a project that uses Bun. ") + import_picocolors2.default.white("Please set the target option to ") + import_picocolors2.default.cyan("`bun`") + import_picocolors2.default.white(`.
330
+ `) + import_picocolors2.default.white("Example: ") + import_picocolors2.default.green("`bunup --target bun`") + import_picocolors2.default.white(" or in config: ") + import_picocolors2.default.green("{ target: 'bun' }"));
331
+ }
332
+ }
333
+ ];
334
+ });
335
+
336
+ // src/utils.ts
337
+ import fsSync from "fs";
338
+ import fs from "fs/promises";
339
+ import path, { normalize } from "path";
340
+ function ensureArray(value) {
341
+ return Array.isArray(value) ? value : [value];
342
+ }
343
+ function getDefaultJsOutputExtension(format, packageType) {
344
+ switch (format) {
345
+ case "esm":
346
+ return isModulePackage(packageType) ? ".js" : ".mjs";
347
+ case "cjs":
348
+ return isModulePackage(packageType) ? ".cjs" : ".js";
349
+ case "iife":
350
+ return ".global.js";
351
+ }
352
+ }
353
+ function getDefaultDtsOutputExtension(format, packageType) {
354
+ switch (format) {
355
+ case "esm":
356
+ return isModulePackage(packageType) ? ".d.ts" : ".d.mts";
357
+ case "cjs":
358
+ return isModulePackage(packageType) ? ".d.cts" : ".d.ts";
359
+ case "iife":
360
+ return ".global.d.ts";
361
+ }
362
+ }
363
+ function getBaseFileName(filePath) {
364
+ const filename = path.basename(filePath);
365
+ const extension = path.extname(filename);
366
+ return extension ? filename.slice(0, -extension.length) : filename;
367
+ }
368
+ function removeExtension(filePath) {
369
+ return filePath.replace(path.extname(filePath), "");
370
+ }
371
+ function cleanPath(filePath) {
372
+ return filePath.replace(/\\/g, "/");
373
+ }
374
+ function isModulePackage(packageType) {
375
+ return packageType === "module";
376
+ }
377
+ function formatTime(ms) {
378
+ return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`;
379
+ }
380
+ function getPackageDeps(packageJson) {
381
+ if (!packageJson)
382
+ return [];
383
+ return Array.from(new Set([
384
+ ...Object.keys(packageJson.dependencies || {}),
385
+ ...Object.keys(packageJson.peerDependencies || {})
386
+ ]));
387
+ }
388
+ function getShortFilePath(filePath, maxLength = 3) {
389
+ const fileParts = filePath.split("/");
390
+ const shortPath = fileParts.slice(-maxLength).join("/");
391
+ return shortPath;
392
+ }
393
+ async function cleanOutDir(rootDir, outDir) {
394
+ const outDirPath = path.join(rootDir, outDir);
395
+ try {
396
+ await fs.rm(outDirPath, { recursive: true, force: true });
397
+ } catch (error) {
398
+ throw new BunupBuildError(`Failed to clean output directory: ${error}`);
399
+ }
400
+ await fs.mkdir(outDirPath, { recursive: true });
401
+ }
402
+ function pathExistsSync(filePath) {
403
+ try {
404
+ fsSync.accessSync(filePath);
405
+ return true;
406
+ } catch (error) {
407
+ return false;
408
+ }
409
+ }
410
+ var init_utils = __esm(() => {
411
+ init_errors();
412
+ });
413
+
414
+ // src/loaders.ts
415
+ import path2 from "path";
416
+ import { loadConfig } from "coffi";
417
+ async function processLoadedConfigs(config, cwd, filter) {
418
+ return Array.isArray(config) && "root" in config[0] ? config.filter((c) => filter ? filter.includes(c.name) : true).map((c) => ({
419
+ rootDir: path2.resolve(cwd, c.root),
420
+ options: addField(c.config, "name", c.name)
421
+ })) : [
422
+ {
423
+ rootDir: cwd,
424
+ options: config
425
+ }
426
+ ];
427
+ }
428
+ function addField(objectOrArray, field, value) {
429
+ return Array.isArray(objectOrArray) ? objectOrArray.map((o) => ({ ...o, [field]: value })) : { ...objectOrArray, [field]: value };
430
+ }
431
+ async function loadPackageJson(cwd) {
432
+ const { config, filepath } = await loadConfig({
433
+ name: "package",
434
+ cwd,
435
+ extensions: [".json"]
436
+ });
437
+ return {
438
+ data: config,
439
+ path: filepath
440
+ };
441
+ }
442
+ var init_loaders = () => {};
443
+
444
+ // src/helpers/entry.ts
445
+ function getProcessableEntries(entry) {
446
+ if (typeof entry === "string") {
447
+ return [
448
+ {
449
+ entry,
450
+ outputBasePath: getEntryOutputBasePath(entry)
451
+ }
452
+ ];
453
+ }
454
+ if (typeof entry === "object" && !Array.isArray(entry)) {
455
+ return Object.entries(entry).map(([name, path3]) => ({
456
+ entry: path3,
457
+ outputBasePath: name
458
+ }));
459
+ }
460
+ return entry.map((_entry) => ({
461
+ entry: _entry,
462
+ outputBasePath: getEntryOutputBasePath(_entry)
463
+ }));
464
+ }
465
+ function getEntryOutputBasePath(entry) {
466
+ const pathSegments = cleanPath(removeExtension(entry)).split("/");
467
+ return pathSegments.length > 1 ? pathSegments.slice(1).join("/") : pathSegments.join("/");
468
+ }
469
+ function getResolvedNaming(outputBasePath, extension) {
470
+ return {
471
+ entry: `[dir]/${outputBasePath}${extension}`,
472
+ chunk: `${outputBasePath}-[hash].[ext]`,
473
+ asset: `${outputBasePath}-[name]-[hash].[ext]`
474
+ };
475
+ }
476
+ var init_entry = __esm(() => {
477
+ init_utils();
478
+ });
479
+
480
+ // src/plugins/internal/use-client.ts
481
+ function useClient() {
482
+ return {
483
+ type: "bunup",
484
+ name: "use-client",
485
+ hooks: {
486
+ onBuildDone: async ({ output }) => {
487
+ for (const file of output.files) {
488
+ let text = await Bun.file(file.fullPath).text();
489
+ const hasUseClient = text.split(`
490
+ `).some((line) => line.trim().startsWith(`"use client";`));
491
+ if (hasUseClient) {
492
+ text = text.replaceAll(`"use client";`, "");
493
+ text = `"use client";
494
+ ${text}`;
495
+ }
496
+ await Bun.write(file.fullPath, text);
497
+ }
498
+ }
499
+ }
500
+ };
501
+ }
502
+
503
+ // src/options.ts
504
+ function createBuildOptions(partialOptions) {
505
+ const options = {
506
+ ...DEFAULT_OPTIONS,
507
+ ...partialOptions
508
+ };
509
+ return {
510
+ ...options,
511
+ plugins: [...options.plugins ?? [], useClient()]
512
+ };
513
+ }
514
+ function getResolvedMinify(options) {
515
+ const { minify, minifyWhitespace, minifyIdentifiers, minifySyntax } = options;
516
+ const defaultValue = minify === true;
517
+ return {
518
+ whitespace: minifyWhitespace ?? defaultValue,
519
+ identifiers: minifyIdentifiers ?? defaultValue,
520
+ syntax: minifySyntax ?? defaultValue
521
+ };
522
+ }
523
+ function getResolvedBytecode(bytecode, format) {
524
+ return format === "cjs" ? bytecode : undefined;
525
+ }
526
+ function getResolvedSourcemap(sourcemap) {
527
+ if (sourcemap === true) {
528
+ return "inline";
529
+ }
530
+ return typeof sourcemap === "string" ? sourcemap : undefined;
531
+ }
532
+ function getResolvedDefine(define, env) {
533
+ return {
534
+ ...typeof env === "object" && Object.keys(env).reduce((acc, key) => {
535
+ const value = JSON.stringify(env[key]);
536
+ acc[`process.env.${key}`] = value;
537
+ acc[`import.meta.env.${key}`] = value;
538
+ return acc;
539
+ }, {}),
540
+ ...define
541
+ };
542
+ }
543
+ function getResolvedSplitting(splitting, format) {
544
+ return splitting === undefined ? format === "esm" : splitting;
545
+ }
546
+ function getResolvedEnv(env) {
547
+ return typeof env === "string" ? env : undefined;
548
+ }
549
+ var DEFAULT_OPTIONS;
550
+ var init_options = __esm(() => {
551
+ DEFAULT_OPTIONS = {
552
+ entry: [],
553
+ format: ["cjs"],
554
+ outDir: "dist",
555
+ target: "node",
556
+ clean: true
557
+ };
558
+ });
559
+
560
+ // src/helpers/external.ts
561
+ function getPackageDepsPatterns(packageJson) {
562
+ return getPackageDeps(packageJson).map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`));
563
+ }
564
+ function matchesPattern(path3, pattern) {
565
+ return typeof pattern === "string" ? pattern === path3 : pattern.test(path3);
566
+ }
567
+ function isExternal(path3, options, packageJson) {
568
+ const packageDepsPatterns = getPackageDepsPatterns(packageJson);
569
+ const matchesExternalPattern = packageDepsPatterns.some((pattern) => pattern.test(path3)) || options.external?.some((pattern) => matchesPattern(path3, pattern));
570
+ const isExcludedFromExternal = options.noExternal?.some((pattern) => matchesPattern(path3, pattern));
571
+ return matchesExternalPattern && !isExcludedFromExternal;
572
+ }
573
+ var init_external = __esm(() => {
574
+ init_utils();
575
+ });
576
+
577
+ // src/plugins/internal/external-option.ts
578
+ function externalOptionPlugin(options, packageJson) {
579
+ return {
580
+ name: "bunup:external-option-plugin",
581
+ setup(build) {
582
+ build.onResolve({ filter: /.*/ }, (args) => {
583
+ const importPath = args.path;
584
+ if (isExternal(importPath, options, packageJson)) {
585
+ return {
586
+ path: importPath,
587
+ external: true
588
+ };
589
+ }
590
+ return null;
591
+ });
592
+ }
593
+ };
594
+ }
595
+ var init_external_option = __esm(() => {
596
+ init_external();
597
+ });
598
+
599
+ // src/plugins/utils.ts
600
+ function filterBunupBunPlugins(plugins) {
601
+ if (!plugins)
602
+ return [];
603
+ return plugins.filter((p) => p.type === "bun");
604
+ }
605
+ function filterBunupPlugins(plugins) {
606
+ if (!plugins)
607
+ return [];
608
+ return plugins.filter((p) => p.type === "bunup");
609
+ }
610
+ async function runPluginBuildStartHooks(bunupPlugins, options) {
611
+ if (!bunupPlugins)
612
+ return;
613
+ for (const plugin of bunupPlugins) {
614
+ if (plugin.hooks.onBuildStart) {
615
+ await plugin.hooks.onBuildStart(options);
616
+ }
617
+ }
618
+ }
619
+ async function runPluginBuildDoneHooks(bunupPlugins, options, output, meta) {
620
+ if (!bunupPlugins)
621
+ return;
622
+ for (const plugin of bunupPlugins) {
623
+ if (plugin.hooks.onBuildDone) {
624
+ await plugin.hooks.onBuildDone({ options, output, meta });
625
+ }
626
+ }
627
+ }
628
+
629
+ // src/build.ts
630
+ var exports_build = {};
631
+ __export(exports_build, {
632
+ build: () => build
633
+ });
634
+ import path3 from "path";
635
+ import { generateDts, logIsolatedDeclarationErrors } from "bun-dts";
636
+ async function build(partialOptions, rootDir = process.cwd()) {
637
+ const buildOutput = {
638
+ files: []
639
+ };
640
+ const options = createBuildOptions(partialOptions);
641
+ if (!options.entry || options.entry.length === 0 || !options.outDir) {
642
+ throw new BunupBuildError("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");
643
+ }
644
+ if (options.clean) {
645
+ cleanOutDir(rootDir, options.outDir);
646
+ }
647
+ setSilent(options.silent);
648
+ const packageJson = await loadPackageJson(rootDir);
649
+ if (packageJson.data && packageJson.path) {
650
+ logger.cli(`Using ${getShortFilePath(packageJson.path, 2)}`, {
651
+ muted: true,
652
+ identifier: options.name,
653
+ once: `${packageJson.path}:${options.name}`
654
+ });
655
+ }
656
+ const bunupPlugins = filterBunupPlugins(options.plugins);
657
+ await runPluginBuildStartHooks(bunupPlugins, options);
658
+ const processableEntries = getProcessableEntries(options.entry);
659
+ const packageType = packageJson.data?.type;
660
+ const plugins = [
661
+ externalOptionPlugin(options, packageJson.data),
662
+ ...filterBunupBunPlugins(options.plugins).map((p) => p.plugin)
663
+ ];
664
+ if (!options.dtsOnly) {
665
+ const buildPromises = options.format.flatMap((fmt) => processableEntries.map(async ({ entry, outputBasePath }) => {
666
+ const extension = options.outputExtension?.({
667
+ format: fmt,
668
+ packageType,
669
+ options,
670
+ entry
671
+ }).js ?? getDefaultJsOutputExtension(fmt, packageType);
672
+ const result = await Bun.build({
673
+ entrypoints: [`${rootDir}/${entry}`],
674
+ format: fmt,
675
+ naming: getResolvedNaming(outputBasePath, extension),
676
+ splitting: getResolvedSplitting(options.splitting, fmt),
677
+ bytecode: getResolvedBytecode(options.bytecode, fmt),
678
+ define: getResolvedDefine(options.define, options.env),
679
+ minify: getResolvedMinify(options),
680
+ outdir: `${rootDir}/${options.outDir}`,
681
+ target: options.target,
682
+ sourcemap: getResolvedSourcemap(options.sourcemap),
683
+ loader: options.loader,
684
+ drop: options.drop,
685
+ banner: options.banner,
686
+ footer: options.footer,
687
+ publicPath: options.publicPath,
688
+ env: getResolvedEnv(options.env),
689
+ plugins,
690
+ throw: false
691
+ });
692
+ for (const log of result.logs) {
693
+ if (log.level === "error") {
694
+ console.log(`
695
+ `);
696
+ console.log(log);
697
+ console.log(`
698
+ `);
699
+ throw new Error;
700
+ }
701
+ if (log.level === "warning")
702
+ logger.warn(log.message);
703
+ else if (log.level === "info")
704
+ logger.info(log.message);
705
+ }
706
+ for (const file of result.outputs) {
707
+ const relativePathToRootDir = getRelativePathToRootDir(file.path, rootDir);
708
+ if (file.kind === "entry-point") {
709
+ logger.progress(fmt.toUpperCase(), relativePathToRootDir, {
710
+ identifier: options.name
711
+ });
712
+ }
713
+ buildOutput.files.push({
714
+ fullPath: file.path,
715
+ relativePathToRootDir,
716
+ dts: false,
717
+ entry,
718
+ outputBasePath,
719
+ format: fmt
720
+ });
721
+ }
722
+ }));
723
+ await Promise.all(buildPromises);
724
+ }
725
+ if (options.dts === true || typeof options.dts === "object" || options.dtsOnly) {
726
+ const dtsResolve = typeof options.dts === "object" && "resolve" in options.dts ? options.dts.resolve : undefined;
727
+ const dtsEntry = typeof options.dts === "object" && "entry" in options.dts ? options.dts.entry : undefined;
728
+ const processableDtsEntries = dtsEntry ? getProcessableEntries(dtsEntry) : processableEntries;
729
+ const dtsPromises = processableDtsEntries.map(async ({ entry, outputBasePath }) => {
730
+ const result = await generateDts(entry, {
731
+ cwd: rootDir,
732
+ preferredTsConfigPath: options.preferredTsconfigPath,
733
+ resolve: dtsResolve
734
+ });
735
+ for (const fmt of options.format) {
736
+ const extension = options.outputExtension?.({
737
+ format: fmt,
738
+ packageType,
739
+ options,
740
+ entry
741
+ }).dts ?? getDefaultDtsOutputExtension(fmt, packageType);
742
+ const filePath = path3.join(rootDir, options.outDir, `${outputBasePath}${extension}`);
743
+ const relativePathToRootDir = getRelativePathToRootDir(filePath, rootDir);
744
+ buildOutput.files.push({
745
+ fullPath: filePath,
746
+ relativePathToRootDir,
747
+ dts: true,
748
+ entry,
749
+ outputBasePath,
750
+ format: fmt
751
+ });
752
+ if (result.errors.length > 0) {
753
+ logIsolatedDeclarationErrors(result.errors, {
754
+ warnInsteadOfError: options.watch,
755
+ shouldExit: true
756
+ });
757
+ }
758
+ await Bun.write(filePath, result.dts);
759
+ logger.progress("DTS", relativePathToRootDir, {
760
+ identifier: options.name
761
+ });
762
+ }
763
+ });
764
+ await Promise.all(dtsPromises);
765
+ }
766
+ await runPluginBuildDoneHooks(bunupPlugins, options, buildOutput, {
767
+ packageJson
768
+ });
769
+ if (options.onSuccess) {
770
+ await options.onSuccess(options);
771
+ }
772
+ }
773
+ function getRelativePathToRootDir(filePath, rootDir) {
774
+ return filePath.replace(`${rootDir}/`, "");
775
+ }
776
+ var init_build = __esm(() => {
777
+ init_errors();
778
+ init_entry();
779
+ init_loaders();
780
+ init_logger();
781
+ init_options();
782
+ init_external_option();
783
+ init_utils();
784
+ });
785
+
786
+ // src/cli/new.ts
787
+ var exports_new = {};
788
+ __export(exports_new, {
789
+ newProject: () => newProject
790
+ });
791
+ import { renameSync } from "fs";
792
+ import path5 from "path";
793
+ import {
794
+ cancel,
795
+ confirm,
796
+ intro,
797
+ outro,
798
+ select,
799
+ tasks,
800
+ text
801
+ } from "@clack/prompts";
802
+ import { downloadTemplate } from "giget";
803
+ import { replaceInFile } from "replace-in-file";
804
+ async function newProject() {
805
+ intro(import_picocolors5.default.bgCyan(import_picocolors5.default.black(" Scaffold a new project with Bunup ")));
806
+ const selectedTemplateDir = await select({
807
+ message: "Select a template",
808
+ options: TEMPLATES.map((template2) => ({
809
+ value: template2.dir,
810
+ label: import_picocolors5.default.blue(template2.name)
811
+ }))
812
+ });
813
+ const template = TEMPLATES.find((t) => t.dir === selectedTemplateDir);
814
+ if (!template) {
815
+ cancel("Invalid template");
816
+ process.exit(1);
817
+ }
818
+ const hasMonorepo = template.monorepoDir !== undefined;
819
+ const projectName = await text({
820
+ message: "Enter the project name",
821
+ placeholder: template.defaultName,
822
+ defaultValue: template.defaultName,
823
+ validate: (value) => {
824
+ if (!value) {
825
+ return "Project name is required";
826
+ }
827
+ if (value.includes(" ")) {
828
+ return "Project name cannot contain spaces";
829
+ }
830
+ if (pathExistsSync(getProjectPath(value))) {
831
+ return "Project already exists";
832
+ }
833
+ }
834
+ });
835
+ const projectPath = getProjectPath(projectName);
836
+ let useMonorepo = false;
837
+ let monorepoFirstPackageName;
838
+ if (hasMonorepo) {
839
+ useMonorepo = await confirm({
840
+ message: "Do you want to create a monorepo?",
841
+ initialValue: false
842
+ });
843
+ if (useMonorepo) {
844
+ monorepoFirstPackageName = await text({
845
+ message: "Enter the name of the first package",
846
+ placeholder: MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER,
847
+ defaultValue: MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER
848
+ });
849
+ }
850
+ }
851
+ const githubRepoInfo = await text({
852
+ message: "GitHub username and repo name (username/repo):",
853
+ placeholder: `${GITHUB_USERNAME_PLACEHOLDER}/${GITHUB_REPO_PLACEHOLDER}`,
854
+ defaultValue: `${GITHUB_USERNAME_PLACEHOLDER}/${GITHUB_REPO_PLACEHOLDER}`
855
+ });
856
+ const [githubUsername, githubRepoName] = githubRepoInfo.split("/");
857
+ await tasks([
858
+ {
859
+ title: "Downloading template",
860
+ task: async () => {
861
+ const templatePath = useMonorepo ? template.monorepoDir : template.dir;
862
+ await downloadTemplate(`github:${TEMPLATE_OWNER}/${TEMPLATE_REPO}/${templatePath}`, {
863
+ dir: projectPath
864
+ });
865
+ return "Template downloaded";
866
+ }
867
+ },
868
+ {
869
+ title: "Making the project yours",
870
+ task: async () => {
871
+ await replaceInFile({
872
+ files: path5.join(projectPath, "**/*"),
873
+ from: [
874
+ new RegExp(GITHUB_REPO_PLACEHOLDER, "g"),
875
+ new RegExp(GITHUB_USERNAME_PLACEHOLDER, "g"),
876
+ new RegExp(template.defaultName, "g")
877
+ ],
878
+ to: [githubRepoName, githubUsername, projectName],
879
+ ignore: ["node_modules", "dist", "bun.lock"]
880
+ });
881
+ if (useMonorepo && monorepoFirstPackageName) {
882
+ await replaceInFile({
883
+ files: path5.join(projectPath, "**/*"),
884
+ from: [
885
+ new RegExp(MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER, "g")
886
+ ],
887
+ to: [monorepoFirstPackageName],
888
+ ignore: ["node_modules", "dist", "bun.lock"]
889
+ });
890
+ renameSync(path5.join(projectPath, MONOREPO_PACKAGES_DIR, MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER), path5.join(projectPath, MONOREPO_PACKAGES_DIR, monorepoFirstPackageName));
891
+ }
892
+ }
893
+ }
894
+ ]);
895
+ outro(`
896
+ ${import_picocolors5.default.green("\u2728 Project scaffolded successfully! \u2728")}
897
+
898
+ ${import_picocolors5.default.bold("Ready to launch your awesome new project?")}
14
899
 
15
- ${R.default.cyan("cd")} ${n}
16
- ${R.default.cyan("bun install")}
17
- ${R.default.cyan("bun run dev")}
900
+ ${import_picocolors5.default.cyan("cd")} ${projectName}
901
+ ${import_picocolors5.default.cyan("bun install")}
902
+ ${import_picocolors5.default.cyan("bun run dev")}
18
903
 
19
- ${R.default.yellow("Happy coding!")} \uD83D\uDE80
20
- `)}function si(i){return Q.join(process.cwd(),i)}var R,Vi="arshad-yaseen",yi="bunup-new",cr="username",mr="repo-name",k="package-1",ii="packages",ni;var di=S(()=>{R=Y(O(),1);W();ni=[{defaultName:"my-ts-lib",name:"Typescript Library",dir:"ts-lib",monorepoDir:"ts-lib-monorepo"}]});import{exec as pi}from"tinyexec";var Z="0.8.2";F();I();var rr=Y(O(),1);var Br="https://bunup.dev/docs/guide/cli-options";F();I();W();function h(i){return(r,s)=>{s[i]=r===!0||r==="true"}}function $(i){return(r,s)=>{if(typeof r==="string")s[i]=r;else throw new M(`Option --${i} requires a string value`)}}function T(i){return(r,s)=>{if(typeof r==="string")s[i]=r.split(",");else throw new M(`Option --${i} requires a string value`)}}function Si(i){return(r,s)=>{if(typeof r==="boolean")s[i]=r;else if(typeof r==="string")if(r.toLowerCase()==="true"||r.toLowerCase()==="false")s[i]=r.toLowerCase()==="true";else s[i]=r;else throw new M(`Option --${i} requires a boolean or string value`)}}function Mi(){console.log(`
904
+ ${import_picocolors5.default.yellow("Happy coding!")} \uD83D\uDE80
905
+ `);
906
+ }
907
+ function getProjectPath(projectName) {
908
+ return path5.join(process.cwd(), projectName);
909
+ }
910
+ var import_picocolors5, TEMPLATE_OWNER = "arshad-yaseen", TEMPLATE_REPO = "bunup-new", GITHUB_USERNAME_PLACEHOLDER = "username", GITHUB_REPO_PLACEHOLDER = "repo-name", MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER = "package-1", MONOREPO_PACKAGES_DIR = "packages", TEMPLATES;
911
+ var init_new = __esm(() => {
912
+ import_picocolors5 = __toESM(require_picocolors(), 1);
913
+ init_utils();
914
+ TEMPLATES = [
915
+ {
916
+ defaultName: "my-ts-lib",
917
+ name: "Typescript Library",
918
+ dir: "ts-lib",
919
+ monorepoDir: "ts-lib-monorepo"
920
+ }
921
+ ];
922
+ });
923
+
924
+ // src/cli/index.ts
925
+ import { exec } from "tinyexec";
926
+ // package.json
927
+ var version = "0.8.4";
928
+
929
+ // src/cli/index.ts
930
+ init_errors();
931
+ init_logger();
932
+
933
+ // src/cli/options.ts
934
+ var import_picocolors3 = __toESM(require_picocolors(), 1);
935
+
936
+ // src/constants/index.ts
937
+ var BUNUP_CLI_OPTIONS_URL = "https://bunup.dev/docs/guide/cli-options";
938
+
939
+ // src/cli/options.ts
940
+ init_errors();
941
+ init_logger();
942
+ init_utils();
943
+ function booleanHandler(optionName) {
944
+ return (value, options) => {
945
+ options[optionName] = value === true || value === "true";
946
+ };
947
+ }
948
+ function stringHandler(optionName) {
949
+ return (value, options) => {
950
+ if (typeof value === "string") {
951
+ options[optionName] = value;
952
+ } else {
953
+ throw new BunupCLIError(`Option --${optionName} requires a string value`);
954
+ }
955
+ };
956
+ }
957
+ function arrayHandler(optionName) {
958
+ return (value, options) => {
959
+ if (typeof value === "string") {
960
+ options[optionName] = value.split(",");
961
+ } else {
962
+ throw new BunupCLIError(`Option --${optionName} requires a string value`);
963
+ }
964
+ };
965
+ }
966
+ function booleanOrStringHandler(optionName) {
967
+ return (value, options) => {
968
+ if (typeof value === "boolean") {
969
+ options[optionName] = value;
970
+ } else if (typeof value === "string") {
971
+ if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
972
+ options[optionName] = value.toLowerCase() === "true";
973
+ } else {
974
+ options[optionName] = value;
975
+ }
976
+ } else {
977
+ throw new BunupCLIError(`Option --${optionName} requires a boolean or string value`);
978
+ }
979
+ };
980
+ }
981
+ function showHelp() {
982
+ console.log(`
21
983
  Bunup - \u26A1\uFE0F A blazing-fast build tool for your libraries built with Bun.
22
- `),console.log("For more information on available options, visit:"),console.log(`${rr.default.cyan(rr.default.underline(Br))}
23
- `),process.exit(0)}function $i(){console.log(Z),process.exit(0)}var qr={name:{flags:["n","name"],handler:$("name")},format:{flags:["f","format"],handler:T("format")},outDir:{flags:["o","out-dir"],handler:$("outDir")},minify:{flags:["m","minify"],handler:h("minify")},watch:{flags:["w","watch"],handler:h("watch")},dts:{flags:["d","dts"],handler:h("dts")},banner:{flags:["bn","banner"],handler:$("banner")},footer:{flags:["ft","footer"],handler:$("footer")},external:{flags:["e","external"],handler:T("external")},sourcemap:{flags:["sm","sourcemap"],handler:Si("sourcemap")},target:{flags:["t","target"],handler:$("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:h("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:h("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:h("minifySyntax")},clean:{flags:["c","clean"],handler:h("clean")},splitting:{flags:["s","splitting"],handler:h("splitting")},noExternal:{flags:["ne","no-external"],handler:T("noExternal")},preferredTsconfigPath:{flags:["tsconfig","preferred-tsconfig-path"],handler:$("preferredTsconfigPath")},bytecode:{flags:["bc","bytecode"],handler:h("bytecode")},silent:{flags:["silent"],handler:h("silent")},config:{flags:["config"],handler:$("config")},publicPath:{flags:["pp","public-path"],handler:$("publicPath")},env:{flags:["env"],handler:$("env")},onSuccess:{flags:["onSuccess"],handler:$("onSuccess")},filter:{flags:["filter"],handler:T("filter")},new:{flags:["new"],handler:h("new")},dtsOnly:{flags:["dts-only"],handler:h("dtsOnly")},entry:{flags:["entry"],handler:(i,r,s)=>{if(typeof i!=="string")throw new M(`Entry${s?` --entry.${s}`:""} requires a string value`);let n=r.entry||{};if(s){if(n[s])m.warn(`Duplicate entry name '${s}' provided via --entry.${s}. Overwriting previous entry.`);n[s]=i}else{let t=$r(i);if(n[t])m.warn(`Duplicate entry name '${t}' derived from '${i}'. Overwriting previous entry.`);n[t]=i}r.entry=n}},resolveDts:{flags:["rd","resolve-dts"],handler:(i,r)=>{if(!r.dts)r.dts={};if(typeof r.dts==="boolean")r.dts={};if(typeof i==="string")if(i==="true"||i==="false")r.dts.resolve=i==="true";else r.dts.resolve=i.split(",");else r.dts.resolve=!0}},help:{flags:["h","help"],handler:()=>Mi()},version:{flags:["v","version"],handler:()=>$i()}},J={};for(let i of Object.values(qr))for(let r of i.flags)J[r]=i.handler;function Ir(i){let r={};for(let s=0;s<i.length;s++){let n=i[s];if(n.startsWith("--")){let t,d;if(n.includes("=")){let[e,g]=n.slice(2).split("=",2);t=e,d=g}else{t=n.slice(2);let e=i[s+1];if(d=e&&!e.startsWith("-")?e:!0,typeof d==="string")s++}if(t.includes(".")){let[e,g]=t.split(".",2),B=J[e];if(B)B(d,r,g);else throw new M(`Unknown option: --${t}`)}else{let e=J[t];if(e)e(d,r);else throw new M(`Unknown option: --${t}`)}}else if(n.startsWith("-")){let t=n.slice(1),d=i[s+1],e=d&&!d.startsWith("-")?d:!0;if(typeof e==="string")s++;let g=J[t];if(g)g(e,r);else throw new M(`Unknown option: -${t}`)}else qr.entry.handler(n,r,void 0)}return r}var ei=Y(O(),1);ir();W();import{loadConfig as Ai}from"coffi";var Pr=Y(O(),1);er();F();nr();I();tr();W();import D from"path";async function ar(i,r){let s=new Set,n=_(i),t=typeof n.dts==="object"&&"entry"in n.dts?n.dts.entry:void 0,d=t?U(t):[],e=U(n.entry),g=new Set([...d.map(({entry:x})=>x),...e.map(({entry:x})=>x)]);for(let x of g){let u=D.resolve(r,x),C=D.dirname(u);s.add(C)}let w=(await import("chokidar")).watch(Array.from(s),{persistent:!0,ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,D.join(r,n.outDir)]}),b=!1,l=async(x=!1)=>{if(b)return;b=!0;try{let u=performance.now();if(await dr(n,r),!x)m.cli(`\uD83D\uDCE6 Rebuild finished in ${Pr.default.green(p(performance.now()-u))}`)}catch(u){a(u)}finally{b=!1}};w.on("change",(x)=>{let u=D.relative(r,x);m.cli(`File changed: ${u}`,{muted:!0,once:u}),l()}),w.on("error",(x)=>{throw new V(`Watcher error: ${P(x)}`)}),await l(!0)}async function Ti(i=Bun.argv.slice(2)){let r=Ir(i);if(r.new){let{newProject:b}=await Promise.resolve().then(() => (di(),ti));await b();return}G(r.silent);let s=process.cwd(),{config:n,filepath:t}=await Ai({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:r.config,packageJsonProperty:"bunup"}),d=!n?[{rootDir:s,options:r}]:await Lr(n,s,r.filter);if(m.cli(`Using bunup v${Z} and bun v${Bun.version}`,{muted:!0}),t)m.cli(`Using ${A(t,2)}`,{muted:!0});let e=performance.now();m.cli("Build started");let{build:g}=await Promise.resolve().then(() => (er(),vr));await Promise.all(d.flatMap(({options:b,rootDir:l})=>{return lr(b).map(async(u)=>{let C={...u,...Ji(r)};if(C.watch)await ar(C,l);else await g(C,l)})}));let B=performance.now()-e,w=p(B);if(m.cli(`\u26A1\uFE0F Build completed in ${ei.default.green(w)}`),r.watch)m.cli("\uD83D\uDC40 Watching for file changes");if(r.onSuccess)m.cli(`Running command: ${r.onSuccess}`,{muted:!0}),await pi(r.onSuccess,[],{nodeOptions:{shell:!0,stdio:"inherit"}});if(!r.watch)process.exit(process.exitCode??0)}function Ji(i){return{...i,onSuccess:void 0,config:void 0,filter:void 0,new:void 0}}Ti().catch((i)=>hr(i));
984
+ `);
985
+ console.log("For more information on available options, visit:");
986
+ console.log(`${import_picocolors3.default.cyan(import_picocolors3.default.underline(BUNUP_CLI_OPTIONS_URL))}
987
+ `);
988
+ process.exit(0);
989
+ }
990
+ function showVersion() {
991
+ console.log(version);
992
+ process.exit(0);
993
+ }
994
+ var optionConfigs = {
995
+ name: { flags: ["n", "name"], handler: stringHandler("name") },
996
+ format: {
997
+ flags: ["f", "format"],
998
+ handler: arrayHandler("format")
999
+ },
1000
+ outDir: { flags: ["o", "out-dir"], handler: stringHandler("outDir") },
1001
+ minify: { flags: ["m", "minify"], handler: booleanHandler("minify") },
1002
+ watch: { flags: ["w", "watch"], handler: booleanHandler("watch") },
1003
+ dts: { flags: ["d", "dts"], handler: booleanHandler("dts") },
1004
+ banner: { flags: ["bn", "banner"], handler: stringHandler("banner") },
1005
+ footer: { flags: ["ft", "footer"], handler: stringHandler("footer") },
1006
+ external: { flags: ["e", "external"], handler: arrayHandler("external") },
1007
+ sourcemap: {
1008
+ flags: ["sm", "sourcemap"],
1009
+ handler: booleanOrStringHandler("sourcemap")
1010
+ },
1011
+ target: { flags: ["t", "target"], handler: stringHandler("target") },
1012
+ minifyWhitespace: {
1013
+ flags: ["mw", "minify-whitespace"],
1014
+ handler: booleanHandler("minifyWhitespace")
1015
+ },
1016
+ minifyIdentifiers: {
1017
+ flags: ["mi", "minify-identifiers"],
1018
+ handler: booleanHandler("minifyIdentifiers")
1019
+ },
1020
+ minifySyntax: {
1021
+ flags: ["ms", "minify-syntax"],
1022
+ handler: booleanHandler("minifySyntax")
1023
+ },
1024
+ clean: { flags: ["c", "clean"], handler: booleanHandler("clean") },
1025
+ splitting: {
1026
+ flags: ["s", "splitting"],
1027
+ handler: booleanHandler("splitting")
1028
+ },
1029
+ noExternal: {
1030
+ flags: ["ne", "no-external"],
1031
+ handler: arrayHandler("noExternal")
1032
+ },
1033
+ preferredTsconfigPath: {
1034
+ flags: ["tsconfig", "preferred-tsconfig-path"],
1035
+ handler: stringHandler("preferredTsconfigPath")
1036
+ },
1037
+ bytecode: {
1038
+ flags: ["bc", "bytecode"],
1039
+ handler: booleanHandler("bytecode")
1040
+ },
1041
+ silent: { flags: ["silent"], handler: booleanHandler("silent") },
1042
+ config: { flags: ["config"], handler: stringHandler("config") },
1043
+ publicPath: {
1044
+ flags: ["pp", "public-path"],
1045
+ handler: stringHandler("publicPath")
1046
+ },
1047
+ env: { flags: ["env"], handler: stringHandler("env") },
1048
+ onSuccess: {
1049
+ flags: ["onSuccess"],
1050
+ handler: stringHandler("onSuccess")
1051
+ },
1052
+ filter: { flags: ["filter"], handler: arrayHandler("filter") },
1053
+ new: { flags: ["new"], handler: booleanHandler("new") },
1054
+ dtsOnly: { flags: ["dts-only"], handler: booleanHandler("dtsOnly") },
1055
+ entry: {
1056
+ flags: ["entry"],
1057
+ handler: (value, options, subPath) => {
1058
+ if (typeof value !== "string") {
1059
+ throw new BunupCLIError(`Entry${subPath ? ` --entry.${subPath}` : ""} requires a string value`);
1060
+ }
1061
+ const entries = options.entry || {};
1062
+ if (subPath) {
1063
+ if (entries[subPath]) {
1064
+ logger.warn(`Duplicate entry name '${subPath}' provided via --entry.${subPath}. Overwriting previous entry.`);
1065
+ }
1066
+ entries[subPath] = value;
1067
+ } else {
1068
+ const name = getBaseFileName(value);
1069
+ if (entries[name]) {
1070
+ logger.warn(`Duplicate entry name '${name}' derived from '${value}'. Overwriting previous entry.`);
1071
+ }
1072
+ entries[name] = value;
1073
+ }
1074
+ options.entry = entries;
1075
+ }
1076
+ },
1077
+ resolveDts: {
1078
+ flags: ["rd", "resolve-dts"],
1079
+ handler: (value, options) => {
1080
+ if (!options.dts)
1081
+ options.dts = {};
1082
+ if (typeof options.dts === "boolean")
1083
+ options.dts = {};
1084
+ if (typeof value === "string") {
1085
+ if (value === "true" || value === "false") {
1086
+ options.dts.resolve = value === "true";
1087
+ } else {
1088
+ options.dts.resolve = value.split(",");
1089
+ }
1090
+ } else {
1091
+ options.dts.resolve = true;
1092
+ }
1093
+ }
1094
+ },
1095
+ help: { flags: ["h", "help"], handler: () => showHelp() },
1096
+ version: { flags: ["v", "version"], handler: () => showVersion() }
1097
+ };
1098
+ var flagToHandler = {};
1099
+ for (const config of Object.values(optionConfigs)) {
1100
+ for (const flag of config.flags) {
1101
+ flagToHandler[flag] = config.handler;
1102
+ }
1103
+ }
1104
+ function parseCliOptions(argv) {
1105
+ const options = {};
1106
+ for (let i = 0;i < argv.length; i++) {
1107
+ const arg = argv[i];
1108
+ if (arg.startsWith("--")) {
1109
+ let key;
1110
+ let value;
1111
+ if (arg.includes("=")) {
1112
+ const [keyPart, valuePart] = arg.slice(2).split("=", 2);
1113
+ key = keyPart;
1114
+ value = valuePart;
1115
+ } else {
1116
+ key = arg.slice(2);
1117
+ const nextArg = argv[i + 1];
1118
+ value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
1119
+ if (typeof value === "string")
1120
+ i++;
1121
+ }
1122
+ if (key.includes(".")) {
1123
+ const [mainOption, subPath] = key.split(".", 2);
1124
+ const handler = flagToHandler[mainOption];
1125
+ if (handler) {
1126
+ handler(value, options, subPath);
1127
+ } else {
1128
+ throw new BunupCLIError(`Unknown option: --${key}`);
1129
+ }
1130
+ } else {
1131
+ const handler = flagToHandler[key];
1132
+ if (handler) {
1133
+ handler(value, options);
1134
+ } else {
1135
+ throw new BunupCLIError(`Unknown option: --${key}`);
1136
+ }
1137
+ }
1138
+ } else if (arg.startsWith("-")) {
1139
+ const key = arg.slice(1);
1140
+ const nextArg = argv[i + 1];
1141
+ const value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
1142
+ if (typeof value === "string")
1143
+ i++;
1144
+ const handler = flagToHandler[key];
1145
+ if (handler) {
1146
+ handler(value, options);
1147
+ } else {
1148
+ throw new BunupCLIError(`Unknown option: -${key}`);
1149
+ }
1150
+ } else {
1151
+ optionConfigs.entry.handler(arg, options, undefined);
1152
+ }
1153
+ }
1154
+ return options;
1155
+ }
1156
+
1157
+ // src/cli/index.ts
1158
+ var import_picocolors6 = __toESM(require_picocolors(), 1);
1159
+ init_loaders();
1160
+ init_utils();
1161
+ import { loadConfig as loadConfig2 } from "coffi";
1162
+
1163
+ // src/watch.ts
1164
+ var import_picocolors4 = __toESM(require_picocolors(), 1);
1165
+ init_build();
1166
+ init_errors();
1167
+ init_entry();
1168
+ init_logger();
1169
+ init_options();
1170
+ init_utils();
1171
+ import path4 from "path";
1172
+ async function watch(partialOptions, rootDir) {
1173
+ const watchPaths = new Set;
1174
+ const options = createBuildOptions(partialOptions);
1175
+ const dtsEntry = typeof options.dts === "object" && "entry" in options.dts ? options.dts.entry : undefined;
1176
+ const processableDtsEntries = dtsEntry ? getProcessableEntries(dtsEntry) : [];
1177
+ const processableEntries = getProcessableEntries(options.entry);
1178
+ const uniqueEntries = new Set([
1179
+ ...processableDtsEntries.map(({ entry }) => entry),
1180
+ ...processableEntries.map(({ entry }) => entry)
1181
+ ]);
1182
+ for (const entry of uniqueEntries) {
1183
+ const entryPath = path4.resolve(rootDir, entry);
1184
+ const parentDir = path4.dirname(entryPath);
1185
+ watchPaths.add(parentDir);
1186
+ }
1187
+ const chokidar = await import("chokidar");
1188
+ const watcher = chokidar.watch(Array.from(watchPaths), {
1189
+ persistent: true,
1190
+ ignoreInitial: true,
1191
+ atomic: true,
1192
+ ignorePermissionErrors: true,
1193
+ ignored: [
1194
+ /[\\/]\.git[\\/]/,
1195
+ /[\\/]node_modules[\\/]/,
1196
+ path4.join(rootDir, options.outDir)
1197
+ ]
1198
+ });
1199
+ let isRebuilding = false;
1200
+ const triggerRebuild = async (initial = false) => {
1201
+ if (isRebuilding)
1202
+ return;
1203
+ isRebuilding = true;
1204
+ try {
1205
+ const start = performance.now();
1206
+ await build(options, rootDir);
1207
+ if (!initial) {
1208
+ logger.cli(`\uD83D\uDCE6 Rebuild finished in ${import_picocolors4.default.green(formatTime(performance.now() - start))}`);
1209
+ }
1210
+ } catch (error) {
1211
+ handleError(error);
1212
+ } finally {
1213
+ isRebuilding = false;
1214
+ }
1215
+ };
1216
+ watcher.on("change", (filePath) => {
1217
+ const changedFile = path4.relative(rootDir, filePath);
1218
+ logger.cli(`File changed: ${changedFile}`, {
1219
+ muted: true,
1220
+ once: changedFile
1221
+ });
1222
+ triggerRebuild();
1223
+ });
1224
+ watcher.on("error", (error) => {
1225
+ throw new BunupWatchError(`Watcher error: ${parseErrorMessage(error)}`);
1226
+ });
1227
+ await triggerRebuild(true);
1228
+ }
1229
+
1230
+ // src/cli/index.ts
1231
+ async function main(args = Bun.argv.slice(2)) {
1232
+ const cliOptions = parseCliOptions(args);
1233
+ if (cliOptions.new) {
1234
+ const { newProject: newProject2 } = await Promise.resolve().then(() => (init_new(), exports_new));
1235
+ await newProject2();
1236
+ return;
1237
+ }
1238
+ setSilent(cliOptions.silent);
1239
+ const cwd = process.cwd();
1240
+ const { config, filepath } = await loadConfig2({
1241
+ name: "bunup.config",
1242
+ extensions: [".ts", ".js", ".mjs", ".cjs"],
1243
+ maxDepth: 1,
1244
+ preferredPath: cliOptions.config,
1245
+ packageJsonProperty: "bunup"
1246
+ });
1247
+ const configsToProcess = !config ? [{ rootDir: cwd, options: cliOptions }] : await processLoadedConfigs(config, cwd, cliOptions.filter);
1248
+ logger.cli(`Using bunup v${version} and bun v${Bun.version}`, {
1249
+ muted: true
1250
+ });
1251
+ if (filepath) {
1252
+ logger.cli(`Using ${getShortFilePath(filepath, 2)}`, {
1253
+ muted: true
1254
+ });
1255
+ }
1256
+ const startTime = performance.now();
1257
+ logger.cli("Build started");
1258
+ const { build: build2 } = await Promise.resolve().then(() => (init_build(), exports_build));
1259
+ await Promise.all(configsToProcess.flatMap(({ options, rootDir }) => {
1260
+ const optionsArray = ensureArray(options);
1261
+ return optionsArray.map(async (o) => {
1262
+ const partialOptions = {
1263
+ ...o,
1264
+ ...removeCliOnlyOptions(cliOptions)
1265
+ };
1266
+ if (partialOptions.watch) {
1267
+ await watch(partialOptions, rootDir);
1268
+ } else {
1269
+ await build2(partialOptions, rootDir);
1270
+ }
1271
+ });
1272
+ }));
1273
+ const buildTimeMs = performance.now() - startTime;
1274
+ const timeDisplay = formatTime(buildTimeMs);
1275
+ logger.cli(`\u26A1\uFE0F Build completed in ${import_picocolors6.default.green(timeDisplay)}`);
1276
+ if (cliOptions.watch) {
1277
+ logger.cli("\uD83D\uDC40 Watching for file changes");
1278
+ }
1279
+ if (cliOptions.onSuccess) {
1280
+ logger.cli(`Running command: ${cliOptions.onSuccess}`, {
1281
+ muted: true
1282
+ });
1283
+ await exec(cliOptions.onSuccess, [], {
1284
+ nodeOptions: { shell: true, stdio: "inherit" }
1285
+ });
1286
+ }
1287
+ if (!cliOptions.watch) {
1288
+ process.exit(process.exitCode ?? 0);
1289
+ }
1290
+ }
1291
+ function removeCliOnlyOptions(options) {
1292
+ return {
1293
+ ...options,
1294
+ onSuccess: undefined,
1295
+ config: undefined,
1296
+ filter: undefined,
1297
+ new: undefined
1298
+ };
1299
+ }
1300
+ main().catch((error) => handleErrorAndExit(error));