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