bunup 0.4.72 → 0.4.74
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/README.md +1 -0
- package/dist/cli.mjs +12 -11
- package/dist/index.d.mts +56 -2
- package/dist/index.d.ts +56 -2
- package/dist/index.js +7 -6
- package/dist/index.mjs +7 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ Bunup is the **blazing-fast build tool** for TypeScript and JavaScript libraries
|
|
|
19
19
|
| **bunup** | **esm, cjs** | **3.42ms ⚡️** | **21.28ms ⚡️** |
|
|
20
20
|
| tsdown | esm, cjs | 8.37ms | 41.48ms |
|
|
21
21
|
| unbuild | esm, cjs | 43.22ms | 326.65ms |
|
|
22
|
+
| bunchee | esm, cjs | 74.98ms | 324.38ms |
|
|
22
23
|
| tsup | esm, cjs | 63.59ms | 943.61ms |
|
|
23
24
|
|
|
24
25
|
</div>
|
package/dist/cli.mjs
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),s.logSolution(
|
|
5
|
-
`);else console.error(
|
|
6
|
-
`)+
|
|
7
|
-
`),t
|
|
8
|
-
`);let g=m.labels[0],
|
|
9
|
-
`)
|
|
3
|
+
var kr=Object.create;var{getPrototypeOf:Sr,defineProperty:on,getOwnPropertyNames:Tr}=Object;var $r=Object.prototype.hasOwnProperty;var E=(n,r,t)=>{t=n!=null?kr(Sr(n)):{};let e=r||!n||!n.__esModule?on(t,"default",{value:n,enumerable:!0}):t;for(let i of Tr(n))if(!$r.call(e,i))on(e,i,{get:()=>n[i],enumerable:!0});return e};var Lr=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Rr=(n,r)=>{for(var t in r)on(n,t,{get:r[t],enumerable:!0,configurable:!0,set:(e)=>r[t]=()=>e})};var d=(n,r)=>()=>(n&&(r=n(n=0)),r);var Ir=import.meta.require;var v=Lr((be,sn)=>{var F=process||{},On=F.argv||[],q=F.env||{},Mr=!(!!q.NO_COLOR||On.includes("--no-color"))&&(!!q.FORCE_COLOR||On.includes("--color")||F.platform==="win32"||(F.stdout||{}).isTTY&&q.TERM!=="dumb"||!!q.CI),Ar=(n,r,t=n)=>(e)=>{let i=""+e,o=i.indexOf(r,n.length);return~o?n+jr(i,r,t,o)+r:n+i+r},jr=(n,r,t,e)=>{let i="",o=0;do i+=n.substring(o,e)+t,o=e+r.length,e=n.indexOf(r,o);while(~e);return i+n.substring(o)},kn=(n=Mr)=>{let r=n?Ar:()=>String;return{isColorSupported:n,reset:r("\x1B[0m","\x1B[0m"),bold:r("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:r("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:r("\x1B[3m","\x1B[23m"),underline:r("\x1B[4m","\x1B[24m"),inverse:r("\x1B[7m","\x1B[27m"),hidden:r("\x1B[8m","\x1B[28m"),strikethrough:r("\x1B[9m","\x1B[29m"),black:r("\x1B[30m","\x1B[39m"),red:r("\x1B[31m","\x1B[39m"),green:r("\x1B[32m","\x1B[39m"),yellow:r("\x1B[33m","\x1B[39m"),blue:r("\x1B[34m","\x1B[39m"),magenta:r("\x1B[35m","\x1B[39m"),cyan:r("\x1B[36m","\x1B[39m"),white:r("\x1B[37m","\x1B[39m"),gray:r("\x1B[90m","\x1B[39m"),bgBlack:r("\x1B[40m","\x1B[49m"),bgRed:r("\x1B[41m","\x1B[49m"),bgGreen:r("\x1B[42m","\x1B[49m"),bgYellow:r("\x1B[43m","\x1B[49m"),bgBlue:r("\x1B[44m","\x1B[49m"),bgMagenta:r("\x1B[45m","\x1B[49m"),bgCyan:r("\x1B[46m","\x1B[49m"),bgWhite:r("\x1B[47m","\x1B[49m"),blackBright:r("\x1B[90m","\x1B[39m"),redBright:r("\x1B[91m","\x1B[39m"),greenBright:r("\x1B[92m","\x1B[39m"),yellowBright:r("\x1B[93m","\x1B[39m"),blueBright:r("\x1B[94m","\x1B[39m"),magentaBright:r("\x1B[95m","\x1B[39m"),cyanBright:r("\x1B[96m","\x1B[39m"),whiteBright:r("\x1B[97m","\x1B[39m"),bgBlackBright:r("\x1B[100m","\x1B[49m"),bgRedBright:r("\x1B[101m","\x1B[49m"),bgGreenBright:r("\x1B[102m","\x1B[49m"),bgYellowBright:r("\x1B[103m","\x1B[49m"),bgBlueBright:r("\x1B[104m","\x1B[49m"),bgMagentaBright:r("\x1B[105m","\x1B[49m"),bgCyanBright:r("\x1B[106m","\x1B[49m"),bgWhiteBright:r("\x1B[107m","\x1B[49m")}};sn.exports=kn();sn.exports.createColors=kn});function G(n){Tn=n??!1}class A{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;cliColor=p.default.blue;mutedColor=p.default.dim;infoColor=p.default.cyan;warnColor=p.default.yellow;errorColor=p.default.red;defaultColor=p.default.white;progressFgColorMap={ESM:p.default.yellow,CJS:p.default.green,IIFE:p.default.magenta,DTS:p.default.blue};progressBgColorMap={ESM:p.default.bgYellow,CJS:p.default.bgGreen,IIFE:p.default.bgMagenta,DTS:p.default.bgBlue};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(n){if(!n?.once)return!0;if(this.loggedOnceMessages.has(n.once))return!1;return this.loggedOnceMessages.add(n.once),!0}formatMessage({fgColor:n,bgColor:r,label:t,message:e,identifier:i,muted:o}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-t.length)),c=o?this.mutedColor(e):e,a=i?` ${r(p.default.black(` ${i} `))}`:"";return`${n(t)} ${s}${c}${a}`}output(n,r={},t=console.log){if(Tn||!this.shouldLog(r))return;if(r.verticalSpace)t("");if(t(n),r.verticalSpace)t("")}cli(n,r={}){let t=this.formatMessage({fgColor:this.cliColor,bgColor:p.default.bgBlue,label:this.labels.cli,message:n,identifier:r.identifier,muted:r.muted});this.output(t,r)}info(n,r={}){let t=this.formatMessage({fgColor:this.infoColor,bgColor:p.default.bgCyan,label:this.labels.info,message:n,identifier:r.identifier,muted:r.muted});this.output(t,r)}warn(n,r={}){let t=this.formatMessage({fgColor:this.warnColor,bgColor:p.default.bgYellow,label:this.labels.warn,message:n,identifier:r.identifier,muted:r.muted});this.output(t,r,console.warn)}error(n,r={}){let t=this.formatMessage({fgColor:this.errorColor,bgColor:p.default.bgRed,label:this.labels.error,message:n,identifier:r.identifier,muted:r.muted});this.output(t,r,console.error)}getProgressFgColor(n){for(let[r,t]of Object.entries(this.progressFgColorMap))if(n.includes(r))return t;return this.defaultColor}getProgressBgColor(n){for(let[r,t]of Object.entries(this.progressBgColorMap))if(n.includes(r))return t;return p.default.bgWhite}progress(n,r,t={}){let e=this.getProgressFgColor(n),i=this.getProgressBgColor(n),o=this.formatMessage({fgColor:e,bgColor:i,label:n,message:r,identifier:t.identifier,muted:t.muted});this.output(o,t)}}var p,Tn=!1,l;var T=d(()=>{p=E(v(),1);l=A.getInstance()});function an(n){return n instanceof Z}var b,R,I,w,C,Q,Z,y=(n)=>{if(n instanceof Error)return n.message;return String(n)},vr,un=(n,r)=>{let t=y(n),e=r?`[${r}] `:"",i=an(n),o="ERROR";if(n instanceof I)o="BUILD ERROR";else if(n instanceof w)o="DTS ERROR";else if(n instanceof C)o="CLI ERROR";else if(n instanceof Q)o="WATCH ERROR";else if(i)o="ISOLATED DECL ERROR";else if(n instanceof R)o="BUNUP ERROR";let s=vr.find((c)=>c.pattern.test(t)&&(c.errorType===o||!c.errorType));if(!s)console.error(`${b.default.red(o)} ${e}${i?b.default.dim(t):t}`);if(s)console.log(`
|
|
4
|
+
`),s.logSolution(t),console.log(`
|
|
5
|
+
`);else if(!i)console.error(b.default.dim(b.default.white("If you think this is a bug, please open an issue at: ")+b.default.cyan("https://github.com/arshad-yaseen/bunup/issues/new")))},$n=(n,r)=>{un(n,r),process.exit(1)};var B=d(()=>{b=E(v(),1);T();R=class R extends Error{constructor(n){super(n);this.name="BunupError"}};I=class I extends R{constructor(n){super(n);this.name="BunupBuildError"}};w=class w extends R{constructor(n){super(n);this.name="BunupDTSBuildError"}};C=class C extends R{constructor(n){super(n);this.name="BunupCLIError"}};Q=class Q extends R{constructor(n){super(n);this.name="BunupWatchError"}};Z=class Z extends R{constructor(n){super(n);this.name="BunupIsolatedDeclError"}};vr=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",logSolution:()=>{l.error(b.default.white("You're trying to build a project that uses Bun. ")+b.default.white("Please set the target option to ")+b.default.cyan("`bun`")+b.default.white(`.
|
|
6
|
+
`)+b.default.white("Example: ")+b.default.green("`bunup --target bun`")+b.default.white(" or in config: ")+b.default.green("{ target: 'bun' }"))}}]});import Ln from"fs/promises";import Ur from"path";function Rn(n,r,t){return Array.isArray(n)?n.map((e)=>({...e,[r]:t})):{...n,[r]:t}}function In(n){return Array.isArray(n)?n:[n]}function Mn(n,r){switch(n){case"esm":return j(r)?".js":".mjs";case"cjs":return j(r)?".cjs":".js";case"iife":return".global.js"}}function An(n,r){switch(n){case"esm":return j(r)?".d.ts":".d.mts";case"cjs":return j(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function cn(n){return n==="node"||n==="bun"}function j(n){return n==="module"}function z(n){return n>=1000?`${(n/1000).toFixed(2)}s`:`${Math.round(n)}ms`}function jn(n){if(!n)return[];return Array.from(new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.peerDependencies||{})]))}function M(n,r=3){return n.split("/").slice(-r).join("/")}async function En(n,r){let t=Ur.join(n,r);try{await Ln.rm(t,{recursive:!0,force:!0})}catch(e){throw new I(`Failed to clean output directory: ${e}`)}await Ln.mkdir(t,{recursive:!0})}function V(n){return[".ts",".mts",".cts",".tsx"].some((r)=>n.endsWith(r))}var O=d(()=>{B()});import{basename as _r,dirname as Hr,extname as Wr}from"path";function X(n){let r=_r(n),t=Wr(r);return t?r.slice(0,-t.length):r}function U(n){if(typeof n==="string")return[{fullEntryPath:n,name:X(n)}];if(typeof n==="object"&&!Array.isArray(n))return Object.entries(n).map(([e,i])=>({fullEntryPath:i,name:e}));let r=[],t=new Set;for(let e of n){let i=X(e);if(!t.has(i)){r.push({fullEntryPath:e,name:i}),t.add(i);continue}let s=Hr(e).split("/").filter((a)=>a!=="."&&a!=="");if(s.length===0){let a=1,u;do u=`${i}_${a++}`;while(t.has(u));r.push({fullEntryPath:e,name:u}),t.add(u);continue}let c=!1;for(let a=1;a<=s.length&&!c;a++){let m=`${s.slice(-a).join("/")}/${i}`;if(!t.has(m))r.push({fullEntryPath:e,name:m}),t.add(m),c=!0}if(!c){let a=1,u;do u=`${s.join("/")}/${i}_${a++}`;while(t.has(u));r.push({fullEntryPath:e,name:u}),t.add(u)}}return r}function vn(n){return n.filter((r)=>V(r.fullEntryPath))}function Un(n,r){return`[dir]/${n}${r}`}var N=d(()=>{O()});import Fr from"path";import{loadConfig as Wn}from"coffi";async function Dn(n,r,t){return Array.isArray(n)&&"root"in n[0]?n.filter((e)=>t?t.includes(e.name):!0).map((e)=>({rootDir:Fr.resolve(r,e.root),options:Rn(e.config,"name",e.name)})):[{rootDir:r,options:n}]}async function Yn(n){let{config:r,filepath:t}=await Wn({name:"package",cwd:n,extensions:[".json"]});return{packageJson:r,path:t}}async function qn(n,r){let{config:t,filepath:e}=await Wn({name:"tsconfig",cwd:n,extensions:[".json"],preferredPath:r});return{tsconfig:t,path:e}}var mn=d(()=>{O()});function Kr(n){return jn(n).map((r)=>new RegExp(`^${r}($|\\/|\\\\)`))}function Fn(n,r){return typeof r==="string"?r===n:r.test(n)}function nn(n,r,t){let i=Kr(t).some((s)=>s.test(n))||r.external?.some((s)=>Fn(n,s)),o=r.noExternal?.some((s)=>Fn(n,s));return i&&!o}var gn=d(()=>{O()});import{resolveTsImportPath as Gr}from"ts-import-resolver";var H="\x00dts:",Kn=(n,r,t)=>{return{name:"bunup:virtual-dts",async resolveId(e,i){if(fn(e))return e;if(!i||!fn(i))return null;let o=r.tsconfig?Gr({path:e,importer:_(i),tsconfig:r.tsconfig,rootDir:t}):null;if(!o)return null;let s=$(o);if(n.has(s))return rn(s);return null},load(e){if(e.startsWith(H)){let i=_(e),o=n.get(i);if(o)return o}return null}}};var pn=d(()=>{W()});function Gn(n){return n.endsWith(".d.ts")||n.endsWith(".d.mts")||n.endsWith(".d.cts")}function Qn(n){return dn.test(n)&&!Gn(n)}function $(n){if(Gn(n))return n;if(n.endsWith(".mts"))return`${n.slice(0,-4)}.d.mts`;if(n.endsWith(".cts"))return`${n.slice(0,-4)}.d.cts`;if(dn.test(n))return n.replace(dn,".d.ts");return`${n}.d.ts`}function fn(n){return n.startsWith(H)}function _(n){return n.replace(H,"")}function rn(n){return`${H}${n}`}function Zn(n,r){if(r===void 0)return"";let t=n.slice(0,r).split(`
|
|
7
|
+
`),e=t.length,i=t[t.length-1].length+1;return` (${e}:${i})`}function zn(n,r,t,e){if(typeof e==="boolean"&&e)return!1;if(Array.isArray(e)){for(let i of e)if(typeof i==="string"&&n===i)return!1;else if(i instanceof RegExp&&i.test(n))return!1}return nn(n,r,t)}var dn;var W=d(()=>{gn();pn();dn=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/});import Vn from"path";import{ResolverFactory as Qr}from"oxc-resolver";function Xn(n,r){return{name:"bunup:types-resolve",buildStart(){bn||=new Qr({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...n.path&&{tsconfig:{configFile:n.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(t,e){if(r===!1)return;if(t==="bun")return;let i=e?_(e):void 0;if(/\0/.test(t))return;if(Array.isArray(r)){if(!r.some((a)=>typeof a==="string"?a===t:a.test(t)))return}let o=i?Vn.dirname(i):process.cwd(),{path:s}=await bn.async(o,t);if(!s)return;if(Qn(s)){let c=$(s);try{let{path:a}=await bn.async(Vn.dirname(s),c);if(a)return a}catch(a){}return}return s}}}var bn;var Nn=d(()=>{W()});import{build as Zr}from"rolldown";import{dts as zr}from"rolldown-plugin-dts";async function Jn(n,r,t,e,i,o){let s=$(n),c=rn(s),a=typeof t.dts==="object"&&"resolve"in t.dts?t.dts.resolve:void 0;try{let{output:u}=await Zr({input:c,output:{dir:t.outDir},write:!1,...i.path&&{resolve:{tsconfigFilename:i.path}},onwarn(m,g){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(m.code??""))return;g(m)},plugins:[Kn(r,i,o),a&&Xn(i,a),zr({dtsInput:!0,emitDtsOnly:!0})],external:(m)=>zn(m,t,e,a)});if(!u[0]?.code)return l.warn(`Generated empty declaration file for entry "${n}"`,{muted:!0}),"";return u[0].code}catch(u){throw new w(`DTS bundling failed for entry "${n}": ${y(u)}`)}}var Pn=d(()=>{B();T();Nn();W();pn()});import{resolveTsImportPath as Vr}from"ts-import-resolver";function te(n){let r=new Set,t=[Xr,Nr,Jr,Pr,ne,re,ee];for(let e of t){let i=n.matchAll(e);for(let o of i)if(o[1])r.add(o[1])}return r}async function nr(n,r,t){let e=new Set([n]),i=[n];while(i.length){let o=i.pop();if(!o)continue;try{let s=await Bun.file(o).text(),c=te(s);for(let a of c){let u=r.tsconfig?Vr({path:a,importer:o,tsconfig:r.tsconfig,rootDir:t}):null;if(!u)continue;if(!e.has(u))e.add(u),i.push(u)}}catch(s){l.warn(`Error processing ${o}: ${y(s)}`)}}return e}var Xr,Nr,Jr,Pr,ne,re,ee;var rr=d(()=>{B();T();Xr=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Nr=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Jr=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Pr=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,ne=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,re=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,ee=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g});import{isolatedDeclaration as ie}from"oxc-transform";async function er(n,r){let t=!1,e=new Map;if(await Promise.all([...n].map(async(i)=>{try{let o=$(i);if(!await Bun.file(i).exists())return;let c=await Bun.file(i).text(),{code:a,errors:u}=ie(i,c);if(a)e.set(o,a);for(let m of u){if(!t&&!r)console.log(`
|
|
8
|
+
`);let g=m.labels[0],f=g?Zn(c,g.start):"",h=`${M(i)}${f}: ${oe(m.message)}`;l[r?"warn":"error"](h),t=!0}}catch(o){l.warn(`Failed to generate declaration for ${i}: ${y(o)}`)}})),t&&!r)throw console.log(`
|
|
9
|
+
`),new Z(`TypeScript is asking for explicit type annotations on your exports. This helps ensure better, more reliable type declarations for your library. Bunup uses TypeScript's ${xn.default.blue("isolatedDeclarations")} feature to generate these declarations, which requires each export from your library to be fully typed. You can learn more here: ${xn.default.blue("https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-5.html#isolated-declarations")}`);return e}function oe(n){return n.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}var xn;var tr=d(()=>{xn=E(v(),1);B();T();O();W()});import ir from"fs/promises";import hn from"path";async function or(n,r){let t=hn.resolve(n),e=hn.resolve(t,r);if(!await ir.exists(t))throw new w(`Root directory does not exist: ${t}`);if(!await Bun.file(e).exists())throw new w(`Entry file does not exist: ${e}`);if(!V(e))throw new w(`Entry file must be a TypeScript file: ${e}`);if(hn.relative(t,e).startsWith(".."))throw new w(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:t,absoluteEntry:e}}var sr=d(()=>{B();O()});async function ar(n,r,t,e,i){let{absoluteEntry:o}=await or(n,r),s=await nr(o,e,n),c=await er(s,t.watch);return Jn(o,c,t,i,e,n)}var ur=d(()=>{Pn();rr();tr();sr()});function en(n){return{...se,...n}}function cr(n){let{minify:r,minifyWhitespace:t,minifyIdentifiers:e,minifySyntax:i}=n,o=r===!0;return{whitespace:t??o,identifiers:e??o,syntax:i??o}}function lr(n,r){return r==="cjs"?n:void 0}function mr(n,r,t,e){return{...typeof t==="object"&&Object.keys(t).reduce((i,o)=>{let s=JSON.stringify(t[o]);return i[`process.env.${o}`]=s,i[`import.meta.env.${o}`]=s,i},{}),...n,...e==="cjs"&&(r===!0||typeof r==="object"&&r.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function gr(n,r){return n===void 0?r==="esm":n}function fr(n){return typeof n==="string"?n:void 0}var se;var wn=d(()=>{se={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0}});function pr(n,r){return{name:"bunup:external-plugin",setup(t){t.onResolve({filter:/.*/},(e)=>{let i=e.path;if(nn(i,n,r))return{path:i,external:!0};return null})}}}var dr=d(()=>{gn()});function br({format:n,target:r,shims:t}){let i=ue(t).map((o)=>yn[o]).filter((o)=>o.appliesTo(n,r));if(i.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:ae},async({path:s})=>{let c=await Bun.file(s).text(),a=i.filter((f)=>f.isNeededInFile(c));if(a.length===0)return;let{shebangLine:u,codeContent:m}=ce(c),g=a.map((f)=>f.generateCode()).join("");return{contents:u+g+m}})}}}function ue(n){if(n===!0)return Object.keys(yn);if(!n)return[];return Object.entries(n).filter(([r,t])=>t&&(r in yn)).map(([r])=>r)}function ce(n){if(!n.startsWith("#!"))return{shebangLine:"",codeContent:n};let r=n.indexOf(`
|
|
10
|
+
`);return r===-1?{shebangLine:"",codeContent:n}:{shebangLine:n.slice(0,r+1),codeContent:n.slice(r+1)}}var ae,yn;var xr=d(()=>{O();ae=/\.(js|ts|jsx|tsx|mts|cts)$/,yn={dirnameFilename:{appliesTo:(n,r)=>n==="esm"&&cn(r),isNeededInFile:(n)=>/\b__dirname\b/.test(n)||/\b__filename\b/.test(n),generateCode:()=>`import { fileURLToPath } from 'url';
|
|
10
11
|
import { dirname } from 'path';
|
|
11
12
|
|
|
12
13
|
const __filename = fileURLToPath(import.meta.url);
|
|
13
14
|
const __dirname = dirname(__filename);
|
|
14
15
|
|
|
15
|
-
`},importMetaUrl:{appliesTo:(n,r)=>n==="cjs"&&
|
|
16
|
+
`},importMetaUrl:{appliesTo:(n,r)=>n==="cjs"&&cn(r),isNeededInFile:(n)=>/\bimport\.meta\.url\b/.test(n),generateCode:()=>`import { pathToFileURL } from 'url';
|
|
16
17
|
|
|
17
18
|
const importMetaUrl = pathToFileURL(__filename).href;
|
|
18
19
|
|
|
19
|
-
`}}});function
|
|
20
|
+
`}}});function hr(n){if(!n)return[];return n.filter((r)=>r.type==="bun")}function wr(n){if(!n)return[];return n.filter((r)=>r.type==="bunup")}async function yr(n,r){if(!n)return;for(let t of n)if(t.hooks.onBuildStart)await t.hooks.onBuildStart(r)}async function Cr(n,r,t){if(!n)return;for(let e of n)if(e.hooks.onBuildDone)await e.hooks.onBuildDone({options:r,output:t})}var Br={};Rr(Br,{build:()=>Cn});async function Cn(n,r=process.cwd()){let t={files:[]},e=en(n);if(!e.entry||e.entry.length===0||!e.outDir)throw new I("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(e.clean)En(r,e.outDir);G(e.silent);let{packageJson:i,path:o}=await Yn(r);if(i&&o)l.cli(`Using package.json: ${M(o,2)}`,{muted:!0,identifier:e.name,once:`${o}:${e.name}`});let s=wr(e.plugins);await yr(s,e);let c=U(e.entry),a=i?.type;if(!e.dtsOnly){let u=[pr(e,i),...hr(e.plugins).map((g)=>g.plugin)],m=e.format.flatMap((g)=>c.map(async(f)=>{let L=e.outputExtension?.({format:g,packageType:a,options:e,entry:f}).js??Mn(g,a),h=await Bun.build({entrypoints:[`${r}/${f.fullEntryPath}`],format:g,naming:{entry:Un(f.name,L)},splitting:gr(e.splitting,g),bytecode:lr(e.bytecode,g),define:mr(e.define,e.shims,e.env,g),minify:cr(e),outdir:`${r}/${e.outDir}`,target:e.target,sourcemap:e.sourcemap,loader:e.loader,drop:e.drop,banner:e.banner,footer:e.footer,publicPath:e.publicPath,env:fr(e.env),plugins:[...u,br({format:g,target:e.target,shims:e.shims})],throw:!1});if(!h.success)for(let S of h.logs){if(S.level==="error")throw new I(S.message);if(S.level==="warning")l.warn(S.message);else if(S.level==="info")l.info(S.message)}let D=`${e.outDir}/${f.name}${L}`,Y=`${r}/${D}`;t.files.push({path:Y}),l.progress(g.toUpperCase(),D,{identifier:e.name})}));await Promise.all(m)}if(e.dts||e.dtsOnly){let u=await qn(r,e.preferredTsconfigPath);if(u.path)l.cli(`Using tsconfig: ${M(u.path,2)}`,{muted:!0,identifier:e.name,once:`${u.path}:${e.name}`});let m=e.format.filter((f)=>{if(f==="iife"&&!j(a)&&e.format.includes("cjs"))return!1;return!0}),g=typeof e.dts==="object"&&e.dts.entry?U(e.dts.entry):vn(c);try{await Promise.all(g.map(async(f)=>{let L=await ar(r,f.fullEntryPath,e,u,i);await Promise.all(m.map(async(h)=>{let D=e.outputExtension?.({format:h,packageType:a,options:e,entry:f}).dts??An(h,a),Y=`${e.outDir}/${f.name}${D}`,S=`${r}/${Y}`;t.files.push({path:S}),await Bun.write(S,L),l.progress("DTS",Y,{identifier:e.name})}))}))}catch(f){if(an(f))throw f;throw new w(y(f))}}if(await Cr(s,e,t),e.onSuccess)await e.onSuccess(e)}var Bn=d(()=>{ur();B();N();mn();T();wn();dr();xr();O()});import{exec as me}from"tinyexec";var ln=E(v(),1);var K="0.4.74";var Sn="https://bunup.dev/cli-options";B();N();T();function x(n){return(r,t)=>{t[n]=r===!0||r==="true"}}function k(n){return(r,t)=>{if(typeof r==="string")t[n]=r;else throw new C(`Option --${n} requires a string value`)}}function J(n){return(r,t)=>{if(typeof r==="string")t[n]=r.split(",");else throw new C(`Option --${n} requires a string value`)}}function Dr(n){return(r,t)=>{if(typeof r==="boolean")t[n]=r;else if(typeof r==="string")if(r.toLowerCase()==="true"||r.toLowerCase()==="false")t[n]=r.toLowerCase()==="true";else t[n]=r;else throw new C(`Option --${n} requires a boolean or string value`)}}function Yr(){console.log(`
|
|
20
21
|
Bunup - \u26A1\uFE0F A blazing-fast build tool for your libraries built with Bun.
|
|
21
|
-
`),console.log("For more information on available options, visit:"),console.log(`${
|
|
22
|
-
`),process.exit(0)}function
|
|
22
|
+
`),console.log("For more information on available options, visit:"),console.log(`${ln.default.cyan(ln.default.underline(Sn))}
|
|
23
|
+
`),process.exit(0)}function qr(){console.log(K),process.exit(0)}var _n={name:{flags:["n","name"],handler:k("name")},format:{flags:["f","format"],handler:J("format")},outDir:{flags:["o","out-dir"],handler:k("outDir")},minify:{flags:["m","minify"],handler:x("minify")},watch:{flags:["w","watch"],handler:x("watch")},dts:{flags:["d","dts"],handler:x("dts")},banner:{flags:["bn","banner"],handler:k("banner")},footer:{flags:["ft","footer"],handler:k("footer")},external:{flags:["e","external"],handler:J("external")},sourcemap:{flags:["sm","sourcemap"],handler:Dr("sourcemap")},target:{flags:["t","target"],handler:k("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:x("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:x("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:x("minifySyntax")},clean:{flags:["c","clean"],handler:x("clean")},splitting:{flags:["s","splitting"],handler:x("splitting")},noExternal:{flags:["ne","no-external"],handler:J("noExternal")},preferredTsconfigPath:{flags:["tsconfig","preferred-tsconfig-path"],handler:k("preferredTsconfigPath")},bytecode:{flags:["bc","bytecode"],handler:x("bytecode")},dtsOnly:{flags:["do","dts-only"],handler:x("dtsOnly")},silent:{flags:["silent"],handler:x("silent")},config:{flags:["config"],handler:k("config")},publicPath:{flags:["pp","public-path"],handler:k("publicPath")},env:{flags:["env"],handler:k("env")},shims:{flags:["shims"],handler:x("shims")},onSuccess:{flags:["onSuccess"],handler:k("onSuccess")},filter:{flags:["filter"],handler:J("filter")},entry:{flags:["entry"],handler:(n,r,t)=>{if(typeof n!=="string")throw new C(`Entry${t?` --entry.${t}`:""} requires a string value`);let e=r.entry||{};if(t){if(e[t])l.warn(`Duplicate entry name '${t}' provided via --entry.${t}. Overwriting previous entry.`);e[t]=n}else{let i=X(n);if(e[i])l.warn(`Duplicate entry name '${i}' derived from '${n}'. Overwriting previous entry.`);e[i]=n}r.entry=e}},resolveDts:{flags:["rd","resolve-dts"],handler:(n,r)=>{if(!r.dts)r.dts={};if(typeof r.dts==="boolean")r.dts={};if(typeof n==="string")if(n==="true"||n==="false")r.dts.resolve=n==="true";else r.dts.resolve=n.split(",");else r.dts.resolve=!0}},help:{flags:["h","help"],handler:()=>Yr()},version:{flags:["v","version"],handler:()=>qr()}},P={};for(let n of Object.values(_n))for(let r of n.flags)P[r]=n.handler;function Hn(n){let r={};for(let t=0;t<n.length;t++){let e=n[t];if(e.startsWith("--")){let i,o;if(e.includes("=")){let[s,c]=e.slice(2).split("=",2);i=s,o=c}else{i=e.slice(2);let s=n[t+1];if(o=s&&!s.startsWith("-")?s:!0,typeof o==="string")t++}if(i.includes(".")){let[s,c]=i.split(".",2),a=P[s];if(a)a(o,r,c);else throw new C(`Unknown option: --${i}`)}else{let s=P[i];if(s)s(o,r);else throw new C(`Unknown option: --${i}`)}}else if(e.startsWith("-")){let i=e.slice(1),o=n[t+1],s=o&&!o.startsWith("-")?o:!0;if(typeof s==="string")t++;let c=P[i];if(c)c(s,r);else throw new C(`Unknown option: -${i}`)}else _n.entry.handler(e,r,void 0)}return r}B();T();import{loadConfig as ge}from"coffi";mn();O();Bn();B();N();T();wn();O();import tn from"path";async function Or(n,r){let t=new Set,e=en(n),i=U(e.entry);for(let u of i){let m=tn.resolve(r,u.fullEntryPath),g=tn.dirname(m);t.add(g)}let s=(await import("chokidar")).watch(Array.from(t),{persistent:!0,ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,tn.join(r,e.outDir)]}),c=!1,a=async(u=!1)=>{if(c)return;c=!0;try{let m=performance.now();if(await Cn({...e,entry:i.map((g)=>g.fullEntryPath),clean:!1},r),!u)l.cli(`\uD83D\uDCE6 Rebuild finished in ${z(performance.now()-m)}`)}catch(m){un(m)}finally{c=!1}};s.on("change",(u)=>{let m=tn.relative(r,u);l.cli(`File changed: ${m}`,{muted:!0,once:m}),a()}),s.on("error",(u)=>{throw new Q(`Watcher error: ${y(u)}`)}),await a(!0)}async function fe(n=Bun.argv.slice(2)){let r=Hn(n);G(r.silent);let t=process.cwd(),{config:e,filepath:i}=await ge({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:r.config,packageJsonProperty:"bunup"}),o=!e?[{rootDir:t,options:r}]:await Dn(e,t,r.filter);if(l.cli(`Using bunup v${K} and bun v${Bun.version}`,{muted:!0}),i)l.cli(`Using config file: ${M(i,2)}`,{muted:!0});let s=performance.now();l.cli("Build started");let{build:c}=await Promise.resolve().then(() => (Bn(),Br));await Promise.all(o.flatMap(({options:m,rootDir:g})=>{return In(m).map(async(L)=>{let h={...L,...pe(r)};if(h.watch)await Or(h,g);else await c(h,g)})}));let a=performance.now()-s,u=z(a);if(l.cli(`\u26A1\uFE0F Build completed in ${u}`),r.watch)l.cli("\uD83D\uDC40 Watching for file changes");if(r.onSuccess)l.cli(`Running command: ${r.onSuccess}`,{muted:!0}),await me(r.onSuccess,[],{nodeOptions:{shell:!0,stdio:"inherit"}});if(!r.watch)process.exit(process.exitCode??0)}function pe(n){return{...n,onSuccess:void 0,config:void 0}}fe().catch((n)=>$n(n));
|
package/dist/index.d.mts
CHANGED
|
@@ -8,12 +8,66 @@ type ProcessableEntry = {
|
|
|
8
8
|
|
|
9
9
|
//#endregion
|
|
10
10
|
//#region \0dts:/home/runner/work/bunup/bunup/src/plugins/types.d.ts
|
|
11
|
+
/**
|
|
12
|
+
* Represents a Bun plugin that can be used with Bunup
|
|
13
|
+
*/
|
|
11
14
|
type BunupBunPlugin = {
|
|
15
|
+
/** Identifies this as a native Bun plugin */
|
|
12
16
|
type: "bun"
|
|
17
|
+
/** Optional name for the plugin */
|
|
13
18
|
name?: string
|
|
19
|
+
/** The actual Bun plugin implementation */
|
|
14
20
|
plugin: BunPlugin
|
|
15
21
|
};
|
|
16
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Represents the output of a build operation
|
|
24
|
+
*/
|
|
25
|
+
type BuildOutput = {
|
|
26
|
+
/** Array of generated files with their paths and contents */
|
|
27
|
+
files: Array<{
|
|
28
|
+
/** Path to the generated file */
|
|
29
|
+
path: string
|
|
30
|
+
}>
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Context provided to build hooks
|
|
34
|
+
*/
|
|
35
|
+
type BuildContext = {
|
|
36
|
+
/** The build options that were used */
|
|
37
|
+
options: BuildOptions
|
|
38
|
+
/** The output of the build */
|
|
39
|
+
output: BuildOutput
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Hooks that can be implemented by Bunup plugins
|
|
43
|
+
*/
|
|
44
|
+
type BunupPluginHooks = {
|
|
45
|
+
/**
|
|
46
|
+
* Called when a build is successfully completed
|
|
47
|
+
* @param ctx Build context containing options and output
|
|
48
|
+
*/
|
|
49
|
+
onBuildDone?: (ctx: BuildContext) => MaybePromise<void>
|
|
50
|
+
/**
|
|
51
|
+
* Called before a build starts
|
|
52
|
+
* @param options Build options that will be used
|
|
53
|
+
*/
|
|
54
|
+
onBuildStart?: (options: BuildOptions) => MaybePromise<void>
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Represents a Bunup-specific plugin
|
|
58
|
+
*/
|
|
59
|
+
type BunupPlugin = {
|
|
60
|
+
/** Identifies this as a Bunup-specific plugin */
|
|
61
|
+
type: "bunup"
|
|
62
|
+
/** Optional name for the plugin */
|
|
63
|
+
name?: string
|
|
64
|
+
/** The hooks implemented by this plugin */
|
|
65
|
+
hooks: BunupPluginHooks
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Union type representing all supported plugin types
|
|
69
|
+
*/
|
|
70
|
+
type Plugin = BunupBunPlugin | BunupPlugin;
|
|
17
71
|
|
|
18
72
|
//#endregion
|
|
19
73
|
//#region \0dts:/home/runner/work/bunup/bunup/src/options.d.ts
|
|
@@ -235,7 +289,7 @@ interface BuildOptions {
|
|
|
235
289
|
*
|
|
236
290
|
* @param options The build options that were used
|
|
237
291
|
*/
|
|
238
|
-
|
|
292
|
+
onSuccess?: (options: Partial<BuildOptions>) => MaybePromise<void>;
|
|
239
293
|
/**
|
|
240
294
|
* A banner to be added to the final bundle, this can be a directive like "use client" for react or a comment block such as a license for the code.
|
|
241
295
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -8,12 +8,66 @@ type ProcessableEntry = {
|
|
|
8
8
|
|
|
9
9
|
//#endregion
|
|
10
10
|
//#region \0dts:/home/runner/work/bunup/bunup/src/plugins/types.d.ts
|
|
11
|
+
/**
|
|
12
|
+
* Represents a Bun plugin that can be used with Bunup
|
|
13
|
+
*/
|
|
11
14
|
type BunupBunPlugin = {
|
|
15
|
+
/** Identifies this as a native Bun plugin */
|
|
12
16
|
type: "bun"
|
|
17
|
+
/** Optional name for the plugin */
|
|
13
18
|
name?: string
|
|
19
|
+
/** The actual Bun plugin implementation */
|
|
14
20
|
plugin: BunPlugin
|
|
15
21
|
};
|
|
16
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Represents the output of a build operation
|
|
24
|
+
*/
|
|
25
|
+
type BuildOutput = {
|
|
26
|
+
/** Array of generated files with their paths and contents */
|
|
27
|
+
files: Array<{
|
|
28
|
+
/** Path to the generated file */
|
|
29
|
+
path: string
|
|
30
|
+
}>
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Context provided to build hooks
|
|
34
|
+
*/
|
|
35
|
+
type BuildContext = {
|
|
36
|
+
/** The build options that were used */
|
|
37
|
+
options: BuildOptions
|
|
38
|
+
/** The output of the build */
|
|
39
|
+
output: BuildOutput
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Hooks that can be implemented by Bunup plugins
|
|
43
|
+
*/
|
|
44
|
+
type BunupPluginHooks = {
|
|
45
|
+
/**
|
|
46
|
+
* Called when a build is successfully completed
|
|
47
|
+
* @param ctx Build context containing options and output
|
|
48
|
+
*/
|
|
49
|
+
onBuildDone?: (ctx: BuildContext) => MaybePromise<void>
|
|
50
|
+
/**
|
|
51
|
+
* Called before a build starts
|
|
52
|
+
* @param options Build options that will be used
|
|
53
|
+
*/
|
|
54
|
+
onBuildStart?: (options: BuildOptions) => MaybePromise<void>
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Represents a Bunup-specific plugin
|
|
58
|
+
*/
|
|
59
|
+
type BunupPlugin = {
|
|
60
|
+
/** Identifies this as a Bunup-specific plugin */
|
|
61
|
+
type: "bunup"
|
|
62
|
+
/** Optional name for the plugin */
|
|
63
|
+
name?: string
|
|
64
|
+
/** The hooks implemented by this plugin */
|
|
65
|
+
hooks: BunupPluginHooks
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Union type representing all supported plugin types
|
|
69
|
+
*/
|
|
70
|
+
type Plugin = BunupBunPlugin | BunupPlugin;
|
|
17
71
|
|
|
18
72
|
//#endregion
|
|
19
73
|
//#region \0dts:/home/runner/work/bunup/bunup/src/options.d.ts
|
|
@@ -235,7 +289,7 @@ interface BuildOptions {
|
|
|
235
289
|
*
|
|
236
290
|
* @param options The build options that were used
|
|
237
291
|
*/
|
|
238
|
-
|
|
292
|
+
onSuccess?: (options: Partial<BuildOptions>) => MaybePromise<void>;
|
|
239
293
|
/**
|
|
240
294
|
* A banner to be added to the final bundle, this can be a directive like "use client" for react or a comment block such as a license for the code.
|
|
241
295
|
*
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
// @bun @bun-cjs
|
|
2
|
-
(function(exports, require, module, __filename, __dirname) {var
|
|
3
|
-
`),e
|
|
4
|
-
`);let x
|
|
2
|
+
(function(exports, require, module, __filename, __dirname) {var Nr=Object.create;var{getPrototypeOf:Jr,defineProperty:I,getOwnPropertyNames:rr,getOwnPropertyDescriptor:vr}=Object,nr=Object.prototype.hasOwnProperty;var d=(r,n,e)=>{e=r!=null?Nr(Jr(r)):{};let t=n||!r||!r.__esModule?I(e,"default",{value:r,enumerable:!0}):e;for(let o of rr(r))if(!nr.call(t,o))I(t,o,{get:()=>r[o],enumerable:!0});return t},P=new WeakMap,Pr=(r)=>{var n=P.get(r),e;if(n)return n;if(n=I({},"__esModule",{value:!0}),r&&typeof r==="object"||typeof r==="function")rr(r).map((t)=>!nr.call(n,t)&&I(n,t,{get:()=>r[t],enumerable:!(e=vr(r,t))||e.enumerable}));return P.set(r,n),n},rn=(r,n)=>()=>(n||r((n={exports:{}}).exports,n),n.exports);var nn=(r,n)=>{for(var e in n)I(r,e,{get:n[e],enumerable:!0,configurable:!0,set:(t)=>n[e]=()=>t})};var j=rn((Tn,K)=>{var A=process||{},or=A.argv||[],$=A.env||{},tn=!(!!$.NO_COLOR||or.includes("--no-color"))&&(!!$.FORCE_COLOR||or.includes("--color")||A.platform==="win32"||(A.stdout||{}).isTTY&&$.TERM!=="dumb"||!!$.CI),en=(r,n,e=r)=>(t)=>{let o=""+t,i=o.indexOf(n,r.length);return~i?r+on(o,n,e,i)+n:r+o+n},on=(r,n,e,t)=>{let o="",i=0;do o+=r.substring(i,t)+e,i=t+n.length,t=r.indexOf(n,i);while(~t);return o+r.substring(i)},ir=(r=tn)=>{let n=r?en:()=>String;return{isColorSupported:r,reset:n("\x1B[0m","\x1B[0m"),bold:n("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:n("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:n("\x1B[3m","\x1B[23m"),underline:n("\x1B[4m","\x1B[24m"),inverse:n("\x1B[7m","\x1B[27m"),hidden:n("\x1B[8m","\x1B[28m"),strikethrough:n("\x1B[9m","\x1B[29m"),black:n("\x1B[30m","\x1B[39m"),red:n("\x1B[31m","\x1B[39m"),green:n("\x1B[32m","\x1B[39m"),yellow:n("\x1B[33m","\x1B[39m"),blue:n("\x1B[34m","\x1B[39m"),magenta:n("\x1B[35m","\x1B[39m"),cyan:n("\x1B[36m","\x1B[39m"),white:n("\x1B[37m","\x1B[39m"),gray:n("\x1B[90m","\x1B[39m"),bgBlack:n("\x1B[40m","\x1B[49m"),bgRed:n("\x1B[41m","\x1B[49m"),bgGreen:n("\x1B[42m","\x1B[49m"),bgYellow:n("\x1B[43m","\x1B[49m"),bgBlue:n("\x1B[44m","\x1B[49m"),bgMagenta:n("\x1B[45m","\x1B[49m"),bgCyan:n("\x1B[46m","\x1B[49m"),bgWhite:n("\x1B[47m","\x1B[49m"),blackBright:n("\x1B[90m","\x1B[39m"),redBright:n("\x1B[91m","\x1B[39m"),greenBright:n("\x1B[92m","\x1B[39m"),yellowBright:n("\x1B[93m","\x1B[39m"),blueBright:n("\x1B[94m","\x1B[39m"),magentaBright:n("\x1B[95m","\x1B[39m"),cyanBright:n("\x1B[96m","\x1B[39m"),whiteBright:n("\x1B[97m","\x1B[39m"),bgBlackBright:n("\x1B[100m","\x1B[49m"),bgRedBright:n("\x1B[101m","\x1B[49m"),bgGreenBright:n("\x1B[102m","\x1B[49m"),bgYellowBright:n("\x1B[103m","\x1B[49m"),bgBlueBright:n("\x1B[104m","\x1B[49m"),bgMagentaBright:n("\x1B[105m","\x1B[49m"),bgCyanBright:n("\x1B[106m","\x1B[49m"),bgWhiteBright:n("\x1B[107m","\x1B[49m")}};K.exports=ir();K.exports.createColors=ir});var hn={};nn(hn,{defineWorkspace:()=>er,defineConfig:()=>tr,build:()=>Xr});module.exports=Pr(hn);function tr(r){return r}function er(r){return r}var Rr=require("rolldown"),Tr=require("rolldown-plugin-dts");var sn=d(j());var c=d(j()),sr=!1;function ur(r){sr=r??!1}class h{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;cliColor=c.default.blue;mutedColor=c.default.dim;infoColor=c.default.cyan;warnColor=c.default.yellow;errorColor=c.default.red;defaultColor=c.default.white;progressFgColorMap={ESM:c.default.yellow,CJS:c.default.green,IIFE:c.default.magenta,DTS:c.default.blue};progressBgColorMap={ESM:c.default.bgYellow,CJS:c.default.bgGreen,IIFE:c.default.bgMagenta,DTS:c.default.bgBlue};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(r){if(!r?.once)return!0;if(this.loggedOnceMessages.has(r.once))return!1;return this.loggedOnceMessages.add(r.once),!0}formatMessage({fgColor:r,bgColor:n,label:e,message:t,identifier:o,muted:i}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length)),m=i?this.mutedColor(t):t,u=o?` ${n(c.default.black(` ${o} `))}`:"";return`${r(e)} ${s}${m}${u}`}output(r,n={},e=console.log){if(sr||!this.shouldLog(n))return;if(n.verticalSpace)e("");if(e(r),n.verticalSpace)e("")}cli(r,n={}){let e=this.formatMessage({fgColor:this.cliColor,bgColor:c.default.bgBlue,label:this.labels.cli,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}info(r,n={}){let e=this.formatMessage({fgColor:this.infoColor,bgColor:c.default.bgCyan,label:this.labels.info,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}warn(r,n={}){let e=this.formatMessage({fgColor:this.warnColor,bgColor:c.default.bgYellow,label:this.labels.warn,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.warn)}error(r,n={}){let e=this.formatMessage({fgColor:this.errorColor,bgColor:c.default.bgRed,label:this.labels.error,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.error)}getProgressFgColor(r){for(let[n,e]of Object.entries(this.progressFgColorMap))if(r.includes(n))return e;return this.defaultColor}getProgressBgColor(r){for(let[n,e]of Object.entries(this.progressBgColorMap))if(r.includes(n))return e;return c.default.bgWhite}progress(r,n,e={}){let t=this.getProgressFgColor(r),o=this.getProgressBgColor(r),i=this.formatMessage({fgColor:t,bgColor:o,label:r,message:n,identifier:e.identifier,muted:e.muted});this.output(i,e)}}var p=h.getInstance();class D extends Error{constructor(r){super(r);this.name="BunupError"}}class O extends D{constructor(r){super(r);this.name="BunupBuildError"}}class f extends D{constructor(r){super(r);this.name="BunupDTSBuildError"}}class W extends D{constructor(r){super(r);this.name="BunupIsolatedDeclError"}}var C=(r)=>{if(r instanceof Error)return r.message;return String(r)};function gr(r){return r instanceof W}var z=d(require("path")),hr=require("oxc-resolver");var q=d(require("fs/promises")),mr=d(require("path"));function cr(r,n){switch(r){case"esm":return R(n)?".js":".mjs";case"cjs":return R(n)?".cjs":".js";case"iife":return".global.js"}}function br(r,n){switch(r){case"esm":return R(n)?".d.ts":".d.mts";case"cjs":return R(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function G(r){return r==="node"||r==="bun"}function R(r){return r==="module"}function ar(r){if(!r)return[];return Array.from(new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.peerDependencies||{})]))}function L(r,n=3){return r.split("/").slice(-n).join("/")}async function xr(r,n){let e=mr.default.join(r,n);try{await q.default.rm(e,{recursive:!0,force:!0})}catch(t){throw new O(`Failed to clean output directory: ${t}`)}await q.default.mkdir(e,{recursive:!0})}function _(r){return[".ts",".mts",".cts",".tsx"].some((n)=>r.endsWith(n))}function un(r){return ar(r).map((n)=>new RegExp(`^${n}($|\\/|\\\\)`))}function pr(r,n){return typeof n==="string"?n===r:n.test(r)}function U(r,n,e){let o=un(e).some((s)=>s.test(r))||n.external?.some((s)=>pr(r,s)),i=n.noExternal?.some((s)=>pr(r,s));return o&&!i}var fr=require("ts-import-resolver");var M="\x00dts:",lr=(r,n,e)=>{return{name:"bunup:virtual-dts",async resolveId(t,o){if(H(t))return t;if(!o||!H(o))return null;let i=n.tsconfig?fr.resolveTsImportPath({path:t,importer:k(o),tsconfig:n.tsconfig,rootDir:e}):null;if(!i)return null;let s=B(i);if(r.has(s))return Y(s);return null},load(t){if(t.startsWith(M)){let o=k(t),i=r.get(o);if(i)return i}return null}}};var Q=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function dr(r){return r.endsWith(".d.ts")||r.endsWith(".d.mts")||r.endsWith(".d.cts")}function Cr(r){return Q.test(r)&&!dr(r)}function B(r){if(dr(r))return r;if(r.endsWith(".mts"))return`${r.slice(0,-4)}.d.mts`;if(r.endsWith(".cts"))return`${r.slice(0,-4)}.d.cts`;if(Q.test(r))return r.replace(Q,".d.ts");return`${r}.d.ts`}function H(r){return r.startsWith(M)}function k(r){return r.replace(M,"")}function Y(r){return`${M}${r}`}function Br(r,n){if(n===void 0)return"";let e=r.slice(0,n).split(`
|
|
3
|
+
`),t=e.length,o=e[e.length-1].length+1;return` (${t}:${o})`}function wr(r,n,e,t){if(typeof t==="boolean"&&t)return!1;if(Array.isArray(t)){for(let o of t)if(typeof o==="string"&&r===o)return!1;else if(o instanceof RegExp&&o.test(r))return!1}return U(r,n,e)}var Z;function Or(r,n){return{name:"bunup:types-resolve",buildStart(){Z||=new hr.ResolverFactory({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...r.path&&{tsconfig:{configFile:r.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(e,t){if(n===!1)return;if(e==="bun")return;let o=t?k(t):void 0;if(/\0/.test(e))return;if(Array.isArray(n)){if(!n.some((u)=>typeof u==="string"?u===e:u.test(e)))return}let i=o?z.default.dirname(o):process.cwd(),{path:s}=await Z.async(i,e);if(!s)return;if(Cr(s)){let m=B(s);try{let{path:u}=await Z.async(z.default.dirname(s),m);if(u)return u}catch(u){}return}return s}}}async function Sr(r,n,e,t,o,i){let s=B(r),m=Y(s),u=typeof e.dts==="object"&&"resolve"in e.dts?e.dts.resolve:void 0;try{let{output:g}=await Rr.build({input:m,output:{dir:e.outDir},write:!1,...o.path&&{resolve:{tsconfigFilename:o.path}},onwarn(x,a){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(x.code??""))return;a(x)},plugins:[lr(n,o,i),u&&Or(o,u),Tr.dts({dtsInput:!0,emitDtsOnly:!0})],external:(x)=>wr(x,e,t,u)});if(!g[0]?.code)return p.warn(`Generated empty declaration file for entry "${r}"`,{muted:!0}),"";return g[0].code}catch(g){throw new f(`DTS bundling failed for entry "${r}": ${C(g)}`)}}var Ir=require("ts-import-resolver");var gn=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,mn=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,cn=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,bn=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,an=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,xn=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,pn=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function fn(r){let n=new Set,e=[gn,mn,cn,bn,an,xn,pn];for(let t of e){let o=r.matchAll(t);for(let i of o)if(i[1])n.add(i[1])}return n}async function Lr(r,n,e){let t=new Set([r]),o=[r];while(o.length){let i=o.pop();if(!i)continue;try{let s=await Bun.file(i).text(),m=fn(s);for(let u of m){let g=n.tsconfig?Ir.resolveTsImportPath({path:u,importer:i,tsconfig:n.tsconfig,rootDir:e}):null;if(!g)continue;if(!t.has(g))t.add(g),o.push(g)}}catch(s){p.warn(`Error processing ${i}: ${C(s)}`)}}return t}var kr=require("oxc-transform"),V=d(j());async function Mr(r,n){let e=!1,t=new Map;if(await Promise.all([...r].map(async(o)=>{try{let i=B(o);if(!await Bun.file(o).exists())return;let m=await Bun.file(o).text(),{code:u,errors:g}=kr.isolatedDeclaration(o,m);if(u)t.set(i,u);for(let x of g){if(!e&&!n)console.log(`
|
|
4
|
+
`);let a=x.labels[0],b=a?Br(m,a.start):"",w=`${L(o)}${b}: ${ln(x.message)}`;p[n?"warn":"error"](w),e=!0}}catch(i){p.warn(`Failed to generate declaration for ${o}: ${C(i)}`)}})),e&&!n)throw console.log(`
|
|
5
|
+
`),new W(`TypeScript is asking for explicit type annotations on your exports. This helps ensure better, more reliable type declarations for your library. Bunup uses TypeScript's ${V.default.blue("isolatedDeclarations")} feature to generate these declarations, which requires each export from your library to be fully typed. You can learn more here: ${V.default.blue("https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-5.html#isolated-declarations")}`);return t}function ln(r){return r.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}var X=d(require("fs/promises")),F=d(require("path"));async function Er(r,n){let e=F.default.resolve(r),t=F.default.resolve(e,n);if(!await X.default.exists(e))throw new f(`Root directory does not exist: ${e}`);if(!await Bun.file(t).exists())throw new f(`Entry file does not exist: ${t}`);if(!_(t))throw new f(`Entry file must be a TypeScript file: ${t}`);if(F.default.relative(e,t).startsWith(".."))throw new f(`Entry file must be within rootDir: ${t}`);return{absoluteRootDir:e,absoluteEntry:t}}async function yr(r,n,e,t,o){let{absoluteEntry:i}=await Er(r,n),s=await Lr(i,t,r),m=await Mr(s,e.watch);return Sr(i,m,e,o,t,r)}var T=require("path");function $r(r){let n=T.basename(r),e=T.extname(n);return e?n.slice(0,-e.length):n}function N(r){if(typeof r==="string")return[{fullEntryPath:r,name:$r(r)}];if(typeof r==="object"&&!Array.isArray(r))return Object.entries(r).map(([t,o])=>({fullEntryPath:o,name:t}));let n=[],e=new Set;for(let t of r){let o=$r(t);if(!e.has(o)){n.push({fullEntryPath:t,name:o}),e.add(o);continue}let s=T.dirname(t).split("/").filter((u)=>u!=="."&&u!=="");if(s.length===0){let u=1,g;do g=`${o}_${u++}`;while(e.has(g));n.push({fullEntryPath:t,name:g}),e.add(g);continue}let m=!1;for(let u=1;u<=s.length&&!m;u++){let x=`${s.slice(-u).join("/")}/${o}`;if(!e.has(x))n.push({fullEntryPath:t,name:x}),e.add(x),m=!0}if(!m){let u=1,g;do g=`${s.join("/")}/${o}_${u++}`;while(e.has(g));n.push({fullEntryPath:t,name:g}),e.add(g)}}return n}function Ar(r){return r.filter((n)=>_(n.fullEntryPath))}function jr(r,n){return`[dir]/${r}${n}`}var J=require("coffi");async function Dr(r){let{config:n,filepath:e}=await J.loadConfig({name:"package",cwd:r,extensions:[".json"]});return{packageJson:n,path:e}}async function Wr(r,n){let{config:e,filepath:t}=await J.loadConfig({name:"tsconfig",cwd:r,extensions:[".json"],preferredPath:n});return{tsconfig:e,path:t}}var dn={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function _r(r){return{...dn,...r}}function Ur(r){let{minify:n,minifyWhitespace:e,minifyIdentifiers:t,minifySyntax:o}=r,i=n===!0;return{whitespace:e??i,identifiers:t??i,syntax:o??i}}function Yr(r,n){return n==="cjs"?r:void 0}function Fr(r,n,e,t){return{...typeof e==="object"&&Object.keys(e).reduce((o,i)=>{let s=JSON.stringify(e[i]);return o[`process.env.${i}`]=s,o[`import.meta.env.${i}`]=s,o},{}),...r,...t==="cjs"&&(n===!0||typeof n==="object"&&n.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Kr(r,n){return r===void 0?n==="esm":r}function qr(r){return typeof r==="string"?r:void 0}function Gr(r,n){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},(t)=>{let o=t.path;if(U(o,r,n))return{path:o,external:!0};return null})}}}var Cn=/\.(js|ts|jsx|tsx|mts|cts)$/,v={dirnameFilename:{appliesTo:(r,n)=>r==="esm"&&G(n),isNeededInFile:(r)=>/\b__dirname\b/.test(r)||/\b__filename\b/.test(r),generateCode:()=>`import { fileURLToPath } from 'url';
|
|
5
6
|
import { dirname } from 'path';
|
|
6
7
|
|
|
7
8
|
const __filename = fileURLToPath(import.meta.url);
|
|
8
9
|
const __dirname = dirname(__filename);
|
|
9
10
|
|
|
10
|
-
`},importMetaUrl:{appliesTo:(r,n)=>r==="cjs"&&
|
|
11
|
+
`},importMetaUrl:{appliesTo:(r,n)=>r==="cjs"&&G(n),isNeededInFile:(r)=>/\bimport\.meta\.url\b/.test(r),generateCode:()=>`import { pathToFileURL } from 'url';
|
|
11
12
|
|
|
12
13
|
const importMetaUrl = pathToFileURL(__filename).href;
|
|
13
14
|
|
|
14
|
-
`}};function Hr({format:r,target:n,shims:
|
|
15
|
-
`);return n===-1?{shebangLine:"",codeContent:r}:{shebangLine:r.slice(0,n+1),codeContent:r.slice(n+1)}}function
|
|
15
|
+
`}};function Hr({format:r,target:n,shims:e}){let o=Bn(e).map((i)=>v[i]).filter((i)=>i.appliesTo(r,n));if(o.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(i){i.onLoad({filter:Cn},async({path:s})=>{let m=await Bun.file(s).text(),u=o.filter((b)=>b.isNeededInFile(m));if(u.length===0)return;let{shebangLine:g,codeContent:x}=wn(m),a=u.map((b)=>b.generateCode()).join("");return{contents:g+a+x}})}}}function Bn(r){if(r===!0)return Object.keys(v);if(!r)return[];return Object.entries(r).filter(([n,e])=>e&&(n in v)).map(([n])=>n)}function wn(r){if(!r.startsWith("#!"))return{shebangLine:"",codeContent:r};let n=r.indexOf(`
|
|
16
|
+
`);return n===-1?{shebangLine:"",codeContent:r}:{shebangLine:r.slice(0,n+1),codeContent:r.slice(n+1)}}function Qr(r){if(!r)return[];return r.filter((n)=>n.type==="bun")}function Zr(r){if(!r)return[];return r.filter((n)=>n.type==="bunup")}async function zr(r,n){if(!r)return;for(let e of r)if(e.hooks.onBuildStart)await e.hooks.onBuildStart(n)}async function Vr(r,n,e){if(!r)return;for(let t of r)if(t.hooks.onBuildDone)await t.hooks.onBuildDone({options:n,output:e})}async function Xr(r,n=process.cwd()){let e={files:[]},t=_r(r);if(!t.entry||t.entry.length===0||!t.outDir)throw new O("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)xr(n,t.outDir);ur(t.silent);let{packageJson:o,path:i}=await Dr(n);if(o&&i)p.cli(`Using package.json: ${L(i,2)}`,{muted:!0,identifier:t.name,once:`${i}:${t.name}`});let s=Zr(t.plugins);await zr(s,t);let m=N(t.entry),u=o?.type;if(!t.dtsOnly){let g=[Gr(t,o),...Qr(t.plugins).map((a)=>a.plugin)],x=t.format.flatMap((a)=>m.map(async(b)=>{let S=t.outputExtension?.({format:a,packageType:u,options:t,entry:b}).js??cr(a,u),w=await Bun.build({entrypoints:[`${n}/${b.fullEntryPath}`],format:a,naming:{entry:jr(b.name,S)},splitting:Kr(t.splitting,a),bytecode:Yr(t.bytecode,a),define:Fr(t.define,t.shims,t.env,a),minify:Ur(t),outdir:`${n}/${t.outDir}`,target:t.target,sourcemap:t.sourcemap,loader:t.loader,drop:t.drop,banner:t.banner,footer:t.footer,publicPath:t.publicPath,env:qr(t.env),plugins:[...g,Hr({format:a,target:t.target,shims:t.shims})],throw:!1});if(!w.success)for(let l of w.logs){if(l.level==="error")throw new O(l.message);if(l.level==="warning")p.warn(l.message);else if(l.level==="info")p.info(l.message)}let E=`${t.outDir}/${b.name}${S}`,y=`${n}/${E}`;e.files.push({path:y}),p.progress(a.toUpperCase(),E,{identifier:t.name})}));await Promise.all(x)}if(t.dts||t.dtsOnly){let g=await Wr(n,t.preferredTsconfigPath);if(g.path)p.cli(`Using tsconfig: ${L(g.path,2)}`,{muted:!0,identifier:t.name,once:`${g.path}:${t.name}`});let x=t.format.filter((b)=>{if(b==="iife"&&!R(u)&&t.format.includes("cjs"))return!1;return!0}),a=typeof t.dts==="object"&&t.dts.entry?N(t.dts.entry):Ar(m);try{await Promise.all(a.map(async(b)=>{let S=await yr(n,b.fullEntryPath,t,g,o);await Promise.all(x.map(async(w)=>{let E=t.outputExtension?.({format:w,packageType:u,options:t,entry:b}).dts??br(w,u),y=`${t.outDir}/${b.name}${E}`,l=`${n}/${y}`;e.files.push({path:l}),await Bun.write(l,S),p.progress("DTS",y,{identifier:t.name})}))}))}catch(b){if(gr(b))throw b;throw new f(C(b))}}if(await Vr(s,t,e),t.onSuccess)await t.onSuccess(t)}})
|
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`),e
|
|
4
|
-
`);let x
|
|
2
|
+
var Wr=Object.create;var{getPrototypeOf:_r,defineProperty:z,getOwnPropertyNames:Ur}=Object;var Yr=Object.prototype.hasOwnProperty;var _=(r,n,e)=>{e=r!=null?Wr(_r(r)):{};let t=n||!r||!r.__esModule?z(e,"default",{value:r,enumerable:!0}):e;for(let o of Ur(r))if(!Yr.call(t,o))z(t,o,{get:()=>r[o],enumerable:!0});return t};var Fr=(r,n)=>()=>(n||r((n={exports:{}}).exports,n),n.exports);var y=Fr((hn,U)=>{var E=process||{},V=E.argv||[],M=E.env||{},Gr=!(!!M.NO_COLOR||V.includes("--no-color"))&&(!!M.FORCE_COLOR||V.includes("--color")||E.platform==="win32"||(E.stdout||{}).isTTY&&M.TERM!=="dumb"||!!M.CI),Hr=(r,n,e=r)=>(t)=>{let o=""+t,i=o.indexOf(n,r.length);return~i?r+Qr(o,n,e,i)+n:r+o+n},Qr=(r,n,e,t)=>{let o="",i=0;do o+=r.substring(i,t)+e,i=t+n.length,t=r.indexOf(n,i);while(~t);return o+r.substring(i)},X=(r=Gr)=>{let n=r?Hr:()=>String;return{isColorSupported:r,reset:n("\x1B[0m","\x1B[0m"),bold:n("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:n("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:n("\x1B[3m","\x1B[23m"),underline:n("\x1B[4m","\x1B[24m"),inverse:n("\x1B[7m","\x1B[27m"),hidden:n("\x1B[8m","\x1B[28m"),strikethrough:n("\x1B[9m","\x1B[29m"),black:n("\x1B[30m","\x1B[39m"),red:n("\x1B[31m","\x1B[39m"),green:n("\x1B[32m","\x1B[39m"),yellow:n("\x1B[33m","\x1B[39m"),blue:n("\x1B[34m","\x1B[39m"),magenta:n("\x1B[35m","\x1B[39m"),cyan:n("\x1B[36m","\x1B[39m"),white:n("\x1B[37m","\x1B[39m"),gray:n("\x1B[90m","\x1B[39m"),bgBlack:n("\x1B[40m","\x1B[49m"),bgRed:n("\x1B[41m","\x1B[49m"),bgGreen:n("\x1B[42m","\x1B[49m"),bgYellow:n("\x1B[43m","\x1B[49m"),bgBlue:n("\x1B[44m","\x1B[49m"),bgMagenta:n("\x1B[45m","\x1B[49m"),bgCyan:n("\x1B[46m","\x1B[49m"),bgWhite:n("\x1B[47m","\x1B[49m"),blackBright:n("\x1B[90m","\x1B[39m"),redBright:n("\x1B[91m","\x1B[39m"),greenBright:n("\x1B[92m","\x1B[39m"),yellowBright:n("\x1B[93m","\x1B[39m"),blueBright:n("\x1B[94m","\x1B[39m"),magentaBright:n("\x1B[95m","\x1B[39m"),cyanBright:n("\x1B[96m","\x1B[39m"),whiteBright:n("\x1B[97m","\x1B[39m"),bgBlackBright:n("\x1B[100m","\x1B[49m"),bgRedBright:n("\x1B[101m","\x1B[49m"),bgGreenBright:n("\x1B[102m","\x1B[49m"),bgYellowBright:n("\x1B[103m","\x1B[49m"),bgBlueBright:n("\x1B[104m","\x1B[49m"),bgMagentaBright:n("\x1B[105m","\x1B[49m"),bgCyanBright:n("\x1B[106m","\x1B[49m"),bgWhiteBright:n("\x1B[107m","\x1B[49m")}};U.exports=X();U.exports.createColors=X});function Kr(r){return r}function qr(r){return r}import{build as Jr}from"rolldown";import{dts as vr}from"rolldown-plugin-dts";var Zr=_(y(),1);var c=_(y(),1),N=!1;function J(r){N=r??!1}class w{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;cliColor=c.default.blue;mutedColor=c.default.dim;infoColor=c.default.cyan;warnColor=c.default.yellow;errorColor=c.default.red;defaultColor=c.default.white;progressFgColorMap={ESM:c.default.yellow,CJS:c.default.green,IIFE:c.default.magenta,DTS:c.default.blue};progressBgColorMap={ESM:c.default.bgYellow,CJS:c.default.bgGreen,IIFE:c.default.bgMagenta,DTS:c.default.bgBlue};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!w.instance)w.instance=new w;return w.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(r){if(!r?.once)return!0;if(this.loggedOnceMessages.has(r.once))return!1;return this.loggedOnceMessages.add(r.once),!0}formatMessage({fgColor:r,bgColor:n,label:e,message:t,identifier:o,muted:i}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length)),m=i?this.mutedColor(t):t,u=o?` ${n(c.default.black(` ${o} `))}`:"";return`${r(e)} ${s}${m}${u}`}output(r,n={},e=console.log){if(N||!this.shouldLog(n))return;if(n.verticalSpace)e("");if(e(r),n.verticalSpace)e("")}cli(r,n={}){let e=this.formatMessage({fgColor:this.cliColor,bgColor:c.default.bgBlue,label:this.labels.cli,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}info(r,n={}){let e=this.formatMessage({fgColor:this.infoColor,bgColor:c.default.bgCyan,label:this.labels.info,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}warn(r,n={}){let e=this.formatMessage({fgColor:this.warnColor,bgColor:c.default.bgYellow,label:this.labels.warn,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.warn)}error(r,n={}){let e=this.formatMessage({fgColor:this.errorColor,bgColor:c.default.bgRed,label:this.labels.error,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.error)}getProgressFgColor(r){for(let[n,e]of Object.entries(this.progressFgColorMap))if(r.includes(n))return e;return this.defaultColor}getProgressBgColor(r){for(let[n,e]of Object.entries(this.progressBgColorMap))if(r.includes(n))return e;return c.default.bgWhite}progress(r,n,e={}){let t=this.getProgressFgColor(r),o=this.getProgressBgColor(r),i=this.formatMessage({fgColor:t,bgColor:o,label:r,message:n,identifier:e.identifier,muted:e.muted});this.output(i,e)}}var p=w.getInstance();class $ extends Error{constructor(r){super(r);this.name="BunupError"}}class h extends ${constructor(r){super(r);this.name="BunupBuildError"}}class f extends ${constructor(r){super(r);this.name="BunupDTSBuildError"}}class A extends ${constructor(r){super(r);this.name="BunupIsolatedDeclError"}}var d=(r)=>{if(r instanceof Error)return r.message;return String(r)};function v(r){return r instanceof A}import cr from"path";import{ResolverFactory as Nr}from"oxc-resolver";import P from"fs/promises";import zr from"path";function rr(r,n){switch(r){case"esm":return O(n)?".js":".mjs";case"cjs":return O(n)?".cjs":".js";case"iife":return".global.js"}}function nr(r,n){switch(r){case"esm":return O(n)?".d.ts":".d.mts";case"cjs":return O(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function Y(r){return r==="node"||r==="bun"}function O(r){return r==="module"}function tr(r){if(!r)return[];return Array.from(new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.peerDependencies||{})]))}function T(r,n=3){return r.split("/").slice(-n).join("/")}async function er(r,n){let e=zr.join(r,n);try{await P.rm(e,{recursive:!0,force:!0})}catch(t){throw new h(`Failed to clean output directory: ${t}`)}await P.mkdir(e,{recursive:!0})}function j(r){return[".ts",".mts",".cts",".tsx"].some((n)=>r.endsWith(n))}function Vr(r){return tr(r).map((n)=>new RegExp(`^${n}($|\\/|\\\\)`))}function or(r,n){return typeof n==="string"?n===r:n.test(r)}function D(r,n,e){let o=Vr(e).some((s)=>s.test(r))||n.external?.some((s)=>or(r,s)),i=n.noExternal?.some((s)=>or(r,s));return o&&!i}import{resolveTsImportPath as Xr}from"ts-import-resolver";var I="\x00dts:",ir=(r,n,e)=>{return{name:"bunup:virtual-dts",async resolveId(t,o){if(F(t))return t;if(!o||!F(o))return null;let i=n.tsconfig?Xr({path:t,importer:S(o),tsconfig:n.tsconfig,rootDir:e}):null;if(!i)return null;let s=C(i);if(r.has(s))return W(s);return null},load(t){if(t.startsWith(I)){let o=S(t),i=r.get(o);if(i)return i}return null}}};var K=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function sr(r){return r.endsWith(".d.ts")||r.endsWith(".d.mts")||r.endsWith(".d.cts")}function ur(r){return K.test(r)&&!sr(r)}function C(r){if(sr(r))return r;if(r.endsWith(".mts"))return`${r.slice(0,-4)}.d.mts`;if(r.endsWith(".cts"))return`${r.slice(0,-4)}.d.cts`;if(K.test(r))return r.replace(K,".d.ts");return`${r}.d.ts`}function F(r){return r.startsWith(I)}function S(r){return r.replace(I,"")}function W(r){return`${I}${r}`}function gr(r,n){if(n===void 0)return"";let e=r.slice(0,n).split(`
|
|
3
|
+
`),t=e.length,o=e[e.length-1].length+1;return` (${t}:${o})`}function mr(r,n,e,t){if(typeof t==="boolean"&&t)return!1;if(Array.isArray(t)){for(let o of t)if(typeof o==="string"&&r===o)return!1;else if(o instanceof RegExp&&o.test(r))return!1}return D(r,n,e)}var q;function br(r,n){return{name:"bunup:types-resolve",buildStart(){q||=new Nr({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...r.path&&{tsconfig:{configFile:r.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(e,t){if(n===!1)return;if(e==="bun")return;let o=t?S(t):void 0;if(/\0/.test(e))return;if(Array.isArray(n)){if(!n.some((u)=>typeof u==="string"?u===e:u.test(e)))return}let i=o?cr.dirname(o):process.cwd(),{path:s}=await q.async(i,e);if(!s)return;if(ur(s)){let m=C(s);try{let{path:u}=await q.async(cr.dirname(s),m);if(u)return u}catch(u){}return}return s}}}async function ar(r,n,e,t,o,i){let s=C(r),m=W(s),u=typeof e.dts==="object"&&"resolve"in e.dts?e.dts.resolve:void 0;try{let{output:g}=await Jr({input:m,output:{dir:e.outDir},write:!1,...o.path&&{resolve:{tsconfigFilename:o.path}},onwarn(x,a){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(x.code??""))return;a(x)},plugins:[ir(n,o,i),u&&br(o,u),vr({dtsInput:!0,emitDtsOnly:!0})],external:(x)=>mr(x,e,t,u)});if(!g[0]?.code)return p.warn(`Generated empty declaration file for entry "${r}"`,{muted:!0}),"";return g[0].code}catch(g){throw new f(`DTS bundling failed for entry "${r}": ${d(g)}`)}}import{resolveTsImportPath as Pr}from"ts-import-resolver";var rn=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,nn=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,tn=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,en=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,on=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,sn=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,un=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function gn(r){let n=new Set,e=[rn,nn,tn,en,on,sn,un];for(let t of e){let o=r.matchAll(t);for(let i of o)if(i[1])n.add(i[1])}return n}async function xr(r,n,e){let t=new Set([r]),o=[r];while(o.length){let i=o.pop();if(!i)continue;try{let s=await Bun.file(i).text(),m=gn(s);for(let u of m){let g=n.tsconfig?Pr({path:u,importer:i,tsconfig:n.tsconfig,rootDir:e}):null;if(!g)continue;if(!t.has(g))t.add(g),o.push(g)}}catch(s){p.warn(`Error processing ${i}: ${d(s)}`)}}return t}var G=_(y(),1);import{isolatedDeclaration as mn}from"oxc-transform";async function pr(r,n){let e=!1,t=new Map;if(await Promise.all([...r].map(async(o)=>{try{let i=C(o);if(!await Bun.file(o).exists())return;let m=await Bun.file(o).text(),{code:u,errors:g}=mn(o,m);if(u)t.set(i,u);for(let x of g){if(!e&&!n)console.log(`
|
|
4
|
+
`);let a=x.labels[0],b=a?gr(m,a.start):"",B=`${T(o)}${b}: ${cn(x.message)}`;p[n?"warn":"error"](B),e=!0}}catch(i){p.warn(`Failed to generate declaration for ${o}: ${d(i)}`)}})),e&&!n)throw console.log(`
|
|
5
|
+
`),new A(`TypeScript is asking for explicit type annotations on your exports. This helps ensure better, more reliable type declarations for your library. Bunup uses TypeScript's ${G.default.blue("isolatedDeclarations")} feature to generate these declarations, which requires each export from your library to be fully typed. You can learn more here: ${G.default.blue("https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-5.html#isolated-declarations")}`);return t}function cn(r){return r.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}import fr from"fs/promises";import H from"path";async function lr(r,n){let e=H.resolve(r),t=H.resolve(e,n);if(!await fr.exists(e))throw new f(`Root directory does not exist: ${e}`);if(!await Bun.file(t).exists())throw new f(`Entry file does not exist: ${t}`);if(!j(t))throw new f(`Entry file must be a TypeScript file: ${t}`);if(H.relative(e,t).startsWith(".."))throw new f(`Entry file must be within rootDir: ${t}`);return{absoluteRootDir:e,absoluteEntry:t}}async function dr(r,n,e,t,o){let{absoluteEntry:i}=await lr(r,n),s=await xr(i,t,r),m=await pr(s,e.watch);return ar(i,m,e,o,t,r)}import{basename as bn,dirname as an,extname as xn}from"path";function Cr(r){let n=bn(r),e=xn(n);return e?n.slice(0,-e.length):n}function Q(r){if(typeof r==="string")return[{fullEntryPath:r,name:Cr(r)}];if(typeof r==="object"&&!Array.isArray(r))return Object.entries(r).map(([t,o])=>({fullEntryPath:o,name:t}));let n=[],e=new Set;for(let t of r){let o=Cr(t);if(!e.has(o)){n.push({fullEntryPath:t,name:o}),e.add(o);continue}let s=an(t).split("/").filter((u)=>u!=="."&&u!=="");if(s.length===0){let u=1,g;do g=`${o}_${u++}`;while(e.has(g));n.push({fullEntryPath:t,name:g}),e.add(g);continue}let m=!1;for(let u=1;u<=s.length&&!m;u++){let x=`${s.slice(-u).join("/")}/${o}`;if(!e.has(x))n.push({fullEntryPath:t,name:x}),e.add(x),m=!0}if(!m){let u=1,g;do g=`${s.join("/")}/${o}_${u++}`;while(e.has(g));n.push({fullEntryPath:t,name:g}),e.add(g)}}return n}function Br(r){return r.filter((n)=>j(n.fullEntryPath))}function wr(r,n){return`[dir]/${r}${n}`}import{loadConfig as hr}from"coffi";async function Or(r){let{config:n,filepath:e}=await hr({name:"package",cwd:r,extensions:[".json"]});return{packageJson:n,path:e}}async function Rr(r,n){let{config:e,filepath:t}=await hr({name:"tsconfig",cwd:r,extensions:[".json"],preferredPath:n});return{tsconfig:e,path:t}}var pn={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function Tr(r){return{...pn,...r}}function Sr(r){let{minify:n,minifyWhitespace:e,minifyIdentifiers:t,minifySyntax:o}=r,i=n===!0;return{whitespace:e??i,identifiers:t??i,syntax:o??i}}function Ir(r,n){return n==="cjs"?r:void 0}function Lr(r,n,e,t){return{...typeof e==="object"&&Object.keys(e).reduce((o,i)=>{let s=JSON.stringify(e[i]);return o[`process.env.${i}`]=s,o[`import.meta.env.${i}`]=s,o},{}),...r,...t==="cjs"&&(n===!0||typeof n==="object"&&n.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function kr(r,n){return r===void 0?n==="esm":r}function Mr(r){return typeof r==="string"?r:void 0}function Er(r,n){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},(t)=>{let o=t.path;if(D(o,r,n))return{path:o,external:!0};return null})}}}var fn=/\.(js|ts|jsx|tsx|mts|cts)$/,Z={dirnameFilename:{appliesTo:(r,n)=>r==="esm"&&Y(n),isNeededInFile:(r)=>/\b__dirname\b/.test(r)||/\b__filename\b/.test(r),generateCode:()=>`import { fileURLToPath } from 'url';
|
|
5
6
|
import { dirname } from 'path';
|
|
6
7
|
|
|
7
8
|
const __filename = fileURLToPath(import.meta.url);
|
|
8
9
|
const __dirname = dirname(__filename);
|
|
9
10
|
|
|
10
|
-
`},importMetaUrl:{appliesTo:(r,n)=>r==="cjs"&&
|
|
11
|
+
`},importMetaUrl:{appliesTo:(r,n)=>r==="cjs"&&Y(n),isNeededInFile:(r)=>/\bimport\.meta\.url\b/.test(r),generateCode:()=>`import { pathToFileURL } from 'url';
|
|
11
12
|
|
|
12
13
|
const importMetaUrl = pathToFileURL(__filename).href;
|
|
13
14
|
|
|
14
|
-
`}};function
|
|
15
|
-
`);return n===-1?{shebangLine:"",codeContent:r}:{shebangLine:r.slice(0,n+1),codeContent:r.slice(n+1)}}function
|
|
15
|
+
`}};function yr({format:r,target:n,shims:e}){let o=ln(e).map((i)=>Z[i]).filter((i)=>i.appliesTo(r,n));if(o.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(i){i.onLoad({filter:fn},async({path:s})=>{let m=await Bun.file(s).text(),u=o.filter((b)=>b.isNeededInFile(m));if(u.length===0)return;let{shebangLine:g,codeContent:x}=dn(m),a=u.map((b)=>b.generateCode()).join("");return{contents:g+a+x}})}}}function ln(r){if(r===!0)return Object.keys(Z);if(!r)return[];return Object.entries(r).filter(([n,e])=>e&&(n in Z)).map(([n])=>n)}function dn(r){if(!r.startsWith("#!"))return{shebangLine:"",codeContent:r};let n=r.indexOf(`
|
|
16
|
+
`);return n===-1?{shebangLine:"",codeContent:r}:{shebangLine:r.slice(0,n+1),codeContent:r.slice(n+1)}}function $r(r){if(!r)return[];return r.filter((n)=>n.type==="bun")}function Ar(r){if(!r)return[];return r.filter((n)=>n.type==="bunup")}async function jr(r,n){if(!r)return;for(let e of r)if(e.hooks.onBuildStart)await e.hooks.onBuildStart(n)}async function Dr(r,n,e){if(!r)return;for(let t of r)if(t.hooks.onBuildDone)await t.hooks.onBuildDone({options:n,output:e})}async function Cn(r,n=process.cwd()){let e={files:[]},t=Tr(r);if(!t.entry||t.entry.length===0||!t.outDir)throw new h("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)er(n,t.outDir);J(t.silent);let{packageJson:o,path:i}=await Or(n);if(o&&i)p.cli(`Using package.json: ${T(i,2)}`,{muted:!0,identifier:t.name,once:`${i}:${t.name}`});let s=Ar(t.plugins);await jr(s,t);let m=Q(t.entry),u=o?.type;if(!t.dtsOnly){let g=[Er(t,o),...$r(t.plugins).map((a)=>a.plugin)],x=t.format.flatMap((a)=>m.map(async(b)=>{let R=t.outputExtension?.({format:a,packageType:u,options:t,entry:b}).js??rr(a,u),B=await Bun.build({entrypoints:[`${n}/${b.fullEntryPath}`],format:a,naming:{entry:wr(b.name,R)},splitting:kr(t.splitting,a),bytecode:Ir(t.bytecode,a),define:Lr(t.define,t.shims,t.env,a),minify:Sr(t),outdir:`${n}/${t.outDir}`,target:t.target,sourcemap:t.sourcemap,loader:t.loader,drop:t.drop,banner:t.banner,footer:t.footer,publicPath:t.publicPath,env:Mr(t.env),plugins:[...g,yr({format:a,target:t.target,shims:t.shims})],throw:!1});if(!B.success)for(let l of B.logs){if(l.level==="error")throw new h(l.message);if(l.level==="warning")p.warn(l.message);else if(l.level==="info")p.info(l.message)}let L=`${t.outDir}/${b.name}${R}`,k=`${n}/${L}`;e.files.push({path:k}),p.progress(a.toUpperCase(),L,{identifier:t.name})}));await Promise.all(x)}if(t.dts||t.dtsOnly){let g=await Rr(n,t.preferredTsconfigPath);if(g.path)p.cli(`Using tsconfig: ${T(g.path,2)}`,{muted:!0,identifier:t.name,once:`${g.path}:${t.name}`});let x=t.format.filter((b)=>{if(b==="iife"&&!O(u)&&t.format.includes("cjs"))return!1;return!0}),a=typeof t.dts==="object"&&t.dts.entry?Q(t.dts.entry):Br(m);try{await Promise.all(a.map(async(b)=>{let R=await dr(n,b.fullEntryPath,t,g,o);await Promise.all(x.map(async(B)=>{let L=t.outputExtension?.({format:B,packageType:u,options:t,entry:b}).dts??nr(B,u),k=`${t.outDir}/${b.name}${L}`,l=`${n}/${k}`;e.files.push({path:l}),await Bun.write(l,R),p.progress("DTS",k,{identifier:t.name})}))}))}catch(b){if(v(b))throw b;throw new f(d(b))}}if(await Dr(s,t,e),t.onSuccess)await t.onSuccess(t)}export{qr as defineWorkspace,Kr as defineConfig,Cn as build};
|
package/package.json
CHANGED