bunup 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.mjs CHANGED
@@ -1,27 +1,39 @@
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 Je}from"rolldown-plugin-dts";class $ extends Error{constructor(e){super(e);this.name="BunupError"}}class w extends ${constructor(e){super(e);this.name="BunupBuildError"}}class h extends ${constructor(e){super(e);this.name="BunupDTSBuildError"}}class p extends ${constructor(e){super(e);this.name="BunupCLIError"}}class L extends ${constructor(e){super(e);this.name="BunupWatchError"}}var x=(e)=>{if(e instanceof Error)return e.message;return String(e)},qe=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",link:"https://bunup.arshadyaseen.com/#could-not-resolve-bun-error"}],V=(e,t)=>{let n=x(e),r=t?`[${t}] `:"",i="ERROR";if(e instanceof w)i="BUILD ERROR";else if(e instanceof h)i="DTS ERROR";else if(e instanceof p)i="CLI ERROR";else if(e instanceof L)i="WATCH ERROR";else if(e instanceof $)i="BUNUP ERROR";console.error(`\x1B[31m${i}\x1B[0m ${r}${n}`);let o=qe.find((s)=>s.pattern.test(n)&&(s.errorType===i||!s.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")},ee=(e,t)=>{V(e,t),process.exit(1)};import te from"node:fs/promises";import Ve from"node:path";function G(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ne(e=8){let t="";while(t.length<e)t+=Math.random().toString(36).substring(2);return t.substring(0,e)}function re(e,t,n){return Array.isArray(e)?e.map((r)=>({...r,[t]:n})):{...e,[t]:n}}function se(e){return Array.isArray(e)?e:[e]}function ie(e,t){switch(e){case"esm":return".mjs";case"cjs":return S(t)?".cjs":".js";case"iife":return".global.js"}}function oe(e,t){switch(e){case"esm":return".d.mts";case"cjs":return S(t)?".d.cts":".d.ts";case"iife":return".d.ts"}}function X(e){return e==="node"||e==="bun"}function S(e){return e==="module"}function A(e){return e>=1000?`${(e/1000).toFixed(2)}s`:`${Math.round(e)}ms`}function ae(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function Y(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 le(e,t){let n=Ve.join(e,t);try{await te.rm(n,{recursive:!0,force:!0})}catch(r){throw new w(`Failed to clean output directory: ${r}`)}await te.mkdir(n,{recursive:!0})}function D(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 M(e,t){return ce(e.external||[]).concat(ae(t).map((n)=>new RegExp(`^${G(n)}($|\\/|\\\\)`)))}function v(e){return ce(e.noExternal||[])}var ue=!1;function I(e){ue=e??!1}class C{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(!C.instance)C.instance=new C;return C.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:i,muted:o}){let s=" ".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)),g=i?` \x1B[48;5;${e};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${s}${c}${m} \x1B[38;5;${this.colors.size}m${r}\x1B[0m ${f.join(" ")}${g}`}let l=i?` \x1B[48;5;${e};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${s}${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 i=String(e),o=this.colors.default,s,a,l={};if(typeof n==="string")s=n,a=r;else if(n)s=n.size,a=n.identifier,l=n;for(let[f,m]of Object.entries(this.colors.progress))if(i.includes(f)){o=m;break}let c=this.formatMessage({colorCode:o,label:i,message:t,size:s,identifier:a,muted:l.muted});this.output(c,l)}}var u=C.getInstance();import Ye from"node:path";import{ResolverFactory as Ke}from"oxc-resolver";import O from"node:path";var P="\x00dts:",fe=(e,t,n)=>{return{name:"bunup:virtual-dts",async resolveId(r,i){if(K(r))return r;if(!i||!K(i))return null;let o=await _(r,t,n,R(i));if(!o)return null;let s=E(o);if(e.has(s))return U(s);return null},load(r){if(r.startsWith(P)){let i=R(r),o=e.get(i);if(o)return T.add(i),o}return null}}};function me(e){return e.tsconfig?.compilerOptions}function E(e){return e.replace(/\.tsx?$/,".d.ts")}function z(e){let t=O.dirname(e.path||""),n=me(e);return n?.baseUrl?O.resolve(t,n.baseUrl):t}function pe(e){let t=new Map,n=me(e)?.paths;if(!n)return t;let r=z(e);for(let[i,o]of Object.entries(n))if(Array.isArray(o)&&o.length){let s=i.replace(/\*/g,"(.*)"),a=o[0].replace(/\*/g,"$1");t.set(`^${s}$`,O.join(r,a))}return t}function Ge(e,t,n){for(let[r,i]of t){let o=new RegExp(r),s=e.match(o);if(s)return i.replace("$1",s[1]||"")}return n?O.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 _(e,t,n,r){let i=e.startsWith(".")?O.resolve(O.dirname(r||""),e):Ge(e,t,n);if(!i)return Promise.resolve(null);return Xe(i)}function K(e){return e.startsWith(P)}function R(e){return e.replace(P,"")}function U(e){return`${P}${e}`}var de;function ge(e){return{name:"bunup:types-resolve",buildStart(){de||=new Ke({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?R(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 i=r?Ye.dirname(r):process.cwd(),{path:o}=await de.async(i,t);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 he(e,t,n,r,i,o){let s=E(e),a=U(s),l=M(n,r),c=v(n);try{let{output:f}=await ze({input:a,output:{dir:n.outDir,inlineDynamicImports:!0},write:!1,onwarn(m,g){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(m.code??""))return;g(m)},plugins:[fe(t,i,o),typeof n.dts==="object"&&"resolve"in n.dts&&ge(typeof n.dts.resolve==="boolean"?void 0:n.dts.resolve),Je({dtsInput:!0})],external:(m)=>l.some((g)=>g.test(m))&&!c.some((g)=>g.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}": ${x(f)}`)}}var Qe=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Ze=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,et=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,tt=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,nt=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,rt=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,st=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function it(e){let t=new Set,n=[Qe,Ze,et,tt,nt,rt,st];for(let r of n){let i=e.matchAll(r);for(let o of i)if(o[1])t.add(o[1])}return t}async function xe(e,t,n){let r=new Set([e]),i=[e];while(i.length){let o=i.pop();if(!o)continue;try{let s=await Bun.file(o).text(),a=it(s);for(let l of a){let c=await _(l,t,n,o);if(!c)continue;if(!r.has(c))r.add(c),i.push(c)}}catch(s){u.warn(`Error processing ${o}: ${x(s)}`)}}return r}import{isolatedDeclaration as ot}from"oxc-transform";async function be(e){let t=new Map;return await Promise.all([...e].map(async(n)=>{try{let r=E(n);if(!await Bun.file(n).exists())return;let o=await Bun.file(n).text(),{code:s}=ot(n,o);if(s)t.set(r,s)}catch(r){u.warn(`Failed to generate declaration for ${n}: ${x(r)}`)}})),t}import ye from"node:fs/promises";import J from"node:path";import{isolatedDeclaration as at}from"oxc-transform";async function we(e,t){let n=J.resolve(e),r=J.resolve(n,t);if(!await ye.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(!D(r))throw new h(`Entry file must be a TypeScript file: ${r}`);if(J.relative(n,r).startsWith(".."))throw new h(`Entry file must be within rootDir: ${r}`);return{absoluteRootDir:n,absoluteEntry:r}}async function $e(e){let t=!1;if(await Promise.all([...e].map(async(n)=>{try{let r=n.replace(/\.d\.ts$/,".ts"),i=await Bun.file(r).text(),{errors:o}=at(r,i);for(let s of o){if(!t)console.log(`
6
+ `);let a=s.labels[0],l=a?lt(i,a.start):"",f=`${b(r)}${l}: ${ct(s.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 lt(e,t){if(t===void 0)return"";let n=e.slice(0,t).split(`
9
+ `),r=n.length,i=n[n.length-1].length+1;return` (${r}:${i})`}function ct(e){return e.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function Ce(e,t,n,r,i){let{absoluteEntry:o}=await we(e,t),s=pe(r),a=z(r),l=await xe(o,s,a),c=await be(l);return he(o,c,n,i,s,a)}function k(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function B(e,{warnOnConflict:t=!0}={}){let n=[],r=new Set,i={};function o(s,a){if(r.has(s)){let l=ne(),c=`${s}_${l}`;if(t)u.warn(`Output name conflict: "${s}" is used by multiple files.
10
10
  Bunup uses filenames without extensions as output names by default.
11
11
 
12
- ${s[i]} -> ${i}.js
12
+ ${i[s]} -> ${s}.js
13
13
  ${a} -> ${c}.js (auto-renamed to avoid conflict)
14
14
 
15
15
  To fix this, use named entries in your configuration:
16
16
  {
17
17
  entry: {
18
- custom_name: "${s[i]}",
18
+ custom_name: "${i[s]}",
19
19
  another_name: "${a}"
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:s,path:a}),r.add(s),i[s]=a}if(Array.isArray(e))for(let s of e){let a=k(s);o(a,s)}else if(typeof e==="object")for(let[s,a]of Object.entries(e))o(s,a);else{let s=k(e);o(s,e)}return n}function Ee(e){return e.filter((t)=>D(t.path))}function Te(e,t){return`[dir]/${e}${t}`}import{loadConfig as Oe}from"coffi";async function Re(e,t){return Array.isArray(e)&&"root"in e[0]?e.map((n)=>({rootDir:n.root,options:re(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 Le={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function Se(e){let{minify:t,minifyWhitespace:n,minifyIdentifiers:r,minifySyntax:i}=e,o=t===!0;return{whitespace:n??o,identifiers:r??o,syntax:i??o}}function Ae(e,t){return t==="cjs"?e:void 0}function De(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 ve(e,t){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},(r)=>{let i=r.path;if(e.some((s)=>s.test(i))&&!t.some((s)=>s.test(i)))return{path:i,external:!0};return null})}}}function Ie(e){if(!e.startsWith("#!"))return{shebangLine:"",codeContent:e};let t=e.indexOf(`
24
+ `);if(t===-1)return{shebangLine:"",codeContent:e};return{shebangLine:e.substring(0,t+1),codeContent:e.substring(t+1)}}function _e(e){let{format:t,target:n}=e,r=e.shims===!0?{dirname:!0,filename:!0,importMetaUrl:!0}:e.shims||{};return{name:"inject-shims",setup(i){if(t==="esm"&&X(n))i.onLoad({filter:/\.(js|ts|jsx|tsx|mts|cts)$/},async(o)=>{let s=await Bun.file(o.path).text();if(!r.dirname&&!r.filename)return;let a=r.dirname&&/\b__dirname\b/.test(s),l=r.filename&&/\b__filename\b/.test(s);if(!a&&!l)return;let{shebangLine:c,codeContent:f}=Ie(s),m="";if(a||l){if(m+=`import { fileURLToPath } from 'url';
25
+ import { dirname } from 'path';
26
+
27
+ `,l)m+=`const __filename = fileURLToPath(import.meta.url);
28
+ `;if(a)if(l)m+=`const __dirname = dirname(__filename);
29
+ `;else m+=`const __dirname = dirname(fileURLToPath(import.meta.url));
30
+ `;m+=`
31
+ `}return{contents:c+m+f}});else if(t==="cjs"&&X(n))i.onLoad({filter:/\.(js|ts|jsx|tsx|mts|cts)$/},async(o)=>{let s=await Bun.file(o.path).text();if(!r.importMetaUrl)return;if(!/\bimport\.meta\.url\b/.test(s))return;let{shebangLine:l,codeContent:c}=Ie(s);return{contents:l+`import { pathToFileURL } from 'url';
32
+
33
+ const importMetaUrl = pathToFileURL(__filename).href;
34
+
35
+ `+c}})}}}var T=new Set;async function j(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)le(t,e.outDir);I(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 i=B(e.entry),o=n?.type,s=M(e,n),a=v(e);if(!e.dtsOnly){let l=[ve(s,a)],c=e.format.flatMap((f)=>i.map((m)=>{return ut(e,t,m,f,o,l)}));await Promise.all(c)}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((m)=>{if(m==="iife"&&!S(o)&&e.format.includes("cjs"))return!1;return!0}),f=typeof e.dts==="object"&&e.dts.entry?B(e.dts.entry):Ee(i);try{await Promise.all(f.map(async(m)=>{let g=await Ce(t,m.path,e,l,n);await Promise.all(c.map(async(H)=>{let We=oe(H,o),q=`${t}/${e.outDir}/${m.name}${We}`;await Bun.write(q,g);let He=Bun.file(q).size||0;u.progress("DTS",b(q),Y(He),e.name)}))}))}catch(m){throw new h(x(m))}}}async function ut(e,t,n,r,i,o){let s=ie(r,i),a=await Bun.build({entrypoints:[`${t}/${n.path}`],format:r,naming:{entry:Te(n.name,s)},splitting:Me(e.splitting,r),bytecode:Ae(e.bytecode,r),define:De(e.define,e.shims,r),minify:Se(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,_e({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}${s}`,c=Bun.file(l).size||0;u.progress(r.toUpperCase(),b(l),Y(c),e.name)}var F="0.4.3";var Ue="https://bun.sh/docs/installation",ke="https://bunup.arshadyaseen.com/#cli-options";function d(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 p(`Option --${e} requires a string value`)}}function Q(e){return(t,n)=>{if(typeof t==="string")n[e]=t.split(",");else throw new p(`Option --${e} requires a string value`)}}function mt(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 p(`Option --${e} requires a boolean or string value`)}}function pt(){console.log(`
24
36
  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};
37
+ `),console.log("For more information on available options, visit:"),console.log(`\x1B[36m\x1B[4m${ke}\x1B[0m
38
+ `),process.exit(0)}function dt(){console.log(F),process.exit(0)}var je={name:{flags:["n","name"],handler:y("name")},format:{flags:["f","format"],handler:Q("format")},outDir:{flags:["o","out-dir"],handler:y("outDir")},minify:{flags:["m","minify"],handler:d("minify")},watch:{flags:["w","watch"],handler:d("watch")},dts:{flags:["d","dts"],handler:d("dts")},banner:{flags:["bn","banner"],handler:y("banner")},footer:{flags:["ft","footer"],handler:y("footer")},external:{flags:["e","external"],handler:Q("external")},sourcemap:{flags:["sm","sourcemap"],handler:mt("sourcemap")},target:{flags:["t","target"],handler:y("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:d("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:d("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:d("minifySyntax")},clean:{flags:["c","clean"],handler:d("clean")},splitting:{flags:["s","splitting"],handler:d("splitting")},noExternal:{flags:["ne","no-external"],handler:Q("noExternal")},preferredTsconfigPath:{flags:["tsconfig","preferred-tsconfig-path"],handler:y("preferredTsconfigPath")},bytecode:{flags:["bc","bytecode"],handler:d("bytecode")},dtsOnly:{flags:["do","dts-only"],handler:d("dtsOnly")},silent:{flags:["silent"],handler:d("silent")},config:{flags:["config"],handler:y("config")},publicPath:{flags:["pp","public-path"],handler:y("publicPath")},shims:{flags:["shims"],handler:d("shims")},entry:{flags:["entry"],handler:(e,t,n)=>{if(typeof e!=="string")throw new p(`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 i=k(e);if(r[i])u.warn(`Duplicate entry name '${i}' derived from '${e}'. Overwriting previous entry.`);r[i]=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:()=>pt()},version:{flags:["v","version"],handler:()=>dt()}},N={};for(let e of Object.values(je))for(let t of e.flags)N[t]=e.handler;function Fe(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")){let i,o;if(r.includes("=")){let[s,a]=r.slice(2).split("=",2);i=s,o=a}else{i=r.slice(2);let s=e[n+1];if(o=s&&!s.startsWith("-")?s:!0,typeof o==="string")n++}if(i.includes(".")){let[s,a]=i.split(".",2),l=N[s];if(l)l(o,t,a);else throw new p(`Unknown option: --${i}`)}else{let s=N[i];if(s)s(o,t);else throw new p(`Unknown option: --${i}`)}}else if(r.startsWith("-")){let i=r.slice(1),o=e[n+1],s=o&&!o.startsWith("-")?o:!0;if(typeof s==="string")n++;let a=N[i];if(a)a(s,t);else throw new p(`Unknown option: -${i}`)}else je.entry.handler(r,t,void 0)}return t}(()=>{if(typeof Bun==="undefined")throw new p(`Bunup requires Bun to run.
39
+ To install Bun, visit ${Ue}`)})();import{loadConfig as ht}from"coffi";import W from"node:path";import gt from"chokidar";async function Ne(e,t){let n=new Set,r=B(e.entry);for(let a of r){let l=W.resolve(t,a.path),c=W.dirname(l);n.add(c)}let i=gt.watch(Array.from(n),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,W.join(t,e.outDir)]}),o=!1,s=async(a=!1)=>{if(o)return;o=!0;try{let l=performance.now();if(await j({...e,entry:r.map((c)=>c.path),clean:!1},t),e.onBuildSuccess?.(),!a)u.cli(`\uD83D\uDCE6 Rebuild finished in ${A(performance.now()-l)}`);await Z()}catch(l){V(l)}finally{o=!1}};i.on("change",(a)=>{let l=W.relative(t,a);u.cli(`File changed: ${l}`,{muted:!0}),s()}),i.on("error",(a)=>{throw new L(`Watcher error: ${x(a)}`)}),await s(!0)}async function xt(e=Bun.argv.slice(2)){let t=Fe(e);I(t.silent);let n=process.cwd(),{config:r,filepath:i}=await ht({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:t.config}),o=!r?[{rootDir:n,options:t}]:await Re(r,n);if(u.cli(`Using bunup v${F} and bun v${Bun.version}`,{muted:!0}),i)u.cli(`Using config file: ${b(i,2)}`,{muted:!0});let s=performance.now();u.cli("Build started"),await Promise.all(o.flatMap(({options:c,rootDir:f})=>{return se(c).map(async(g)=>{let H={...Le,...g,...t};return bt(H,f)})}));let a=performance.now()-s,l=A(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(T.size>0)await $e(T),T.clear()}async function bt(e,t){if(e.watch)await Ne(e,t);else await j(e,t),e.onBuildSuccess?.()}xt().catch((e)=>ee(e));export{Z as validateDtsFiles,xt 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 Shims = boolean | {
12
+ dirname?: boolean
13
+ filename?: boolean
14
+ importMetaUrl?: boolean
15
+ };
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
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 Shims = boolean | {
12
+ dirname?: boolean
13
+ filename?: boolean
14
+ importMetaUrl?: boolean
15
+ };
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
package/build/index.js CHANGED
@@ -1,15 +1,27 @@
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 vt=require("node:module");var _t=Object.create;var{getPrototypeOf:jt,defineProperty:R,getOwnPropertyNames:G,getOwnPropertyDescriptor:Ut}=Object,q=Object.prototype.hasOwnProperty;var h=(t,e,r)=>{r=t!=null?_t(jt(t)):{};let n=e||!t||!t.__esModule?R(r,"default",{value:t,enumerable:!0}):r;for(let i of G(t))if(!q.call(n,i))R(n,i,{get:()=>t[i],enumerable:!0});return n},V=new WeakMap,kt=(t)=>{var e=V.get(t),r;if(e)return e;if(e=R({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function")G(t).map((n)=>!q.call(e,n)&&R(e,n,{get:()=>t[n],enumerable:!(r=Ut(t,n))||r.enumerable}));return V.set(t,e),e};var Ft=(t,e)=>{for(var r in e)R(t,r,{get:e[r],enumerable:!0,configurable:!0,set:(n)=>e[r]=()=>n})};var Jt={};Ft(Jt,{defineWorkspace:()=>H,defineConfig:()=>X,build:()=>Lt});module.exports=kt(Jt);function X(t){return t}function H(t){return t}var ft=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 g extends A{constructor(t){super(t);this.name="BunupDTSBuildError"}}var d=(t)=>{if(t instanceof Error)return t.message;return String(t)};var I=h(require("node:fs/promises")),K=h(require("node:path"));function _(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(t=8){let e="";while(e.length<t)e+=Math.random().toString(36).substring(2);return e.substring(0,t)}function Q(t,e){switch(t){case"esm":return".mjs";case"cjs":return T(e)?".cjs":".js";case"iife":return".global.js"}}function Z(t,e){switch(t){case"esm":return".d.mts";case"cjs":return T(e)?".d.cts":".d.ts";case"iife":return".d.ts"}}function j(t){return t==="node"||t==="bun"}function T(t){return t==="module"}function z(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function U(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 J(t,e){let r=K.default.join(t,e);try{await I.default.rm(r,{recursive:!0,force:!0})}catch(n){throw new b(`Failed to clean output directory: ${n}`)}await I.default.mkdir(r,{recursive:!0})}function C(t){return[".ts",".mts",".cts",".tsx"].some((e)=>t.endsWith(e))}function tt(t){return t.map((e)=>typeof e==="string"?new RegExp(`^${_(e)}($|\\/|\\\\)`):e)}function B(t,e){return tt(t.external||[]).concat(z(e).map((r)=>new RegExp(`^${_(r)}($|\\/|\\\\)`)))}function D(t){return tt(t.noExternal||[])}var et=!1;function rt(t){et=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: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[u,...f]=a.split(" "),l=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-u.length)),p=i?` \x1B[48;5;${t};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${u}${l} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${f.join(" ")}${p}`}let c=i?` \x1B[48;5;${t};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${t}m${e}\x1B[0m ${s}${a}${c}`}output(t,e={},r=console.log){if(et)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,c={};if(typeof r==="string")s=r,a=n;else if(r)s=r.size,a=r.identifier,c=r;for(let[f,l]of Object.entries(this.colors.progress))if(i.includes(f)){o=l;break}let u=this.formatMessage({colorCode:o,label:i,message:e,size:s,identifier:a,muted:c.muted});this.output(u,c)}}var m=w.getInstance();var ct=h(require("node:path")),ut=require("oxc-resolver");var x=h(require("node:path"));var P="\x00dts:",nt=(t,e,r)=>{return{name:"bunup:virtual-dts",async resolveId(n,i){if(k(n))return n;if(!i||!k(i))return null;let o=await M(n,e,r,$(i));if(!o)return null;let s=E(o);if(t.has(s))return S(s);return null},load(n){if(n.startsWith(P)){let i=$(n),o=t.get(i);if(o)return st.add(i),o}return null}}};function it(t){return t.tsconfig?.compilerOptions}function E(t){return t.replace(/\.tsx?$/,".d.ts")}function F(t){let e=x.default.dirname(t.path||""),r=it(t);return r?.baseUrl?x.default.resolve(e,r.baseUrl):e}function ot(t){let e=new Map,r=it(t)?.paths;if(!r)return e;let n=F(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 Wt(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 Nt(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 M(t,e,r,n){let i=t.startsWith(".")?x.default.resolve(x.default.dirname(n||""),t):Wt(t,e,r);if(!i)return Promise.resolve(null);return Nt(i)}function k(t){return t.startsWith(P)}function $(t){return t.replace(P,"")}function S(t){return`${P}${t}`}var at;function lt(t){return{name:"bunup:types-resolve",buildStart(){at||=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?$(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 i=n?ct.default.dirname(n):process.cwd(),{path:o}=await at.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 gt(t,e,r,n,i,o){let s=E(t),a=S(s),c=B(r,n),u=D(r);try{let{output:f}=await ft.build({input:a,output:{dir:r.outDir,inlineDynamicImports:!0},write:!1,onwarn(l,p){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;p(l)},plugins:[nt(e,i,o),typeof r.dts==="object"&&"resolve"in r.dts&&lt(typeof r.dts.resolve==="boolean"?void 0:r.dts.resolve),mt.dts({dtsInput:!0})],external:(l)=>c.some((p)=>p.test(l))&&!u.some((p)=>p.test(l))});if(!f[0]?.code)return m.warn(`Generated empty declaration file for entry "${t}"`,{muted:!0}),"";return f[0].code}catch(f){throw new g(`DTS bundling failed for entry "${t}": ${d(f)}`)}}var Vt=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Gt=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,qt=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Xt=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ht=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Kt=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Yt=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Qt(t){let e=new Set,r=[Vt,Gt,qt,Xt,Ht,Kt,Yt];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 pt(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=Qt(s);for(let c of a){let u=await M(c,e,r,o);if(!u)continue;if(!n.has(u))n.add(u),i.push(u)}}catch(s){m.warn(`Error processing ${o}: ${d(s)}`)}}return n}var dt=require("oxc-transform");async function xt(t){let e=new Map;return await Promise.all([...t].map(async(r)=>{try{let n=E(r);if(!await Bun.file(r).exists())return;let o=await Bun.file(r).text(),{code:s}=dt.isolatedDeclaration(r,o);if(s)e.set(n,s)}catch(n){m.warn(`Failed to generate declaration for ${r}: ${d(n)}`)}})),e}var v=h(require("node:fs/promises")),L=h(require("node:path")),Zt=require("oxc-transform");async function ht(t,e){let r=L.default.resolve(t),n=L.default.resolve(r,e);if(!await v.default.exists(r))throw new g(`Root directory does not exist: ${r}`);if(!await Bun.file(n).exists())throw new g(`Entry file does not exist: ${n}`);if(!C(n))throw new g(`Entry file must be a TypeScript file: ${n}`);if(L.default.relative(r,n).startsWith(".."))throw new g(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:r,absoluteEntry:n}}async function bt(t,e,r,n,i){let{absoluteEntry:o}=await ht(t,e),s=ot(n),a=F(n),c=await pt(o,s,a),u=await xt(c);return gt(o,u,r,i,s,a)}function yt(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 c=Y(),u=`${s}_${c}`;if(e)m.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
4
+ ${i[s]} -> ${s}.js
5
5
  ${a} -> ${u}.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:u,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=yt(s);o(a,s)}else if(typeof t==="object")for(let[s,a]of Object.entries(t))o(s,a);else{let s=yt(t);o(s,t)}return r}function wt(t){return t.filter((e)=>C(e.path))}function Et(t,e){return`[dir]/${t}${e}`}var N=require("coffi");async function Rt(t){let{config:e,filepath:r}=await N.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 N.loadConfig({name:"tsconfig",cwd:t,extensions:[".json"],preferredPath:e,maxDepth:3});return{tsconfig:r,path:n}}function Pt(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 Tt(t,e){return e==="cjs"?t:void 0}function Ct(t,e,r){return{...t,...r==="cjs"&&(e===!0||typeof e==="object"&&e.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Bt(t,e){return t===void 0?e==="esm":t}function Dt(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})}}}function Mt(t){if(!t.startsWith("#!"))return{shebangLine:"",codeContent:t};let e=t.indexOf(`
16
+ `);if(e===-1)return{shebangLine:"",codeContent:t};return{shebangLine:t.substring(0,e+1),codeContent:t.substring(e+1)}}function St(t){let{format:e,target:r}=t,n=t.shims===!0?{dirname:!0,filename:!0,importMetaUrl:!0}:t.shims||{};return{name:"inject-shims",setup(i){if(e==="esm"&&j(r))i.onLoad({filter:/\.(js|ts|jsx|tsx|mts|cts)$/},async(o)=>{let s=await Bun.file(o.path).text();if(!n.dirname&&!n.filename)return;let a=n.dirname&&/\b__dirname\b/.test(s),c=n.filename&&/\b__filename\b/.test(s);if(!a&&!c)return;let{shebangLine:u,codeContent:f}=Mt(s),l="";if(a||c){if(l+=`import { fileURLToPath } from 'url';
17
+ import { dirname } from 'path';
18
+
19
+ `,c)l+=`const __filename = fileURLToPath(import.meta.url);
20
+ `;if(a)if(c)l+=`const __dirname = dirname(__filename);
21
+ `;else l+=`const __dirname = dirname(fileURLToPath(import.meta.url));
22
+ `;l+=`
23
+ `}return{contents:u+l+f}});else if(e==="cjs"&&j(r))i.onLoad({filter:/\.(js|ts|jsx|tsx|mts|cts)$/},async(o)=>{let s=await Bun.file(o.path).text();if(!n.importMetaUrl)return;if(!/\bimport\.meta\.url\b/.test(s))return;let{shebangLine:c,codeContent:u}=Mt(s);return{contents:c+`import { pathToFileURL } from 'url';
24
+
25
+ const importMetaUrl = pathToFileURL(__filename).href;
26
+
27
+ `+u}})}}}var st=new Set;async function Lt(t,e){if(!t.entry||t.entry.length===0||!t.outDir)throw new b("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)J(e,t.outDir);rt(t.silent);let{packageJson:r,path:n}=await Rt(e);if(r&&n)m.cli(`Using package.json: ${y(n,2)}`,{muted:!0,identifier:t.name,once:`${n}:${t.name}`});let i=W(t.entry),o=r?.type,s=B(t,r),a=D(t);if(!t.dtsOnly){let c=[Dt(s,a)],u=t.format.flatMap((f)=>i.map((l)=>{return zt(t,e,l,f,o,c)}));await Promise.all(u)}if(t.dts||t.dtsOnly){let c=await $t(e,t.preferredTsconfigPath);if(c.path)m.cli(`Using tsconfig: ${y(c.path,2)}`,{muted:!0,identifier:t.name,once:`${c.path}:${t.name}`});let u=t.format.filter((l)=>{if(l==="iife"&&!T(o)&&t.format.includes("cjs"))return!1;return!0}),f=typeof t.dts==="object"&&t.dts.entry?W(t.dts.entry):wt(i);try{await Promise.all(f.map(async(l)=>{let p=await bt(e,l.path,t,c,r);await Promise.all(u.map(async(Ot)=>{let At=Z(Ot,o),O=`${e}/${t.outDir}/${l.name}${At}`;await Bun.write(O,p);let It=Bun.file(O).size||0;m.progress("DTS",y(O),U(It),t.name)}))}))}catch(l){throw new g(d(l))}}}async function zt(t,e,r,n,i,o){let s=Q(n,i),a=await Bun.build({entrypoints:[`${e}/${r.path}`],format:n,naming:{entry:Et(r.name,s)},splitting:Bt(t.splitting,n),bytecode:Tt(t.bytecode,n),define:Ct(t.define,t.shims,n),minify:Pt(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,St({format:n,target:t.target,shims:t.shims})],throw:!1});if(!a.success)for(let f of a.logs){if(f.level==="error")throw new b(f.message);if(f.level==="warning")m.warn(f.message);else if(f.level==="info")m.info(f.message)}let c=`${e}/${t.outDir}/${r.name}${s}`,u=Bun.file(c).size||0;m.progress(n.toUpperCase(),y(c),U(u),t.name)}
package/build/index.mjs CHANGED
@@ -1,4 +1,4 @@
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 Et(t){return t}function Rt(t){return t}import{build as Dt}from"rolldown";import{dts as Mt}from"rolldown-plugin-dts";class S extends Error{constructor(t){super(t);this.name="BunupError"}}class x extends S{constructor(t){super(t);this.name="BunupBuildError"}}class g extends S{constructor(t){super(t);this.name="BunupDTSBuildError"}}var d=(t)=>{if(t instanceof Error)return t.message;return String(t)};import k from"node:fs/promises";import $t from"node:path";function L(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function F(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 $(e)?".cjs":".js";case"iife":return".global.js"}}function W(t,e){switch(t){case"esm":return".d.mts";case"cjs":return $(e)?".d.cts":".d.ts";case"iife":return".d.ts"}}function O(t){return t==="node"||t==="bun"}function $(t){return t==="module"}function N(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=$t.join(t,e);try{await k.rm(r,{recursive:!0,force:!0})}catch(n){throw new x(`Failed to clean output directory: ${n}`)}await k.mkdir(r,{recursive:!0})}function P(t){return[".ts",".mts",".cts",".tsx"].some((e)=>t.endsWith(e))}function G(t){return t.map((e)=>typeof e==="string"?new RegExp(`^${L(e)}($|\\/|\\\\)`):e)}function T(t,e){return G(t.external||[]).concat(N(e).map((r)=>new RegExp(`^${L(r)}($|\\/|\\\\)`)))}function C(t){return G(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[u,...f]=a.split(" "),l=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-u.length)),p=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 ${f.join(" ")}${p}`}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(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,c={};if(typeof r==="string")s=r,a=n;else if(r)s=r.size,a=r.identifier,c=r;for(let[f,l]of Object.entries(this.colors.progress))if(o.includes(f)){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 m=b.getInstance();import Ct from"node:path";import{ResolverFactory as Bt}from"oxc-resolver";import w from"node:path";var R="\x00dts:",H=(t,e,r)=>{return{name:"bunup:virtual-dts",async resolveId(n,o){if(I(n))return n;if(!o||!I(o))return null;let i=await B(n,e,r,E(o));if(!i)return null;let s=y(i);if(t.has(s))return D(s);return null},load(n){if(n.startsWith(R)){let o=E(n),i=t.get(o);if(i)return K.add(o),i}return null}}};function Y(t){return t.tsconfig?.compilerOptions}function y(t){return t.replace(/\.tsx?$/,".d.ts")}function _(t){let e=w.dirname(t.path||""),r=Y(t);return r?.baseUrl?w.resolve(e,r.baseUrl):e}function Q(t){let e=new Map,r=Y(t)?.paths;if(!r)return e;let n=_(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 Pt(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 Tt(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 o=t.startsWith(".")?w.resolve(w.dirname(n||""),t):Pt(t,e,r);if(!o)return Promise.resolve(null);return Tt(o)}function I(t){return t.startsWith(R)}function E(t){return t.replace(R,"")}function D(t){return`${R}${t}`}var Z;function z(t){return{name:"bunup:types-resolve",buildStart(){Z||=new Bt({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?E(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?Ct.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 J(t,e,r,n,o,i){let s=y(t),a=D(s),c=T(r,n),u=C(r);try{let{output:f}=await Dt({input:a,output:{dir:r.outDir,inlineDynamicImports:!0},write:!1,onwarn(l,p){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;p(l)},plugins:[H(e,o,i),typeof r.dts==="object"&&"resolve"in r.dts&&z(typeof r.dts.resolve==="boolean"?void 0:r.dts.resolve),Mt({dtsInput:!0})],external:(l)=>c.some((p)=>p.test(l))&&!u.some((p)=>p.test(l))});if(!f[0]?.code)return m.warn(`Generated empty declaration file for entry "${t}"`,{muted:!0}),"";return f[0].code}catch(f){throw new g(`DTS bundling failed for entry "${t}": ${d(f)}`)}}var St=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Lt=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Ot=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,At=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,It=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,_t=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,jt=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Ut(t){let e=new Set,r=[St,Lt,Ot,At,It,_t,jt];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 tt(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=Ut(s);for(let c of a){let u=await B(c,e,r,i);if(!u)continue;if(!n.has(u))n.add(u),o.push(u)}}catch(s){m.warn(`Error processing ${i}: ${d(s)}`)}}return n}import{isolatedDeclaration as kt}from"oxc-transform";async function et(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}=kt(r,i);if(s)e.set(n,s)}catch(n){m.warn(`Failed to generate declaration for ${r}: ${d(n)}`)}})),e}import rt from"node:fs/promises";import j from"node:path";import{isolatedDeclaration as Be}from"oxc-transform";async function nt(t,e){let r=j.resolve(t),n=j.resolve(r,e);if(!await rt.exists(r))throw new g(`Root directory does not exist: ${r}`);if(!await Bun.file(n).exists())throw new g(`Entry file does not exist: ${n}`);if(!P(n))throw new g(`Entry file must be a TypeScript file: ${n}`);if(j.relative(r,n).startsWith(".."))throw new g(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:r,absoluteEntry:n}}async function st(t,e,r,n,o){let{absoluteEntry:i}=await nt(t,e),s=Q(n),a=_(n),c=await tt(i,s,a),u=await et(c);return J(i,u,r,o,s,a)}function it(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function U(t,{warnOnConflict:e=!0}={}){let r=[],n=new Set,o={};function i(s,a){if(n.has(s)){let c=F(),u=`${s}_${c}`;if(e)m.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
@@ -12,4 +12,16 @@ 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: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=it(s);i(a,s)}else if(typeof t==="object")for(let[s,a]of Object.entries(t))i(s,a);else{let s=it(t);i(s,t)}return r}function ot(t){return t.filter((e)=>P(e.path))}function at(t,e){return`[dir]/${t}${e}`}import{loadConfig as ct}from"coffi";async function ut(t){let{config:e,filepath:r}=await ct({name:"package",cwd:t,extensions:[".json"],maxDepth:1});return{packageJson:e,path:r}}async function lt(t,e){let{config:r,filepath:n}=await ct({name:"tsconfig",cwd:t,extensions:[".json"],preferredPath:e,maxDepth:3});return{tsconfig:r,path:n}}function ft(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 e==="cjs"?t:void 0}function gt(t,e,r){return{...t,...r==="cjs"&&(e===!0||typeof e==="object"&&e.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function pt(t,e){return t===void 0?e==="esm":t}function dt(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})}}}function xt(t){if(!t.startsWith("#!"))return{shebangLine:"",codeContent:t};let e=t.indexOf(`
16
+ `);if(e===-1)return{shebangLine:"",codeContent:t};return{shebangLine:t.substring(0,e+1),codeContent:t.substring(e+1)}}function ht(t){let{format:e,target:r}=t,n=t.shims===!0?{dirname:!0,filename:!0,importMetaUrl:!0}:t.shims||{};return{name:"inject-shims",setup(o){if(e==="esm"&&O(r))o.onLoad({filter:/\.(js|ts|jsx|tsx|mts|cts)$/},async(i)=>{let s=await Bun.file(i.path).text();if(!n.dirname&&!n.filename)return;let a=n.dirname&&/\b__dirname\b/.test(s),c=n.filename&&/\b__filename\b/.test(s);if(!a&&!c)return;let{shebangLine:u,codeContent:f}=xt(s),l="";if(a||c){if(l+=`import { fileURLToPath } from 'url';
17
+ import { dirname } from 'path';
18
+
19
+ `,c)l+=`const __filename = fileURLToPath(import.meta.url);
20
+ `;if(a)if(c)l+=`const __dirname = dirname(__filename);
21
+ `;else l+=`const __dirname = dirname(fileURLToPath(import.meta.url));
22
+ `;l+=`
23
+ `}return{contents:u+l+f}});else if(e==="cjs"&&O(r))o.onLoad({filter:/\.(js|ts|jsx|tsx|mts|cts)$/},async(i)=>{let s=await Bun.file(i.path).text();if(!n.importMetaUrl)return;if(!/\bimport\.meta\.url\b/.test(s))return;let{shebangLine:c,codeContent:u}=xt(s);return{contents:c+`import { pathToFileURL } from 'url';
24
+
25
+ const importMetaUrl = pathToFileURL(__filename).href;
26
+
27
+ `+u}})}}}var K=new Set;async function Ft(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)V(e,t.outDir);X(t.silent);let{packageJson:r,path:n}=await ut(e);if(r&&n)m.cli(`Using package.json: ${h(n,2)}`,{muted:!0,identifier:t.name,once:`${n}:${t.name}`});let o=U(t.entry),i=r?.type,s=T(t,r),a=C(t);if(!t.dtsOnly){let c=[dt(s,a)],u=t.format.flatMap((f)=>o.map((l)=>{return vt(t,e,l,f,i,c)}));await Promise.all(u)}if(t.dts||t.dtsOnly){let c=await lt(e,t.preferredTsconfigPath);if(c.path)m.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"&&!$(i)&&t.format.includes("cjs"))return!1;return!0}),f=typeof t.dts==="object"&&t.dts.entry?U(t.dts.entry):ot(o);try{await Promise.all(f.map(async(l)=>{let p=await st(e,l.path,t,c,r);await Promise.all(u.map(async(bt)=>{let yt=W(bt,i),M=`${e}/${t.outDir}/${l.name}${yt}`;await Bun.write(M,p);let wt=Bun.file(M).size||0;m.progress("DTS",h(M),A(wt),t.name)}))}))}catch(l){throw new g(d(l))}}}async function vt(t,e,r,n,o,i){let s=v(n,o),a=await Bun.build({entrypoints:[`${e}/${r.path}`],format:n,naming:{entry:at(r.name,s)},splitting:pt(t.splitting,n),bytecode:mt(t.bytecode,n),define:gt(t.define,t.shims,n),minify:ft(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,ht({format:n,target:t.target,shims:t.shims})],throw:!1});if(!a.success)for(let f of a.logs){if(f.level==="error")throw new x(f.message);if(f.level==="warning")m.warn(f.message);else if(f.level==="info")m.info(f.message)}let c=`${e}/${t.outDir}/${r.name}${s}`,u=Bun.file(c).size||0;m.progress(n.toUpperCase(),h(c),A(u),t.name)}export{Rt as defineWorkspace,Et as defineConfig,Ft 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.3",
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.3"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "typescript": ">=4.5.0"