bunup 0.1.34 → 0.1.35
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 +6 -6
- package/build/dtsWorker.js +6 -6
- package/package.json +1 -1
package/build/cli.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import
|
|
3
|
+
import J from"fs";import bt from"path";import{isMainThread as kt}from"worker_threads";import{isMainThread as Gt,parentPort as M,Worker as Xt,workerData as Kt}from"node:worker_threads";class R extends Error{constructor(t){super(t);this.name="BunupError"}}class y extends R{constructor(t){super(t);this.name="BunupBuildError"}}class g extends R{constructor(t){super(t);this.name="BunupDTSBuildError"}}class d extends R{constructor(t){super(t);this.name="BunupCLIError"}}class j extends R{constructor(t){super(t);this.name="BunupWatchError"}}var p=(t)=>{if(t instanceof Error)return t.message;return String(t)},St=(t,n)=>{let r=p(t),e=n?`[${n}] `:"",s="ERROR";if(t instanceof y)s="BUILD ERROR";else if(t instanceof g)s="DTS ERROR";else if(t instanceof d)s="CLI ERROR";else if(t instanceof j)s="WATCH ERROR";else if(t instanceof R)s="BUNUP ERROR";if(console.error(`\x1B[31m[${s}]\x1B[0m ${e}${r}`),t instanceof Error&&t.stack)console.error("\x1B[2m"+t.stack.split(`
|
|
4
4
|
`).slice(1).join(`
|
|
5
|
-
`)+"\x1B[0m")},k=(t,n)=>{
|
|
6
|
-
`);let a
|
|
5
|
+
`)+"\x1B[0m")},k=(t,n)=>{St(t,n),process.exit(1)};var l={MAX_LABEL_LENGTH:5,colors:{cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,n,r,e){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-n.length));if(e){let[i,...a]=r.split(" ");return`\x1B[38;5;${t}m[${n}]\x1B[0m ${s}${i} \x1B[38;5;${this.colors.size}m${e}\x1B[0m ${a.join(" ")}`}return`\x1B[38;5;${t}m[${n}]\x1B[0m ${s}${r}`},cli(t){let n=this.labels.cli;console.log(this.formatMessage(this.colors.cli,n,t))},info(t){console.log(`\x1B[38;5;${this.colors.info}m${t}\x1B[0m`)},warn(t){let n=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,n,t))},error(t){let n=this.labels.error;console.error(this.formatMessage(this.colors.error,n,t))},progress(t,n,r){let e=String(t),s=this.colors.default;for(let[i,a]of Object.entries(this.colors.progress))if(e.includes(i)){s=a;break}console.log(this.formatMessage(s,e,n,r))}};function D(t,n){return`${n?`${n.replace(/-/g,"_")}_`:""}${t}`.toUpperCase()}function Y(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function z(t=8){return Math.random().toString(36).substring(2,2+t)}function tt(t,n){switch(t){case"esm":return".mjs";case"cjs":return N(n)?".cjs":".js";case"iife":return".global.js"}}function nt(t,n){switch(t){case"esm":return".d.mts";case"cjs":return N(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function N(t){return t==="module"}function I(t){return t>=1000?`${(t/1000).toFixed(2)}s`:`${Math.round(t)}ms`}function rt(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function et(t,n){return t===void 0?n==="esm":t}function W(t){if(t===0)return"0 B";let n=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(1024));if(r===0)return`${t} ${n[r]}`;return`${(t/Math.pow(1024,r)).toFixed(2)} ${n[r]}`}import{loadTsConfig as jt}from"load-tsconfig";function st(t){try{return jt(".",t)}catch(n){return l.warn(`Failed to load tsconfig: ${p(n)}`),{path:t,data:{},files:[]}}}import B from"node:path";import{rollup as Nt}from"rollup";import It from"rollup-plugin-dts";import G from"typescript";function it(t){return t.map((n)=>typeof n==="string"?new RegExp(`^${Y(n)}($|\\/|\\\\)`):n)}function H(t,n){return it(t.external||[]).concat(rt(n).map((r)=>new RegExp(`^${Y(r)}($|\\/|\\\\)`)))}function F(t){return it(t.noExternal||[])}import q from"node:fs";import ot from"node:path";var P={entry:[],format:["cjs"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0,sourcemap:"none"};function at(t,n){return{outdir:`${n}/${t.outDir}`,minify:At(t),target:t.target,splitting:t.splitting,sourcemap:t.sourcemap}}function At(t){let{minify:n,minifyWhitespace:r,minifyIdentifiers:e,minifySyntax:s}=t,i=n===!0;return{whitespace:r??i,identifiers:e??i,syntax:s??i}}async function ft(t){let n=[];for(let r of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let e=ot.join(t,`bunup.config${r}`);try{if(!q.existsSync(e))continue;let s;if(r===".json"||r===".jsonc"){let i=q.readFileSync(e,"utf8");s=JSON.parse(i)}else{let i=await import(`file://${e}`);if(s=i.default||i,!s)l.warn(`No default export found in ${e}`),s={}}if(Array.isArray(s))for(let i of s)n.push({options:{...P,...i},rootDir:t});else n.push({options:{...P,...s},rootDir:t});break}catch(s){throw new y(`Failed to load config from ${e}: ${p(s)}`)}if(n.length>0)break}return n}function U(t){let n=ot.join(t,"package.json");try{if(!q.existsSync(n))return null;let r=q.readFileSync(n,"utf8");return JSON.parse(r)}catch(r){return l.warn(`Failed to load package.json at ${n}: ${p(r)}`),null}}var Wt=()=>{return global.allFilesUsedToBundleDts||O||new Set};async function ct(t,n,r,e,s){let o=`\x00virtual:${t.replace(/\.tsx?$/,".d.ts")}`,f=s.data?.compilerOptions,m={name:"bunup:virtual-dts",resolveId(x,$){if(x.startsWith("\x00virtual:"))return x;if(!$?.startsWith("\x00virtual:")||!x.startsWith("."))return null;let h=$.slice(9),C=B.resolve(B.dirname(h),x);if(x==="."){let S=B.join(B.dirname(h),"index.d.ts");if(n.has(S))return`\x00virtual:${S}`;C=B.dirname(h)}if(n.has(C))return`\x00virtual:${C}`;let b=`${C}.d.ts`;if(n.has(b))return`\x00virtual:${b}`;if(x.startsWith(".")){let S=B.join(C,"index.d.ts");if(n.has(S))return`\x00virtual:${S}`}return null},load(x){if(x.startsWith("\x00virtual:")){let $=x.slice(9),h=n.get($);if(h)return Wt().add($),h}return null}},u=U(e),c=H(r,u),w=F(r),E;try{E=await Nt({input:o,onwarn($,h){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes($.code??""))return;h($)},plugins:[m,It({tsconfig:s.path,compilerOptions:{...f?G.parseJsonConfigFileContent({compilerOptions:f},G.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:G.ScriptTarget.ESNext}})],external:($)=>c.some((h)=>h.test($))&&!w.some((h)=>h.test($))});let{output:x}=await E.generate({});if(!x[0]?.code)throw new g("Generated bundle is empty");return x[0].code}catch(x){throw new g(`DTS bundling failed: ${p(x)}`)}finally{if(E)await E.close()}}import mt from"node:fs";import pt from"node:path";import L from"node:path";function X(t){let n=L.dirname(t.path||"");return t.data?.compilerOptions?.baseUrl?L.resolve(n,t.data.compilerOptions.baseUrl):n}function lt(t){let n=new Map,r=t.data?.compilerOptions?.paths;if(!r)return n;let e=X(t);for(let[s,i]of Object.entries(r))if(Array.isArray(i)&&i.length){let a=s.replace(/\*/g,"(.*)"),o=i[0].replace(/\*/g,"$1");n.set(`^${a}$`,L.join(e,o))}return n}function ut(t,n,r){for(let[e,s]of n){let i=new RegExp(e),a=t.match(i);if(a)return s.replace("$1",a[1]||"")}return r?L.join(r,t):null}var Ht=/(?:import|export)(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*|[\s\n]+)(["'`])([^'"]+)\1/g,Ft=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;async function xt(t,n){let r=new Set([t]),e=[t],s=lt(n),i=X(n);while(e.length){let a=e.pop();if(!a)continue;try{let o=await mt.promises.readFile(a,"utf8"),f=qt(o);for(let m of f){let u=m.startsWith(".")?pt.resolve(pt.dirname(a),m):ut(m,s,i);if(!u)continue;let c=Ut(u);if(c&&!r.has(c))r.add(c),e.push(c)}}catch(o){l.warn(`Error processing ${a}: ${p(o)}`)}}return r}function qt(t){let n=new Set;for(let r of[Ht,Ft]){let e;while((e=r.exec(t))!==null)n.add(e[2])}return Array.from(n)}function Ut(t){let n=["",".ts",".tsx","/index.ts","/index.tsx"];for(let r of n){let e=`${t}${r}`;if(mt.existsSync(e)&&(e.endsWith(".ts")||e.endsWith(".tsx")))return e}return null}import Lt from"node:fs";import{isolatedDeclaration as Mt}from"oxc-transform";async function gt(t){let n=new Map;return await Promise.all([...t].map(async(r)=>{try{let e=r.replace(/\.tsx?$/,".d.ts"),s=await Lt.promises.readFile(r,"utf8"),{code:i}=Mt(r,s);if(i)n.set(e,i)}catch(e){l.warn(`Failed to generate declaration for ${r}: ${p(e)}`)}})),n}import Q from"node:fs";import K from"node:path";import{isolatedDeclaration as _t}from"oxc-transform";function ht(t,n){let r=K.resolve(t),e=K.resolve(r,n);if(!Q.existsSync(r))throw new g(`Root directory does not exist: ${r}`);if(!Q.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(K.relative(r,e).startsWith(".."))throw new g(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:r,absoluteEntry:e}}async function dt(t){let n=!1;if(await Promise.all([...t].map(async(r)=>{try{let e=r.replace(/\.d\.ts$/,".ts"),s=await Q.promises.readFile(e,"utf8"),{errors:i}=_t(e,s);i.forEach((a)=>{if(!n)console.log(`
|
|
6
|
+
`);let o=a.labels[0],f=o?Tt(s,o.start):"",c=`${e.split("/").slice(-3).join("/")}${f}: ${Yt(a.message)}`;l.warn(c),n=!0})}catch{}})),n)l.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
|
|
9
|
-
`),e=r.length,s=r[r.length-1].length+1;return` (${e}:${s})`}function
|
|
10
|
-
To install Bun, visit https://bun.sh/docs/installation`)})();import
|
|
8
|
+
`)}function Tt(t,n){if(n===void 0)return"";let r=t.slice(0,n).split(`
|
|
9
|
+
`),e=r.length,s=r[r.length-1].length+1;return` (${e}:${s})`}function Yt(t){return t.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function $t(t,n,r){let{absoluteRootDir:e,absoluteEntry:s}=ht(t,n),i=st(r.preferredTsconfigPath),a=await xt(s,i),o=await gt(a);return ct(s,o,r,e,i)}async function wt(t,n,r,e,s){return new Promise((i,a)=>{let{onBuildEnd:o,...f}=e,m={rootDir:t,entries:n,formats:r,options:f,packageType:s},u=new Xt(new URL("./dtsWorker.js",import.meta.url),{workerData:m});u.on("message",async(c)=>{if(c.success){let w=I(c.timeMs);if(l.progress("DTS",`Bundled types in ${w}`),c.filesUsed)c.filesUsed.forEach((E)=>O.add(E));i()}else a(new g(c.error||"Unknown DTS worker error"))}),u.on("error",a),u.on("exit",(c)=>{if(c!==0)a(new g(`DTS worker stopped with exit code ${c}`))})})}if(!Gt&&M){let{rootDir:t,entries:n,formats:r,options:e,packageType:s}=Kt,i=performance.now(),a=new Set;global.allFilesUsedToBundleDts=a,l.progress("DTS","Bundling types");try{(async()=>{try{await Promise.all(n.map(async(f)=>{let m=await $t(t,f.path,e);await Promise.all(r.map(async(u)=>{let c=nt(u,s),w=`${e.outDir}/${f.name}${c}`,E=`${t}/${w}`;await Bun.write(E,m);let x=Bun.file(E).size||0;l.progress("DTS",w,W(x))}))}));let o=performance.now()-i;M?.postMessage({success:!0,timeMs:o,filesUsed:[...a]})}catch(o){M?.postMessage({success:!1,error:p(o)})}})()}catch(o){M?.postMessage({success:!1,error:p(o)})}}function Qt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function A(t){let n=[],r=new Set;function e(s,i){if(r.has(s)){let a=z();n.push({name:`${s}_${a}`,path:i})}else n.push({name:s,path:i}),r.add(s)}if(Array.isArray(t))for(let s of t){let i=Qt(s);e(i,s)}else Object.entries(t).forEach(([s,i])=>{e(s,i)});return n}function yt(t,n){return`[dir]/${t}${n}`}function Et(t,n){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(e)=>{let s=e.path;if(t.some((a)=>a.test(s))&&!n.some((a)=>a.test(s)))return{path:s,external:!0};return null})}}}async function _(t,n){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 r=performance.now();l.cli("Build started");let e=U(n),s=e?.type,i=H(t,e),a=F(t),o=[Et(i,a)],f=A(t.entry),m=t.format.flatMap((u)=>f.map((c)=>{return Vt(t,n,c,u,s,o)}));try{await Promise.all(m);let u=performance.now()-r,c=I(u);l.cli(`\uD83D\uDCE6 Build success in ${c}`)}catch{throw new y("Build process encountered errors")}if(t.dts){let u=t.format.filter((w)=>{if(w==="iife"&&!N(s)&&t.format.includes("cjs"))return!1;return!0}),c=t.dts===!0?f:A(t.dts.entry);try{await wt(n,c,u,t,s)}catch(w){throw new g(`DTS build process encountered errors: ${p(w)}`)}}}async function Vt(t,n,r,e,s,i){let a=tt(e,s),o=at(t,n),f=await Bun.build({...o,entrypoints:[`${n}/${r.path}`],format:e,naming:{entry:yt(r.name,a)},splitting:et(t.splitting,e),plugins:i,throw:!1});if(!f.success)throw f.logs.forEach((c)=>{if(c.level==="error")l.error(c.message);else if(c.level==="warning")l.warn(c.message);else if(c.level==="info")l.info(c.message)}),new y(`Build failed for ${r} (${e})`);let m=`${t.outDir}/${r.name}${a}`,u=Bun.file(m).size||0;l.progress(D(e,t.name),m,W(u))}function v(t){return(n,r)=>{r[t]=n===!0?!0:n==="true"}}function T(t){return(n,r)=>{if(typeof n==="string")r[t]=n;else throw new d(`Option --${t} requires a string value`)}}function vt(t){return(n,r)=>{if(typeof n==="string")r[t]=n.split(",");else throw new d(`Option --${t} requires a string value`)}}var Zt={name:{flags:["n","name"],handler:T("name")},format:{flags:["f","format"],handler:(t,n)=>{if(typeof t==="string")n.format=t.split(",");else throw new d("Option --format requires a string value")}},outDir:{flags:["o","out-dir"],handler:T("outDir")},minify:{flags:["m","minify"],handler:v("minify")},watch:{flags:["w","watch"],handler:v("watch")},dts:{flags:["d","dts"],handler:v("dts")},external:{flags:["e","external"],handler:vt("external")},sourcemap:{flags:["sm","sourcemap"],handler:T("sourcemap")},target:{flags:["t","target"],handler:T("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:v("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:v("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:v("minifySyntax")},clean:{flags:["c","clean"],handler:v("clean")},splitting:{flags:["s","splitting"],handler:v("splitting")},noExternal:{flags:["ne","no-external"],handler:vt("noExternal")}},V={};for(let t of Object.values(Zt))if(t)for(let n of t.flags)V[n]=t.handler;function Ot(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function Rt(t){let n={},r={},e=0;while(e<t.length){let s=t[e];if(s.startsWith("--")){let i,a;if(s.includes("=")){let[o,f]=s.slice(2).split("=",2);i=o,a=f}else{i=s.slice(2);let o=t[e+1];if(a=o&&!o.startsWith("-")?o:!0,typeof a==="string")e++}if(i==="entry")if(typeof a==="string"){let o=Ot(a);if(r[o])l.warn(`Duplicate entry name '${o}' derived from '${a}'. Overwriting previous entry.`);r[o]=a}else throw new d("Option --entry requires a string value");else if(i.startsWith("entry.")){let o=i.slice(6);if(typeof a==="string"){if(r[o])l.warn(`Duplicate entry name '${o}' provided via --entry.${o}. Overwriting previous entry.`);r[o]=a}else throw new d(`Option --entry.${o} requires a string value`)}else{let o=V[i];if(o)o(a,n);else throw new d(`Unknown option: --${i}`)}}else if(s.startsWith("-")){let i=s.slice(1),a=t[e+1],o=a&&!a.startsWith("-")?a:!0;if(typeof o==="string")e++;let f=V[i];if(f)f(o,n);else throw new d(`Unknown option: -${i}`)}else{let i=Ot(s);if(r[i])l.warn(`Duplicate entry name '${i}' derived from positional argument '${s}'. Overwriting previous entry.`);r[i]=s}e++}if(Object.keys(r).length>0)n.entry=r;return n}(()=>{if(typeof Bun==="undefined")throw new d(`Bunup requires Bun to run.
|
|
10
|
+
To install Bun, visit https://bun.sh/docs/installation`)})();import Z from"node:path";import Jt from"chokidar";async function Pt(t,n){let r=new Set,e=A(t.entry);e.forEach((f)=>{let m=Z.resolve(n,f.path),u=Z.dirname(m);r.add(u)});let s=Jt.watch(Array.from(r),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,t.outDir]}),i=null,a=!1,o=async()=>{if(a)return;a=!0;try{await _({...t,entry:e.map((f)=>f.path),clean:!1},n),t.onBuildEnd?.()}catch(f){throw new j(`Build failed: ${p(f)}`)}finally{a=!1}};s.on("change",(f)=>{let m=Z.relative(n,f);if(l.cli(`File changed: ${m}`),i)clearTimeout(i);i=setTimeout(()=>o(),300)}),s.on("error",(f)=>{throw new j(`Watcher error: ${p(f)}`)}),await o()}var O=new Set;async function Dt(t=Bun.argv.slice(2)){let n=Rt(t),r=await ft(process.cwd()),e=process.cwd();if(n.watch)l.cli("Starting watch mode"),l.cli("Watching for file changes");if(r.length===0){let s={...P,...n};if(s.clean)Ct(e,s.outDir);await Bt(s,e)}else{for(let{options:s,rootDir:i}of r)if(s.clean)Ct(i,s.outDir);await Promise.all(r.map(async({options:s,rootDir:i})=>{let a={...P,...s,...n};await Bt(a,i)}))}if(O.size>0)await dt(O),O.clear();if(!n.watch)process.exit(0)}async function Bt(t,n){if(t.watch)await Pt(t,n);else await _(t,n),t.onBuildEnd?.()}function Ct(t,n){let r=bt.join(t,n);if(J.existsSync(r))try{J.rmSync(r,{recursive:!0,force:!0})}catch(e){throw new y(`Failed to clean output directory: ${e}`)}J.mkdirSync(r,{recursive:!0})}if(kt)Dt().catch((t)=>k(t));export{Dt as main,O as allFilesUsedToBundleDts};
|
package/build/dtsWorker.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Vt=require("node:module");var Yt=Object.create;var{getPrototypeOf:Gt,defineProperty:N,getOwnPropertyNames:st,getOwnPropertyDescriptor:Xt}=Object,it=Object.prototype.hasOwnProperty;var g=(t,n,r)=>{r=t!=null?Yt(Gt(t)):{};let e=n||!t||!t.__esModule?N(r,"default",{value:t,enumerable:!0}):r;for(let s of st(t))if(!it.call(e,s))N(e,s,{get:()=>t[s],enumerable:!0});return e},et=new WeakMap,Kt=(t)=>{var n=et.get(t),r;if(n)return n;if(n=N({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function")st(t).map((e)=>!it.call(n,e)&&N(n,e,{get:()=>t[e],enumerable:!(r=Xt(t,e))||r.enumerable}));return et.set(t,n),n};var Qt=(t,n)=>{for(var r in n)N(t,r,{get:n[r],enumerable:!0,configurable:!0,set:(e)=>n[r]=()=>e})};var fn={};Qt(fn,{runDtsInWorker:()=>k});module.exports=Kt(fn);var y=require("node:worker_threads");var V=g(require("node:fs")),St=g(require("node:path")),jt=require("node:worker_threads");class C extends Error{constructor(t){super(t);this.name="BunupError"}}class v extends C{constructor(t){super(t);this.name="BunupBuildError"}}class h extends C{constructor(t){super(t);this.name="BunupDTSBuildError"}}class $ extends C{constructor(t){super(t);this.name="BunupCLIError"}}class I extends C{constructor(t){super(t);this.name="BunupWatchError"}}var p=(t)=>{if(t instanceof Error)return t.message;return String(t)},Zt=(t,n)=>{let r=p(t),e=n?`[${n}] `:"",s="ERROR";if(t instanceof v)s="BUILD ERROR";else if(t instanceof h)s="DTS ERROR";else if(t instanceof $)s="CLI ERROR";else if(t instanceof I)s="WATCH ERROR";else if(t instanceof C)s="BUNUP ERROR";if(console.error(`\x1B[31m[${s}]\x1B[0m ${e}${r}`),t instanceof Error&&t.stack)console.error("\x1B[2m"+t.stack.split(`
|
|
2
2
|
`).slice(1).join(`
|
|
3
|
-
`)+"\x1B[0m")},
|
|
4
|
-
To install Bun, visit https://bun.sh/docs/installation`)})();var
|
|
5
|
-
`);let a
|
|
3
|
+
`)+"\x1B[0m")},at=(t,n)=>{Zt(t,n),process.exit(1)};function J(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ot(t=8){return Math.random().toString(36).substring(2,2+t)}function ft(t,n){switch(t){case"esm":return".mjs";case"cjs":return q(n)?".cjs":".js";case"iife":return".global.js"}}function ct(t,n){switch(t){case"esm":return".d.mts";case"cjs":return q(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function q(t){return t==="module"}function U(t){return t>=1000?`${(t/1000).toFixed(2)}s`:`${Math.round(t)}ms`}function lt(t){if(!t)return[];return Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})]))}function ut(t,n){return t===void 0?n==="esm":t}function L(t){if(t===0)return"0 B";let n=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(1024));if(r===0)return`${t} ${n[r]}`;return`${(t/Math.pow(1024,r)).toFixed(2)} ${n[r]}`}function Jt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function W(t){let n=[],r=new Set;function e(s,i){if(r.has(s)){let a=ot();n.push({name:`${s}_${a}`,path:i})}else n.push({name:s,path:i}),r.add(s)}if(Array.isArray(t))for(let s of t){let i=Jt(s);e(i,s)}else Object.entries(t).forEach(([s,i])=>{e(s,i)});return n}function pt(t,n){return`[dir]/${t}${n}`}function mt(t){return t.map((n)=>typeof n==="string"?new RegExp(`^${J(n)}($|\\/|\\\\)`):n)}function M(t,n){return mt(t.external||[]).concat(lt(n).map((r)=>new RegExp(`^${J(r)}($|\\/|\\\\)`)))}function _(t){return mt(t.noExternal||[])}var H=g(require("node:fs")),b=g(require("node:path"));var l={MAX_LABEL_LENGTH:5,colors:{cli:"147",info:"245",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,n,r,e){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-n.length));if(e){let[i,...a]=r.split(" ");return`\x1B[38;5;${t}m[${n}]\x1B[0m ${s}${i} \x1B[38;5;${this.colors.size}m${e}\x1B[0m ${a.join(" ")}`}return`\x1B[38;5;${t}m[${n}]\x1B[0m ${s}${r}`},cli(t){let n=this.labels.cli;console.log(this.formatMessage(this.colors.cli,n,t))},info(t){console.log(`\x1B[38;5;${this.colors.info}m${t}\x1B[0m`)},warn(t){let n=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,n,t))},error(t){let n=this.labels.error;console.error(this.formatMessage(this.colors.error,n,t))},progress(t,n,r){let e=String(t),s=this.colors.default;for(let[i,a]of Object.entries(this.colors.progress))if(e.includes(i)){s=a;break}console.log(this.formatMessage(s,e,n,r))}};function xt(t,n){return`${n?`${n.replace(/-/g,"_")}_`:""}${t}`.toUpperCase()}var S={entry:[],format:["cjs"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0,sourcemap:"none"};function gt(t,n){return{outdir:`${n}/${t.outDir}`,minify:bt(t),target:t.target,splitting:t.splitting,sourcemap:t.sourcemap}}function bt(t){let{minify:n,minifyWhitespace:r,minifyIdentifiers:e,minifySyntax:s}=t,i=n===!0;return{whitespace:r??i,identifiers:e??i,syntax:s??i}}async function ht(t){let n=[];for(let r of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let e=b.default.join(t,`bunup.config${r}`);try{if(!H.default.existsSync(e))continue;let s;if(r===".json"||r===".jsonc"){let i=H.default.readFileSync(e,"utf8");s=JSON.parse(i)}else{let i=await import(`file://${e}`);if(s=i.default||i,!s)l.warn(`No default export found in ${e}`),s={}}if(Array.isArray(s))for(let i of s)n.push({options:{...S,...i},rootDir:t});else n.push({options:{...S,...s},rootDir:t});break}catch(s){throw new v(`Failed to load config from ${e}: ${p(s)}`)}if(n.length>0)break}return n}function T(t){let n=b.default.join(t,"package.json");try{if(!H.default.existsSync(n))return null;let r=H.default.readFileSync(n,"utf8");return JSON.parse(r)}catch(r){return l.warn(`Failed to load package.json at ${n}: ${p(r)}`),null}}function dt(t,n){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(e)=>{let s=e.path;if(t.some((a)=>a.test(s))&&!n.some((a)=>a.test(s)))return{path:s,external:!0};return null})}}}async function Y(t,n){if(!t.entry||t.entry.length===0||!t.outDir)throw new v("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");let r=performance.now();l.cli("Build started");let e=T(n),s=e?.type,i=M(t,e),a=_(t),o=[dt(i,a)],f=W(t.entry),m=t.format.flatMap((u)=>f.map((c)=>{return kt(t,n,c,u,s,o)}));try{await Promise.all(m);let u=performance.now()-r,c=U(u);l.cli(`\uD83D\uDCE6 Build success in ${c}`)}catch{throw new v("Build process encountered errors")}if(t.dts){let u=t.format.filter((E)=>{if(E==="iife"&&!q(s)&&t.format.includes("cjs"))return!1;return!0}),c=t.dts===!0?f:W(t.dts.entry);try{await k(n,c,u,t,s)}catch(E){throw new h(`DTS build process encountered errors: ${p(E)}`)}}}async function kt(t,n,r,e,s,i){let a=ft(e,s),o=gt(t,n),f=await Bun.build({...o,entrypoints:[`${n}/${r.path}`],format:e,naming:{entry:pt(r.name,a)},splitting:ut(t.splitting,e),plugins:i,throw:!1});if(!f.success)throw f.logs.forEach((c)=>{if(c.level==="error")l.error(c.message);else if(c.level==="warning")l.warn(c.message);else if(c.level==="info")l.info(c.message)}),new v(`Build failed for ${r} (${e})`);let m=`${t.outDir}/${r.name}${a}`,u=Bun.file(m).size||0;l.progress(xt(e,t.name),m,L(u))}function R(t){return(n,r)=>{r[t]=n===!0?!0:n==="true"}}function G(t){return(n,r)=>{if(typeof n==="string")r[t]=n;else throw new $(`Option --${t} requires a string value`)}}function $t(t){return(n,r)=>{if(typeof n==="string")r[t]=n.split(",");else throw new $(`Option --${t} requires a string value`)}}var Dt={name:{flags:["n","name"],handler:G("name")},format:{flags:["f","format"],handler:(t,n)=>{if(typeof t==="string")n.format=t.split(",");else throw new $("Option --format requires a string value")}},outDir:{flags:["o","out-dir"],handler:G("outDir")},minify:{flags:["m","minify"],handler:R("minify")},watch:{flags:["w","watch"],handler:R("watch")},dts:{flags:["d","dts"],handler:R("dts")},external:{flags:["e","external"],handler:$t("external")},sourcemap:{flags:["sm","sourcemap"],handler:G("sourcemap")},target:{flags:["t","target"],handler:G("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:R("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:R("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:R("minifySyntax")},clean:{flags:["c","clean"],handler:R("clean")},splitting:{flags:["s","splitting"],handler:R("splitting")},noExternal:{flags:["ne","no-external"],handler:$t("noExternal")}},D={};for(let t of Object.values(Dt))if(t)for(let n of t.flags)D[n]=t.handler;function wt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function yt(t){let n={},r={},e=0;while(e<t.length){let s=t[e];if(s.startsWith("--")){let i,a;if(s.includes("=")){let[o,f]=s.slice(2).split("=",2);i=o,a=f}else{i=s.slice(2);let o=t[e+1];if(a=o&&!o.startsWith("-")?o:!0,typeof a==="string")e++}if(i==="entry")if(typeof a==="string"){let o=wt(a);if(r[o])l.warn(`Duplicate entry name '${o}' derived from '${a}'. Overwriting previous entry.`);r[o]=a}else throw new $("Option --entry requires a string value");else if(i.startsWith("entry.")){let o=i.slice(6);if(typeof a==="string"){if(r[o])l.warn(`Duplicate entry name '${o}' provided via --entry.${o}. Overwriting previous entry.`);r[o]=a}else throw new $(`Option --entry.${o} requires a string value`)}else{let o=D[i];if(o)o(a,n);else throw new $(`Unknown option: --${i}`)}}else if(s.startsWith("-")){let i=s.slice(1),a=t[e+1],o=a&&!a.startsWith("-")?a:!0;if(typeof o==="string")e++;let f=D[i];if(f)f(o,n);else throw new $(`Unknown option: -${i}`)}else{let i=wt(s);if(r[i])l.warn(`Duplicate entry name '${i}' derived from positional argument '${s}'. Overwriting previous entry.`);r[i]=s}e++}if(Object.keys(r).length>0)n.entry=r;return n}(()=>{if(typeof Bun==="undefined")throw new $(`Bunup requires Bun to run.
|
|
4
|
+
To install Bun, visit https://bun.sh/docs/installation`)})();var K=g(require("node:fs")),X=g(require("node:path")),Et=require("oxc-transform");function vt(t,n){let r=X.default.resolve(t),e=X.default.resolve(r,n);if(!K.default.existsSync(r))throw new h(`Root directory does not exist: ${r}`);if(!K.default.existsSync(e))throw new h(`Entry file does not exist: ${e}`);if(!e.endsWith(".ts"))throw new h(`Entry file must be a TypeScript file (.ts): ${e}`);if(X.default.relative(r,e).startsWith(".."))throw new h(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:r,absoluteEntry:e}}async function Ot(t){let n=!1;if(await Promise.all([...t].map(async(r)=>{try{let e=r.replace(/\.d\.ts$/,".ts"),s=await K.default.promises.readFile(e,"utf8"),{errors:i}=Et.isolatedDeclaration(e,s);i.forEach((a)=>{if(!n)console.log(`
|
|
5
|
+
`);let o=a.labels[0],f=o?zt(s,o.start):"",c=`${e.split("/").slice(-3).join("/")}${f}: ${tn(a.message)}`;l.warn(c),n=!0})}catch{}})),n)l.info(`
|
|
6
6
|
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.
|
|
7
|
-
`)}function
|
|
8
|
-
`),e=r.length,s=r[r.length-1].length+1;return` (${e}:${s})`}function tn(t){return t.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}var
|
|
7
|
+
`)}function zt(t,n){if(n===void 0)return"";let r=t.slice(0,n).split(`
|
|
8
|
+
`),e=r.length,s=r[r.length-1].length+1;return` (${e}:${s})`}function tn(t){return t.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}var Q=g(require("node:path")),Rt=g(require("chokidar"));async function Pt(t,n){let r=new Set,e=W(t.entry);e.forEach((f)=>{let m=Q.default.resolve(n,f.path),u=Q.default.dirname(m);r.add(u)});let s=Rt.default.watch(Array.from(r),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,t.outDir]}),i=null,a=!1,o=async()=>{if(a)return;a=!0;try{await Y({...t,entry:e.map((f)=>f.path),clean:!1},n),t.onBuildEnd?.()}catch(f){throw new I(`Build failed: ${p(f)}`)}finally{a=!1}};s.on("change",(f)=>{let m=Q.default.relative(n,f);if(l.cli(`File changed: ${m}`),i)clearTimeout(i);i=setTimeout(()=>o(),300)}),s.on("error",(f)=>{throw new I(`Watcher error: ${p(f)}`)}),await o()}var P=new Set;async function nn(t=Bun.argv.slice(2)){let n=yt(t),r=await ht(process.cwd()),e=process.cwd();if(n.watch)l.cli("Starting watch mode"),l.cli("Watching for file changes");if(r.length===0){let s={...S,...n};if(s.clean)Ct(e,s.outDir);await Bt(s,e)}else{for(let{options:s,rootDir:i}of r)if(s.clean)Ct(i,s.outDir);await Promise.all(r.map(async({options:s,rootDir:i})=>{let a={...S,...s,...n};await Bt(a,i)}))}if(P.size>0)await Ot(P),P.clear();if(!n.watch)process.exit(0)}async function Bt(t,n){if(t.watch)await Pt(t,n);else await Y(t,n),t.onBuildEnd?.()}function Ct(t,n){let r=St.default.join(t,n);if(V.default.existsSync(r))try{V.default.rmSync(r,{recursive:!0,force:!0})}catch(e){throw new v(`Failed to clean output directory: ${e}`)}V.default.mkdirSync(r,{recursive:!0})}if(jt.isMainThread)nn().catch((t)=>at(t));var At=require("load-tsconfig");function Nt(t){try{return At.loadTsConfig(".",t)}catch(n){return l.warn(`Failed to load tsconfig: ${p(n)}`),{path:t,data:{},files:[]}}}var B=g(require("node:path")),It=require("rollup"),Wt=g(require("rollup-plugin-dts")),Z=g(require("typescript"));var rn=()=>{return global.allFilesUsedToBundleDts||P||new Set};async function Ht(t,n,r,e,s){let o=`\x00virtual:${t.replace(/\.tsx?$/,".d.ts")}`,f=s.data?.compilerOptions,m={name:"bunup:virtual-dts",resolveId(x,w){if(x.startsWith("\x00virtual:"))return x;if(!w?.startsWith("\x00virtual:")||!x.startsWith("."))return null;let d=w.slice(9),j=B.default.resolve(B.default.dirname(d),x);if(x==="."){let A=B.default.join(B.default.dirname(d),"index.d.ts");if(n.has(A))return`\x00virtual:${A}`;j=B.default.dirname(d)}if(n.has(j))return`\x00virtual:${j}`;let rt=`${j}.d.ts`;if(n.has(rt))return`\x00virtual:${rt}`;if(x.startsWith(".")){let A=B.default.join(j,"index.d.ts");if(n.has(A))return`\x00virtual:${A}`}return null},load(x){if(x.startsWith("\x00virtual:")){let w=x.slice(9),d=n.get(w);if(d)return rn().add(w),d}return null}},u=T(e),c=M(r,u),E=_(r),O;try{O=await It.rollup({input:o,onwarn(w,d){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(w.code??""))return;d(w)},plugins:[m,Wt.default({tsconfig:s.path,compilerOptions:{...f?Z.default.parseJsonConfigFileContent({compilerOptions:f},Z.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:Z.default.ScriptTarget.ESNext}})],external:(w)=>c.some((d)=>d.test(w))&&!E.some((d)=>d.test(w))});let{output:x}=await O.generate({});if(!x[0]?.code)throw new h("Generated bundle is empty");return x[0].code}catch(x){throw new h(`DTS bundling failed: ${p(x)}`)}finally{if(O)await O.close()}}var nt=g(require("node:fs")),tt=g(require("node:path"));var F=g(require("node:path"));function z(t){let n=F.default.dirname(t.path||"");return t.data?.compilerOptions?.baseUrl?F.default.resolve(n,t.data.compilerOptions.baseUrl):n}function Ft(t){let n=new Map,r=t.data?.compilerOptions?.paths;if(!r)return n;let e=z(t);for(let[s,i]of Object.entries(r))if(Array.isArray(i)&&i.length){let a=s.replace(/\*/g,"(.*)"),o=i[0].replace(/\*/g,"$1");n.set(`^${a}$`,F.default.join(e,o))}return n}function qt(t,n,r){for(let[e,s]of n){let i=new RegExp(e),a=t.match(i);if(a)return s.replace("$1",a[1]||"")}return r?F.default.join(r,t):null}var en=/(?:import|export)(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*|[\s\n]+)(["'`])([^'"]+)\1/g,sn=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;async function Ut(t,n){let r=new Set([t]),e=[t],s=Ft(n),i=z(n);while(e.length){let a=e.pop();if(!a)continue;try{let o=await nt.default.promises.readFile(a,"utf8"),f=an(o);for(let m of f){let u=m.startsWith(".")?tt.default.resolve(tt.default.dirname(a),m):qt(m,s,i);if(!u)continue;let c=on(u);if(c&&!r.has(c))r.add(c),e.push(c)}}catch(o){l.warn(`Error processing ${a}: ${p(o)}`)}}return r}function an(t){let n=new Set;for(let r of[en,sn]){let e;while((e=r.exec(t))!==null)n.add(e[2])}return Array.from(n)}function on(t){let n=["",".ts",".tsx","/index.ts","/index.tsx"];for(let r of n){let e=`${t}${r}`;if(nt.default.existsSync(e)&&(e.endsWith(".ts")||e.endsWith(".tsx")))return e}return null}var Lt=g(require("node:fs")),Mt=require("oxc-transform");async function _t(t){let n=new Map;return await Promise.all([...t].map(async(r)=>{try{let e=r.replace(/\.tsx?$/,".d.ts"),s=await Lt.default.promises.readFile(r,"utf8"),{code:i}=Mt.isolatedDeclaration(r,s);if(i)n.set(e,i)}catch(e){l.warn(`Failed to generate declaration for ${r}: ${p(e)}`)}})),n}async function Tt(t,n,r){let{absoluteRootDir:e,absoluteEntry:s}=vt(t,n),i=Nt(r.preferredTsconfigPath),a=await Ut(s,i),o=await _t(a);return Ht(s,o,r,e,i)}async function k(t,n,r,e,s){return new Promise((i,a)=>{let{onBuildEnd:o,...f}=e,m={rootDir:t,entries:n,formats:r,options:f,packageType:s},u=new y.Worker(new URL("./dtsWorker.js",import.meta.url),{workerData:m});u.on("message",async(c)=>{if(c.success){let E=U(c.timeMs);if(l.progress("DTS",`Bundled types in ${E}`),c.filesUsed)c.filesUsed.forEach((O)=>P.add(O));i()}else a(new h(c.error||"Unknown DTS worker error"))}),u.on("error",a),u.on("exit",(c)=>{if(c!==0)a(new h(`DTS worker stopped with exit code ${c}`))})})}if(!y.isMainThread&&y.parentPort){let{rootDir:t,entries:n,formats:r,options:e,packageType:s}=y.workerData,i=performance.now(),a=new Set;global.allFilesUsedToBundleDts=a,l.progress("DTS","Bundling types");try{(async()=>{try{await Promise.all(n.map(async(f)=>{let m=await Tt(t,f.path,e);await Promise.all(r.map(async(u)=>{let c=ct(u,s),E=`${e.outDir}/${f.name}${c}`,O=`${t}/${E}`;await Bun.write(O,m);let x=Bun.file(O).size||0;l.progress("DTS",E,L(x))}))}));let o=performance.now()-i;y.parentPort?.postMessage({success:!0,timeMs:o,filesUsed:[...a]})}catch(o){y.parentPort?.postMessage({success:!1,error:p(o)})}})()}catch(o){y.parentPort?.postMessage({success:!1,error:p(o)})}}
|