bunup 0.1.18 → 0.1.19

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,5 +1,6 @@
1
1
  #!/usr/bin/env bun
2
- import z from"node:fs";import qt from"node:path";import{isMainThread as It,parentPort as j,Worker as Nt,workerData as Lt}from"node:worker_threads";import mt from"node:fs";import _ from"node:path";var P=class extends Error{constructor(r){super(r),this.name="BunupError"}},y=class extends P{constructor(r){super(r),this.name="BunupBuildError"}},g=class extends P{constructor(r){super(r),this.name="BunupDTSBuildError"}},d=class extends P{constructor(r){super(r),this.name="BunupCLIError"}},B=class extends P{constructor(r){super(r),this.name="BunupWatchError"}},f=t=>t instanceof Error?t.message:String(t),$t=(t,r)=>{let e=f(t),n=r?`[${r}] `:"",o="ERROR";t instanceof y?o="BUILD ERROR":t instanceof g?o="DTS ERROR":t instanceof d?o="CLI ERROR":t instanceof B?o="WATCH ERROR":t instanceof P&&(o="BUNUP ERROR"),console.error(`\x1B[31m[${o}]\x1B[0m ${n}${e}`),process.env.NODE_ENV!=="production"&&t instanceof Error&&t.stack&&console.error("\x1B[2m"+t.stack.split(`
2
+ // @bun
3
+ import q from"fs";import Ht from"path";import{isMainThread as Nt,parentPort as A,Worker as It,workerData as Wt}from"node:worker_threads";import pt from"node:fs";import L from"node:path";class $ extends Error{constructor(t){super(t);this.name="BunupError"}}class x extends ${constructor(t){super(t);this.name="BunupBuildError"}}class g extends ${constructor(t){super(t);this.name="BunupDTSBuildError"}}class h extends ${constructor(t){super(t);this.name="BunupCLIError"}}class C extends ${constructor(t){super(t);this.name="BunupWatchError"}}var u=(t)=>{if(t instanceof Error)return t.message;return String(t)},Ct=(t,r)=>{let n=u(t),e=r?`[${r}] `:"",s="ERROR";if(t instanceof x)s="BUILD ERROR";else if(t instanceof g)s="DTS ERROR";else if(t instanceof h)s="CLI ERROR";else if(t instanceof C)s="WATCH ERROR";else if(t instanceof $)s="BUNUP ERROR";if(console.error(`\x1B[31m[${s}]\x1B[0m ${e}${n}`),t instanceof Error&&t.stack)console.error("\x1B[2m"+t.stack.split(`
3
4
  `).slice(1).join(`
4
- `)+"\x1B[0m")},V=(t,r)=>{$t(t,r),process.exit(1)};import{loadTsConfig as Dt}from"load-tsconfig";var p={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,e){let n=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${n}${e}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let e=String(t),n=this.colors.default;for(let[o,s]of Object.entries(this.colors.progress))if(e.includes(o)){n=s;break}console.log(this.formatMessage(n,e,r))}};function X(t,r){return`${r?`${r.replace(/-/g,"_")}_`:""}${t}`.toUpperCase()}function Y(t){try{return Dt(".",t)}catch(r){return p.warn(`Failed to load tsconfig: ${f(r)}`),{path:t,data:{},files:[]}}}import it from"node:path";import{rollup as vt}from"rollup";import Rt from"rollup-plugin-dts";import U from"typescript";function L(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function K(t=8){return Math.random().toString(36).substring(2,2+t)}function Q(t,r){switch(t){case"esm":return".mjs";case"cjs":return v(r)?".cjs":".js";case"iife":return".global.js"}}function Z(t,r){switch(t){case"esm":return".d.mts";case"cjs":return v(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function v(t){return t==="module"}function R(t){return t>=1e3?`${(t/1e3).toFixed(2)}s`:`${Math.round(t)}ms`}function tt(t){return t?Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})])):[]}function rt(t,r){return t===void 0?r==="esm":t}function et(t){return t.map(r=>typeof r=="string"?new RegExp(`^${L(r)}($|\\/|\\\\)`):r)}function k(t,r){return et(t.external||[]).concat(tt(r).map(e=>new RegExp(`^${L(e)}($|\\/|\\\\)`)))}function S(t){return et(t.noExternal||[])}import C from"node:fs";import ot from"node:path";var b={entry:[],format:["cjs"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function nt(t,r){return{outdir:`${r}/${t.outDir}`,minify:Tt(t),target:t.target,splitting:t.splitting}}function Tt(t){let{minify:r,minifyWhitespace:e,minifyIdentifiers:n,minifySyntax:o}=t,s=r===!0;return{whitespace:e??s,identifiers:n??s,syntax:o??s}}async function st(t){let r=[];for(let e of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let n=ot.join(t,`bunup.config${e}`);try{if(!C.existsSync(n))continue;let o;if(e===".json"||e===".jsonc"){let s=C.readFileSync(n,"utf8");o=JSON.parse(s)}else{let s=await import(`file://${n}`);o=s.default||s,o||(p.warn(`No default export found in ${n}`),o={})}if(Array.isArray(o))for(let s of o)r.push({options:{...b,...s},rootDir:t});else r.push({options:{...b,...o},rootDir:t});break}catch(o){throw new y(`Failed to load config from ${n}: ${f(o)}`)}if(r.length>0)break}return r}function M(t){let r=ot.join(t,"package.json");try{if(!C.existsSync(r))return null;let e=C.readFileSync(r,"utf8");return JSON.parse(e)}catch(e){return p.warn(`Failed to load package.json at ${r}: ${f(e)}`),null}}async function at(t,r,e,n,o,s){let i="\0virtual:",a=t.replace(/\.tsx?$/,".d.ts"),c=`${i}${a}`,l=s.data?.compilerOptions,u={name:"bunup:virtual-dts",resolveId(h,x){if(h.startsWith(i))return h;if(!x?.startsWith(i)||!h.startsWith("."))return null;let O=x.slice(i.length),N=it.resolve(it.dirname(O),h),G=r.has(N)?N:`${N}.d.ts`;return r.has(G)?`${i}${G}`:null},load(h){return h.startsWith(i)&&r.get(h.slice(i.length))||null}},m=M(o),E=k(n,m),bt=S(n),T;try{T=await vt({input:c,onwarn(x,O){["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(x.code??"")||O(x)},plugins:[u,Rt({tsconfig:s.path,compilerOptions:{...l?U.parseJsonConfigFileContent({compilerOptions:l},U.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:U.ScriptTarget.ESNext}})],external:x=>E.some(O=>O.test(x))&&!bt.some(O=>O.test(x))});let{output:h}=await T.generate({format:e});if(!h[0]?.code)throw new g("Generated bundle is empty");return h[0].code}catch(h){throw new g(`DTS bundling failed: ${f(h)}`)}finally{T&&await T.close()}}import ct from"node:fs";import lt from"node:path";import F from"node:path";function $(t){let r=F.dirname(t.path||"");return t.data?.compilerOptions?.baseUrl?F.resolve(r,t.data.compilerOptions.baseUrl):r}function W(t){let r=new Map,e=t.data?.compilerOptions?.paths;if(!e)return r;let n=$(t);for(let[o,s]of Object.entries(e))if(Array.isArray(s)&&s.length){let i=o.replace(/\*/g,"(.*)"),a=s[0].replace(/\*/g,"$1");r.set(`^${i}$`,F.join(n,a))}return r}function A(t,r,e){for(let[n,o]of r){let s=new RegExp(n),i=t.match(s);if(i)return o.replace("$1",i[1]||"")}return e?F.join(e,t):null}var kt=/(?:import|export)(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*|[\s\n]+)(["'`])([^'"]+)\1/g,St=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;async function pt(t,r){let e=new Set([t]),n=[t],o=W(r),s=$(r);for(;n.length;){let i=n.pop();if(i)try{let a=await ct.promises.readFile(i,"utf8"),c=Ct(a);for(let l of c){let u=l.startsWith(".")?lt.resolve(lt.dirname(i),l):A(l,o,s);if(!u)continue;let m=Mt(u);m&&!e.has(m)&&(e.add(m),n.push(m))}}catch(a){p.warn(`Error processing ${i}: ${f(a)}`)}}return e}function Ct(t){let r=new Set;for(let e of[kt,St]){let n;for(;(n=e.exec(t))!==null;)r.add(n[2])}return Array.from(r)}function Mt(t){let r=["",".ts",".tsx","/index.ts","/index.tsx"];for(let e of r){let n=`${t}${e}`;if(ct.existsSync(n)&&(n.endsWith(".ts")||n.endsWith(".tsx")))return n}return null}import Ft from"node:fs";import ut from"node:path";import Wt from"oxc-transform";async function ft(t,r){let e=new Map,n=$(r),o=W(r);return await Promise.all([...t].map(async s=>{try{let i=s.replace(/\.tsx?$/,".d.ts"),a=await Ft.promises.readFile(s,"utf8"),{code:c}=Wt.isolatedDeclaration(s,a);if(c){let l=At(c,o,n,ut.dirname(s));e.set(i,l)}}catch(i){p.warn(`Failed to generate declaration for ${s}: ${f(i)}`)}})),e}function At(t,r,e,n){return t.replace(/(import|export)(.+?from\s+['"])([^'"]+)(['"])/g,(o,s,i,a,c)=>{if(a.startsWith(".")||a.startsWith("/"))return o;let l=A(a,r,e);if(!l)return o;let u=ut.relative(n,l).replace(/\\/g,"/"),m=u.startsWith(".")?u:`./${u}`;return`${s}${i}${m}${c}`})}async function gt(t,r,e,n){let{absoluteRootDir:o,absoluteEntry:s}=jt(t,r),i=Y(n.preferredTsconfigPath),a=await pt(s,i),c=await ft(a,i);return at(s,c,e,n,o,i)}function jt(t,r){let e=_.resolve(t),n=_.resolve(e,r);if(!mt.existsSync(e))throw new g(`Root directory does not exist: ${e}`);if(!mt.existsSync(n))throw new g(`Entry file does not exist: ${n}`);if(!n.endsWith(".ts"))throw new g(`Entry file must be a TypeScript file (.ts): ${n}`);if(_.relative(e,n).startsWith(".."))throw new g(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:e,absoluteEntry:n}}async function dt(t,r,e,n,o){return new Promise((s,i)=>{let a={rootDir:t,entries:r,formats:e,options:n,packageType:o},c=new Nt(new URL("./dtsWorker.js",import.meta.url),{workerData:a});c.on("message",l=>{if(l.success){if(l.timeMs){let u=R(l.timeMs);p.progress("DTS",`Bundled types in ${u}`)}s()}else i(new g(l.error||"Unknown DTS worker error"))}),c.on("error",i),c.on("exit",l=>{l!==0&&i(new g(`DTS worker stopped with exit code ${l}`))})})}if(!It&&j){let{rootDir:t,entries:r,formats:e,options:n,packageType:o}=Lt,s=performance.now();p.progress("DTS","Bundling types");try{let i=e.flatMap(a=>r.map(async c=>{let l=await gt(t,c.path,a,n),u=Z(a,o),m=`${n.outDir}/${c.name}${u}`,E=`${t}/${m}`;await Bun.write(E,l),p.progress("DTS",m)}));Promise.all(i).then(()=>{let a=performance.now()-s;j?.postMessage({success:!0,timeMs:a})}).catch(a=>{j?.postMessage({success:!1,error:f(a)})})}catch(i){j?.postMessage({success:!1,error:f(i)})}}function Ut(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function D(t){let r=[],e=new Set;function n(o,s){if(e.has(o)){let i=K();r.push({name:`${o}_${i}`,path:s})}else r.push({name:o,path:s}),e.add(o)}if(Array.isArray(t))for(let o of t){let s=Ut(o);n(s,o)}else Object.entries(t).forEach(([o,s])=>{n(o,s)});return r}function ht(t,r){return`[dir]/${t}${r}`}function yt(t,r){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},n=>{let o=n.path;return t.some(i=>i.test(o))&&!r.some(i=>i.test(o))?{path:o,external:!0}:null})}}}async function I(t,r){if(!t.entry||t.entry.length===0||!t.outDir)throw new y("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");let e=performance.now();p.cli("Build started");let n=M(r),o=n?.type,s=k(t,n),i=S(t),a=[yt(s,i)],c=D(t.entry),l=t.format.flatMap(u=>c.map(m=>_t(t,r,m,u,o,a)));try{await Promise.all(l);let u=performance.now()-e,m=R(u);p.cli(`\u26A1 Build success in ${m}`)}catch{throw new y("Build process encountered errors")}if(t.dts){p.progress("DTS","Bundling types");let u=t.format.filter(E=>!(E==="iife"&&!v(o)&&t.format.includes("cjs"))),m=t.dts===!0?c:D(t.dts.entry);try{await dt(r,m,u,t,o)}catch(E){throw new g(`DTS build process encountered errors: ${f(E)}`)}}}async function _t(t,r,e,n,o,s){let i=Q(n,o),a=nt(t,r),c=await Bun.build({...a,entrypoints:[`${r}/${e.path}`],format:n,naming:{entry:ht(e.name,i)},splitting:rt(t.splitting,n),plugins:s,throw:!1});if(!c.success)throw c.logs.forEach(l=>{l.level==="error"?p.error(l.message):l.level==="warning"?p.warn(l.message):l.level==="info"&&p.info(l.message)}),new y(`Build failed for ${e} (${n})`);p.progress(X(n,t.name),`${t.outDir}/${e.name}${i}`)}function w(t){return(r,e)=>{e[t]=r===!0?!0:r==="true"}}function H(t){return(r,e)=>{if(typeof r=="string")e[t]=r;else throw new d(`Option --${t} requires a string value`)}}function xt(t){return(r,e)=>{if(typeof r=="string")e[t]=r.split(",");else throw new d(`Option --${t} requires a string value`)}}var Ht={name:{flags:["n","name"],handler:H("name")},format:{flags:["f","format"],handler:(t,r)=>{if(typeof t=="string")r.format=t.split(",");else throw new d("Option --format requires a string value")}},outDir:{flags:["o","out-dir"],handler:H("outDir")},minify:{flags:["m","minify"],handler:w("minify")},watch:{flags:["w","watch"],handler:w("watch")},dts:{flags:["d","dts"],handler:w("dts")},external:{flags:["e","external"],handler:xt("external")},target:{flags:["t","target"],handler:H("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:w("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:w("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:w("minifySyntax")},clean:{flags:["c","clean"],handler:w("clean")},splitting:{flags:["s","splitting"],handler:w("splitting")},noExternal:{flags:["ne","no-external"],handler:xt("noExternal")}},J={};for(let t of Object.values(Ht))if(t)for(let r of t.flags)J[r]=t.handler;function wt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function Et(t){let r={},e={},n=0;for(;n<t.length;){let o=t[n];if(o.startsWith("--")){let s,i;if(o.includes("=")){let[a,c]=o.slice(2).split("=",2);s=a,i=c}else{s=o.slice(2);let a=t[n+1];i=a&&!a.startsWith("-")?a:!0,typeof i=="string"&&n++}if(s==="entry")if(typeof i=="string"){let a=wt(i);e[a]&&p.warn(`Duplicate entry name '${a}' derived from '${i}'. Overwriting previous entry.`),e[a]=i}else throw new d("Option --entry requires a string value");else if(s.startsWith("entry.")){let a=s.slice(6);if(typeof i=="string")e[a]&&p.warn(`Duplicate entry name '${a}' provided via --entry.${a}. Overwriting previous entry.`),e[a]=i;else throw new d(`Option --entry.${a} requires a string value`)}else{let a=J[s];if(a)a(i,r);else throw new d(`Unknown option: --${s}`)}}else if(o.startsWith("-")){let s=o.slice(1),i=t[n+1],a=i&&!i.startsWith("-")?i:!0;typeof a=="string"&&n++;let c=J[s];if(c)c(a,r);else throw new d(`Unknown option: -${s}`)}else{let s=wt(o);e[s]&&p.warn(`Duplicate entry name '${s}' derived from positional argument '${o}'. Overwriting previous entry.`),e[s]=o}n++}return Object.keys(e).length>0&&(r.entry=e),r}(()=>{if(typeof Bun>"u")throw new d(`Bunup requires Bun to run.
5
- To install Bun, visit https://bun.sh/docs/installation`)})();import q from"node:path";import Jt from"chokidar";async function Ot(t,r){let e=new Set;D(t.entry).forEach(c=>{let l=q.resolve(r,c.path),u=q.dirname(l);e.add(u)});let o=Jt.watch(Array.from(e),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,t.outDir]}),s=null,i=!1,a=async c=>{if(!i){i=!0;try{await I({...t,entry:[c],clean:!1},r)}catch(l){throw new B(`Build failed: ${f(l)}`)}finally{i=!1}}};o.on("change",c=>{let l=q.relative(r,c);p.cli(`File changed: ${l}`),s&&clearTimeout(s),s=setTimeout(()=>a(l),300)}),o.on("error",c=>{throw new B(`Watcher error: ${f(c)}`)})}async function zt(t=Bun.argv.slice(2)){let r=Et(t),e=await st(process.cwd()),n=process.cwd();if(r.watch&&(p.cli("Starting watch mode"),p.cli("Watching for file changes")),e.length===0){let o={...b,...r};o.clean&&Bt(n,o.outDir),await Pt(o,n)}else{for(let{options:o,rootDir:s}of e)o.clean&&Bt(s,o.outDir);await Promise.all(e.map(async({options:o,rootDir:s})=>{let i={...b,...o,...r};await Pt(i,s)}))}r.watch||process.exit(0)}async function Pt(t,r){t.watch?await Ot(t,r):await I(t,r)}function Bt(t,r){let e=qt.join(t,r);if(z.existsSync(e))try{z.rmSync(e,{recursive:!0,force:!0})}catch(n){throw new y(`Failed to clean output directory: ${n}`)}z.mkdirSync(e,{recursive:!0})}zt().catch(t=>V(t));export{zt as main};
5
+ `)+"\x1B[0m")},X=(t,r)=>{Ct(t,r),process.exit(1)};import{loadTsConfig as Bt}from"load-tsconfig";var f={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,n){let e=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${e}${n}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let n=String(t),e=this.colors.default;for(let[s,o]of Object.entries(this.colors.progress))if(n.includes(s)){e=o;break}console.log(this.formatMessage(e,n,r))}};function Y(t,r){return`${r?`${r.replace(/-/g,"_")}_`:""}${t}`.toUpperCase()}function J(t){try{return Bt(".",t)}catch(r){return f.warn(`Failed to load tsconfig: ${u(r)}`),{path:t,data:{},files:[]}}}import st from"node:path";import{rollup as Pt}from"rollup";import St from"rollup-plugin-dts";import W from"typescript";function I(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function K(t=8){return Math.random().toString(36).substring(2,2+t)}function Q(t,r){switch(t){case"esm":return".mjs";case"cjs":return P(r)?".cjs":".js";case"iife":return".global.js"}}function V(t,r){switch(t){case"esm":return".d.mts";case"cjs":return P(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function P(t){return t==="module"}function S(t){return t>=1000?`${(t/1000).toFixed(2)}s`:`${Math.round(t)}ms`}function Z(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function z(t,r){return t===void 0?r==="esm":t}function tt(t){return t.map((r)=>typeof r==="string"?new RegExp(`^${I(r)}($|\\/|\\\\)`):r)}function D(t,r){return tt(t.external||[]).concat(Z(r).map((n)=>new RegExp(`^${I(n)}($|\\/|\\\\)`)))}function T(t){return tt(t.noExternal||[])}import b from"node:fs";import nt from"node:path";var v={entry:[],format:["cjs"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function rt(t,r){return{outdir:`${r}/${t.outDir}`,minify:Rt(t),target:t.target,splitting:t.splitting}}function Rt(t){let{minify:r,minifyWhitespace:n,minifyIdentifiers:e,minifySyntax:s}=t,o=r===!0;return{whitespace:n??o,identifiers:e??o,syntax:s??o}}async function et(t){let r=[];for(let n of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let e=nt.join(t,`bunup.config${n}`);try{if(!b.existsSync(e))continue;let s;if(n===".json"||n===".jsonc"){let o=b.readFileSync(e,"utf8");s=JSON.parse(o)}else{let o=await import(`file://${e}`);if(s=o.default||o,!s)f.warn(`No default export found in ${e}`),s={}}if(Array.isArray(s))for(let o of s)r.push({options:{...v,...o},rootDir:t});else r.push({options:{...v,...s},rootDir:t});break}catch(s){throw new x(`Failed to load config from ${e}: ${u(s)}`)}if(r.length>0)break}return r}function M(t){let r=nt.join(t,"package.json");try{if(!b.existsSync(r))return null;let n=b.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return f.warn(`Failed to load package.json at ${r}: ${u(n)}`),null}}async function ot(t,r,n,e,s,o){let c=`\x00virtual:${t.replace(/\.tsx?$/,".d.ts")}`,l=o.data?.compilerOptions,p={name:"bunup:virtual-dts",resolveId(d,w){if(d.startsWith("\x00virtual:"))return d;if(!w?.startsWith("\x00virtual:")||!d.startsWith("."))return null;let O=w.slice(9),N=st.resolve(st.dirname(O),d),G=r.has(N)?N:`${N}.d.ts`;return r.has(G)?`\x00virtual:${G}`:null},load(d){return d.startsWith("\x00virtual:")?r.get(d.slice(9))||null:null}},m=M(s),E=D(e,m),vt=T(e),R;try{R=await Pt({input:c,onwarn(w,O){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(w.code??""))return;O(w)},plugins:[p,St({tsconfig:o.path,compilerOptions:{...l?W.parseJsonConfigFileContent({compilerOptions:l},W.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:W.ScriptTarget.ESNext}})],external:(w)=>E.some((O)=>O.test(w))&&!vt.some((O)=>O.test(w))});let{output:d}=await R.generate({format:n});if(!d[0]?.code)throw new g("Generated bundle is empty");return d[0].code}catch(d){throw new g(`DTS bundling failed: ${u(d)}`)}finally{if(R)await R.close()}}import ct from"node:fs";import lt from"node:path";import k from"node:path";function j(t){let r=k.dirname(t.path||"");return t.data?.compilerOptions?.baseUrl?k.resolve(r,t.data.compilerOptions.baseUrl):r}function it(t){let r=new Map,n=t.data?.compilerOptions?.paths;if(!n)return r;let e=j(t);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");r.set(`^${i}$`,k.join(e,a))}return r}function at(t,r,n){for(let[e,s]of r){let o=new RegExp(e),i=t.match(o);if(i)return s.replace("$1",i[1]||"")}return n?k.join(n,t):null}var Dt=/(?:import|export)(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*|[\s\n]+)(["'`])([^'"]+)\1/g,Tt=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;async function ft(t,r){let n=new Set([t]),e=[t],s=it(r),o=j(r);while(e.length){let i=e.pop();if(!i)continue;try{let a=await ct.promises.readFile(i,"utf8"),c=bt(a);for(let l of c){let p=l.startsWith(".")?lt.resolve(lt.dirname(i),l):at(l,s,o);if(!p)continue;let m=Mt(p);if(m&&!n.has(m))n.add(m),e.push(m)}}catch(a){f.warn(`Error processing ${i}: ${u(a)}`)}}return n}function bt(t){let r=new Set;for(let n of[Dt,Tt]){let e;while((e=n.exec(t))!==null)r.add(e[2])}return Array.from(r)}function Mt(t){let r=["",".ts",".tsx","/index.ts","/index.tsx"];for(let n of r){let e=`${t}${n}`;if(ct.existsSync(e)&&(e.endsWith(".ts")||e.endsWith(".tsx")))return e}return null}import kt from"node:fs";import At from"oxc-transform";async function ut(t){let r=new Map;return await Promise.all([...t].map(async(n)=>{try{let e=n.replace(/\.tsx?$/,".d.ts"),s=await kt.promises.readFile(n,"utf8"),{code:o}=At.isolatedDeclaration(n,s);if(o)r.set(e,o)}catch(e){f.warn(`Failed to generate declaration for ${n}: ${u(e)}`)}})),r}async function mt(t,r,n,e){let{absoluteRootDir:s,absoluteEntry:o}=Ft(t,r),i=J(e.preferredTsconfigPath),a=await ft(o,i),c=await ut(a);return ot(o,c,n,e,s,i)}function Ft(t,r){let n=L.resolve(t),e=L.resolve(n,r);if(!pt.existsSync(n))throw new g(`Root directory does not exist: ${n}`);if(!pt.existsSync(e))throw new g(`Entry file does not exist: ${e}`);if(!e.endsWith(".ts"))throw new g(`Entry file must be a TypeScript file (.ts): ${e}`);if(L.relative(n,e).startsWith(".."))throw new g(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:n,absoluteEntry:e}}async function gt(t,r,n,e,s){return new Promise((o,i)=>{let a={rootDir:t,entries:r,formats:n,options:e,packageType:s},c=new It(new URL("./dtsWorker.js",import.meta.url),{workerData:a});c.on("message",(l)=>{if(l.success){if(l.timeMs){let p=S(l.timeMs);f.progress("DTS",`Bundled types in ${p}`)}o()}else i(new g(l.error||"Unknown DTS worker error"))}),c.on("error",i),c.on("exit",(l)=>{if(l!==0)i(new g(`DTS worker stopped with exit code ${l}`))})})}if(!Nt&&A){let{rootDir:t,entries:r,formats:n,options:e,packageType:s}=Wt,o=performance.now();f.progress("DTS","Bundling types");try{let i=n.flatMap((a)=>r.map(async(c)=>{let l=await mt(t,c.path,a,e),p=V(a,s),m=`${e.outDir}/${c.name}${p}`,E=`${t}/${m}`;await Bun.write(E,l),f.progress("DTS",m)}));Promise.all(i).then(()=>{let a=performance.now()-o;A?.postMessage({success:!0,timeMs:a})}).catch((a)=>{A?.postMessage({success:!1,error:u(a)})})}catch(i){A?.postMessage({success:!1,error:u(i)})}}function jt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function B(t){let r=[],n=new Set;function e(s,o){if(n.has(s)){let i=K();r.push({name:`${s}_${i}`,path:o})}else r.push({name:s,path:o}),n.add(s)}if(Array.isArray(t))for(let s of t){let o=jt(s);e(o,s)}else Object.entries(t).forEach(([s,o])=>{e(s,o)});return r}function dt(t,r){return`[dir]/${t}${r}`}function ht(t,r){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},(e)=>{let s=e.path;if(t.some((i)=>i.test(s))&&!r.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}async function F(t,r){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.");let n=performance.now();f.cli("Build started");let e=M(r),s=e?.type,o=D(t,e),i=T(t),a=[ht(o,i)],c=B(t.entry),l=t.format.flatMap((p)=>c.map((m)=>Lt(t,r,m,p,s,a)));try{await Promise.all(l);let p=performance.now()-n,m=S(p);f.cli(`⚡ Build success in ${m}`)}catch{throw new x("Build process encountered errors")}if(t.dts){f.progress("DTS","Bundling types");let p=t.format.filter((E)=>{if(E==="iife"&&!P(s)&&t.format.includes("cjs"))return!1;return!0}),m=t.dts===!0?c:B(t.dts.entry);try{await gt(r,m,p,t,s)}catch(E){throw new g(`DTS build process encountered errors: ${u(E)}`)}}}async function Lt(t,r,n,e,s,o){let i=Q(e,s),a=rt(t,r),c=await Bun.build({...a,entrypoints:[`${r}/${n.path}`],format:e,naming:{entry:dt(n.name,i)},splitting:z(t.splitting,e),plugins:o,throw:!1});if(!c.success)throw c.logs.forEach((l)=>{if(l.level==="error")f.error(l.message);else if(l.level==="warning")f.warn(l.message);else if(l.level==="info")f.info(l.message)}),new x(`Build failed for ${n} (${e})`);f.progress(Y(e,t.name),`${t.outDir}/${n.name}${i}`)}function y(t){return(r,n)=>{n[t]=r===!0?!0:r==="true"}}function U(t){return(r,n)=>{if(typeof r==="string")n[t]=r;else throw new h(`Option --${t} requires a string value`)}}function xt(t){return(r,n)=>{if(typeof r==="string")n[t]=r.split(",");else throw new h(`Option --${t} requires a string value`)}}var Ut={name:{flags:["n","name"],handler:U("name")},format:{flags:["f","format"],handler:(t,r)=>{if(typeof t==="string")r.format=t.split(",");else throw new h("Option --format requires a string value")}},outDir:{flags:["o","out-dir"],handler:U("outDir")},minify:{flags:["m","minify"],handler:y("minify")},watch:{flags:["w","watch"],handler:y("watch")},dts:{flags:["d","dts"],handler:y("dts")},external:{flags:["e","external"],handler:xt("external")},target:{flags:["t","target"],handler:U("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:y("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:y("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:y("minifySyntax")},clean:{flags:["c","clean"],handler:y("clean")},splitting:{flags:["s","splitting"],handler:y("splitting")},noExternal:{flags:["ne","no-external"],handler:xt("noExternal")}},_={};for(let t of Object.values(Ut))if(t)for(let r of t.flags)_[r]=t.handler;function wt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function yt(t){let r={},n={},e=0;while(e<t.length){let s=t[e];if(s.startsWith("--")){let o,i;if(s.includes("=")){let[a,c]=s.slice(2).split("=",2);o=a,i=c}else{o=s.slice(2);let a=t[e+1];if(i=a&&!a.startsWith("-")?a:!0,typeof i==="string")e++}if(o==="entry")if(typeof i==="string"){let a=wt(i);if(n[a])f.warn(`Duplicate entry name '${a}' derived from '${i}'. Overwriting previous entry.`);n[a]=i}else throw new h("Option --entry requires a string value");else if(o.startsWith("entry.")){let a=o.slice(6);if(typeof i==="string"){if(n[a])f.warn(`Duplicate entry name '${a}' provided via --entry.${a}. Overwriting previous entry.`);n[a]=i}else throw new h(`Option --entry.${a} requires a string value`)}else{let a=_[o];if(a)a(i,r);else throw new h(`Unknown option: --${o}`)}}else if(s.startsWith("-")){let o=s.slice(1),i=t[e+1],a=i&&!i.startsWith("-")?i:!0;if(typeof a==="string")e++;let c=_[o];if(c)c(a,r);else throw new h(`Unknown option: -${o}`)}else{let o=wt(s);if(n[o])f.warn(`Duplicate entry name '${o}' derived from positional argument '${s}'. Overwriting previous entry.`);n[o]=s}e++}if(Object.keys(n).length>0)r.entry=n;return r}(()=>{if(typeof Bun==="undefined")throw new h(`Bunup requires Bun to run.
6
+ To install Bun, visit https://bun.sh/docs/installation`)})();import H from"node:path";import _t from"chokidar";async function Et(t,r){let n=new Set;B(t.entry).forEach((c)=>{let l=H.resolve(r,c.path),p=H.dirname(l);n.add(p)});let s=_t.watch(Array.from(n),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,t.outDir]}),o=null,i=!1,a=async(c)=>{if(i)return;i=!0;try{await F({...t,entry:[c],clean:!1},r)}catch(l){throw new C(`Build failed: ${u(l)}`)}finally{i=!1}};s.on("change",(c)=>{let l=H.relative(r,c);if(f.cli(`File changed: ${l}`),o)clearTimeout(o);o=setTimeout(()=>a(l),300)}),s.on("error",(c)=>{throw new C(`Watcher error: ${u(c)}`)})}async function qt(t=Bun.argv.slice(2)){let r=yt(t),n=await et(process.cwd()),e=process.cwd();if(r.watch)f.cli("Starting watch mode"),f.cli("Watching for file changes");if(n.length===0){let s={...v,...r};if(s.clean)$t(e,s.outDir);await Ot(s,e)}else{for(let{options:s,rootDir:o}of n)if(s.clean)$t(o,s.outDir);await Promise.all(n.map(async({options:s,rootDir:o})=>{let i={...v,...s,...r};await Ot(i,o)}))}if(!r.watch)process.exit(0)}async function Ot(t,r){if(t.watch)await Et(t,r);else await F(t,r)}function $t(t,r){let n=Ht.join(t,r);if(q.existsSync(n))try{q.rmSync(n,{recursive:!0,force:!0})}catch(e){throw new x(`Failed to clean output directory: ${e}`)}q.mkdirSync(n,{recursive:!0})}qt().catch((t)=>X(t));export{qt as main};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _worker_threads = require('worker_threads');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _path = require('path'); var _path2 = _interopRequireDefault(_path);var O=class extends Error{constructor(r){super(r),this.name="BunupError"}};var p=class extends O{constructor(r){super(r),this.name="BunupDTSBuildError"}};var f=t=>t instanceof Error?t.message:String(t);var _loadtsconfig = require('load-tsconfig');var m={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,n){let e=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${e}${n}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let n=String(t),e=this.colors.default;for(let[c,s]of Object.entries(this.colors.progress))if(n.includes(c)){e=s;break}console.log(this.formatMessage(e,n,r))}};function M(t){try{return _loadtsconfig.loadTsConfig.call(void 0, ".",t)}catch(r){return m.warn(`Failed to load tsconfig: ${f(r)}`),{path:t,data:{},files:[]}}}var _rollup = require('rollup');var _rollupplugindts = require('rollup-plugin-dts'); var _rollupplugindts2 = _interopRequireDefault(_rollupplugindts);var _typescript = require('typescript'); var _typescript2 = _interopRequireDefault(_typescript);function P(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k(t,r){switch(t){case"esm":return".d.mts";case"cjs":return K(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function K(t){return t==="module"}function v(t){return t>=1e3?`${(t/1e3).toFixed(2)}s`:`${Math.round(t)}ms`}function F(t){return t?Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})])):[]}function j(t){return t.map(r=>typeof r=="string"?new RegExp(`^${P(r)}($|\\/|\\\\)`):r)}function A(t,r){return j(t.external||[]).concat(F(r).map(n=>new RegExp(`^${P(n)}($|\\/|\\\\)`)))}function N(t){return j(t.noExternal||[])}function I(t){let r=_path2.default.join(t,"package.json");try{if(!_fs2.default.existsSync(r))return null;let n=_fs2.default.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return m.warn(`Failed to load package.json at ${r}: ${f(n)}`),null}}async function L(t,r,n,e,c,s){let o="\0virtual:",i=t.replace(/\.tsx?$/,".d.ts"),l=`${o}${i}`,a=_optionalChain([s, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.compilerOptions]),u={name:"bunup:virtual-dts",resolveId(g,x){if(g.startsWith(o))return g;if(!_optionalChain([x, 'optionalAccess', _4 => _4.startsWith, 'call', _5 => _5(o)])||!g.startsWith("."))return null;let h=x.slice(o.length),T=_path2.default.resolve(_path2.default.dirname(h),g),S=r.has(T)?T:`${T}.d.ts`;return r.has(S)?`${o}${S}`:null},load(g){return g.startsWith(o)&&r.get(g.slice(o.length))||null}},d=I(c),R=A(e,d),z=N(e),E;try{E=await _rollup.rollup.call(void 0, {input:l,onwarn(x,h){["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(_nullishCoalesce(x.code, () => ("")))||h(x)},plugins:[u,_rollupplugindts2.default.call(void 0, {tsconfig:s.path,compilerOptions:{...a?_typescript2.default.parseJsonConfigFileContent({compilerOptions:a},_typescript2.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:_typescript2.default.ScriptTarget.ESNext}})],external:x=>R.some(h=>h.test(x))&&!z.some(h=>h.test(x))});let{output:g}=await E.generate({format:n});if(!_optionalChain([g, 'access', _6 => _6[0], 'optionalAccess', _7 => _7.code]))throw new p("Generated bundle is empty");return g[0].code}catch(g){throw new p(`DTS bundling failed: ${f(g)}`)}finally{E&&await E.close()}}function y(t){let r=_path2.default.dirname(t.path||"");return _optionalChain([t, 'access', _8 => _8.data, 'optionalAccess', _9 => _9.compilerOptions, 'optionalAccess', _10 => _10.baseUrl])?_path2.default.resolve(r,t.data.compilerOptions.baseUrl):r}function D(t){let r=new Map,n=_optionalChain([t, 'access', _11 => _11.data, 'optionalAccess', _12 => _12.compilerOptions, 'optionalAccess', _13 => _13.paths]);if(!n)return r;let e=y(t);for(let[c,s]of Object.entries(n))if(Array.isArray(s)&&s.length){let o=c.replace(/\*/g,"(.*)"),i=s[0].replace(/\*/g,"$1");r.set(`^${o}$`,_path2.default.join(e,i))}return r}function $(t,r,n){for(let[e,c]of r){let s=new RegExp(e),o=t.match(s);if(o)return c.replace("$1",o[1]||"")}return n?_path2.default.join(n,t):null}var rt=/(?:import|export)(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*|[\s\n]+)(["'`])([^'"]+)\1/g,et=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;async function G(t,r){let n=new Set([t]),e=[t],c=D(r),s=y(r);for(;e.length;){let o=e.pop();if(o)try{let i=await _fs2.default.promises.readFile(o,"utf8"),l=nt(i);for(let a of l){let u=a.startsWith(".")?_path2.default.resolve(_path2.default.dirname(o),a):$(a,c,s);if(!u)continue;let d=ot(u);d&&!n.has(d)&&(n.add(d),e.push(d))}}catch(i){m.warn(`Error processing ${o}: ${f(i)}`)}}return n}function nt(t){let r=new Set;for(let n of[rt,et]){let e;for(;(e=n.exec(t))!==null;)r.add(e[2])}return Array.from(r)}function ot(t){let r=["",".ts",".tsx","/index.ts","/index.tsx"];for(let n of r){let e=`${t}${n}`;if(_fs2.default.existsSync(e)&&(e.endsWith(".ts")||e.endsWith(".tsx")))return e}return null}var _oxctransform = require('oxc-transform'); var _oxctransform2 = _interopRequireDefault(_oxctransform);async function X(t,r){let n=new Map,e=y(r),c=D(r);return await Promise.all([...t].map(async s=>{try{let o=s.replace(/\.tsx?$/,".d.ts"),i=await _fs2.default.promises.readFile(s,"utf8"),{code:l}=_oxctransform2.default.isolatedDeclaration(s,i);if(l){let a=at(l,c,e,_path2.default.dirname(s));n.set(o,a)}}catch(o){m.warn(`Failed to generate declaration for ${s}: ${f(o)}`)}})),n}function at(t,r,n,e){return t.replace(/(import|export)(.+?from\s+['"])([^'"]+)(['"])/g,(c,s,o,i,l)=>{if(i.startsWith(".")||i.startsWith("/"))return c;let a=$(i,r,n);if(!a)return c;let u=_path2.default.relative(e,a).replace(/\\/g,"/"),d=u.startsWith(".")?u:`./${u}`;return`${s}${o}${d}${l}`})}async function Y(t,r,n,e){let{absoluteRootDir:c,absoluteEntry:s}=ct(t,r),o=M(e.preferredTsconfigPath),i=await G(s,o),l=await X(i,o);return L(s,l,n,e,c,o)}function ct(t,r){let n=_path2.default.resolve(t),e=_path2.default.resolve(n,r);if(!_fs2.default.existsSync(n))throw new p(`Root directory does not exist: ${n}`);if(!_fs2.default.existsSync(e))throw new p(`Entry file does not exist: ${e}`);if(!e.endsWith(".ts"))throw new p(`Entry file must be a TypeScript file (.ts): ${e}`);if(_path2.default.relative(n,e).startsWith(".."))throw new p(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:n,absoluteEntry:e}}async function mr(t,r,n,e,c){return new Promise((s,o)=>{let i={rootDir:t,entries:r,formats:n,options:e,packageType:c},l=new (0, _worker_threads.Worker)(new URL("./dtsWorker.js",import.meta.url),{workerData:i});l.on("message",a=>{if(a.success){if(a.timeMs){let u=v(a.timeMs);m.progress("DTS",`Bundled types in ${u}`)}s()}else o(new p(a.error||"Unknown DTS worker error"))}),l.on("error",o),l.on("exit",a=>{a!==0&&o(new p(`DTS worker stopped with exit code ${a}`))})})}if(!_worker_threads.isMainThread&&_worker_threads.parentPort){let{rootDir:t,entries:r,formats:n,options:e,packageType:c}=_worker_threads.workerData,s=performance.now();m.progress("DTS","Bundling types");try{let o=n.flatMap(i=>r.map(async l=>{let a=await Y(t,l.path,i,e),u=k(i,c),d=`${e.outDir}/${l.name}${u}`,R=`${t}/${d}`;await Bun.write(R,a),m.progress("DTS",d)}));Promise.all(o).then(()=>{let i=performance.now()-s;_optionalChain([_worker_threads.parentPort, 'optionalAccess', _14 => _14.postMessage, 'call', _15 => _15({success:!0,timeMs:i})])}).catch(i=>{_optionalChain([_worker_threads.parentPort, 'optionalAccess', _16 => _16.postMessage, 'call', _17 => _17({success:!1,error:f(i)})])})}catch(o){_optionalChain([_worker_threads.parentPort, 'optionalAccess', _18 => _18.postMessage, 'call', _19 => _19({success:!1,error:f(o)})])}}exports.runDtsInWorker = mr;
1
+ var ft=require("node:module");var it=Object.create;var{getPrototypeOf:at,defineProperty:P,getOwnPropertyNames:L,getOwnPropertyDescriptor:ct}=Object,A=Object.prototype.hasOwnProperty;var u=(t,r,e)=>{e=t!=null?it(at(t)):{};let o=r||!t||!t.__esModule?P(e,"default",{value:t,enumerable:!0}):e;for(let n of L(t))if(!A.call(o,n))P(o,n,{get:()=>t[n],enumerable:!0});return o},N=new WeakMap,lt=(t)=>{var r=N.get(t),e;if(r)return r;if(r=P({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function")L(t).map((o)=>!A.call(r,o)&&P(r,o,{get:()=>t[o],enumerable:!(e=ct(t,o))||e.enumerable}));return N.set(t,r),r};var pt=(t,r)=>{for(var e in r)P(t,e,{get:r[e],enumerable:!0,configurable:!0,set:(o)=>r[e]=()=>o})};var wt={};pt(wt,{runDtsInWorker:()=>Et});module.exports=lt(wt);var d=require("node:worker_threads");var k=u(require("node:fs")),y=u(require("node:path"));class I extends Error{constructor(t){super(t);this.name="BunupError"}}class g extends I{constructor(t){super(t);this.name="BunupDTSBuildError"}}var l=(t)=>{if(t instanceof Error)return t.message;return String(t)};var U=require("load-tsconfig");var m={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,e){let o=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${o}${e}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let e=String(t),o=this.colors.default;for(let[n,s]of Object.entries(this.colors.progress))if(e.includes(n)){o=s;break}console.log(this.formatMessage(o,e,r))}};function W(t){try{return U.loadTsConfig(".",t)}catch(r){return m.warn(`Failed to load tsconfig: ${l(r)}`),{path:t,data:{},files:[]}}}var v=u(require("node:path")),z=require("rollup"),K=u(require("rollup-plugin-dts")),$=u(require("typescript"));function B(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(t,r){switch(t){case"esm":return".d.mts";case"cjs":return ut(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function ut(t){return t==="module"}function _(t){return t>=1000?`${(t/1000).toFixed(2)}s`:`${Math.round(t)}ms`}function G(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function J(t){return t.map((r)=>typeof r==="string"?new RegExp(`^${B(r)}($|\\/|\\\\)`):r)}function X(t,r){return J(t.external||[]).concat(G(r).map((e)=>new RegExp(`^${B(e)}($|\\/|\\\\)`)))}function H(t){return J(t.noExternal||[])}var O=u(require("node:fs")),Y=u(require("node:path"));function q(t){let r=Y.default.join(t,"package.json");try{if(!O.default.existsSync(r))return null;let e=O.default.readFileSync(r,"utf8");return JSON.parse(e)}catch(e){return m.warn(`Failed to load package.json at ${r}: ${l(e)}`),null}}async function Q(t,r,e,o,n,s){let p=`\x00virtual:${t.replace(/\.tsx?$/,".d.ts")}`,c=s.data?.compilerOptions,h={name:"bunup:virtual-dts",resolveId(f,E){if(f.startsWith("\x00virtual:"))return f;if(!E?.startsWith("\x00virtual:")||!f.startsWith("."))return null;let w=E.slice(9),T=v.default.resolve(v.default.dirname(w),f),F=r.has(T)?T:`${T}.d.ts`;return r.has(F)?`\x00virtual:${F}`:null},load(f){return f.startsWith("\x00virtual:")?r.get(f.slice(9))||null:null}},x=q(n),C=X(o,x),nt=H(o),R;try{R=await z.rollup({input:p,onwarn(E,w){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(E.code??""))return;w(E)},plugins:[h,K.default({tsconfig:s.path,compilerOptions:{...c?$.default.parseJsonConfigFileContent({compilerOptions:c},$.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:$.default.ScriptTarget.ESNext}})],external:(E)=>C.some((w)=>w.test(E))&&!nt.some((w)=>w.test(E))});let{output:f}=await R.generate({format:e});if(!f[0]?.code)throw new g("Generated bundle is empty");return f[0].code}catch(f){throw new g(`DTS bundling failed: ${l(f)}`)}finally{if(R)await R.close()}}var b=u(require("node:fs")),M=u(require("node:path"));var D=u(require("node:path"));function S(t){let r=D.default.dirname(t.path||"");return t.data?.compilerOptions?.baseUrl?D.default.resolve(r,t.data.compilerOptions.baseUrl):r}function V(t){let r=new Map,e=t.data?.compilerOptions?.paths;if(!e)return r;let o=S(t);for(let[n,s]of Object.entries(e))if(Array.isArray(s)&&s.length){let i=n.replace(/\*/g,"(.*)"),a=s[0].replace(/\*/g,"$1");r.set(`^${i}$`,D.default.join(o,a))}return r}function Z(t,r,e){for(let[o,n]of r){let s=new RegExp(o),i=t.match(s);if(i)return n.replace("$1",i[1]||"")}return e?D.default.join(e,t):null}var gt=/(?:import|export)(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*|[\s\n]+)(["'`])([^'"]+)\1/g,mt=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;async function tt(t,r){let e=new Set([t]),o=[t],n=V(r),s=S(r);while(o.length){let i=o.pop();if(!i)continue;try{let a=await b.default.promises.readFile(i,"utf8"),p=dt(a);for(let c of p){let h=c.startsWith(".")?M.default.resolve(M.default.dirname(i),c):Z(c,n,s);if(!h)continue;let x=xt(h);if(x&&!e.has(x))e.add(x),o.push(x)}}catch(a){m.warn(`Error processing ${i}: ${l(a)}`)}}return e}function dt(t){let r=new Set;for(let e of[gt,mt]){let o;while((o=e.exec(t))!==null)r.add(o[2])}return Array.from(r)}function xt(t){let r=["",".ts",".tsx","/index.ts","/index.tsx"];for(let e of r){let o=`${t}${e}`;if(b.default.existsSync(o)&&(o.endsWith(".ts")||o.endsWith(".tsx")))return o}return null}var rt=u(require("node:fs")),ot=u(require("oxc-transform"));async function et(t){let r=new Map;return await Promise.all([...t].map(async(e)=>{try{let o=e.replace(/\.tsx?$/,".d.ts"),n=await rt.default.promises.readFile(e,"utf8"),{code:s}=ot.default.isolatedDeclaration(e,n);if(s)r.set(o,s)}catch(o){m.warn(`Failed to generate declaration for ${e}: ${l(o)}`)}})),r}async function st(t,r,e,o){let{absoluteRootDir:n,absoluteEntry:s}=ht(t,r),i=W(o.preferredTsconfigPath),a=await tt(s,i),p=await et(a);return Q(s,p,e,o,n,i)}function ht(t,r){let e=y.default.resolve(t),o=y.default.resolve(e,r);if(!k.default.existsSync(e))throw new g(`Root directory does not exist: ${e}`);if(!k.default.existsSync(o))throw new g(`Entry file does not exist: ${o}`);if(!o.endsWith(".ts"))throw new g(`Entry file must be a TypeScript file (.ts): ${o}`);if(y.default.relative(e,o).startsWith(".."))throw new g(`Entry file must be within rootDir: ${o}`);return{absoluteRootDir:e,absoluteEntry:o}}async function Et(t,r,e,o,n){return new Promise((s,i)=>{let a={rootDir:t,entries:r,formats:e,options:o,packageType:n},p=new d.Worker(new URL("./dtsWorker.js",import.meta.url),{workerData:a});p.on("message",(c)=>{if(c.success){if(c.timeMs){let h=_(c.timeMs);m.progress("DTS",`Bundled types in ${h}`)}s()}else i(new g(c.error||"Unknown DTS worker error"))}),p.on("error",i),p.on("exit",(c)=>{if(c!==0)i(new g(`DTS worker stopped with exit code ${c}`))})})}if(!d.isMainThread&&d.parentPort){let{rootDir:t,entries:r,formats:e,options:o,packageType:n}=d.workerData,s=performance.now();m.progress("DTS","Bundling types");try{let i=e.flatMap((a)=>r.map(async(p)=>{let c=await st(t,p.path,a,o),h=j(a,n),x=`${o.outDir}/${p.name}${h}`,C=`${t}/${x}`;await Bun.write(C,c),m.progress("DTS",x)}));Promise.all(i).then(()=>{let a=performance.now()-s;d.parentPort?.postMessage({success:!0,timeMs:a})}).catch((a)=>{d.parentPort?.postMessage({success:!1,error:l(a)})})}catch(i){d.parentPort?.postMessage({success:!1,error:l(i)})}}
package/build/index.d.mts CHANGED
@@ -1,143 +1,146 @@
1
- type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
1
+ type WithOptional<
2
+ T,
3
+ K extends keyof T
4
+ > = Omit<T, K> & Partial<Pick<T, K>>;
2
5
 
3
- type Format = 'esm' | 'cjs' | 'iife';
4
- type Target = 'bun' | 'node' | 'browser';
6
+ type Format = "esm" | "cjs" | "iife";
7
+ type Target = "bun" | "node" | "browser";
5
8
  type External = string[];
6
9
  type Entry = string[] | Record<string, string>;
7
10
  type DtsOptions = {
8
- /**
9
- * Entry point files for TypeScript declaration file generation
10
- *
11
- * This can be:
12
- * - An array of file paths
13
- * - An object where keys are output names and values are input file paths
14
- *
15
- * The key names are used for the generated declaration files.
16
- * For example, {custom: './src/index.ts'} will generate custom.d.ts
17
- *
18
- * If not specified, the main entry points will be used for declaration file generation.
19
- *
20
- * If a string path is provided in an array, the file name (without extension)
21
- * will be used as the name for the output declaration file.
22
- *
23
- * @example
24
- * // Using string paths in an array
25
- * entry: ['./src/index.ts'] // Generates index.d.ts
26
- *
27
- * // Using named outputs as an object
28
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
29
- */
30
- entry: Entry;
11
+ /**
12
+ * Entry point files for TypeScript declaration file generation
13
+ *
14
+ * This can be:
15
+ * - An array of file paths
16
+ * - An object where keys are output names and values are input file paths
17
+ *
18
+ * The key names are used for the generated declaration files.
19
+ * For example, {custom: './src/index.ts'} will generate custom.d.ts
20
+ *
21
+ * If not specified, the main entry points will be used for declaration file generation.
22
+ *
23
+ * If a string path is provided in an array, the file name (without extension)
24
+ * will be used as the name for the output declaration file.
25
+ *
26
+ * @example
27
+ * // Using string paths in an array
28
+ * entry: ['./src/index.ts'] // Generates index.d.ts
29
+ *
30
+ * // Using named outputs as an object
31
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
32
+ */
33
+ entry: Entry
31
34
  };
32
35
  interface BunupOptions {
33
- /**
34
- * Name of the build configuration
35
- * Used for logging and identification purposes
36
- */
37
- name?: string;
38
- /**
39
- * Entry point files for the build
40
- *
41
- * This can be:
42
- * - An array of file paths
43
- * - An object where keys are output names and values are input file paths
44
- *
45
- * The key names are used for the generated output files.
46
- * For example, {custom: './src/index.ts'} will generate custom.js
47
- *
48
- * If a string path is provided in an array, the file name (without extension)
49
- * will be used as the name for the output file.
50
- *
51
- * @example
52
- * // Using string paths in an array
53
- * entry: ['./src/index.ts'] // Generates index.js
54
- *
55
- * // Using named outputs as an object
56
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
57
- */
58
- entry: Entry;
59
- /**
60
- * Output directory for the bundled files
61
- * Defaults to 'dist' if not specified
62
- */
63
- outDir: string;
64
- /**
65
- * Output formats for the bundle
66
- * Can include 'esm', 'cjs', and/or 'iife'
67
- * Defaults to ['cjs'] if not specified
68
- */
69
- format: Format[];
70
- /**
71
- * Whether to enable all minification options
72
- * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
73
- */
74
- minify?: boolean;
75
- /**
76
- * Whether to enable code splitting
77
- * Defaults to true for ESM format, false for CJS format
78
- */
79
- splitting?: boolean;
80
- /**
81
- * Whether to minify whitespace in the output
82
- * Removes unnecessary whitespace to reduce file size
83
- */
84
- minifyWhitespace?: boolean;
85
- /**
86
- * Whether to minify identifiers in the output
87
- * Renames variables and functions to shorter names
88
- */
89
- minifyIdentifiers?: boolean;
90
- /**
91
- * Whether to minify syntax in the output
92
- * Optimizes code structure for smaller file size
93
- */
94
- minifySyntax?: boolean;
95
- /**
96
- * Whether to watch for file changes and rebuild automatically
97
- */
98
- watch?: boolean;
99
- /**
100
- * Whether to generate TypeScript declaration files (.d.ts)
101
- * When set to true, generates declaration files for all entry points
102
- * Can also be configured with DtsOptions for more control
103
- */
104
- dts?: boolean | DtsOptions;
105
- /**
106
- * Path to a preferred tsconfig.json file to use for declaration generation
107
- *
108
- * If not specified, the tsconfig.json in the project root will be used.
109
- * This option allows you to use a different TypeScript configuration
110
- * specifically for declaration file generation.
111
- *
112
- * @example
113
- * preferredTsconfigPath: './tsconfig.build.json'
114
- */
115
- preferredTsconfigPath?: string;
116
- /**
117
- * External packages that should not be bundled
118
- * Useful for dependencies that should be kept as external imports
119
- */
120
- external?: External;
121
- /**
122
- * Packages that should be bundled even if they are in external
123
- * Useful for dependencies that should be included in the bundle
124
- */
125
- noExternal?: External;
126
- /**
127
- * The target environment for the bundle
128
- * Can be 'browser', 'bun', 'node', etc.
129
- * Defaults to 'node' if not specified
130
- */
131
- target?: Target;
132
- /**
133
- * Whether to clean the output directory before building
134
- * When true, removes all files in the outDir before starting a new build
135
- * Defaults to true if not specified
136
- */
137
- clean?: boolean;
36
+ /**
37
+ * Name of the build configuration
38
+ * Used for logging and identification purposes
39
+ */
40
+ name?: string;
41
+ /**
42
+ * Entry point files for the build
43
+ *
44
+ * This can be:
45
+ * - An array of file paths
46
+ * - An object where keys are output names and values are input file paths
47
+ *
48
+ * The key names are used for the generated output files.
49
+ * For example, {custom: './src/index.ts'} will generate custom.js
50
+ *
51
+ * If a string path is provided in an array, the file name (without extension)
52
+ * will be used as the name for the output file.
53
+ *
54
+ * @example
55
+ * // Using string paths in an array
56
+ * entry: ['./src/index.ts'] // Generates index.js
57
+ *
58
+ * // Using named outputs as an object
59
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
60
+ */
61
+ entry: Entry;
62
+ /**
63
+ * Output directory for the bundled files
64
+ * Defaults to 'dist' if not specified
65
+ */
66
+ outDir: string;
67
+ /**
68
+ * Output formats for the bundle
69
+ * Can include 'esm', 'cjs', and/or 'iife'
70
+ * Defaults to ['cjs'] if not specified
71
+ */
72
+ format: Format[];
73
+ /**
74
+ * Whether to enable all minification options
75
+ * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
76
+ */
77
+ minify?: boolean;
78
+ /**
79
+ * Whether to enable code splitting
80
+ * Defaults to true for ESM format, false for CJS format
81
+ */
82
+ splitting?: boolean;
83
+ /**
84
+ * Whether to minify whitespace in the output
85
+ * Removes unnecessary whitespace to reduce file size
86
+ */
87
+ minifyWhitespace?: boolean;
88
+ /**
89
+ * Whether to minify identifiers in the output
90
+ * Renames variables and functions to shorter names
91
+ */
92
+ minifyIdentifiers?: boolean;
93
+ /**
94
+ * Whether to minify syntax in the output
95
+ * Optimizes code structure for smaller file size
96
+ */
97
+ minifySyntax?: boolean;
98
+ /**
99
+ * Whether to watch for file changes and rebuild automatically
100
+ */
101
+ watch?: boolean;
102
+ /**
103
+ * Whether to generate TypeScript declaration files (.d.ts)
104
+ * When set to true, generates declaration files for all entry points
105
+ * Can also be configured with DtsOptions for more control
106
+ */
107
+ dts?: boolean | DtsOptions;
108
+ /**
109
+ * Path to a preferred tsconfig.json file to use for declaration generation
110
+ *
111
+ * If not specified, the tsconfig.json in the project root will be used.
112
+ * This option allows you to use a different TypeScript configuration
113
+ * specifically for declaration file generation.
114
+ *
115
+ * @example
116
+ * preferredTsconfigPath: './tsconfig.build.json'
117
+ */
118
+ preferredTsconfigPath?: string;
119
+ /**
120
+ * External packages that should not be bundled
121
+ * Useful for dependencies that should be kept as external imports
122
+ */
123
+ external?: External;
124
+ /**
125
+ * Packages that should be bundled even if they are in external
126
+ * Useful for dependencies that should be included in the bundle
127
+ */
128
+ noExternal?: External;
129
+ /**
130
+ * The target environment for the bundle
131
+ * Can be 'browser', 'bun', 'node', etc.
132
+ * Defaults to 'node' if not specified
133
+ */
134
+ target?: Target;
135
+ /**
136
+ * Whether to clean the output directory before building
137
+ * When true, removes all files in the outDir before starting a new build
138
+ * Defaults to true if not specified
139
+ */
140
+ clean?: boolean;
138
141
  }
139
142
 
140
- type DefineConfigOption = WithOptional<BunupOptions, 'outDir' | 'format'>;
143
+ type DefineConfigOption = WithOptional<BunupOptions, "outDir" | "format">;
141
144
  type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
142
145
  declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
143
146
 
package/build/index.d.ts CHANGED
@@ -1,143 +1,146 @@
1
- type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
1
+ type WithOptional<
2
+ T,
3
+ K extends keyof T
4
+ > = Omit<T, K> & Partial<Pick<T, K>>;
2
5
 
3
- type Format = 'esm' | 'cjs' | 'iife';
4
- type Target = 'bun' | 'node' | 'browser';
6
+ type Format = "esm" | "cjs" | "iife";
7
+ type Target = "bun" | "node" | "browser";
5
8
  type External = string[];
6
9
  type Entry = string[] | Record<string, string>;
7
10
  type DtsOptions = {
8
- /**
9
- * Entry point files for TypeScript declaration file generation
10
- *
11
- * This can be:
12
- * - An array of file paths
13
- * - An object where keys are output names and values are input file paths
14
- *
15
- * The key names are used for the generated declaration files.
16
- * For example, {custom: './src/index.ts'} will generate custom.d.ts
17
- *
18
- * If not specified, the main entry points will be used for declaration file generation.
19
- *
20
- * If a string path is provided in an array, the file name (without extension)
21
- * will be used as the name for the output declaration file.
22
- *
23
- * @example
24
- * // Using string paths in an array
25
- * entry: ['./src/index.ts'] // Generates index.d.ts
26
- *
27
- * // Using named outputs as an object
28
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
29
- */
30
- entry: Entry;
11
+ /**
12
+ * Entry point files for TypeScript declaration file generation
13
+ *
14
+ * This can be:
15
+ * - An array of file paths
16
+ * - An object where keys are output names and values are input file paths
17
+ *
18
+ * The key names are used for the generated declaration files.
19
+ * For example, {custom: './src/index.ts'} will generate custom.d.ts
20
+ *
21
+ * If not specified, the main entry points will be used for declaration file generation.
22
+ *
23
+ * If a string path is provided in an array, the file name (without extension)
24
+ * will be used as the name for the output declaration file.
25
+ *
26
+ * @example
27
+ * // Using string paths in an array
28
+ * entry: ['./src/index.ts'] // Generates index.d.ts
29
+ *
30
+ * // Using named outputs as an object
31
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
32
+ */
33
+ entry: Entry
31
34
  };
32
35
  interface BunupOptions {
33
- /**
34
- * Name of the build configuration
35
- * Used for logging and identification purposes
36
- */
37
- name?: string;
38
- /**
39
- * Entry point files for the build
40
- *
41
- * This can be:
42
- * - An array of file paths
43
- * - An object where keys are output names and values are input file paths
44
- *
45
- * The key names are used for the generated output files.
46
- * For example, {custom: './src/index.ts'} will generate custom.js
47
- *
48
- * If a string path is provided in an array, the file name (without extension)
49
- * will be used as the name for the output file.
50
- *
51
- * @example
52
- * // Using string paths in an array
53
- * entry: ['./src/index.ts'] // Generates index.js
54
- *
55
- * // Using named outputs as an object
56
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
57
- */
58
- entry: Entry;
59
- /**
60
- * Output directory for the bundled files
61
- * Defaults to 'dist' if not specified
62
- */
63
- outDir: string;
64
- /**
65
- * Output formats for the bundle
66
- * Can include 'esm', 'cjs', and/or 'iife'
67
- * Defaults to ['cjs'] if not specified
68
- */
69
- format: Format[];
70
- /**
71
- * Whether to enable all minification options
72
- * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
73
- */
74
- minify?: boolean;
75
- /**
76
- * Whether to enable code splitting
77
- * Defaults to true for ESM format, false for CJS format
78
- */
79
- splitting?: boolean;
80
- /**
81
- * Whether to minify whitespace in the output
82
- * Removes unnecessary whitespace to reduce file size
83
- */
84
- minifyWhitespace?: boolean;
85
- /**
86
- * Whether to minify identifiers in the output
87
- * Renames variables and functions to shorter names
88
- */
89
- minifyIdentifiers?: boolean;
90
- /**
91
- * Whether to minify syntax in the output
92
- * Optimizes code structure for smaller file size
93
- */
94
- minifySyntax?: boolean;
95
- /**
96
- * Whether to watch for file changes and rebuild automatically
97
- */
98
- watch?: boolean;
99
- /**
100
- * Whether to generate TypeScript declaration files (.d.ts)
101
- * When set to true, generates declaration files for all entry points
102
- * Can also be configured with DtsOptions for more control
103
- */
104
- dts?: boolean | DtsOptions;
105
- /**
106
- * Path to a preferred tsconfig.json file to use for declaration generation
107
- *
108
- * If not specified, the tsconfig.json in the project root will be used.
109
- * This option allows you to use a different TypeScript configuration
110
- * specifically for declaration file generation.
111
- *
112
- * @example
113
- * preferredTsconfigPath: './tsconfig.build.json'
114
- */
115
- preferredTsconfigPath?: string;
116
- /**
117
- * External packages that should not be bundled
118
- * Useful for dependencies that should be kept as external imports
119
- */
120
- external?: External;
121
- /**
122
- * Packages that should be bundled even if they are in external
123
- * Useful for dependencies that should be included in the bundle
124
- */
125
- noExternal?: External;
126
- /**
127
- * The target environment for the bundle
128
- * Can be 'browser', 'bun', 'node', etc.
129
- * Defaults to 'node' if not specified
130
- */
131
- target?: Target;
132
- /**
133
- * Whether to clean the output directory before building
134
- * When true, removes all files in the outDir before starting a new build
135
- * Defaults to true if not specified
136
- */
137
- clean?: boolean;
36
+ /**
37
+ * Name of the build configuration
38
+ * Used for logging and identification purposes
39
+ */
40
+ name?: string;
41
+ /**
42
+ * Entry point files for the build
43
+ *
44
+ * This can be:
45
+ * - An array of file paths
46
+ * - An object where keys are output names and values are input file paths
47
+ *
48
+ * The key names are used for the generated output files.
49
+ * For example, {custom: './src/index.ts'} will generate custom.js
50
+ *
51
+ * If a string path is provided in an array, the file name (without extension)
52
+ * will be used as the name for the output file.
53
+ *
54
+ * @example
55
+ * // Using string paths in an array
56
+ * entry: ['./src/index.ts'] // Generates index.js
57
+ *
58
+ * // Using named outputs as an object
59
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
60
+ */
61
+ entry: Entry;
62
+ /**
63
+ * Output directory for the bundled files
64
+ * Defaults to 'dist' if not specified
65
+ */
66
+ outDir: string;
67
+ /**
68
+ * Output formats for the bundle
69
+ * Can include 'esm', 'cjs', and/or 'iife'
70
+ * Defaults to ['cjs'] if not specified
71
+ */
72
+ format: Format[];
73
+ /**
74
+ * Whether to enable all minification options
75
+ * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
76
+ */
77
+ minify?: boolean;
78
+ /**
79
+ * Whether to enable code splitting
80
+ * Defaults to true for ESM format, false for CJS format
81
+ */
82
+ splitting?: boolean;
83
+ /**
84
+ * Whether to minify whitespace in the output
85
+ * Removes unnecessary whitespace to reduce file size
86
+ */
87
+ minifyWhitespace?: boolean;
88
+ /**
89
+ * Whether to minify identifiers in the output
90
+ * Renames variables and functions to shorter names
91
+ */
92
+ minifyIdentifiers?: boolean;
93
+ /**
94
+ * Whether to minify syntax in the output
95
+ * Optimizes code structure for smaller file size
96
+ */
97
+ minifySyntax?: boolean;
98
+ /**
99
+ * Whether to watch for file changes and rebuild automatically
100
+ */
101
+ watch?: boolean;
102
+ /**
103
+ * Whether to generate TypeScript declaration files (.d.ts)
104
+ * When set to true, generates declaration files for all entry points
105
+ * Can also be configured with DtsOptions for more control
106
+ */
107
+ dts?: boolean | DtsOptions;
108
+ /**
109
+ * Path to a preferred tsconfig.json file to use for declaration generation
110
+ *
111
+ * If not specified, the tsconfig.json in the project root will be used.
112
+ * This option allows you to use a different TypeScript configuration
113
+ * specifically for declaration file generation.
114
+ *
115
+ * @example
116
+ * preferredTsconfigPath: './tsconfig.build.json'
117
+ */
118
+ preferredTsconfigPath?: string;
119
+ /**
120
+ * External packages that should not be bundled
121
+ * Useful for dependencies that should be kept as external imports
122
+ */
123
+ external?: External;
124
+ /**
125
+ * Packages that should be bundled even if they are in external
126
+ * Useful for dependencies that should be included in the bundle
127
+ */
128
+ noExternal?: External;
129
+ /**
130
+ * The target environment for the bundle
131
+ * Can be 'browser', 'bun', 'node', etc.
132
+ * Defaults to 'node' if not specified
133
+ */
134
+ target?: Target;
135
+ /**
136
+ * Whether to clean the output directory before building
137
+ * When true, removes all files in the outDir before starting a new build
138
+ * Defaults to true if not specified
139
+ */
140
+ clean?: boolean;
138
141
  }
139
142
 
140
- type DefineConfigOption = WithOptional<BunupOptions, 'outDir' | 'format'>;
143
+ type DefineConfigOption = WithOptional<BunupOptions, "outDir" | "format">;
141
144
  type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
142
145
  declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
143
146
 
package/build/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});function n(i){return i}exports.defineConfig = n;
1
+ var D=require("node:module");var{defineProperty:e,getOwnPropertyNames:r,getOwnPropertyDescriptor:O}=Object,g=Object.prototype.hasOwnProperty;var f=new WeakMap,C=(i)=>{var n=f.get(i),o;if(n)return n;if(n=e({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")r(i).map((t)=>!g.call(n,t)&&e(n,t,{get:()=>i[t],enumerable:!(o=O(i,t))||o.enumerable}));return f.set(i,n),n};var u=(i,n)=>{for(var o in n)e(i,o,{get:n[o],enumerable:!0,configurable:!0,set:(t)=>n[o]=()=>t})};var m={};u(m,{defineConfig:()=>p});module.exports=C(m);function p(i){return i}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunup",
3
- "version": "0.1.18",
3
+ "version": "0.1.19",
4
4
  "description": "A extremely fast, zero-config bundler for TypeScript & JavaScript, powered by Bun.",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -18,7 +18,7 @@
18
18
  "@types/bun": "^1.2.5",
19
19
  "@typescript-eslint/eslint-plugin": "^7.3.1",
20
20
  "bumpp": "^10.1.0",
21
- "bunup": "^0.1.16",
21
+ "bunup": "^0.1.18",
22
22
  "eslint": "^8.57.0",
23
23
  "husky": "^9.1.6",
24
24
  "prettier": "^3.2.5",
@@ -60,8 +60,8 @@
60
60
  "rollup-plugin-dts": "^6.1.1"
61
61
  },
62
62
  "scripts": {
63
- "build": "tsup",
64
- "dev": "tsup --watch",
63
+ "build": "bunup",
64
+ "dev": "bunup --watch",
65
65
  "build:docs": "pnpm -C docs build",
66
66
  "dev:docs": "pnpm -C docs dev",
67
67
  "test-build": "pnpm -C tests build",
@@ -71,6 +71,6 @@
71
71
  "validate": "pnpm run tsc && pnpm run lint",
72
72
  "format": "prettier --write .",
73
73
  "release": "bumpp",
74
- "publish:ci": "pnpm -r --filter '!tests' --filter '!docs' publish --access public --no-git-checks"
74
+ "publish:ci": "pnpm publish --access public --no-git-checks"
75
75
  }
76
76
  }