bunup 0.4.2 → 0.4.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/build/cli.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{build as Ge}from"rolldown";import{dts as Xe}from"rolldown-plugin-dts";class E extends Error{constructor(e){super(e);this.name="BunupError"}}class w extends E{constructor(e){super(e);this.name="BunupBuildError"}}class g extends E{constructor(e){super(e);this.name="BunupDTSBuildError"}}class d extends E{constructor(e){super(e);this.name="BunupCLIError"}}class v extends E{constructor(e){super(e);this.name="BunupWatchError"}}var h=(e)=>{if(e instanceof Error)return e.message;return String(e)},ke=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",link:"https://bunup.arshadyaseen.com/#could-not-resolve-bun-error"}],V=(e,t)=>{let n=h(e),r=t?`[${t}] `:"",s="ERROR";if(e instanceof w)s="BUILD ERROR";else if(e instanceof g)s="DTS ERROR";else if(e instanceof d)s="CLI ERROR";else if(e instanceof v)s="WATCH ERROR";else if(e instanceof E)s="BUNUP ERROR";console.error(`\x1B[31m${s}\x1B[0m ${r}${n}`);let o=ke.find((i)=>i.pattern.test(n)&&(i.errorType===s||!i.errorType));if(o)console.error(`
3
+ import{build as ze}from"rolldown";import{dts as Qe}from"rolldown-plugin-dts";class C extends Error{constructor(e){super(e);this.name="BunupError"}}class w extends C{constructor(e){super(e);this.name="BunupBuildError"}}class h extends C{constructor(e){super(e);this.name="BunupDTSBuildError"}}class d extends C{constructor(e){super(e);this.name="BunupCLIError"}}class B extends C{constructor(e){super(e);this.name="BunupWatchError"}}var b=(e)=>{if(e instanceof Error)return e.message;return String(e)},Ge=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",link:"https://bunup.arshadyaseen.com/#could-not-resolve-bun-error"}],Y=(e,t)=>{let n=b(e),r=t?`[${t}] `:"",s="ERROR";if(e instanceof w)s="BUILD ERROR";else if(e instanceof h)s="DTS ERROR";else if(e instanceof d)s="CLI ERROR";else if(e instanceof B)s="WATCH ERROR";else if(e instanceof C)s="BUNUP ERROR";console.error(`\x1B[31m${s}\x1B[0m ${r}${n}`);let o=Ge.find((i)=>i.pattern.test(n)&&(i.errorType===s||!i.errorType));if(o)console.error(`
4
4
  \x1B[90mA solution for this error is available at: \x1B[36m${o.link}\x1B[0m
5
- `);else console.error("\x1B[90mIf you think this is a bug, please open an issue at: \x1B[36mhttps://github.com/arshadyaseen/bunup/issues/new\x1B[0m")},z=(e,t)=>{V(e,t),process.exit(1)};import J from"node:fs/promises";import je from"node:path";function G(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ee(e=8){let t="";while(t.length<e)t+=Math.random().toString(36).substring(2);return t.substring(0,e)}function te(e,t,n){return Array.isArray(e)?e.map((r)=>({...r,[t]:n})):{...e,[t]:n}}function ne(e){return Array.isArray(e)?e:[e]}function re(e,t){switch(e){case"esm":return".mjs";case"cjs":return S(t)?".cjs":".js";case"iife":return".global.js"}}function se(e,t){switch(e){case"esm":return".d.mts";case"cjs":return S(t)?".d.cts":".d.ts";case"iife":return".d.ts"}}function S(e){return e==="module"}function L(e){return e>=1000?`${(e/1000).toFixed(2)}s`:`${Math.round(e)}ms`}function ie(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function oe(e,t){return e===void 0?t==="esm":e}function X(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));if(n===0)return`${e} ${t[n]}`;return`${(e/1024**n).toFixed(2)} ${t[n]}`}function b(e,t=3){return e.split("/").slice(-t).join("/")}async function ae(e,t){let n=je.join(e,t);try{await J.rm(n,{recursive:!0,force:!0})}catch(r){throw new w(`Failed to clean output directory: ${r}`)}await J.mkdir(n,{recursive:!0})}function le(e,t){return t==="cjs"?e:void 0}function A(e){return[".ts",".mts",".cts",".tsx"].some((t)=>e.endsWith(t))}function ce(e){return e.map((t)=>typeof t==="string"?new RegExp(`^${G(t)}($|\\/|\\\\)`):t)}function I(e,t){return ce(e.external||[]).concat(ie(t).map((n)=>new RegExp(`^${G(n)}($|\\/|\\\\)`)))}function M(e){return ce(e.noExternal||[])}var ue=!1;function D(e){ue=e??!1}class ${static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!$.instance)$.instance=new $;return $.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(e){if(!e?.once)return!0;if(this.loggedOnceMessages.has(e.once))return!1;return this.loggedOnceMessages.add(e.once),!0}formatMessage({colorCode:e,label:t,message:n,size:r,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-t.length)),a=o?`\x1B[38;5;${this.colors.info}m${n}\x1B[0m`:n;if(r){let[c,...p]=a.split(" "),f=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),m=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${i}${c}${f} \x1B[38;5;${this.colors.size}m${r}\x1B[0m ${p.join(" ")}${m}`}let l=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${i}${a}${l}`}output(e,t={},n=console.log){if(ue)return;if(!this.shouldLog(t))return;if(t.verticalSpace)console.log("");if(n(e),t.verticalSpace)console.log("")}cli(e,t={}){let n=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t)}info(e,t={}){let n=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t)}warn(e,t={}){let n=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t,console.warn)}error(e,t={}){let n=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t,console.error)}progress(e,t,n,r){let s=String(e),o=this.colors.default,i,a,l={};if(typeof n==="string")i=n,a=r;else if(n)i=n.size,a=n.identifier,l=n;for(let[p,f]of Object.entries(this.colors.progress))if(s.includes(p)){o=f;break}let c=this.formatMessage({colorCode:o,label:s,message:t,size:i,identifier:a,muted:l.muted});this.output(c,l)}}var u=$.getInstance();import qe from"node:path";import{ResolverFactory as Ve}from"oxc-resolver";import O from"node:path";var P="\x00dts:",fe=(e,t,n)=>{return{name:"bunup:virtual-dts",async resolveId(r,s){if(Y(r))return r;if(!s||!Y(s))return null;let o=await U(r,t,n,T(s));if(!o)return null;let i=C(o);if(e.has(i))return _(i);return null},load(r){if(r.startsWith(P)){let s=T(r),o=e.get(s);if(o)return R.add(s),o}return null}}};function pe(e){return e.tsconfig?.compilerOptions}function C(e){return e.replace(/\.tsx?$/,".d.ts")}function K(e){let t=O.dirname(e.path||""),n=pe(e);return n?.baseUrl?O.resolve(t,n.baseUrl):t}function me(e){let t=new Map,n=pe(e)?.paths;if(!n)return t;let r=K(e);for(let[s,o]of Object.entries(n))if(Array.isArray(o)&&o.length){let i=s.replace(/\*/g,"(.*)"),a=o[0].replace(/\*/g,"$1");t.set(`^${i}$`,O.join(r,a))}return t}function Fe(e,t,n){for(let[r,s]of t){let o=new RegExp(r),i=e.match(o);if(i)return s.replace("$1",i[1]||"")}return n?O.join(n,e):null}async function He(e){let t=["",".ts",".tsx",".cts",".mts","/index.ts","/index.tsx","/index.cts","/index.mts"];for(let n of t){let r=`${e}${n}`;if(await Bun.file(r).exists()&&(r.endsWith(".ts")||r.endsWith(".tsx")||r.endsWith(".cts")||r.endsWith(".mts")))return r}return null}function U(e,t,n,r){let s=e.startsWith(".")?O.resolve(O.dirname(r||""),e):Fe(e,t,n);if(!s)return Promise.resolve(null);return He(s)}function Y(e){return e.startsWith(P)}function T(e){return e.replace(P,"")}function _(e){return`${P}${e}`}var de;function ge(e){return{name:"bunup:types-resolve",buildStart(){de||=new Ve({mainFields:["types"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".ts",".d.cts",".d.mts",".cts",".mts"],modules:["node_modules","node_modules/@types"]})},async resolveId(t,n){let r=n?T(n):void 0;if(/\0/.test(t))return;if(e){if(!e.some((a)=>{let l=!1;if(typeof a==="string")l=a===t||!!r?.includes(a);else l=a.test(t)||!!(r&&a.test(r));return l}))return}let s=r?qe.dirname(r):process.cwd(),{path:o}=await de.async(s,t);if(!o)return;if(/[cm]?jsx?$/.test(o)){let i=o.replace(/\.([cm]?)jsx?$/,".d.$1ts");return await Bun.file(i).exists()?i:void 0}return o}}}async function he(e,t,n,r,s,o){let i=C(e),a=_(i),l=I(n,r),c=M(n);try{let{output:p}=await Ge({input:a,output:{dir:n.outDir,inlineDynamicImports:!0},write:!1,onwarn(f,m){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(f.code??""))return;m(f)},plugins:[fe(t,s,o),typeof n.dts==="object"&&"resolve"in n.dts&&ge(typeof n.dts.resolve==="boolean"?void 0:n.dts.resolve),Xe({dtsInput:!0})],external:(f)=>l.some((m)=>m.test(f))&&!c.some((m)=>m.test(f))});if(!p[0]?.code)return u.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return p[0].code}catch(p){throw new g(`DTS bundling failed for entry "${e}": ${h(p)}`)}}var Ye=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Ke=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Qe=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ze=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,ze=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Je=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,et=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function tt(e){let t=new Set,n=[Ye,Ke,Qe,Ze,ze,Je,et];for(let r of n){let s=e.matchAll(r);for(let o of s)if(o[1])t.add(o[1])}return t}async function xe(e,t,n){let r=new Set([e]),s=[e];while(s.length){let o=s.pop();if(!o)continue;try{let i=await Bun.file(o).text(),a=tt(i);for(let l of a){let c=await U(l,t,n,o);if(!c)continue;if(!r.has(c))r.add(c),s.push(c)}}catch(i){u.warn(`Error processing ${o}: ${h(i)}`)}}return r}import{isolatedDeclaration as nt}from"oxc-transform";async function be(e){let t=new Map;return await Promise.all([...e].map(async(n)=>{try{let r=C(n);if(!await Bun.file(n).exists())return;let o=await Bun.file(n).text(),{code:i}=nt(n,o);if(i)t.set(r,i)}catch(r){u.warn(`Failed to generate declaration for ${n}: ${h(r)}`)}})),t}import ye from"node:fs/promises";import Q from"node:path";import{isolatedDeclaration as rt}from"oxc-transform";async function we(e,t){let n=Q.resolve(e),r=Q.resolve(n,t);if(!await ye.exists(n))throw new g(`Root directory does not exist: ${n}`);if(!await Bun.file(r).exists())throw new g(`Entry file does not exist: ${r}`);if(!A(r))throw new g(`Entry file must be a TypeScript file: ${r}`);if(Q.relative(n,r).startsWith(".."))throw new g(`Entry file must be within rootDir: ${r}`);return{absoluteRootDir:n,absoluteEntry:r}}async function Ee(e){let t=!1;if(await Promise.all([...e].map(async(n)=>{try{let r=n.replace(/\.d\.ts$/,".ts"),s=await Bun.file(r).text(),{errors:o}=rt(r,s);for(let i of o){if(!t)console.log(`
6
- `);let a=i.labels[0],l=a?st(s,a.start):"",p=`${b(r)}${l}: ${it(i.message)}`;u.warn(p),t=!0}}catch{}})),t)u.info(`
5
+ `);else console.error("\x1B[90mIf you think this is a bug, please open an issue at: \x1B[36mhttps://github.com/arshadyaseen/bunup/issues/new\x1B[0m")},ne=(e,t)=>{Y(e,t),process.exit(1)};import re from"node:fs/promises";import Ve from"node:path";function X(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function se(e=8){let t="";while(t.length<e)t+=Math.random().toString(36).substring(2);return t.substring(0,e)}function ie(e,t,n){return Array.isArray(e)?e.map((r)=>({...r,[t]:n})):{...e,[t]:n}}function oe(e){return Array.isArray(e)?e:[e]}function ae(e,t){switch(e){case"esm":return".mjs";case"cjs":return L(t)?".cjs":".js";case"iife":return".global.js"}}function le(e,t){switch(e){case"esm":return".d.mts";case"cjs":return L(t)?".d.cts":".d.ts";case"iife":return".d.ts"}}function K(e){return e==="node"||e==="bun"}function L(e){return e==="module"}function A(e){return e>=1000?`${(e/1000).toFixed(2)}s`:`${Math.round(e)}ms`}function ce(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function J(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));if(n===0)return`${e} ${t[n]}`;return`${(e/1024**n).toFixed(2)} ${t[n]}`}function x(e,t=3){return e.split("/").slice(-t).join("/")}async function ue(e,t){let n=Ve.join(e,t);try{await re.rm(n,{recursive:!0,force:!0})}catch(r){throw new w(`Failed to clean output directory: ${r}`)}await re.mkdir(n,{recursive:!0})}function I(e){return[".ts",".mts",".cts",".tsx"].some((t)=>e.endsWith(t))}function fe(e){return e.map((t)=>typeof t==="string"?new RegExp(`^${X(t)}($|\\/|\\\\)`):t)}function v(e,t){return fe(e.external||[]).concat(ce(t).map((n)=>new RegExp(`^${X(n)}($|\\/|\\\\)`)))}function M(e){return fe(e.noExternal||[])}var pe=!1;function D(e){pe=e??!1}class E{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!E.instance)E.instance=new E;return E.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(e){if(!e?.once)return!0;if(this.loggedOnceMessages.has(e.once))return!1;return this.loggedOnceMessages.add(e.once),!0}formatMessage({colorCode:e,label:t,message:n,size:r,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-t.length)),a=o?`\x1B[38;5;${this.colors.info}m${n}\x1B[0m`:n;if(r){let[c,...f]=a.split(" "),m=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),p=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${i}${c}${m} \x1B[38;5;${this.colors.size}m${r}\x1B[0m ${f.join(" ")}${p}`}let l=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${i}${a}${l}`}output(e,t={},n=console.log){if(pe)return;if(!this.shouldLog(t))return;if(t.verticalSpace)console.log("");if(n(e),t.verticalSpace)console.log("")}cli(e,t={}){let n=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t)}info(e,t={}){let n=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t)}warn(e,t={}){let n=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t,console.warn)}error(e,t={}){let n=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t,console.error)}progress(e,t,n,r){let s=String(e),o=this.colors.default,i,a,l={};if(typeof n==="string")i=n,a=r;else if(n)i=n.size,a=n.identifier,l=n;for(let[f,m]of Object.entries(this.colors.progress))if(s.includes(f)){o=m;break}let c=this.formatMessage({colorCode:o,label:s,message:t,size:i,identifier:a,muted:l.muted});this.output(c,l)}}var u=E.getInstance();import Ke from"node:path";import{ResolverFactory as Je}from"oxc-resolver";import R from"node:path";var O="\x00dts:",me=(e,t,n)=>{return{name:"bunup:virtual-dts",async resolveId(r,s){if(z(r))return r;if(!s||!z(s))return null;let o=await k(r,t,n,S(s));if(!o)return null;let i=T(o);if(e.has(i))return _(i);return null},load(r){if(r.startsWith(O)){let s=S(r),o=e.get(s);if(o)return $.add(s),o}return null}}};function de(e){return e.tsconfig?.compilerOptions}function T(e){return e.replace(/\.tsx?$/,".d.ts")}function Q(e){let t=R.dirname(e.path||""),n=de(e);return n?.baseUrl?R.resolve(t,n.baseUrl):t}function ge(e){let t=new Map,n=de(e)?.paths;if(!n)return t;let r=Q(e);for(let[s,o]of Object.entries(n))if(Array.isArray(o)&&o.length){let i=s.replace(/\*/g,"(.*)"),a=o[0].replace(/\*/g,"$1");t.set(`^${i}$`,R.join(r,a))}return t}function Ye(e,t,n){for(let[r,s]of t){let o=new RegExp(r),i=e.match(o);if(i)return s.replace("$1",i[1]||"")}return n?R.join(n,e):null}async function Xe(e){let t=["",".ts",".tsx",".cts",".mts","/index.ts","/index.tsx","/index.cts","/index.mts"];for(let n of t){let r=`${e}${n}`;if(await Bun.file(r).exists()&&(r.endsWith(".ts")||r.endsWith(".tsx")||r.endsWith(".cts")||r.endsWith(".mts")))return r}return null}function k(e,t,n,r){let s=e.startsWith(".")?R.resolve(R.dirname(r||""),e):Ye(e,t,n);if(!s)return Promise.resolve(null);return Xe(s)}function z(e){return e.startsWith(O)}function S(e){return e.replace(O,"")}function _(e){return`${O}${e}`}var he;function be(e){return{name:"bunup:types-resolve",buildStart(){he||=new Je({mainFields:["types"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".ts",".d.cts",".d.mts",".cts",".mts"],modules:["node_modules","node_modules/@types"]})},async resolveId(t,n){let r=n?S(n):void 0;if(/\0/.test(t))return;if(e){if(!e.some((a)=>{let l=!1;if(typeof a==="string")l=a===t||!!r?.includes(a);else l=a.test(t)||!!(r&&a.test(r));return l}))return}let s=r?Ke.dirname(r):process.cwd(),{path:o}=await he.async(s,t);if(!o)return;if(/[cm]?jsx?$/.test(o)){let i=o.replace(/\.([cm]?)jsx?$/,".d.$1ts");return await Bun.file(i).exists()?i:void 0}return o}}}async function xe(e,t,n,r,s,o){let i=T(e),a=_(i),l=v(n,r),c=M(n);try{let{output:f}=await ze({input:a,output:{dir:n.outDir,inlineDynamicImports:!0},write:!1,onwarn(m,p){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(m.code??""))return;p(m)},plugins:[me(t,s,o),typeof n.dts==="object"&&"resolve"in n.dts&&be(typeof n.dts.resolve==="boolean"?void 0:n.dts.resolve),Qe({dtsInput:!0})],external:(m)=>l.some((p)=>p.test(m))&&!c.some((p)=>p.test(m))});if(!f[0]?.code)return u.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return f[0].code}catch(f){throw new h(`DTS bundling failed for entry "${e}": ${b(f)}`)}}var Ze=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,et=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,tt=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,nt=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,rt=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,st=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,it=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function ot(e){let t=new Set,n=[Ze,et,tt,nt,rt,st,it];for(let r of n){let s=e.matchAll(r);for(let o of s)if(o[1])t.add(o[1])}return t}async function ye(e,t,n){let r=new Set([e]),s=[e];while(s.length){let o=s.pop();if(!o)continue;try{let i=await Bun.file(o).text(),a=ot(i);for(let l of a){let c=await k(l,t,n,o);if(!c)continue;if(!r.has(c))r.add(c),s.push(c)}}catch(i){u.warn(`Error processing ${o}: ${b(i)}`)}}return r}import{isolatedDeclaration as at}from"oxc-transform";async function we(e){let t=new Map;return await Promise.all([...e].map(async(n)=>{try{let r=T(n);if(!await Bun.file(n).exists())return;let o=await Bun.file(n).text(),{code:i}=at(n,o);if(i)t.set(r,i)}catch(r){u.warn(`Failed to generate declaration for ${n}: ${b(r)}`)}})),t}import Ce from"node:fs/promises";import Z from"node:path";import{isolatedDeclaration as lt}from"oxc-transform";async function Ee(e,t){let n=Z.resolve(e),r=Z.resolve(n,t);if(!await Ce.exists(n))throw new h(`Root directory does not exist: ${n}`);if(!await Bun.file(r).exists())throw new h(`Entry file does not exist: ${r}`);if(!I(r))throw new h(`Entry file must be a TypeScript file: ${r}`);if(Z.relative(n,r).startsWith(".."))throw new h(`Entry file must be within rootDir: ${r}`);return{absoluteRootDir:n,absoluteEntry:r}}async function Te(e){let t=!1;if(await Promise.all([...e].map(async(n)=>{try{let r=n.replace(/\.d\.ts$/,".ts"),s=await Bun.file(r).text(),{errors:o}=lt(r,s);for(let i of o){if(!t)console.log(`
6
+ `);let a=i.labels[0],l=a?ct(s,a.start):"",f=`${x(r)}${l}: ${ut(i.message)}`;u.warn(f),t=!0}}catch{}})),t)u.info(`
7
7
  You may have noticed some TypeScript warnings above related to missing type annotations. This is because Bunup uses TypeScript's "isolatedDeclarations" approach for generating declaration files. This modern approach requires explicit type annotations on exports for better, more accurate type declarations. Other bundlers might not show these warnings because they use different, potentially less precise methods. Adding the suggested type annotations will not only silence these warnings but also improve the quality of your published type definitions, making your library more reliable for consumers.
8
- `)}function st(e,t){if(t===void 0)return"";let n=e.slice(0,t).split(`
9
- `),r=n.length,s=n[n.length-1].length+1;return` (${r}:${s})`}function it(e){return e.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function $e(e,t,n,r,s){let{absoluteEntry:o}=await we(e,t),i=me(r),a=K(r),l=await xe(o,i,a),c=await be(l);return he(o,c,n,s,i,a)}function N(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function B(e,{warnOnConflict:t=!0}={}){let n=[],r=new Set,s={};function o(i,a){if(r.has(i)){let l=ee(),c=`${i}_${l}`;if(t)u.warn(`Output name conflict: "${i}" is used by multiple files.
8
+ `)}function ct(e,t){if(t===void 0)return"";let n=e.slice(0,t).split(`
9
+ `),r=n.length,s=n[n.length-1].length+1;return` (${r}:${s})`}function ut(e){return e.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function $e(e,t,n,r,s){let{absoluteEntry:o}=await Ee(e,t),i=ge(r),a=Q(r),l=await ye(o,i,a),c=await we(l);return xe(o,c,n,s,i,a)}function j(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function P(e,{warnOnConflict:t=!0}={}){let n=[],r=new Set,s={};function o(i,a){if(r.has(i)){let l=se(),c=`${i}_${l}`;if(t)u.warn(`Output name conflict: "${i}" is used by multiple files.
10
10
  Bunup uses filenames without extensions as output names by default.
11
11
 
12
12
  ${s[i]} -> ${i}.js
@@ -20,8 +20,19 @@ To fix this, use named entries in your configuration:
20
20
  }
21
21
  }
22
22
 
23
- See: https://bunup.arshadyaseen.com/#named-entries`,{muted:!0,verticalSpace:!0});n.push({name:c,path:a})}else n.push({name:i,path:a}),r.add(i),s[i]=a}if(Array.isArray(e))for(let i of e){let a=N(i);o(a,i)}else if(typeof e==="object")for(let[i,a]of Object.entries(e))o(i,a);else{let i=N(e);o(i,e)}return n}function Ce(e){return e.filter((t)=>A(t.path))}function Re(e,t){return`[dir]/${e}${t}`}import{loadConfig as Oe}from"coffi";async function Te(e,t){return Array.isArray(e)&&"root"in e[0]?e.map((n)=>({rootDir:n.root,options:te(n.config,"name",n.name)})):[{rootDir:t,options:e}]}async function Pe(e){let{config:t,filepath:n}=await Oe({name:"package",cwd:e,extensions:[".json"],maxDepth:1});return{packageJson:t,path:n}}async function Be(e,t){let{config:n,filepath:r}=await Oe({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:t,maxDepth:3});return{tsconfig:n,path:r}}var ve={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function Se(e,t){return{outdir:`${t}/${e.outDir}`,minify:ot(e),target:e.target,splitting:e.splitting,sourcemap:e.sourcemap,define:e.define,loader:e.loader,drop:e.drop,banner:e.banner,footer:e.footer,publicPath:e.publicPath}}function ot(e){let{minify:t,minifyWhitespace:n,minifyIdentifiers:r,minifySyntax:s}=e,o=t===!0;return{whitespace:n??o,identifiers:r??o,syntax:s??o}}function Le(e,t){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},(r)=>{let s=r.path;if(e.some((i)=>i.test(s))&&!t.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}var R=new Set;async function W(e,t){if(!e.entry||e.entry.length===0||!e.outDir)throw new w("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(e.clean)ae(t,e.outDir);D(e.silent);let{packageJson:n,path:r}=await Pe(t);if(n&&r)u.cli(`Using package.json: ${b(r,2)}`,{muted:!0,identifier:e.name,once:`${r}:${e.name}`});let s=B(e.entry),o=n?.type,i=I(e,n),a=M(e);if(!e.dtsOnly){let l=[Le(i,a)],c=Se(e,t),p=e.format.flatMap((f)=>s.map((m)=>{return at(e,t,m,f,o,l,c)}));await Promise.all(p)}if(e.dts||e.dtsOnly){let l=await Be(t,e.preferredTsconfigPath);if(l.path)u.cli(`Using tsconfig: ${b(l.path,2)}`,{muted:!0,identifier:e.name,once:`${l.path}:${e.name}`});let c=e.format.filter((f)=>{if(f==="iife"&&!S(o)&&e.format.includes("cjs"))return!1;return!0}),p=typeof e.dts==="object"&&e.dts.entry?B(e.dts.entry):Ce(s);try{await Promise.all(p.map(async(f)=>{let m=await $e(t,f.path,e,l,n);await Promise.all(c.map(async(H)=>{let Ne=se(H,o),q=`${t}/${e.outDir}/${f.name}${Ne}`;await Bun.write(q,m);let We=Bun.file(q).size||0;u.progress("DTS",b(q),X(We),e.name)}))}))}catch(f){throw new g(h(f))}}}async function at(e,t,n,r,s,o,i){let a=re(r,s),l=await Bun.build({...i,entrypoints:[`${t}/${n.path}`],format:r,naming:{entry:Re(n.name,a)},splitting:oe(e.splitting,r),bytecode:le(e.bytecode,r),plugins:o,throw:!1});if(!l.success)for(let f of l.logs){if(f.level==="error")throw new w(f.message);if(f.level==="warning")u.warn(f.message);else if(f.level==="info")u.info(f.message)}let c=`${t}/${e.outDir}/${n.name}${a}`,p=Bun.file(c).size||0;u.progress(r.toUpperCase(),b(c),X(p),e.name)}var k="0.4.2";var Ae="https://bun.sh/docs/installation",Ie="https://bunup.arshadyaseen.com/#cli-options";function x(e){return(t,n)=>{n[e]=t===!0||t==="true"}}function y(e){return(t,n)=>{if(typeof t==="string")n[e]=t;else throw new d(`Option --${e} requires a string value`)}}function Me(e){return(t,n)=>{if(typeof t==="string")n[e]=t.split(",");else throw new d(`Option --${e} requires a string value`)}}function ct(){console.log(`
23
+ See: https://bunup.arshadyaseen.com/#named-entries`,{muted:!0,verticalSpace:!0});n.push({name:c,path:a})}else n.push({name:i,path:a}),r.add(i),s[i]=a}if(Array.isArray(e))for(let i of e){let a=j(i);o(a,i)}else if(typeof e==="object")for(let[i,a]of Object.entries(e))o(i,a);else{let i=j(e);o(i,e)}return n}function Re(e){return e.filter((t)=>I(t.path))}function Se(e,t){return`[dir]/${e}${t}`}import{loadConfig as Oe}from"coffi";async function Pe(e,t){return Array.isArray(e)&&"root"in e[0]?e.map((n)=>({rootDir:n.root,options:ie(n.config,"name",n.name)})):[{rootDir:t,options:e}]}async function Be(e){let{config:t,filepath:n}=await Oe({name:"package",cwd:e,extensions:[".json"],maxDepth:1});return{packageJson:t,path:n}}async function Le(e,t){let{config:n,filepath:r}=await Oe({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:t,maxDepth:3});return{tsconfig:n,path:r}}var ft={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function U(e){return{...ft,...e}}function Ae(e){let{minify:t,minifyWhitespace:n,minifyIdentifiers:r,minifySyntax:s}=e,o=t===!0;return{whitespace:n??o,identifiers:r??o,syntax:s??o}}function Ie(e,t){return t==="cjs"?e:void 0}function ve(e,t,n){return{...e,...n==="cjs"&&(t===!0||typeof t==="object"&&t.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Me(e,t){return e===void 0?t==="esm":e}function De(e,t){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},(r)=>{let s=r.path;if(e.some((i)=>i.test(s))&&!t.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}var N={dirnameFilename:{appliesTo:(e,t)=>e==="esm"&&K(t),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
24
+ import { dirname } from 'path';
25
+
26
+ const __filename = fileURLToPath(import.meta.url);
27
+ const __dirname = dirname(__filename);
28
+
29
+ `},importMetaUrl:{appliesTo:(e,t)=>e==="cjs"&&K(t),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
30
+
31
+ const importMetaUrl = pathToFileURL(__filename).href;
32
+
33
+ `}};var pt=/\.(js|ts|jsx|tsx|mts|cts)$/;function ke({format:e,target:t,shims:n}){let s=mt(n).map((o)=>N[o]).filter((o)=>o.appliesTo(e,t));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:pt},async({path:i})=>{let a=await Bun.file(i).text(),l=s.filter((p)=>p.isNeededInFile(a));if(l.length===0)return;let{shebangLine:c,codeContent:f}=dt(a),m=l.map((p)=>p.generateCode()).join("");return{contents:c+m+f}})}}}function mt(e){if(e===!0)return Object.keys(N);if(!e)return[];return Object.entries(e).filter(([t,n])=>n&&(t in N)).map(([t])=>t)}function dt(e){if(!e.startsWith("#!"))return{shebangLine:"",codeContent:e};let t=e.indexOf(`
34
+ `);return t===-1?{shebangLine:"",codeContent:e}:{shebangLine:e.slice(0,t+1),codeContent:e.slice(t+1)}}var $=new Set;async function F(e,t){let n=U(e);if(!n.entry||n.entry.length===0||!n.outDir)throw new w("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(n.clean)ue(t,n.outDir);D(n.silent);let{packageJson:r,path:s}=await Be(t);if(r&&s)u.cli(`Using package.json: ${x(s,2)}`,{muted:!0,identifier:n.name,once:`${s}:${n.name}`});let o=P(n.entry),i=r?.type,a=v(n,r),l=M(n);if(!n.dtsOnly){let c=[De(a,l)],f=n.format.flatMap((m)=>o.map((p)=>{return gt(n,t,p,m,i,c)}));await Promise.all(f)}if(n.dts||n.dtsOnly){let c=await Le(t,n.preferredTsconfigPath);if(c.path)u.cli(`Using tsconfig: ${x(c.path,2)}`,{muted:!0,identifier:n.name,once:`${c.path}:${n.name}`});let f=n.format.filter((p)=>{if(p==="iife"&&!L(i)&&n.format.includes("cjs"))return!1;return!0}),m=typeof n.dts==="object"&&n.dts.entry?P(n.dts.entry):Re(o);try{await Promise.all(m.map(async(p)=>{let G=await $e(t,p.path,n,c,r);await Promise.all(f.map(async(We)=>{let He=le(We,i),V=`${t}/${n.outDir}/${p.name}${He}`;await Bun.write(V,G);let qe=Bun.file(V).size||0;u.progress("DTS",x(V),J(qe),n.name)}))}))}catch(p){throw new h(b(p))}}}async function gt(e,t,n,r,s,o){let i=ae(r,s),a=await Bun.build({entrypoints:[`${t}/${n.path}`],format:r,naming:{entry:Se(n.name,i)},splitting:Me(e.splitting,r),bytecode:Ie(e.bytecode,r),define:ve(e.define,e.shims,r),minify:Ae(e),outdir:`${t}/${e.outDir}`,target:e.target,sourcemap:e.sourcemap,loader:e.loader,drop:e.drop,banner:e.banner,footer:e.footer,publicPath:e.publicPath,plugins:[...o,ke({format:r,target:e.target,shims:e.shims})],throw:!1});if(!a.success)for(let f of a.logs){if(f.level==="error")throw new w(f.message);if(f.level==="warning")u.warn(f.message);else if(f.level==="info")u.info(f.message)}let l=`${t}/${e.outDir}/${n.name}${i}`,c=Bun.file(l).size||0;u.progress(r.toUpperCase(),x(l),J(c),e.name)}var W="0.4.4";var _e="https://bun.sh/docs/installation",je="https://bunup.arshadyaseen.com/#cli-options";function g(e){return(t,n)=>{n[e]=t===!0||t==="true"}}function y(e){return(t,n)=>{if(typeof t==="string")n[e]=t;else throw new d(`Option --${e} requires a string value`)}}function ee(e){return(t,n)=>{if(typeof t==="string")n[e]=t.split(",");else throw new d(`Option --${e} requires a string value`)}}function bt(e){return(t,n)=>{if(typeof t==="boolean")n[e]=t;else if(typeof t==="string")if(t.toLowerCase()==="true"||t.toLowerCase()==="false")n[e]=t.toLowerCase()==="true";else n[e]=t;else throw new d(`Option --${e} requires a boolean or string value`)}}function xt(){console.log(`
24
35
  Bunup - An extremely fast, zero-config bundler for JavaScript and TypeScript, powered by Bun.
25
- `),console.log("For more information on available options, visit:"),console.log(`\x1B[36m\x1B[4m${Ie}\x1B[0m
26
- `),process.exit(0)}function ut(){console.log(k),process.exit(0)}var De={name:{flags:["n","name"],handler:y("name")},format:{flags:["f","format"],handler:(e,t)=>{if(typeof e==="string")t.format=e.split(",");else throw new d("Option --format requires a string value")}},outDir:{flags:["o","out-dir"],handler:y("outDir")},minify:{flags:["m","minify"],handler:x("minify")},watch:{flags:["w","watch"],handler:x("watch")},dts:{flags:["d","dts"],handler:x("dts")},banner:{flags:["bn","banner"],handler:y("banner")},footer:{flags:["ft","footer"],handler:y("footer")},external:{flags:["e","external"],handler:Me("external")},sourcemap:{flags:["sm","sourcemap"],handler:y("sourcemap")},target:{flags:["t","target"],handler:y("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:x("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:x("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:x("minifySyntax")},clean:{flags:["c","clean"],handler:x("clean")},splitting:{flags:["s","splitting"],handler:x("splitting")},noExternal:{flags:["ne","no-external"],handler:Me("noExternal")},preferredTsconfigPath:{flags:["tsconfig","preferred-tsconfig-path"],handler:y("preferredTsconfigPath")},bytecode:{flags:["bc","bytecode"],handler:x("bytecode")},dtsOnly:{flags:["do","dts-only"],handler:x("dtsOnly")},silent:{flags:["silent"],handler:x("silent")},config:{flags:["config"],handler:y("config")},publicPath:{flags:["pp","public-path"],handler:y("publicPath")},entry:{flags:["entry"],handler:(e,t,n)=>{if(typeof e!=="string")throw new d(`Entry${n?` --entry.${n}`:""} requires a string value`);let r=t.entry||{};if(n){if(r[n])u.warn(`Duplicate entry name '${n}' provided via --entry.${n}. Overwriting previous entry.`);r[n]=e}else{let s=N(e);if(r[s])u.warn(`Duplicate entry name '${s}' derived from '${e}'. Overwriting previous entry.`);r[s]=e}t.entry=r}},resolveDts:{flags:["rd","resolve-dts"],handler:(e,t)=>{if(!t.dts)t.dts={};if(typeof t.dts==="boolean")t.dts={};if(typeof e==="string")if(e==="true"||e==="false")t.dts.resolve=e==="true";else t.dts.resolve=e.split(",");else t.dts.resolve=!0}},help:{flags:["h","help"],handler:()=>ct()},version:{flags:["v","version"],handler:()=>ut()}},j={};for(let e of Object.values(De))for(let t of e.flags)j[t]=e.handler;function Ue(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")){let s,o;if(r.includes("=")){let[i,a]=r.slice(2).split("=",2);s=i,o=a}else{s=r.slice(2);let i=e[n+1];if(o=i&&!i.startsWith("-")?i:!0,typeof o==="string")n++}if(s.includes(".")){let[i,a]=s.split(".",2),l=j[i];if(l)l(o,t,a);else throw new d(`Unknown option: --${s}`)}else{let i=j[s];if(i)i(o,t);else throw new d(`Unknown option: --${s}`)}}else if(r.startsWith("-")){let s=r.slice(1),o=e[n+1],i=o&&!o.startsWith("-")?o:!0;if(typeof i==="string")n++;let a=j[s];if(a)a(i,t);else throw new d(`Unknown option: -${s}`)}else De.entry.handler(r,t,void 0)}return t}(()=>{if(typeof Bun==="undefined")throw new d(`Bunup requires Bun to run.
27
- To install Bun, visit ${Ae}`)})();import{loadConfig as pt}from"coffi";import F from"node:path";import ft from"chokidar";async function _e(e,t){let n=new Set,r=B(e.entry);for(let a of r){let l=F.resolve(t,a.path),c=F.dirname(l);n.add(c)}let s=ft.watch(Array.from(n),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,F.join(t,e.outDir)]}),o=!1,i=async(a=!1)=>{if(o)return;o=!0;try{let l=performance.now();if(await W({...e,entry:r.map((c)=>c.path),clean:!1},t),e.onBuildSuccess?.(),!a)u.cli(`\uD83D\uDCE6 Rebuild finished in ${L(performance.now()-l)}`);await Z()}catch(l){V(l)}finally{o=!1}};s.on("change",(a)=>{let l=F.relative(t,a);u.cli(`File changed: ${l}`,{muted:!0}),i()}),s.on("error",(a)=>{throw new v(`Watcher error: ${h(a)}`)}),await i(!0)}async function mt(e=Bun.argv.slice(2)){let t=Ue(e);D(t.silent);let n=process.cwd(),{config:r,filepath:s}=await pt({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:t.config}),o=!r?[{rootDir:n,options:t}]:await Te(r,n);if(u.cli(`Using bunup v${k} and bun v${Bun.version}`,{muted:!0}),s)u.cli(`Using config file: ${b(s,2)}`,{muted:!0});let i=performance.now();u.cli("Build started"),await Promise.all(o.flatMap(({options:c,rootDir:p})=>{return ne(c).map(async(m)=>{let H={...ve,...m,...t};return dt(H,p)})}));let a=performance.now()-i,l=L(a);if(u.cli(`\u26A1\uFE0F Build completed in ${l}`),await Z(),t.watch)u.cli("\uD83D\uDC40 Watching for file changes");if(!t.watch)process.exit(0)}async function Z(){if(R.size>0)await Ee(R),R.clear()}async function dt(e,t){if(e.watch)await _e(e,t);else await W(e,t),e.onBuildSuccess?.()}mt().catch((e)=>z(e));export{Z as validateDtsFiles,mt as main};
36
+ `),console.log("For more information on available options, visit:"),console.log(`\x1B[36m\x1B[4m${je}\x1B[0m
37
+ `),process.exit(0)}function yt(){console.log(W),process.exit(0)}var Ue={name:{flags:["n","name"],handler:y("name")},format:{flags:["f","format"],handler:ee("format")},outDir:{flags:["o","out-dir"],handler:y("outDir")},minify:{flags:["m","minify"],handler:g("minify")},watch:{flags:["w","watch"],handler:g("watch")},dts:{flags:["d","dts"],handler:g("dts")},banner:{flags:["bn","banner"],handler:y("banner")},footer:{flags:["ft","footer"],handler:y("footer")},external:{flags:["e","external"],handler:ee("external")},sourcemap:{flags:["sm","sourcemap"],handler:bt("sourcemap")},target:{flags:["t","target"],handler:y("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:g("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:g("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:g("minifySyntax")},clean:{flags:["c","clean"],handler:g("clean")},splitting:{flags:["s","splitting"],handler:g("splitting")},noExternal:{flags:["ne","no-external"],handler:ee("noExternal")},preferredTsconfigPath:{flags:["tsconfig","preferred-tsconfig-path"],handler:y("preferredTsconfigPath")},bytecode:{flags:["bc","bytecode"],handler:g("bytecode")},dtsOnly:{flags:["do","dts-only"],handler:g("dtsOnly")},silent:{flags:["silent"],handler:g("silent")},config:{flags:["config"],handler:y("config")},publicPath:{flags:["pp","public-path"],handler:y("publicPath")},shims:{flags:["shims"],handler:g("shims")},entry:{flags:["entry"],handler:(e,t,n)=>{if(typeof e!=="string")throw new d(`Entry${n?` --entry.${n}`:""} requires a string value`);let r=t.entry||{};if(n){if(r[n])u.warn(`Duplicate entry name '${n}' provided via --entry.${n}. Overwriting previous entry.`);r[n]=e}else{let s=j(e);if(r[s])u.warn(`Duplicate entry name '${s}' derived from '${e}'. Overwriting previous entry.`);r[s]=e}t.entry=r}},resolveDts:{flags:["rd","resolve-dts"],handler:(e,t)=>{if(!t.dts)t.dts={};if(typeof t.dts==="boolean")t.dts={};if(typeof e==="string")if(e==="true"||e==="false")t.dts.resolve=e==="true";else t.dts.resolve=e.split(",");else t.dts.resolve=!0}},help:{flags:["h","help"],handler:()=>xt()},version:{flags:["v","version"],handler:()=>yt()}},H={};for(let e of Object.values(Ue))for(let t of e.flags)H[t]=e.handler;function Ne(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")){let s,o;if(r.includes("=")){let[i,a]=r.slice(2).split("=",2);s=i,o=a}else{s=r.slice(2);let i=e[n+1];if(o=i&&!i.startsWith("-")?i:!0,typeof o==="string")n++}if(s.includes(".")){let[i,a]=s.split(".",2),l=H[i];if(l)l(o,t,a);else throw new d(`Unknown option: --${s}`)}else{let i=H[s];if(i)i(o,t);else throw new d(`Unknown option: --${s}`)}}else if(r.startsWith("-")){let s=r.slice(1),o=e[n+1],i=o&&!o.startsWith("-")?o:!0;if(typeof i==="string")n++;let a=H[s];if(a)a(i,t);else throw new d(`Unknown option: -${s}`)}else Ue.entry.handler(r,t,void 0)}return t}(()=>{if(typeof Bun==="undefined")throw new d(`Bunup requires Bun to run.
38
+ To install Bun, visit ${_e}`)})();import{loadConfig as Ct}from"coffi";import q from"node:path";import wt from"chokidar";async function Fe(e,t){let n=new Set,r=U(e),s=P(r.entry);for(let l of s){let c=q.resolve(t,l.path),f=q.dirname(c);n.add(f)}let o=wt.watch(Array.from(n),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,q.join(t,r.outDir)]}),i=!1,a=async(l=!1)=>{if(i)return;i=!0;try{let c=performance.now();if(await F({...r,entry:s.map((f)=>f.path),clean:!1},t),r.onBuildSuccess?.(),!l)u.cli(`\uD83D\uDCE6 Rebuild finished in ${A(performance.now()-c)}`);await te()}catch(c){Y(c)}finally{i=!1}};o.on("change",(l)=>{let c=q.relative(t,l);u.cli(`File changed: ${c}`,{muted:!0}),a()}),o.on("error",(l)=>{throw new B(`Watcher error: ${b(l)}`)}),await a(!0)}async function Et(e=Bun.argv.slice(2)){let t=Ne(e);D(t.silent);let n=process.cwd(),{config:r,filepath:s}=await Ct({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:t.config}),o=!r?[{rootDir:n,options:t}]:await Pe(r,n);if(u.cli(`Using bunup v${W} and bun v${Bun.version}`,{muted:!0}),s)u.cli(`Using config file: ${x(s,2)}`,{muted:!0});let i=performance.now();u.cli("Build started"),await Promise.all(o.flatMap(({options:c,rootDir:f})=>{return oe(c).map(async(p)=>{let G={...p,...t};return Tt(G,f)})}));let a=performance.now()-i,l=A(a);if(u.cli(`\u26A1\uFE0F Build completed in ${l}`),await te(),t.watch)u.cli("\uD83D\uDC40 Watching for file changes");if(!t.watch)process.exit(0)}async function te(){if($.size>0)await Te($),$.clear()}async function Tt(e,t){if(e.watch)await Fe(e,t);else await F(e,t),e.onBuildSuccess?.()}Et().catch((e)=>ne(e));export{te as validateDtsFiles,Et as main};
package/build/index.d.mts CHANGED
@@ -8,6 +8,11 @@ type Format = Exclude<BunBuildOptions["format"], undefined>;
8
8
  type Target = BunBuildOptions["target"];
9
9
  type External = (string | RegExp)[];
10
10
  type Entry = Arrayable<string> | Record<string, string>;
11
+ type ShimOptions = {
12
+ dirnameFilename?: boolean
13
+ importMetaUrl?: boolean
14
+ };
15
+ type Shims = boolean | ShimOptions;
11
16
  type DtsOptions = {
12
17
  /**
13
18
  * Entry point files for TypeScript declaration file generation
@@ -169,6 +174,7 @@ interface BuildOptions {
169
174
  /**
170
175
  * Specifies the type of sourcemap to generate
171
176
  * Can be 'none', 'linked', 'external', or 'inline'
177
+ * Can also be a boolean - when true, it will use 'inline'
172
178
  *
173
179
  * @see https://bun.sh/docs/bundler#sourcemap
174
180
  *
@@ -176,6 +182,8 @@ interface BuildOptions {
176
182
  *
177
183
  * @example
178
184
  * sourcemap: 'linked'
185
+ * // or
186
+ * sourcemap: true // equivalent to 'inline'
179
187
  */
180
188
  sourcemap?: Sourcemap;
181
189
  /**
@@ -267,6 +275,25 @@ interface BuildOptions {
267
275
  * publicPath: 'https://cdn.example.com/'
268
276
  */
269
277
  publicPath?: string;
278
+ /**
279
+ * Inject Node.js compatibility shims for ESM/CJS interoperability
280
+ *
281
+ * When set to true, automatically injects all shims when needed
282
+ * When set to an object, only injects the specified shims
283
+ *
284
+ * Available shims:
285
+ * - dirname: Adds __dirname for ESM files when used
286
+ * - filename: Adds __filename for ESM files when used
287
+ * - importMetaUrl: Adds import.meta.url for CJS files when used
288
+ *
289
+ * @example
290
+ * // Enable all shims
291
+ * shims: true
292
+ *
293
+ * // Enable only specific shims
294
+ * shims: { dirname: true, importMetaUrl: true }
295
+ */
296
+ shims?: Shims;
270
297
  }
271
298
 
272
299
  //#endregion
@@ -293,7 +320,7 @@ declare function defineWorkspace(options: DefineWorkspaceItem[]): DefineWorkspac
293
320
 
294
321
  //#endregion
295
322
  //#region \0dts:/home/runner/work/bunup/bunup/src/build.d.ts
296
- declare function build(options: BuildOptions, rootDir: string): Promise<void>;
323
+ declare function build(partialOptions: Partial<BuildOptions>, rootDir: string): Promise<void>;
297
324
 
298
325
  //#endregion
299
326
  export { BuildOptions, DefineConfigItem, DefineWorkspaceItem, build, defineConfig, defineWorkspace };
package/build/index.d.ts CHANGED
@@ -8,6 +8,11 @@ type Format = Exclude<BunBuildOptions["format"], undefined>;
8
8
  type Target = BunBuildOptions["target"];
9
9
  type External = (string | RegExp)[];
10
10
  type Entry = Arrayable<string> | Record<string, string>;
11
+ type ShimOptions = {
12
+ dirnameFilename?: boolean
13
+ importMetaUrl?: boolean
14
+ };
15
+ type Shims = boolean | ShimOptions;
11
16
  type DtsOptions = {
12
17
  /**
13
18
  * Entry point files for TypeScript declaration file generation
@@ -169,6 +174,7 @@ interface BuildOptions {
169
174
  /**
170
175
  * Specifies the type of sourcemap to generate
171
176
  * Can be 'none', 'linked', 'external', or 'inline'
177
+ * Can also be a boolean - when true, it will use 'inline'
172
178
  *
173
179
  * @see https://bun.sh/docs/bundler#sourcemap
174
180
  *
@@ -176,6 +182,8 @@ interface BuildOptions {
176
182
  *
177
183
  * @example
178
184
  * sourcemap: 'linked'
185
+ * // or
186
+ * sourcemap: true // equivalent to 'inline'
179
187
  */
180
188
  sourcemap?: Sourcemap;
181
189
  /**
@@ -267,6 +275,25 @@ interface BuildOptions {
267
275
  * publicPath: 'https://cdn.example.com/'
268
276
  */
269
277
  publicPath?: string;
278
+ /**
279
+ * Inject Node.js compatibility shims for ESM/CJS interoperability
280
+ *
281
+ * When set to true, automatically injects all shims when needed
282
+ * When set to an object, only injects the specified shims
283
+ *
284
+ * Available shims:
285
+ * - dirname: Adds __dirname for ESM files when used
286
+ * - filename: Adds __filename for ESM files when used
287
+ * - importMetaUrl: Adds import.meta.url for CJS files when used
288
+ *
289
+ * @example
290
+ * // Enable all shims
291
+ * shims: true
292
+ *
293
+ * // Enable only specific shims
294
+ * shims: { dirname: true, importMetaUrl: true }
295
+ */
296
+ shims?: Shims;
270
297
  }
271
298
 
272
299
  //#endregion
@@ -293,7 +320,7 @@ declare function defineWorkspace(options: DefineWorkspaceItem[]): DefineWorkspac
293
320
 
294
321
  //#endregion
295
322
  //#region \0dts:/home/runner/work/bunup/bunup/src/build.d.ts
296
- declare function build(options: BuildOptions, rootDir: string): Promise<void>;
323
+ declare function build(partialOptions: Partial<BuildOptions>, rootDir: string): Promise<void>;
297
324
 
298
325
  //#endregion
299
326
  export { BuildOptions, DefineConfigItem, DefineWorkspaceItem, build, defineConfig, defineWorkspace };
package/build/index.js CHANGED
@@ -1,15 +1,26 @@
1
- var Wt=require("node:module");var St=Object.create;var{getPrototypeOf:Lt,defineProperty:$,getOwnPropertyNames:G,getOwnPropertyDescriptor:At}=Object,q=Object.prototype.hasOwnProperty;var h=(t,e,r)=>{r=t!=null?St(Lt(t)):{};let n=e||!t||!t.__esModule?$(r,"default",{value:t,enumerable:!0}):r;for(let s of G(t))if(!q.call(n,s))$(n,s,{get:()=>t[s],enumerable:!0});return n},j=new WeakMap,Ot=(t)=>{var e=j.get(t),r;if(e)return e;if(e=$({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function")G(t).map((n)=>!q.call(e,n)&&$(e,n,{get:()=>t[n],enumerable:!(r=At(t,n))||r.enumerable}));return j.set(t,e),e};var _t=(t,e)=>{for(var r in e)$(t,r,{get:e[r],enumerable:!0,configurable:!0,set:(n)=>e[r]=()=>n})};var Qt={};_t(Qt,{defineWorkspace:()=>H,defineConfig:()=>X,build:()=>Dt});module.exports=Ot(Qt);function X(t){return t}function H(t){return t}var gt=require("rolldown"),mt=require("rolldown-plugin-dts");class A extends Error{constructor(t){super(t);this.name="BunupError"}}class E extends A{constructor(t){super(t);this.name="BunupBuildError"}}class d extends A{constructor(t){super(t);this.name="BunupDTSBuildError"}}var p=(t)=>{if(t instanceof Error)return t.message;return String(t)};var O=h(require("node:fs/promises")),k=h(require("node:path"));function _(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function K(t=8){let e="";while(e.length<t)e+=Math.random().toString(36).substring(2);return e.substring(0,t)}function Y(t,e){switch(t){case"esm":return".mjs";case"cjs":return P(e)?".cjs":".js";case"iife":return".global.js"}}function Q(t,e){switch(t){case"esm":return".d.mts";case"cjs":return P(e)?".d.cts":".d.ts";case"iife":return".d.ts"}}function P(t){return t==="module"}function Z(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function z(t,e){return t===void 0?e==="esm":t}function W(t){if(t===0)return"0 B";let e=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(1024));if(r===0)return`${t} ${e[r]}`;return`${(t/1024**r).toFixed(2)} ${e[r]}`}function b(t,e=3){return t.split("/").slice(-e).join("/")}async function J(t,e){let r=k.default.join(t,e);try{await O.default.rm(r,{recursive:!0,force:!0})}catch(n){throw new E(`Failed to clean output directory: ${n}`)}await O.default.mkdir(r,{recursive:!0})}function tt(t,e){return e==="cjs"?t:void 0}function T(t){return[".ts",".mts",".cts",".tsx"].some((e)=>t.endsWith(e))}function et(t){return t.map((e)=>typeof e==="string"?new RegExp(`^${_(e)}($|\\/|\\\\)`):e)}function D(t,e){return et(t.external||[]).concat(Z(e).map((r)=>new RegExp(`^${_(r)}($|\\/|\\\\)`)))}function M(t){return et(t.noExternal||[])}var rt=!1;function nt(t){rt=t??!1}class w{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!w.instance)w.instance=new w;return w.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(t){if(!t?.once)return!0;if(this.loggedOnceMessages.has(t.once))return!1;return this.loggedOnceMessages.add(t.once),!0}formatMessage({colorCode:t,label:e,message:r,size:n,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length)),a=o?`\x1B[38;5;${this.colors.info}m${r}\x1B[0m`:r;if(n){let[u,...g]=a.split(" "),l=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-u.length)),m=s?` \x1B[48;5;${t};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${i}${u}${l} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${g.join(" ")}${m}`}let c=s?` \x1B[48;5;${t};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${i}${a}${c}`}output(t,e={},r=console.log){if(rt)return;if(!this.shouldLog(e))return;if(e.verticalSpace)console.log("");if(r(t),e.verticalSpace)console.log("")}cli(t,e={}){let r=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}info(t,e={}){let r=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}warn(t,e={}){let r=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.warn)}error(t,e={}){let r=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.error)}progress(t,e,r,n){let s=String(t),o=this.colors.default,i,a,c={};if(typeof r==="string")i=r,a=n;else if(r)i=r.size,a=r.identifier,c=r;for(let[g,l]of Object.entries(this.colors.progress))if(s.includes(g)){o=l;break}let u=this.formatMessage({colorCode:o,label:s,message:e,size:i,identifier:a,muted:c.muted});this.output(u,c)}}var f=w.getInstance();var lt=h(require("node:path")),ut=require("oxc-resolver");var x=h(require("node:path"));var C="\x00dts:",st=(t,e,r)=>{return{name:"bunup:virtual-dts",async resolveId(n,s){if(N(n))return n;if(!s||!N(s))return null;let o=await B(n,e,r,y(s));if(!o)return null;let i=R(o);if(t.has(i))return I(i);return null},load(n){if(n.startsWith(C)){let s=y(n),o=t.get(s);if(o)return it.add(s),o}return null}}};function ot(t){return t.tsconfig?.compilerOptions}function R(t){return t.replace(/\.tsx?$/,".d.ts")}function U(t){let e=x.default.dirname(t.path||""),r=ot(t);return r?.baseUrl?x.default.resolve(e,r.baseUrl):e}function at(t){let e=new Map,r=ot(t)?.paths;if(!r)return e;let n=U(t);for(let[s,o]of Object.entries(r))if(Array.isArray(o)&&o.length){let i=s.replace(/\*/g,"(.*)"),a=o[0].replace(/\*/g,"$1");e.set(`^${i}$`,x.default.join(n,a))}return e}function Nt(t,e,r){for(let[n,s]of e){let o=new RegExp(n),i=t.match(o);if(i)return s.replace("$1",i[1]||"")}return r?x.default.join(r,t):null}async function Ut(t){let e=["",".ts",".tsx",".cts",".mts","/index.ts","/index.tsx","/index.cts","/index.mts"];for(let r of e){let n=`${t}${r}`;if(await Bun.file(n).exists()&&(n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".cts")||n.endsWith(".mts")))return n}return null}function B(t,e,r,n){let s=t.startsWith(".")?x.default.resolve(x.default.dirname(n||""),t):Nt(t,e,r);if(!s)return Promise.resolve(null);return Ut(s)}function N(t){return t.startsWith(C)}function y(t){return t.replace(C,"")}function I(t){return`${C}${t}`}var ct;function ft(t){return{name:"bunup:types-resolve",buildStart(){ct||=new ut.ResolverFactory({mainFields:["types"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".ts",".d.cts",".d.mts",".cts",".mts"],modules:["node_modules","node_modules/@types"]})},async resolveId(e,r){let n=r?y(r):void 0;if(/\0/.test(e))return;if(t){if(!t.some((a)=>{let c=!1;if(typeof a==="string")c=a===e||!!n?.includes(a);else c=a.test(e)||!!(n&&a.test(n));return c}))return}let s=n?lt.default.dirname(n):process.cwd(),{path:o}=await ct.async(s,e);if(!o)return;if(/[cm]?jsx?$/.test(o)){let i=o.replace(/\.([cm]?)jsx?$/,".d.$1ts");return await Bun.file(i).exists()?i:void 0}return o}}}async function dt(t,e,r,n,s,o){let i=R(t),a=I(i),c=D(r,n),u=M(r);try{let{output:g}=await gt.build({input:a,output:{dir:r.outDir,inlineDynamicImports:!0},write:!1,onwarn(l,m){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;m(l)},plugins:[st(e,s,o),typeof r.dts==="object"&&"resolve"in r.dts&&ft(typeof r.dts.resolve==="boolean"?void 0:r.dts.resolve),mt.dts({dtsInput:!0})],external:(l)=>c.some((m)=>m.test(l))&&!u.some((m)=>m.test(l))});if(!g[0]?.code)return f.warn(`Generated empty declaration file for entry "${t}"`,{muted:!0}),"";return g[0].code}catch(g){throw new d(`DTS bundling failed for entry "${t}": ${p(g)}`)}}var vt=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Ft=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Vt=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,jt=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Gt=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,qt=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Xt=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Ht(t){let e=new Set,r=[vt,Ft,Vt,jt,Gt,qt,Xt];for(let n of r){let s=t.matchAll(n);for(let o of s)if(o[1])e.add(o[1])}return e}async function pt(t,e,r){let n=new Set([t]),s=[t];while(s.length){let o=s.pop();if(!o)continue;try{let i=await Bun.file(o).text(),a=Ht(i);for(let c of a){let u=await B(c,e,r,o);if(!u)continue;if(!n.has(u))n.add(u),s.push(u)}}catch(i){f.warn(`Error processing ${o}: ${p(i)}`)}}return n}var xt=require("oxc-transform");async function ht(t){let e=new Map;return await Promise.all([...t].map(async(r)=>{try{let n=R(r);if(!await Bun.file(r).exists())return;let o=await Bun.file(r).text(),{code:i}=xt.isolatedDeclaration(r,o);if(i)e.set(n,i)}catch(n){f.warn(`Failed to generate declaration for ${r}: ${p(n)}`)}})),e}var v=h(require("node:fs/promises")),S=h(require("node:path")),kt=require("oxc-transform");async function Et(t,e){let r=S.default.resolve(t),n=S.default.resolve(r,e);if(!await v.default.exists(r))throw new d(`Root directory does not exist: ${r}`);if(!await Bun.file(n).exists())throw new d(`Entry file does not exist: ${n}`);if(!T(n))throw new d(`Entry file must be a TypeScript file: ${n}`);if(S.default.relative(r,n).startsWith(".."))throw new d(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:r,absoluteEntry:n}}async function bt(t,e,r,n,s){let{absoluteEntry:o}=await Et(t,e),i=at(n),a=U(n),c=await pt(o,i,a),u=await ht(c);return dt(o,u,r,s,i,a)}function wt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function F(t,{warnOnConflict:e=!0}={}){let r=[],n=new Set,s={};function o(i,a){if(n.has(i)){let c=K(),u=`${i}_${c}`;if(e)f.warn(`Output name conflict: "${i}" is used by multiple files.
1
+ var Wt=require("node:module");var Ft=Object.create;var{getPrototypeOf:kt,defineProperty:R,getOwnPropertyNames:H,getOwnPropertyDescriptor:Nt}=Object,q=Object.prototype.hasOwnProperty;var h=(t,e,r)=>{r=t!=null?Ft(kt(t)):{};let n=e||!t||!t.__esModule?R(r,"default",{value:t,enumerable:!0}):r;for(let i of H(t))if(!q.call(n,i))R(n,i,{get:()=>t[i],enumerable:!0});return n},V=new WeakMap,vt=(t)=>{var e=V.get(t),r;if(e)return e;if(e=R({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function")H(t).map((n)=>!q.call(e,n)&&R(e,n,{get:()=>t[n],enumerable:!(r=Nt(t,n))||r.enumerable}));return V.set(t,e),e};var Ut=(t,e)=>{for(var r in e)R(t,r,{get:e[r],enumerable:!0,configurable:!0,set:(n)=>e[r]=()=>n})};var ie={};Ut(ie,{defineWorkspace:()=>Y,defineConfig:()=>X,build:()=>Lt});module.exports=vt(ie);function X(t){return t}function Y(t){return t}var gt=require("rolldown"),mt=require("rolldown-plugin-dts");class A extends Error{constructor(t){super(t);this.name="BunupError"}}class b extends A{constructor(t){super(t);this.name="BunupBuildError"}}class p extends A{constructor(t){super(t);this.name="BunupDTSBuildError"}}var d=(t)=>{if(t instanceof Error)return t.message;return String(t)};var _=h(require("node:fs/promises")),K=h(require("node:path"));function j(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q(t=8){let e="";while(e.length<t)e+=Math.random().toString(36).substring(2);return e.substring(0,t)}function Z(t,e){switch(t){case"esm":return".mjs";case"cjs":return S(e)?".cjs":".js";case"iife":return".global.js"}}function z(t,e){switch(t){case"esm":return".d.mts";case"cjs":return S(e)?".d.cts":".d.ts";case"iife":return".d.ts"}}function F(t){return t==="node"||t==="bun"}function S(t){return t==="module"}function J(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function k(t){if(t===0)return"0 B";let e=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(1024));if(r===0)return`${t} ${e[r]}`;return`${(t/1024**r).toFixed(2)} ${e[r]}`}function y(t,e=3){return t.split("/").slice(-e).join("/")}async function tt(t,e){let r=K.default.join(t,e);try{await _.default.rm(r,{recursive:!0,force:!0})}catch(n){throw new b(`Failed to clean output directory: ${n}`)}await _.default.mkdir(r,{recursive:!0})}function C(t){return[".ts",".mts",".cts",".tsx"].some((e)=>t.endsWith(e))}function et(t){return t.map((e)=>typeof e==="string"?new RegExp(`^${j(e)}($|\\/|\\\\)`):e)}function P(t,e){return et(t.external||[]).concat(J(e).map((r)=>new RegExp(`^${j(r)}($|\\/|\\\\)`)))}function B(t){return et(t.noExternal||[])}var rt=!1;function nt(t){rt=t??!1}class E{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!E.instance)E.instance=new E;return E.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(t){if(!t?.once)return!0;if(this.loggedOnceMessages.has(t.once))return!1;return this.loggedOnceMessages.add(t.once),!0}formatMessage({colorCode:t,label:e,message:r,size:n,identifier:i,muted:o}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length)),a=o?`\x1B[38;5;${this.colors.info}m${r}\x1B[0m`:r;if(n){let[c,...l]=a.split(" "),m=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),f=i?` \x1B[48;5;${t};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${c}${m} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${l.join(" ")}${f}`}let u=i?` \x1B[48;5;${t};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${a}${u}`}output(t,e={},r=console.log){if(rt)return;if(!this.shouldLog(e))return;if(e.verticalSpace)console.log("");if(r(t),e.verticalSpace)console.log("")}cli(t,e={}){let r=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}info(t,e={}){let r=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}warn(t,e={}){let r=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.warn)}error(t,e={}){let r=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.error)}progress(t,e,r,n){let i=String(t),o=this.colors.default,s,a,u={};if(typeof r==="string")s=r,a=n;else if(r)s=r.size,a=r.identifier,u=r;for(let[l,m]of Object.entries(this.colors.progress))if(i.includes(l)){o=m;break}let c=this.formatMessage({colorCode:o,label:i,message:e,size:s,identifier:a,muted:u.muted});this.output(c,u)}}var g=E.getInstance();var ut=h(require("node:path")),lt=require("oxc-resolver");var x=h(require("node:path"));var $="\x00dts:",st=(t,e,r)=>{return{name:"bunup:virtual-dts",async resolveId(n,i){if(N(n))return n;if(!i||!N(i))return null;let o=await D(n,e,r,T(i));if(!o)return null;let s=w(o);if(t.has(s))return M(s);return null},load(n){if(n.startsWith($)){let i=T(n),o=t.get(i);if(o)return it.add(i),o}return null}}};function ot(t){return t.tsconfig?.compilerOptions}function w(t){return t.replace(/\.tsx?$/,".d.ts")}function v(t){let e=x.default.dirname(t.path||""),r=ot(t);return r?.baseUrl?x.default.resolve(e,r.baseUrl):e}function at(t){let e=new Map,r=ot(t)?.paths;if(!r)return e;let n=v(t);for(let[i,o]of Object.entries(r))if(Array.isArray(o)&&o.length){let s=i.replace(/\*/g,"(.*)"),a=o[0].replace(/\*/g,"$1");e.set(`^${s}$`,x.default.join(n,a))}return e}function Gt(t,e,r){for(let[n,i]of e){let o=new RegExp(n),s=t.match(o);if(s)return i.replace("$1",s[1]||"")}return r?x.default.join(r,t):null}async function Vt(t){let e=["",".ts",".tsx",".cts",".mts","/index.ts","/index.tsx","/index.cts","/index.mts"];for(let r of e){let n=`${t}${r}`;if(await Bun.file(n).exists()&&(n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".cts")||n.endsWith(".mts")))return n}return null}function D(t,e,r,n){let i=t.startsWith(".")?x.default.resolve(x.default.dirname(n||""),t):Gt(t,e,r);if(!i)return Promise.resolve(null);return Vt(i)}function N(t){return t.startsWith($)}function T(t){return t.replace($,"")}function M(t){return`${$}${t}`}var ct;function ft(t){return{name:"bunup:types-resolve",buildStart(){ct||=new lt.ResolverFactory({mainFields:["types"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".ts",".d.cts",".d.mts",".cts",".mts"],modules:["node_modules","node_modules/@types"]})},async resolveId(e,r){let n=r?T(r):void 0;if(/\0/.test(e))return;if(t){if(!t.some((a)=>{let u=!1;if(typeof a==="string")u=a===e||!!n?.includes(a);else u=a.test(e)||!!(n&&a.test(n));return u}))return}let i=n?ut.default.dirname(n):process.cwd(),{path:o}=await ct.async(i,e);if(!o)return;if(/[cm]?jsx?$/.test(o)){let s=o.replace(/\.([cm]?)jsx?$/,".d.$1ts");return await Bun.file(s).exists()?s:void 0}return o}}}async function pt(t,e,r,n,i,o){let s=w(t),a=M(s),u=P(r,n),c=B(r);try{let{output:l}=await gt.build({input:a,output:{dir:r.outDir,inlineDynamicImports:!0},write:!1,onwarn(m,f){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(m.code??""))return;f(m)},plugins:[st(e,i,o),typeof r.dts==="object"&&"resolve"in r.dts&&ft(typeof r.dts.resolve==="boolean"?void 0:r.dts.resolve),mt.dts({dtsInput:!0})],external:(m)=>u.some((f)=>f.test(m))&&!c.some((f)=>f.test(m))});if(!l[0]?.code)return g.warn(`Generated empty declaration file for entry "${t}"`,{muted:!0}),"";return l[0].code}catch(l){throw new p(`DTS bundling failed for entry "${t}": ${d(l)}`)}}var Ht=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,qt=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Xt=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Yt=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Kt=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Qt=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Zt=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function zt(t){let e=new Set,r=[Ht,qt,Xt,Yt,Kt,Qt,Zt];for(let n of r){let i=t.matchAll(n);for(let o of i)if(o[1])e.add(o[1])}return e}async function dt(t,e,r){let n=new Set([t]),i=[t];while(i.length){let o=i.pop();if(!o)continue;try{let s=await Bun.file(o).text(),a=zt(s);for(let u of a){let c=await D(u,e,r,o);if(!c)continue;if(!n.has(c))n.add(c),i.push(c)}}catch(s){g.warn(`Error processing ${o}: ${d(s)}`)}}return n}var xt=require("oxc-transform");async function ht(t){let e=new Map;return await Promise.all([...t].map(async(r)=>{try{let n=w(r);if(!await Bun.file(r).exists())return;let o=await Bun.file(r).text(),{code:s}=xt.isolatedDeclaration(r,o);if(s)e.set(n,s)}catch(n){g.warn(`Failed to generate declaration for ${r}: ${d(n)}`)}})),e}var U=h(require("node:fs/promises")),I=h(require("node:path")),Jt=require("oxc-transform");async function bt(t,e){let r=I.default.resolve(t),n=I.default.resolve(r,e);if(!await U.default.exists(r))throw new p(`Root directory does not exist: ${r}`);if(!await Bun.file(n).exists())throw new p(`Entry file does not exist: ${n}`);if(!C(n))throw new p(`Entry file must be a TypeScript file: ${n}`);if(I.default.relative(r,n).startsWith(".."))throw new p(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:r,absoluteEntry:n}}async function yt(t,e,r,n,i){let{absoluteEntry:o}=await bt(t,e),s=at(n),a=v(n),u=await dt(o,s,a),c=await ht(u);return pt(o,c,r,i,s,a)}function Et(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function W(t,{warnOnConflict:e=!0}={}){let r=[],n=new Set,i={};function o(s,a){if(n.has(s)){let u=Q(),c=`${s}_${u}`;if(e)g.warn(`Output name conflict: "${s}" is used by multiple files.
2
2
  Bunup uses filenames without extensions as output names by default.
3
3
 
4
- ${s[i]} -> ${i}.js
5
- ${a} -> ${u}.js (auto-renamed to avoid conflict)
4
+ ${i[s]} -> ${s}.js
5
+ ${a} -> ${c}.js (auto-renamed to avoid conflict)
6
6
 
7
7
  To fix this, use named entries in your configuration:
8
8
  {
9
9
  entry: {
10
- custom_name: "${s[i]}",
10
+ custom_name: "${i[s]}",
11
11
  another_name: "${a}"
12
12
  }
13
13
  }
14
14
 
15
- See: https://bunup.arshadyaseen.com/#named-entries`,{muted:!0,verticalSpace:!0});r.push({name:u,path:a})}else r.push({name:i,path:a}),n.add(i),s[i]=a}if(Array.isArray(t))for(let i of t){let a=wt(i);o(a,i)}else if(typeof t==="object")for(let[i,a]of Object.entries(t))o(i,a);else{let i=wt(t);o(i,t)}return r}function Rt(t){return t.filter((e)=>T(e.path))}function $t(t,e){return`[dir]/${t}${e}`}var V=require("coffi");async function yt(t){let{config:e,filepath:r}=await V.loadConfig({name:"package",cwd:t,extensions:[".json"],maxDepth:1});return{packageJson:e,path:r}}async function Ct(t,e){let{config:r,filepath:n}=await V.loadConfig({name:"tsconfig",cwd:t,extensions:[".json"],preferredPath:e,maxDepth:3});return{tsconfig:r,path:n}}function Pt(t,e){return{outdir:`${e}/${t.outDir}`,minify:Kt(t),target:t.target,splitting:t.splitting,sourcemap:t.sourcemap,define:t.define,loader:t.loader,drop:t.drop,banner:t.banner,footer:t.footer,publicPath:t.publicPath}}function Kt(t){let{minify:e,minifyWhitespace:r,minifyIdentifiers:n,minifySyntax:s}=t,o=e===!0;return{whitespace:r??o,identifiers:n??o,syntax:s??o}}function Tt(t,e){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(n)=>{let s=n.path;if(t.some((i)=>i.test(s))&&!e.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}var it=new Set;async function Dt(t,e){if(!t.entry||t.entry.length===0||!t.outDir)throw new E("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)J(e,t.outDir);nt(t.silent);let{packageJson:r,path:n}=await yt(e);if(r&&n)f.cli(`Using package.json: ${b(n,2)}`,{muted:!0,identifier:t.name,once:`${n}:${t.name}`});let s=F(t.entry),o=r?.type,i=D(t,r),a=M(t);if(!t.dtsOnly){let c=[Tt(i,a)],u=Pt(t,e),g=t.format.flatMap((l)=>s.map((m)=>{return Yt(t,e,m,l,o,c,u)}));await Promise.all(g)}if(t.dts||t.dtsOnly){let c=await Ct(e,t.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${b(c.path,2)}`,{muted:!0,identifier:t.name,once:`${c.path}:${t.name}`});let u=t.format.filter((l)=>{if(l==="iife"&&!P(o)&&t.format.includes("cjs"))return!1;return!0}),g=typeof t.dts==="object"&&t.dts.entry?F(t.dts.entry):Rt(s);try{await Promise.all(g.map(async(l)=>{let m=await bt(e,l.path,t,c,r);await Promise.all(u.map(async(Mt)=>{let Bt=Q(Mt,o),L=`${e}/${t.outDir}/${l.name}${Bt}`;await Bun.write(L,m);let It=Bun.file(L).size||0;f.progress("DTS",b(L),W(It),t.name)}))}))}catch(l){throw new d(p(l))}}}async function Yt(t,e,r,n,s,o,i){let a=Y(n,s),c=await Bun.build({...i,entrypoints:[`${e}/${r.path}`],format:n,naming:{entry:$t(r.name,a)},splitting:z(t.splitting,n),bytecode:tt(t.bytecode,n),plugins:o,throw:!1});if(!c.success)for(let l of c.logs){if(l.level==="error")throw new E(l.message);if(l.level==="warning")f.warn(l.message);else if(l.level==="info")f.info(l.message)}let u=`${e}/${t.outDir}/${r.name}${a}`,g=Bun.file(u).size||0;f.progress(n.toUpperCase(),b(u),W(g),t.name)}
15
+ See: https://bunup.arshadyaseen.com/#named-entries`,{muted:!0,verticalSpace:!0});r.push({name:c,path:a})}else r.push({name:s,path:a}),n.add(s),i[s]=a}if(Array.isArray(t))for(let s of t){let a=Et(s);o(a,s)}else if(typeof t==="object")for(let[s,a]of Object.entries(t))o(s,a);else{let s=Et(t);o(s,t)}return r}function wt(t){return t.filter((e)=>C(e.path))}function Rt(t,e){return`[dir]/${t}${e}`}var G=require("coffi");async function Tt(t){let{config:e,filepath:r}=await G.loadConfig({name:"package",cwd:t,extensions:[".json"],maxDepth:1});return{packageJson:e,path:r}}async function $t(t,e){let{config:r,filepath:n}=await G.loadConfig({name:"tsconfig",cwd:t,extensions:[".json"],preferredPath:e,maxDepth:3});return{tsconfig:r,path:n}}var te={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function St(t){return{...te,...t}}function Ct(t){let{minify:e,minifyWhitespace:r,minifyIdentifiers:n,minifySyntax:i}=t,o=e===!0;return{whitespace:r??o,identifiers:n??o,syntax:i??o}}function Pt(t,e){return e==="cjs"?t:void 0}function Bt(t,e,r){return{...t,...r==="cjs"&&(e===!0||typeof e==="object"&&e.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Dt(t,e){return t===void 0?e==="esm":t}function Mt(t,e){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(n)=>{let i=n.path;if(t.some((s)=>s.test(i))&&!e.some((s)=>s.test(i)))return{path:i,external:!0};return null})}}}var L={dirnameFilename:{appliesTo:(t,e)=>t==="esm"&&F(e),isNeededInFile:(t)=>/\b__dirname\b/.test(t)||/\b__filename\b/.test(t),generateCode:()=>`import { fileURLToPath } from 'url';
16
+ import { dirname } from 'path';
17
+
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = dirname(__filename);
20
+
21
+ `},importMetaUrl:{appliesTo:(t,e)=>t==="cjs"&&F(e),isNeededInFile:(t)=>/\bimport\.meta\.url\b/.test(t),generateCode:()=>`import { pathToFileURL } from 'url';
22
+
23
+ const importMetaUrl = pathToFileURL(__filename).href;
24
+
25
+ `}};var ee=/\.(js|ts|jsx|tsx|mts|cts)$/;function It({format:t,target:e,shims:r}){let i=re(r).map((o)=>L[o]).filter((o)=>o.appliesTo(t,e));if(i.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:ee},async({path:s})=>{let a=await Bun.file(s).text(),u=i.filter((f)=>f.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:l}=ne(a),m=u.map((f)=>f.generateCode()).join("");return{contents:c+m+l}})}}}function re(t){if(t===!0)return Object.keys(L);if(!t)return[];return Object.entries(t).filter(([e,r])=>r&&(e in L)).map(([e])=>e)}function ne(t){if(!t.startsWith("#!"))return{shebangLine:"",codeContent:t};let e=t.indexOf(`
26
+ `);return e===-1?{shebangLine:"",codeContent:t}:{shebangLine:t.slice(0,e+1),codeContent:t.slice(e+1)}}var it=new Set;async function Lt(t,e){let r=St(t);if(!r.entry||r.entry.length===0||!r.outDir)throw new b("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(r.clean)tt(e,r.outDir);nt(r.silent);let{packageJson:n,path:i}=await Tt(e);if(n&&i)g.cli(`Using package.json: ${y(i,2)}`,{muted:!0,identifier:r.name,once:`${i}:${r.name}`});let o=W(r.entry),s=n?.type,a=P(r,n),u=B(r);if(!r.dtsOnly){let c=[Mt(a,u)],l=r.format.flatMap((m)=>o.map((f)=>{return se(r,e,f,m,s,c)}));await Promise.all(l)}if(r.dts||r.dtsOnly){let c=await $t(e,r.preferredTsconfigPath);if(c.path)g.cli(`Using tsconfig: ${y(c.path,2)}`,{muted:!0,identifier:r.name,once:`${c.path}:${r.name}`});let l=r.format.filter((f)=>{if(f==="iife"&&!S(s)&&r.format.includes("cjs"))return!1;return!0}),m=typeof r.dts==="object"&&r.dts.entry?W(r.dts.entry):wt(o);try{await Promise.all(m.map(async(f)=>{let Ot=await yt(e,f.path,r,c,n);await Promise.all(l.map(async(At)=>{let _t=z(At,s),O=`${e}/${r.outDir}/${f.name}${_t}`;await Bun.write(O,Ot);let jt=Bun.file(O).size||0;g.progress("DTS",y(O),k(jt),r.name)}))}))}catch(f){throw new p(d(f))}}}async function se(t,e,r,n,i,o){let s=Z(n,i),a=await Bun.build({entrypoints:[`${e}/${r.path}`],format:n,naming:{entry:Rt(r.name,s)},splitting:Dt(t.splitting,n),bytecode:Pt(t.bytecode,n),define:Bt(t.define,t.shims,n),minify:Ct(t),outdir:`${e}/${t.outDir}`,target:t.target,sourcemap:t.sourcemap,loader:t.loader,drop:t.drop,banner:t.banner,footer:t.footer,publicPath:t.publicPath,plugins:[...o,It({format:n,target:t.target,shims:t.shims})],throw:!1});if(!a.success)for(let l of a.logs){if(l.level==="error")throw new b(l.message);if(l.level==="warning")g.warn(l.message);else if(l.level==="info")g.info(l.message)}let u=`${e}/${t.outDir}/${r.name}${s}`,c=Bun.file(u).size||0;g.progress(n.toUpperCase(),y(u),k(c),t.name)}
package/build/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- function ht(t){return t}function Et(t){return t}import{build as Ct}from"rolldown";import{dts as Pt}from"rolldown-plugin-dts";class I extends Error{constructor(t){super(t);this.name="BunupError"}}class x extends I{constructor(t){super(t);this.name="BunupBuildError"}}class d extends I{constructor(t){super(t);this.name="BunupDTSBuildError"}}var p=(t)=>{if(t instanceof Error)return t.message;return String(t)};import N from"node:fs/promises";import bt from"node:path";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(t=8){let e="";while(e.length<t)e+=Math.random().toString(36).substring(2);return e.substring(0,t)}function v(t,e){switch(t){case"esm":return".mjs";case"cjs":return y(e)?".cjs":".js";case"iife":return".global.js"}}function F(t,e){switch(t){case"esm":return".d.mts";case"cjs":return y(e)?".d.cts":".d.ts";case"iife":return".d.ts"}}function y(t){return t==="module"}function V(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function j(t,e){return t===void 0?e==="esm":t}function L(t){if(t===0)return"0 B";let e=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(1024));if(r===0)return`${t} ${e[r]}`;return`${(t/1024**r).toFixed(2)} ${e[r]}`}function h(t,e=3){return t.split("/").slice(-e).join("/")}async function G(t,e){let r=bt.join(t,e);try{await N.rm(r,{recursive:!0,force:!0})}catch(n){throw new x(`Failed to clean output directory: ${n}`)}await N.mkdir(r,{recursive:!0})}function q(t,e){return e==="cjs"?t:void 0}function C(t){return[".ts",".mts",".cts",".tsx"].some((e)=>t.endsWith(e))}function X(t){return t.map((e)=>typeof e==="string"?new RegExp(`^${S(e)}($|\\/|\\\\)`):e)}function P(t,e){return X(t.external||[]).concat(V(e).map((r)=>new RegExp(`^${S(r)}($|\\/|\\\\)`)))}function T(t){return X(t.noExternal||[])}var H=!1;function k(t){H=t??!1}class E{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!E.instance)E.instance=new E;return E.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(t){if(!t?.once)return!0;if(this.loggedOnceMessages.has(t.once))return!1;return this.loggedOnceMessages.add(t.once),!0}formatMessage({colorCode:t,label:e,message:r,size:n,identifier:o,muted:i}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length)),a=i?`\x1B[38;5;${this.colors.info}m${r}\x1B[0m`:r;if(n){let[u,...g]=a.split(" "),l=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-u.length)),m=o?` \x1B[48;5;${t};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${u}${l} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${g.join(" ")}${m}`}let c=o?` \x1B[48;5;${t};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${a}${c}`}output(t,e={},r=console.log){if(H)return;if(!this.shouldLog(e))return;if(e.verticalSpace)console.log("");if(r(t),e.verticalSpace)console.log("")}cli(t,e={}){let r=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}info(t,e={}){let r=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}warn(t,e={}){let r=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.warn)}error(t,e={}){let r=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.error)}progress(t,e,r,n){let o=String(t),i=this.colors.default,s,a,c={};if(typeof r==="string")s=r,a=n;else if(r)s=r.size,a=r.identifier,c=r;for(let[g,l]of Object.entries(this.colors.progress))if(o.includes(g)){i=l;break}let u=this.formatMessage({colorCode:i,label:o,message:e,size:s,identifier:a,muted:c.muted});this.output(u,c)}}var f=E.getInstance();import $t from"node:path";import{ResolverFactory as yt}from"oxc-resolver";import w from"node:path";var $="\x00dts:",K=(t,e,r)=>{return{name:"bunup:virtual-dts",async resolveId(n,o){if(A(n))return n;if(!o||!A(o))return null;let i=await D(n,e,r,R(o));if(!i)return null;let s=b(i);if(t.has(s))return M(s);return null},load(n){if(n.startsWith($)){let o=R(n),i=t.get(o);if(i)return Y.add(o),i}return null}}};function Q(t){return t.tsconfig?.compilerOptions}function b(t){return t.replace(/\.tsx?$/,".d.ts")}function O(t){let e=w.dirname(t.path||""),r=Q(t);return r?.baseUrl?w.resolve(e,r.baseUrl):e}function Z(t){let e=new Map,r=Q(t)?.paths;if(!r)return e;let n=O(t);for(let[o,i]of Object.entries(r))if(Array.isArray(i)&&i.length){let s=o.replace(/\*/g,"(.*)"),a=i[0].replace(/\*/g,"$1");e.set(`^${s}$`,w.join(n,a))}return e}function wt(t,e,r){for(let[n,o]of e){let i=new RegExp(n),s=t.match(i);if(s)return o.replace("$1",s[1]||"")}return r?w.join(r,t):null}async function Rt(t){let e=["",".ts",".tsx",".cts",".mts","/index.ts","/index.tsx","/index.cts","/index.mts"];for(let r of e){let n=`${t}${r}`;if(await Bun.file(n).exists()&&(n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".cts")||n.endsWith(".mts")))return n}return null}function D(t,e,r,n){let o=t.startsWith(".")?w.resolve(w.dirname(n||""),t):wt(t,e,r);if(!o)return Promise.resolve(null);return Rt(o)}function A(t){return t.startsWith($)}function R(t){return t.replace($,"")}function M(t){return`${$}${t}`}var z;function J(t){return{name:"bunup:types-resolve",buildStart(){z||=new yt({mainFields:["types"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".ts",".d.cts",".d.mts",".cts",".mts"],modules:["node_modules","node_modules/@types"]})},async resolveId(e,r){let n=r?R(r):void 0;if(/\0/.test(e))return;if(t){if(!t.some((a)=>{let c=!1;if(typeof a==="string")c=a===e||!!n?.includes(a);else c=a.test(e)||!!(n&&a.test(n));return c}))return}let o=n?$t.dirname(n):process.cwd(),{path:i}=await z.async(o,e);if(!i)return;if(/[cm]?jsx?$/.test(i)){let s=i.replace(/\.([cm]?)jsx?$/,".d.$1ts");return await Bun.file(s).exists()?s:void 0}return i}}}async function tt(t,e,r,n,o,i){let s=b(t),a=M(s),c=P(r,n),u=T(r);try{let{output:g}=await Ct({input:a,output:{dir:r.outDir,inlineDynamicImports:!0},write:!1,onwarn(l,m){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;m(l)},plugins:[K(e,o,i),typeof r.dts==="object"&&"resolve"in r.dts&&J(typeof r.dts.resolve==="boolean"?void 0:r.dts.resolve),Pt({dtsInput:!0})],external:(l)=>c.some((m)=>m.test(l))&&!u.some((m)=>m.test(l))});if(!g[0]?.code)return f.warn(`Generated empty declaration file for entry "${t}"`,{muted:!0}),"";return g[0].code}catch(g){throw new d(`DTS bundling failed for entry "${t}": ${p(g)}`)}}var Tt=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Dt=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Mt=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Bt=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,It=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,St=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Lt=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function At(t){let e=new Set,r=[Tt,Dt,Mt,Bt,It,St,Lt];for(let n of r){let o=t.matchAll(n);for(let i of o)if(i[1])e.add(i[1])}return e}async function et(t,e,r){let n=new Set([t]),o=[t];while(o.length){let i=o.pop();if(!i)continue;try{let s=await Bun.file(i).text(),a=At(s);for(let c of a){let u=await D(c,e,r,i);if(!u)continue;if(!n.has(u))n.add(u),o.push(u)}}catch(s){f.warn(`Error processing ${i}: ${p(s)}`)}}return n}import{isolatedDeclaration as Ot}from"oxc-transform";async function rt(t){let e=new Map;return await Promise.all([...t].map(async(r)=>{try{let n=b(r);if(!await Bun.file(r).exists())return;let i=await Bun.file(r).text(),{code:s}=Ot(r,i);if(s)e.set(n,s)}catch(n){f.warn(`Failed to generate declaration for ${r}: ${p(n)}`)}})),e}import nt from"node:fs/promises";import _ from"node:path";import{isolatedDeclaration as Ce}from"oxc-transform";async function st(t,e){let r=_.resolve(t),n=_.resolve(r,e);if(!await nt.exists(r))throw new d(`Root directory does not exist: ${r}`);if(!await Bun.file(n).exists())throw new d(`Entry file does not exist: ${n}`);if(!C(n))throw new d(`Entry file must be a TypeScript file: ${n}`);if(_.relative(r,n).startsWith(".."))throw new d(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:r,absoluteEntry:n}}async function it(t,e,r,n,o){let{absoluteEntry:i}=await st(t,e),s=Z(n),a=O(n),c=await et(i,s,a),u=await rt(c);return tt(i,u,r,o,s,a)}function ot(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function W(t,{warnOnConflict:e=!0}={}){let r=[],n=new Set,o={};function i(s,a){if(n.has(s)){let c=U(),u=`${s}_${c}`;if(e)f.warn(`Output name conflict: "${s}" is used by multiple files.
1
+ function Tt(t){return t}function $t(t){return t}import{build as Mt}from"rolldown";import{dts as It}from"rolldown-plugin-dts";class I extends Error{constructor(t){super(t);this.name="BunupError"}}class x extends I{constructor(t){super(t);this.name="BunupBuildError"}}class p extends I{constructor(t){super(t);this.name="BunupDTSBuildError"}}var d=(t)=>{if(t instanceof Error)return t.message;return String(t)};import N from"node:fs/promises";import St from"node:path";function L(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v(t=8){let e="";while(e.length<t)e+=Math.random().toString(36).substring(2);return e.substring(0,t)}function U(t,e){switch(t){case"esm":return".mjs";case"cjs":return T(e)?".cjs":".js";case"iife":return".global.js"}}function W(t,e){switch(t){case"esm":return".d.mts";case"cjs":return T(e)?".d.cts":".d.ts";case"iife":return".d.ts"}}function O(t){return t==="node"||t==="bun"}function T(t){return t==="module"}function G(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function A(t){if(t===0)return"0 B";let e=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(1024));if(r===0)return`${t} ${e[r]}`;return`${(t/1024**r).toFixed(2)} ${e[r]}`}function h(t,e=3){return t.split("/").slice(-e).join("/")}async function V(t,e){let r=St.join(t,e);try{await N.rm(r,{recursive:!0,force:!0})}catch(n){throw new x(`Failed to clean output directory: ${n}`)}await N.mkdir(r,{recursive:!0})}function $(t){return[".ts",".mts",".cts",".tsx"].some((e)=>t.endsWith(e))}function H(t){return t.map((e)=>typeof e==="string"?new RegExp(`^${L(e)}($|\\/|\\\\)`):e)}function S(t,e){return H(t.external||[]).concat(G(e).map((r)=>new RegExp(`^${L(r)}($|\\/|\\\\)`)))}function C(t){return H(t.noExternal||[])}var q=!1;function X(t){q=t??!1}class b{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!b.instance)b.instance=new b;return b.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(t){if(!t?.once)return!0;if(this.loggedOnceMessages.has(t.once))return!1;return this.loggedOnceMessages.add(t.once),!0}formatMessage({colorCode:t,label:e,message:r,size:n,identifier:o,muted:i}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length)),a=i?`\x1B[38;5;${this.colors.info}m${r}\x1B[0m`:r;if(n){let[c,...l]=a.split(" "),m=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),f=o?` \x1B[48;5;${t};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${c}${m} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${l.join(" ")}${f}`}let u=o?` \x1B[48;5;${t};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${a}${u}`}output(t,e={},r=console.log){if(q)return;if(!this.shouldLog(e))return;if(e.verticalSpace)console.log("");if(r(t),e.verticalSpace)console.log("")}cli(t,e={}){let r=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}info(t,e={}){let r=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e)}warn(t,e={}){let r=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.warn)}error(t,e={}){let r=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:t,identifier:e.identifier,muted:e.muted});this.output(r,e,console.error)}progress(t,e,r,n){let o=String(t),i=this.colors.default,s,a,u={};if(typeof r==="string")s=r,a=n;else if(r)s=r.size,a=r.identifier,u=r;for(let[l,m]of Object.entries(this.colors.progress))if(o.includes(l)){i=m;break}let c=this.formatMessage({colorCode:i,label:o,message:e,size:s,identifier:a,muted:u.muted});this.output(c,u)}}var g=b.getInstance();import Bt from"node:path";import{ResolverFactory as Dt}from"oxc-resolver";import E from"node:path";var R="\x00dts:",Y=(t,e,r)=>{return{name:"bunup:virtual-dts",async resolveId(n,o){if(_(n))return n;if(!o||!_(o))return null;let i=await P(n,e,r,w(o));if(!i)return null;let s=y(i);if(t.has(s))return B(s);return null},load(n){if(n.startsWith(R)){let o=w(n),i=t.get(o);if(i)return K.add(o),i}return null}}};function Q(t){return t.tsconfig?.compilerOptions}function y(t){return t.replace(/\.tsx?$/,".d.ts")}function j(t){let e=E.dirname(t.path||""),r=Q(t);return r?.baseUrl?E.resolve(e,r.baseUrl):e}function Z(t){let e=new Map,r=Q(t)?.paths;if(!r)return e;let n=j(t);for(let[o,i]of Object.entries(r))if(Array.isArray(i)&&i.length){let s=o.replace(/\*/g,"(.*)"),a=i[0].replace(/\*/g,"$1");e.set(`^${s}$`,E.join(n,a))}return e}function Ct(t,e,r){for(let[n,o]of e){let i=new RegExp(n),s=t.match(i);if(s)return o.replace("$1",s[1]||"")}return r?E.join(r,t):null}async function Pt(t){let e=["",".ts",".tsx",".cts",".mts","/index.ts","/index.tsx","/index.cts","/index.mts"];for(let r of e){let n=`${t}${r}`;if(await Bun.file(n).exists()&&(n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".cts")||n.endsWith(".mts")))return n}return null}function P(t,e,r,n){let o=t.startsWith(".")?E.resolve(E.dirname(n||""),t):Ct(t,e,r);if(!o)return Promise.resolve(null);return Pt(o)}function _(t){return t.startsWith(R)}function w(t){return t.replace(R,"")}function B(t){return`${R}${t}`}var z;function J(t){return{name:"bunup:types-resolve",buildStart(){z||=new Dt({mainFields:["types"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".ts",".d.cts",".d.mts",".cts",".mts"],modules:["node_modules","node_modules/@types"]})},async resolveId(e,r){let n=r?w(r):void 0;if(/\0/.test(e))return;if(t){if(!t.some((a)=>{let u=!1;if(typeof a==="string")u=a===e||!!n?.includes(a);else u=a.test(e)||!!(n&&a.test(n));return u}))return}let o=n?Bt.dirname(n):process.cwd(),{path:i}=await z.async(o,e);if(!i)return;if(/[cm]?jsx?$/.test(i)){let s=i.replace(/\.([cm]?)jsx?$/,".d.$1ts");return await Bun.file(s).exists()?s:void 0}return i}}}async function tt(t,e,r,n,o,i){let s=y(t),a=B(s),u=S(r,n),c=C(r);try{let{output:l}=await Mt({input:a,output:{dir:r.outDir,inlineDynamicImports:!0},write:!1,onwarn(m,f){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(m.code??""))return;f(m)},plugins:[Y(e,o,i),typeof r.dts==="object"&&"resolve"in r.dts&&J(typeof r.dts.resolve==="boolean"?void 0:r.dts.resolve),It({dtsInput:!0})],external:(m)=>u.some((f)=>f.test(m))&&!c.some((f)=>f.test(m))});if(!l[0]?.code)return g.warn(`Generated empty declaration file for entry "${t}"`,{muted:!0}),"";return l[0].code}catch(l){throw new p(`DTS bundling failed for entry "${t}": ${d(l)}`)}}var Lt=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Ot=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,At=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,_t=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,jt=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ft=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,kt=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Nt(t){let e=new Set,r=[Lt,Ot,At,_t,jt,Ft,kt];for(let n of r){let o=t.matchAll(n);for(let i of o)if(i[1])e.add(i[1])}return e}async function et(t,e,r){let n=new Set([t]),o=[t];while(o.length){let i=o.pop();if(!i)continue;try{let s=await Bun.file(i).text(),a=Nt(s);for(let u of a){let c=await P(u,e,r,i);if(!c)continue;if(!n.has(c))n.add(c),o.push(c)}}catch(s){g.warn(`Error processing ${i}: ${d(s)}`)}}return n}import{isolatedDeclaration as vt}from"oxc-transform";async function rt(t){let e=new Map;return await Promise.all([...t].map(async(r)=>{try{let n=y(r);if(!await Bun.file(r).exists())return;let i=await Bun.file(r).text(),{code:s}=vt(r,i);if(s)e.set(n,s)}catch(n){g.warn(`Failed to generate declaration for ${r}: ${d(n)}`)}})),e}import nt from"node:fs/promises";import F from"node:path";import{isolatedDeclaration as Oe}from"oxc-transform";async function st(t,e){let r=F.resolve(t),n=F.resolve(r,e);if(!await nt.exists(r))throw new p(`Root directory does not exist: ${r}`);if(!await Bun.file(n).exists())throw new p(`Entry file does not exist: ${n}`);if(!$(n))throw new p(`Entry file must be a TypeScript file: ${n}`);if(F.relative(r,n).startsWith(".."))throw new p(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:r,absoluteEntry:n}}async function it(t,e,r,n,o){let{absoluteEntry:i}=await st(t,e),s=Z(n),a=j(n),u=await et(i,s,a),c=await rt(u);return tt(i,c,r,o,s,a)}function ot(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function k(t,{warnOnConflict:e=!0}={}){let r=[],n=new Set,o={};function i(s,a){if(n.has(s)){let u=v(),c=`${s}_${u}`;if(e)g.warn(`Output name conflict: "${s}" is used by multiple files.
2
2
  Bunup uses filenames without extensions as output names by default.
3
3
 
4
4
  ${o[s]} -> ${s}.js
5
- ${a} -> ${u}.js (auto-renamed to avoid conflict)
5
+ ${a} -> ${c}.js (auto-renamed to avoid conflict)
6
6
 
7
7
  To fix this, use named entries in your configuration:
8
8
  {
@@ -12,4 +12,15 @@ To fix this, use named entries in your configuration:
12
12
  }
13
13
  }
14
14
 
15
- See: https://bunup.arshadyaseen.com/#named-entries`,{muted:!0,verticalSpace:!0});r.push({name:u,path:a})}else r.push({name:s,path:a}),n.add(s),o[s]=a}if(Array.isArray(t))for(let s of t){let a=ot(s);i(a,s)}else if(typeof t==="object")for(let[s,a]of Object.entries(t))i(s,a);else{let s=ot(t);i(s,t)}return r}function at(t){return t.filter((e)=>C(e.path))}function ct(t,e){return`[dir]/${t}${e}`}import{loadConfig as lt}from"coffi";async function ut(t){let{config:e,filepath:r}=await lt({name:"package",cwd:t,extensions:[".json"],maxDepth:1});return{packageJson:e,path:r}}async function ft(t,e){let{config:r,filepath:n}=await lt({name:"tsconfig",cwd:t,extensions:[".json"],preferredPath:e,maxDepth:3});return{tsconfig:r,path:n}}function gt(t,e){return{outdir:`${e}/${t.outDir}`,minify:_t(t),target:t.target,splitting:t.splitting,sourcemap:t.sourcemap,define:t.define,loader:t.loader,drop:t.drop,banner:t.banner,footer:t.footer,publicPath:t.publicPath}}function _t(t){let{minify:e,minifyWhitespace:r,minifyIdentifiers:n,minifySyntax:o}=t,i=e===!0;return{whitespace:r??i,identifiers:n??i,syntax:o??i}}function mt(t,e){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(n)=>{let o=n.path;if(t.some((s)=>s.test(o))&&!e.some((s)=>s.test(o)))return{path:o,external:!0};return null})}}}var Y=new Set;async function Wt(t,e){if(!t.entry||t.entry.length===0||!t.outDir)throw new x("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)G(e,t.outDir);k(t.silent);let{packageJson:r,path:n}=await ut(e);if(r&&n)f.cli(`Using package.json: ${h(n,2)}`,{muted:!0,identifier:t.name,once:`${n}:${t.name}`});let o=W(t.entry),i=r?.type,s=P(t,r),a=T(t);if(!t.dtsOnly){let c=[mt(s,a)],u=gt(t,e),g=t.format.flatMap((l)=>o.map((m)=>{return Nt(t,e,m,l,i,c,u)}));await Promise.all(g)}if(t.dts||t.dtsOnly){let c=await ft(e,t.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${h(c.path,2)}`,{muted:!0,identifier:t.name,once:`${c.path}:${t.name}`});let u=t.format.filter((l)=>{if(l==="iife"&&!y(i)&&t.format.includes("cjs"))return!1;return!0}),g=typeof t.dts==="object"&&t.dts.entry?W(t.dts.entry):at(o);try{await Promise.all(g.map(async(l)=>{let m=await it(e,l.path,t,c,r);await Promise.all(u.map(async(dt)=>{let pt=F(dt,i),B=`${e}/${t.outDir}/${l.name}${pt}`;await Bun.write(B,m);let xt=Bun.file(B).size||0;f.progress("DTS",h(B),L(xt),t.name)}))}))}catch(l){throw new d(p(l))}}}async function Nt(t,e,r,n,o,i,s){let a=v(n,o),c=await Bun.build({...s,entrypoints:[`${e}/${r.path}`],format:n,naming:{entry:ct(r.name,a)},splitting:j(t.splitting,n),bytecode:q(t.bytecode,n),plugins:i,throw:!1});if(!c.success)for(let l of c.logs){if(l.level==="error")throw new x(l.message);if(l.level==="warning")f.warn(l.message);else if(l.level==="info")f.info(l.message)}let u=`${e}/${t.outDir}/${r.name}${a}`,g=Bun.file(u).size||0;f.progress(n.toUpperCase(),h(u),L(g),t.name)}export{Et as defineWorkspace,ht as defineConfig,Wt as build};
15
+ See: https://bunup.arshadyaseen.com/#named-entries`,{muted:!0,verticalSpace:!0});r.push({name:c,path:a})}else r.push({name:s,path:a}),n.add(s),o[s]=a}if(Array.isArray(t))for(let s of t){let a=ot(s);i(a,s)}else if(typeof t==="object")for(let[s,a]of Object.entries(t))i(s,a);else{let s=ot(t);i(s,t)}return r}function at(t){return t.filter((e)=>$(e.path))}function ct(t,e){return`[dir]/${t}${e}`}import{loadConfig as ut}from"coffi";async function lt(t){let{config:e,filepath:r}=await ut({name:"package",cwd:t,extensions:[".json"],maxDepth:1});return{packageJson:e,path:r}}async function ft(t,e){let{config:r,filepath:n}=await ut({name:"tsconfig",cwd:t,extensions:[".json"],preferredPath:e,maxDepth:3});return{tsconfig:r,path:n}}var Ut={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function gt(t){return{...Ut,...t}}function mt(t){let{minify:e,minifyWhitespace:r,minifyIdentifiers:n,minifySyntax:o}=t,i=e===!0;return{whitespace:r??i,identifiers:n??i,syntax:o??i}}function pt(t,e){return e==="cjs"?t:void 0}function dt(t,e,r){return{...t,...r==="cjs"&&(e===!0||typeof e==="object"&&e.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function xt(t,e){return t===void 0?e==="esm":t}function ht(t,e){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(n)=>{let o=n.path;if(t.some((s)=>s.test(o))&&!e.some((s)=>s.test(o)))return{path:o,external:!0};return null})}}}var D={dirnameFilename:{appliesTo:(t,e)=>t==="esm"&&O(e),isNeededInFile:(t)=>/\b__dirname\b/.test(t)||/\b__filename\b/.test(t),generateCode:()=>`import { fileURLToPath } from 'url';
16
+ import { dirname } from 'path';
17
+
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = dirname(__filename);
20
+
21
+ `},importMetaUrl:{appliesTo:(t,e)=>t==="cjs"&&O(e),isNeededInFile:(t)=>/\bimport\.meta\.url\b/.test(t),generateCode:()=>`import { pathToFileURL } from 'url';
22
+
23
+ const importMetaUrl = pathToFileURL(__filename).href;
24
+
25
+ `}};var Wt=/\.(js|ts|jsx|tsx|mts|cts)$/;function bt({format:t,target:e,shims:r}){let o=Gt(r).map((i)=>D[i]).filter((i)=>i.appliesTo(t,e));if(o.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(i){i.onLoad({filter:Wt},async({path:s})=>{let a=await Bun.file(s).text(),u=o.filter((f)=>f.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:l}=Vt(a),m=u.map((f)=>f.generateCode()).join("");return{contents:c+m+l}})}}}function Gt(t){if(t===!0)return Object.keys(D);if(!t)return[];return Object.entries(t).filter(([e,r])=>r&&(e in D)).map(([e])=>e)}function Vt(t){if(!t.startsWith("#!"))return{shebangLine:"",codeContent:t};let e=t.indexOf(`
26
+ `);return e===-1?{shebangLine:"",codeContent:t}:{shebangLine:t.slice(0,e+1),codeContent:t.slice(e+1)}}var K=new Set;async function Ht(t,e){let r=gt(t);if(!r.entry||r.entry.length===0||!r.outDir)throw new x("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(r.clean)V(e,r.outDir);X(r.silent);let{packageJson:n,path:o}=await lt(e);if(n&&o)g.cli(`Using package.json: ${h(o,2)}`,{muted:!0,identifier:r.name,once:`${o}:${r.name}`});let i=k(r.entry),s=n?.type,a=S(r,n),u=C(r);if(!r.dtsOnly){let c=[ht(a,u)],l=r.format.flatMap((m)=>i.map((f)=>{return qt(r,e,f,m,s,c)}));await Promise.all(l)}if(r.dts||r.dtsOnly){let c=await ft(e,r.preferredTsconfigPath);if(c.path)g.cli(`Using tsconfig: ${h(c.path,2)}`,{muted:!0,identifier:r.name,once:`${c.path}:${r.name}`});let l=r.format.filter((f)=>{if(f==="iife"&&!T(s)&&r.format.includes("cjs"))return!1;return!0}),m=typeof r.dts==="object"&&r.dts.entry?k(r.dts.entry):at(i);try{await Promise.all(m.map(async(f)=>{let yt=await it(e,f.path,r,c,n);await Promise.all(l.map(async(Et)=>{let wt=W(Et,s),M=`${e}/${r.outDir}/${f.name}${wt}`;await Bun.write(M,yt);let Rt=Bun.file(M).size||0;g.progress("DTS",h(M),A(Rt),r.name)}))}))}catch(f){throw new p(d(f))}}}async function qt(t,e,r,n,o,i){let s=U(n,o),a=await Bun.build({entrypoints:[`${e}/${r.path}`],format:n,naming:{entry:ct(r.name,s)},splitting:xt(t.splitting,n),bytecode:pt(t.bytecode,n),define:dt(t.define,t.shims,n),minify:mt(t),outdir:`${e}/${t.outDir}`,target:t.target,sourcemap:t.sourcemap,loader:t.loader,drop:t.drop,banner:t.banner,footer:t.footer,publicPath:t.publicPath,plugins:[...i,bt({format:n,target:t.target,shims:t.shims})],throw:!1});if(!a.success)for(let l of a.logs){if(l.level==="error")throw new x(l.message);if(l.level==="warning")g.warn(l.message);else if(l.level==="info")g.info(l.message)}let u=`${e}/${t.outDir}/${r.name}${s}`,c=Bun.file(u).size||0;g.progress(n.toUpperCase(),h(u),A(c),t.name)}export{$t as defineWorkspace,Tt as defineConfig,Ht as build};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunup",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "An extremely fast, zero-config bundler for TypeScript & JavaScript, powered by Bun.",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -20,7 +20,7 @@
20
20
  "bunup": "^0.4.1",
21
21
  "husky": "^9.1.7",
22
22
  "typescript": "^5.8.3",
23
- "create-bunup": "0.4.2"
23
+ "create-bunup": "0.4.4"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "typescript": ">=4.5.0"