balda 0.0.56 → 0.0.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +38 -38
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +4 -0
- package/lib/index.d.ts +4 -0
- package/lib/index.js +38 -38
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/index.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var ht=require('path'),no=require('pino'),ajv=require('ajv'),lo=require('fast-json-stringify'),child_process=require('child_process'),Vr=require('readline'),module$1=require('module'),Qo=require('crypto'),util=require('util'),zlib=require('zlib'),ot=require('fs'),stream=require('stream'),async_hooks=require('async_hooks'),http=require('http'),http2=require('http2'),https=require('https'),promises=require('stream/promises');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ht__default=/*#__PURE__*/_interopDefault(ht);var no__default=/*#__PURE__*/_interopDefault(no);var lo__default=/*#__PURE__*/_interopDefault(lo);var Vr__namespace=/*#__PURE__*/_interopNamespace(Vr);var Qo__default=/*#__PURE__*/_interopDefault(Qo);var ot__default=/*#__PURE__*/_interopDefault(ot);var Ks=Object.create;var mt=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var Vs=Object.getOwnPropertyNames;var Xs=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty;var Zt=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var Ys=(o,e)=>()=>(o&&(e=o(o=0)),e);var eo=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),to=(o,e)=>{for(var t in e)mt(o,t,{get:e[t],enumerable:true});},ro=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vs(e))!Zs.call(o,s)&&s!==t&&mt(o,s,{get:()=>e[s],enumerable:!(r=Wr(e,s))||r.enumerable});return o};var so=(o,e,t)=>(t=o!=null?Ks(Xs(o)):{},ro(mt(t,"default",{value:o,enumerable:true}),o));var T=(o,e,t,r)=>{for(var s=void 0,n=o.length-1,i;n>=0;n--)(i=o[n])&&(s=(i(e,t,s))||s);return s&&mt(e,t,s),s};var Kr={};to(Kr,{runtime:()=>j});var Yt,j,G=Ys(()=>{Yt=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},j=new Yt;});var ms=eo((Tt,dr)=>{(function(e,t){typeof Tt=="object"&&typeof dr=="object"?dr.exports=t():typeof define=="function"&&define.amd?define("cronstrue",[],t):typeof Tt=="object"?Tt.cronstrue=t():e.cronstrue=t();})(globalThis,()=>(()=>{var o={949:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.CronParser=void 0;var a=i(515),c=(function(){function d(p,l,m){l===void 0&&(l=true),m===void 0&&(m=false),this.expression=p,this.dayOfWeekStartIndexZero=l,this.monthStartIndexZero=m;}return d.prototype.parse=function(){var p,l,m=(p=this.expression)!==null&&p!==void 0?p:"";if(m==="@reboot")return l=["@reboot","","","","","",""],l;if(m.startsWith("@")){var f=this.parseSpecial(this.expression);l=this.extractParts(f);}else l=this.extractParts(this.expression);return this.normalize(l),this.validate(l),l},d.prototype.parseSpecial=function(p){var l={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},m=l[p];if(!m)throw new Error("Unknown special expression.");return m},d.prototype.extractParts=function(p){if(!this.expression)throw new Error("cron expression is empty");for(var l=p.trim().split(/[ ]+/),m=0;m<l.length;m++)if(l[m].includes(",")){var f=l[m].split(",").map(function(h){return h.trim()}).filter(function(h){return h!==""}).map(function(h){return isNaN(Number(h))?h:Number(h)}).filter(function(h){return h!==null&&h!==""});f.length===0&&f.push("*"),f.sort(function(h,g){return h!==null&&g!==null?h-g:0}),l[m]=f.map(function(h){return h!==null?h.toString():""}).join(",");}if(l.length<5)throw new Error("Expression has only ".concat(l.length," part").concat(l.length==1?"":"s",". At least 5 parts are required."));if(l.length==5)l.unshift(""),l.push("");else if(l.length==6){var u=/\d{4}$/.test(l[5])||l[4]=="?"||l[2]=="?";u?l.unshift(""):l.push("");}else if(l.length>7)throw new Error("Expression has ".concat(l.length," parts; too many!"));return l},d.prototype.normalize=function(p){var l=this;if(p[3]=p[3].replace("?","*"),p[5]=p[5].replace("?","*"),p[2]=p[2].replace("?","*"),p[0].indexOf("0/")==0&&(p[0]=p[0].replace("0/","*/")),p[1].indexOf("0/")==0&&(p[1]=p[1].replace("0/","*/")),p[2].indexOf("0/")==0&&(p[2]=p[2].replace("0/","*/")),p[3].indexOf("1/")==0&&(p[3]=p[3].replace("1/","*/")),p[4].indexOf("1/")==0&&(p[4]=p[4].replace("1/","*/")),p[6].indexOf("1/")==0&&(p[6]=p[6].replace("1/","*/")),p[5]=p[5].replace(/(^\d)|([^#/\s]\d)/g,function(S){var v=S.replace(/\D/,""),w=v;return l.dayOfWeekStartIndexZero?v=="7"&&(w="0"):w=(parseInt(v)-1).toString(),S.replace(v,w)}),p[5]=="L"&&(p[5]="6"),p[3]=="?"&&(p[3]="*"),p[3].indexOf("W")>-1&&(p[3].indexOf(",")>-1||p[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var m={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var f in m)p[5]=p[5].replace(new RegExp(f,"gi"),m[f].toString());p[4]=p[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(S){var v=S.replace(/\D/,""),w=v;return l.monthStartIndexZero&&(w=(parseInt(v)+1).toString()),S.replace(v,w)});var u={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var h in u)p[4]=p[4].replace(new RegExp(h,"gi"),u[h].toString());p[0]=="0"&&(p[0]=""),!/\*|\-|\,|\//.test(p[2])&&(/\*|\//.test(p[1])||/\*|\//.test(p[0]))&&(p[2]+="-".concat(p[2]));for(var g=0;g<p.length;g++)if(p[g].indexOf(",")!=-1&&(p[g]=p[g].split(",").filter(function(S){return S!==""}).join(",")||"*"),p[g]=="*/1"&&(p[g]="*"),p[g].indexOf("/")>-1&&!/^\*|\-|\,/.test(p[g])){var b=null;switch(g){case 4:b="12";break;case 5:b="6";break;case 6:b="9999";break;default:b=null;break}if(b!==null){var P=p[g].split("/");p[g]="".concat(P[0],"-").concat(b,"/").concat(P[1]);}}},d.prototype.validate=function(p){var l="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(p[0],l),this.validateOnlyExpectedCharactersFound(p[1],l),this.validateOnlyExpectedCharactersFound(p[2],l),this.validateOnlyExpectedCharactersFound(p[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(p[4],l),this.validateOnlyExpectedCharactersFound(p[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(p[6],l),this.validateAnyRanges(p);},d.prototype.validateAnyRanges=function(p){a.default.secondRange(p[0]),a.default.minuteRange(p[1]),a.default.hourRange(p[2]),a.default.dayOfMonthRange(p[3]),a.default.monthRange(p[4],this.monthStartIndexZero),a.default.dayOfWeekRange(p[5],this.dayOfWeekStartIndexZero);},d.prototype.validateOnlyExpectedCharactersFound=function(p,l){var m=p.match(new RegExp("[^".concat(l,"]+"),"gi"));if(m&&m.length)throw new Error("Expression contains invalid values: '".concat(m.toString(),"'"))},d})();n.CronParser=c;}),333:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.ExpressionDescriptor=void 0;var a=i(823),c=i(949),d=(function(){function p(l,m){if(this.expression=l,this.options=m,this.expressionParts=new Array(5),!this.options.locale&&p.defaultLocale&&(this.options.locale=p.defaultLocale),!p.locales[this.options.locale]){var f=Object.keys(p.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(f,"'.")),this.options.locale=f;}this.i18n=p.locales[this.options.locale],m.use24HourTimeFormat===void 0&&(m.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault());}return p.toString=function(l,m){var f=m===void 0?{}:m,u=f.throwExceptionOnParseError,h=u===void 0?true:u,g=f.verbose,b=g===void 0?false:g,P=f.dayOfWeekStartIndexZero,S=P===void 0?true:P,v=f.monthStartIndexZero,w=v===void 0?false:v,k=f.use24HourTimeFormat,E=f.locale,$=E===void 0?null:E,ce=f.logicalAndDayFields,le=ce===void 0?false:ce,Z={throwExceptionOnParseError:h,verbose:b,dayOfWeekStartIndexZero:S,monthStartIndexZero:w,use24HourTimeFormat:k,locale:$,logicalAndDayFields:le};Z.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Vt=new p(l,Z);return Vt.getFullDescription()},p.initialize=function(l,m){m===void 0&&(m="en"),p.specialCharacters=["/","-",",","*"],p.defaultLocale=m,l.load(p.locales);},p.prototype.getFullDescription=function(){var l,m,f="";try{var u=new c.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=u.parse(),this.expressionParts[0]==="@reboot")return ((m=(l=this.i18n).atReboot)===null||m===void 0?void 0:m.call(l))||"Run once, at startup";var h=this.getTimeOfDayDescription(),g=this.getDayOfMonthDescription(),b=this.getMonthDescription(),P=this.getDayOfWeekDescription(),S=this.getYearDescription();f+=h+g+P+b+S,f=this.transformVerbosity(f,!!this.options.verbose),f=f.charAt(0).toLocaleUpperCase()+f.substr(1);}catch(v){if(!this.options.throwExceptionOnParseError)f=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw "".concat(v)}return f},p.prototype.getTimeOfDayDescription=function(){var l=this.expressionParts[0],m=this.expressionParts[1],f=this.expressionParts[2],u="";if(!a.StringUtilities.containsAny(m,p.specialCharacters)&&!a.StringUtilities.containsAny(f,p.specialCharacters)&&!a.StringUtilities.containsAny(l,p.specialCharacters))u+=this.i18n.atSpace()+this.formatTime(f,m,l);else if(!l&&m.indexOf("-")>-1&&!(m.indexOf(",")>-1)&&!(m.indexOf("/")>-1)&&!a.StringUtilities.containsAny(f,p.specialCharacters)){var h=m.split("-");u+=a.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(f,h[0],""),this.formatTime(f,h[1],""));}else if(!l&&f.indexOf(",")>-1&&f.indexOf("-")==-1&&f.indexOf("/")==-1&&!a.StringUtilities.containsAny(m,p.specialCharacters)){var g=f.split(",");u+=this.i18n.at();for(var b=0;b<g.length;b++)u+=" ",u+=this.formatTime(g[b],m,""),b<g.length-2&&(u+=","),b==g.length-2&&(u+=this.i18n.spaceAnd());}else {var P=this.getSecondsDescription(),S=this.getMinutesDescription(),v=this.getHoursDescription();if(u+=P,u&&S&&(u+=", "),u+=S,S===v)return u;u&&v&&(u+=", "),u+=v;}return u},p.prototype.getSecondsDescription=function(){var l=this,m=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(f){return f},function(f){return a.StringUtilities.format(l.i18n.everyX0Seconds(f),f)},function(f){return l.i18n.secondsX0ThroughX1PastTheMinute()},function(f){return f=="0"?"":parseInt(f)<20?l.i18n.atX0SecondsPastTheMinute(f):l.i18n.atX0SecondsPastTheMinuteGt20()||l.i18n.atX0SecondsPastTheMinute(f)});return m},p.prototype.getMinutesDescription=function(){var l=this,m=this.expressionParts[0],f=this.expressionParts[2],u=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(h){return h},function(h){return a.StringUtilities.format(l.i18n.everyX0Minutes(h),h)},function(h){return l.i18n.minutesX0ThroughX1PastTheHour()},function(h){try{return h=="0"&&f.indexOf("/")==-1&&m==""?l.i18n.everyHour():parseInt(h)<20?l.i18n.atX0MinutesPastTheHour(h):l.i18n.atX0MinutesPastTheHourGt20()||l.i18n.atX0MinutesPastTheHour(h)}catch{return l.i18n.atX0MinutesPastTheHour(h)}});return u},p.prototype.getHoursDescription=function(){var l=this,m=this.expressionParts[2],f=0,u=[];m.split("/")[0].split(",").forEach(function(b){var P=b.split("-");P.length===2&&u.push({value:P[1],index:f+1}),f+=P.length;});var h=0,g=this.getSegmentDescription(m,this.i18n.everyHour(),function(b){var P=u.find(function(v){return v.value===b&&v.index===h}),S=P&&l.expressionParts[1]!=="0";return h++,S?l.formatTime(b,"59",""):l.formatTime(b,"0","")},function(b){return a.StringUtilities.format(l.i18n.everyX0Hours(b),b)},function(b){return l.i18n.betweenX0AndX1()},function(b){return l.i18n.atX0()});return g},p.prototype.getDayOfWeekDescription=function(){var l=this,m=this.i18n.daysOfTheWeek(),f=null;return this.expressionParts[5]=="*"?f="":f=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(u,h){var g=u;u.indexOf("#")>-1?g=u.substring(0,u.indexOf("#")):u.indexOf("L")>-1&&(g=g.replace("L",""));var b=parseInt(g),P=l.i18n.daysOfTheWeekInCase?l.i18n.daysOfTheWeekInCase(h)[b]:m[b];if(u.indexOf("#")>-1){var S=null,v=u.substring(u.indexOf("#")+1),w=u.substring(0,u.indexOf("#"));switch(v){case "1":S=l.i18n.first(w);break;case "2":S=l.i18n.second(w);break;case "3":S=l.i18n.third(w);break;case "4":S=l.i18n.fourth(w);break;case "5":S=l.i18n.fifth(w);break}P=S+" "+P;}return P},function(u){return parseInt(u)==1?"":a.StringUtilities.format(l.i18n.commaEveryX0DaysOfTheWeek(u),u)},function(u){var h=u.substring(0,u.indexOf("-")),g=l.expressionParts[3]!="*";return g?l.i18n.commaAndX0ThroughX1(h):l.i18n.commaX0ThroughX1(h)},function(u){var h=null;if(u.indexOf("#")>-1){var g=u.substring(u.indexOf("#")+1),b=u.substring(0,u.indexOf("#"));h=l.i18n.commaOnThe(g,b).trim()+l.i18n.spaceX0OfTheMonth();}else if(u.indexOf("L")>-1)h=l.i18n.commaOnTheLastX0OfTheMonth(u.replace("L",""));else {var P=l.expressionParts[3]!="*";P?l.options.logicalAndDayFields?h=l.i18n.commaOnlyOnX0(u):h=l.i18n.commaAndOnX0():h=l.i18n.commaOnlyOnX0(u);}return h}),f},p.prototype.getMonthDescription=function(){var l=this,m=this.i18n.monthsOfTheYear(),f=this.getSegmentDescription(this.expressionParts[4],"",function(u,h){return h&&l.i18n.monthsOfTheYearInCase?l.i18n.monthsOfTheYearInCase(h)[parseInt(u)-1]:m[parseInt(u)-1]},function(u){return parseInt(u)==1?"":a.StringUtilities.format(l.i18n.commaEveryX0Months(u),u)},function(u){return l.i18n.commaMonthX0ThroughMonthX1()||l.i18n.commaX0ThroughX1()},function(u){return l.i18n.commaOnlyInMonthX0?l.i18n.commaOnlyInMonthX0():l.i18n.commaOnlyInX0()});return f},p.prototype.getDayOfMonthDescription=function(){var l=this,m=null,f=this.expressionParts[3];switch(f){case "L":m=this.i18n.commaOnTheLastDayOfTheMonth();break;case "WL":case "LW":m=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var u=f.match(/(\d{1,2}W)|(W\d{1,2})/);if(u){var h=parseInt(u[0].replace("W","")),g=h==1?this.i18n.firstWeekday():a.StringUtilities.format(this.i18n.weekdayNearestDayX0(),h.toString());m=a.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),g);break}else {var b=f.match(/L-(\d{1,2})/);if(b){var P=b[1];m=a.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(P),P);break}else {if(f=="*"&&this.expressionParts[5]!="*")return "";m=this.getSegmentDescription(f,this.i18n.commaEveryDay(),function(S){return S=="L"?l.i18n.lastDay():l.i18n.dayX0?a.StringUtilities.format(l.i18n.dayX0(),S):S},function(S){return S=="1"?l.i18n.commaEveryDay():l.i18n.commaEveryX0Days(S)},function(S){return l.i18n.commaBetweenDayX0AndX1OfTheMonth(S)},function(S){return l.i18n.commaOnDayX0OfTheMonth(S)});}break}}return m},p.prototype.getYearDescription=function(){var l=this,m=this.getSegmentDescription(this.expressionParts[6],"",function(f){return /^\d+$/.test(f)?new Date(parseInt(f),1).getFullYear().toString():f},function(f){return a.StringUtilities.format(l.i18n.commaEveryX0Years(f),f)},function(f){return l.i18n.commaYearX0ThroughYearX1()||l.i18n.commaX0ThroughX1()},function(f){return l.i18n.commaOnlyInYearX0?l.i18n.commaOnlyInYearX0():l.i18n.commaOnlyInX0()});return m},p.prototype.getSegmentDescription=function(l,m,f,u,h,g){var b=null,P=l.indexOf("/")>-1,S=l.indexOf("-")>-1,v=l.indexOf(",")>-1;if(!l)b="";else if(l==="*")b=m;else if(!P&&!S&&!v)b=a.StringUtilities.format(g(l),f(l));else if(v){for(var w=l.split(","),k="",E=0;E<w.length;E++)if(E>0&&w.length>2&&(k+=",",E<w.length-1&&(k+=" ")),E>0&&w.length>1&&(E==w.length-1||w.length==2)&&(k+="".concat(this.i18n.spaceAnd()," ")),w[E].indexOf("/")>-1||w[E].indexOf("-")>-1){var $=w[E].indexOf("-")>-1&&w[E].indexOf("/")==-1,ce=this.getSegmentDescription(w[E],m,f,u,$?this.i18n.commaX0ThroughX1:h,g);$&&(ce=ce.replace(", ","")),k+=ce;}else P?k+=this.getSegmentDescription(w[E],m,f,u,h,g):k+=f(w[E]);P?b=k:b=a.StringUtilities.format(g(l),k);}else if(P){var w=l.split("/");if(b=a.StringUtilities.format(u(w[1]),w[1]),w[0].indexOf("-")>-1){var le=this.generateRangeSegmentDescription(w[0],h,f);le.indexOf(", ")!=0&&(b+=", "),b+=le;}else if(w[0].indexOf("*")==-1){var Z=a.StringUtilities.format(g(w[0]),f(w[0]));Z=Z.replace(", ",""),b+=a.StringUtilities.format(this.i18n.commaStartingX0(),Z);}}else S&&(b=this.generateRangeSegmentDescription(l,h,f));return b},p.prototype.generateRangeSegmentDescription=function(l,m,f){var u="",h=l.split("-"),g=f(h[0],1),b=f(h[1],2),P=m(l);return u+=a.StringUtilities.format(P,g,b),u},p.prototype.formatTime=function(l,m,f){var u=0,h=0,g=parseInt(l)+u,b=parseInt(m)+h;b>=60?(b-=60,g+=1):b<0&&(b+=60,g-=1),g>=24?g=g-24:g<0&&(g=24+g);var P="",S=false;this.options.use24HourTimeFormat||(S=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),P=S?"".concat(this.getPeriod(g)," "):" ".concat(this.getPeriod(g)),g>12&&(g-=12),g===0&&(g=12));var v="";return f&&(v=":".concat(("00"+f).substring(f.length))),"".concat(S?P:"").concat(("00"+g.toString()).substring(g.toString().length),":").concat(("00"+b.toString()).substring(b.toString().length)).concat(v).concat(S?"":P)},p.prototype.transformVerbosity=function(l,m){if(!m&&(l=l.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),l=l.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),l=l.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),l=l.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var f=0,u=Object.entries(this.i18n.conciseVerbosityReplacements());f<u.length;f++){var h=u[f],g=h[0],b=h[1];l=l.replace(new RegExp(g,"g"),b);}return l},p.prototype.getPeriod=function(l){return l>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},p.locales={},p})();n.ExpressionDescriptor=d;}),747:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.enLocaleLoader=void 0;var a=i(486),c=(function(){function d(){}return d.prototype.load=function(p){p.en=new a.en;},d})();n.enLocaleLoader=c;}),486:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.en=void 0;var i=(function(){function a(){}return a.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},a.prototype.atX0MinutesPastTheHourGt20=function(){return null},a.prototype.commaMonthX0ThroughMonthX1=function(){return null},a.prototype.commaYearX0ThroughYearX1=function(){return null},a.prototype.use24HourTimeFormatByDefault=function(){return false},a.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return "An error occurred when generating the expression description. Check the cron expression syntax."},a.prototype.everyMinute=function(){return "every minute"},a.prototype.everyHour=function(){return "every hour"},a.prototype.atSpace=function(){return "At "},a.prototype.everyMinuteBetweenX0AndX1=function(){return "Every minute between %s and %s"},a.prototype.at=function(){return "At"},a.prototype.spaceAnd=function(){return " and"},a.prototype.everySecond=function(){return "every second"},a.prototype.everyX0Seconds=function(){return "every %s seconds"},a.prototype.secondsX0ThroughX1PastTheMinute=function(){return "seconds %s through %s past the minute"},a.prototype.atX0SecondsPastTheMinute=function(){return "at %s seconds past the minute"},a.prototype.everyX0Minutes=function(){return "every %s minutes"},a.prototype.minutesX0ThroughX1PastTheHour=function(){return "minutes %s through %s past the hour"},a.prototype.atX0MinutesPastTheHour=function(){return "at %s minutes past the hour"},a.prototype.everyX0Hours=function(){return "every %s hours"},a.prototype.betweenX0AndX1=function(){return "between %s and %s"},a.prototype.atX0=function(){return "at %s"},a.prototype.commaEveryDay=function(){return ", every day"},a.prototype.commaEveryX0DaysOfTheWeek=function(){return ", every %s days of the week"},a.prototype.commaX0ThroughX1=function(){return ", %s through %s"},a.prototype.commaAndX0ThroughX1=function(){return ", %s through %s"},a.prototype.first=function(){return "first"},a.prototype.second=function(){return "second"},a.prototype.third=function(){return "third"},a.prototype.fourth=function(){return "fourth"},a.prototype.fifth=function(){return "fifth"},a.prototype.commaOnThe=function(){return ", on the "},a.prototype.spaceX0OfTheMonth=function(){return " %s of the month"},a.prototype.lastDay=function(){return "the last day"},a.prototype.commaOnTheLastX0OfTheMonth=function(){return ", on the last %s of the month"},a.prototype.commaOnlyOnX0=function(){return ", only on %s"},a.prototype.commaAndOnX0=function(){return ", and on %s"},a.prototype.commaEveryX0Months=function(){return ", every %s months"},a.prototype.commaOnlyInX0=function(){return ", only in %s"},a.prototype.commaOnTheLastDayOfTheMonth=function(){return ", on the last day of the month"},a.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return ", on the last weekday of the month"},a.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return ", %s days before the last day of the month"},a.prototype.firstWeekday=function(){return "first weekday"},a.prototype.weekdayNearestDayX0=function(){return "weekday nearest day %s"},a.prototype.commaOnTheX0OfTheMonth=function(){return ", on the %s of the month"},a.prototype.commaEveryX0Days=function(){return ", every %s days"},a.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return ", between day %s and %s of the month"},a.prototype.commaOnDayX0OfTheMonth=function(){return ", on day %s of the month"},a.prototype.commaEveryHour=function(){return ", every hour"},a.prototype.commaEveryX0Years=function(){return ", every %s years"},a.prototype.commaStartingX0=function(){return ", starting %s"},a.prototype.daysOfTheWeek=function(){return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},a.prototype.monthsOfTheYear=function(){return ["January","February","March","April","May","June","July","August","September","October","November","December"]},a.prototype.atReboot=function(){return "Run once, at startup"},a})();n.en=i;}),515:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true});function i(c,d){if(!c)throw new Error(d)}var a=(function(){function c(){}return c.secondRange=function(d){for(var p=d.split(","),l=0;l<p.length;l++)if(!isNaN(parseInt(p[l],10))){var m=parseInt(p[l],10);i(m>=0&&m<=59,"seconds part must be >= 0 and <= 59");}},c.minuteRange=function(d){for(var p=d.split(","),l=0;l<p.length;l++)if(!isNaN(parseInt(p[l],10))){var m=parseInt(p[l],10);i(m>=0&&m<=59,"minutes part must be >= 0 and <= 59");}},c.hourRange=function(d){for(var p=d.split(","),l=0;l<p.length;l++)if(!isNaN(parseInt(p[l],10))){var m=parseInt(p[l],10);i(m>=0&&m<=23,"hours part must be >= 0 and <= 23");}},c.dayOfMonthRange=function(d){for(var p=d.split(","),l=0;l<p.length;l++)if(!isNaN(parseInt(p[l],10))){var m=parseInt(p[l],10);i(m>=1&&m<=31,"DOM part must be >= 1 and <= 31");}},c.monthRange=function(d,p){for(var l=d.split(","),m=0;m<l.length;m++)if(!isNaN(parseInt(l[m],10))){var f=parseInt(l[m],10);i(f>=1&&f<=12,p?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12");}},c.dayOfWeekRange=function(d,p){for(var l=d.split(","),m=0;m<l.length;m++)if(!isNaN(parseInt(l[m],10))){var f=parseInt(l[m],10);i(f>=0&&f<=6,p?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7");}},c})();n.default=a;}),823:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.StringUtilities=void 0;var i=(function(){function a(){}return a.format=function(c){for(var d=[],p=1;p<arguments.length;p++)d[p-1]=arguments[p];return c.replace(/%s/g,function(l){for(var m=[],f=1;f<arguments.length;f++)m[f-1]=arguments[f];return d.shift()})},a.containsAny=function(c,d){return d.some(function(p){return c.indexOf(p)>-1})},a})();n.StringUtilities=i;})},e={};function t(s){var n=e[s];if(n!==void 0)return n.exports;var i=e[s]={exports:{}};return o[s](i,i.exports,t),i.exports}var r={};return (()=>{var s=r;Object.defineProperty(s,"__esModule",{value:true}),s.toString=void 0;var n=t(333),i=t(747);n.ExpressionDescriptor.initialize(new i.enLocaleLoader),s.default=n.ExpressionDescriptor;var a=n.ExpressionDescriptor.toString;s.toString=a;})(),r})());});var O=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var oo=o=>(e,t,r)=>{let s=O.get(e,t);return s||(s={middlewares:[]}),s.cacheConfig=o,O.set(e,t,s),r};G();G();var er=class{getCwd(){switch(j.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},L=new er;G();var tr=class{basename(e){switch(j.type){case "node":case "bun":case "deno":return ht__default.default.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(j.type){case "node":case "bun":case "deno":return ht__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(j.type){case "bun":case "node":case "deno":return ht__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(j.type){case "bun":case "node":case "deno":return ht__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},x=new tr;var rr=class{async glob(...e){let t=await import('fs/promises'),r=L.getCwd(),s=x.resolve(r,e[1]?.cwd??""),n=[];for await(let i of t.glob(...e)){if(typeof i=="string"){n.push(x.resolve(s,i));continue}i.isFile()&&n.push(x.resolve(s,i.name));}return n}async mkdir(e,t){switch(j.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(j.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(j.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.arrayBuffer());case "deno":let i=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(i):new Uint8Array(i)}}async writeFile(e,t){switch(j.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(j.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.size}}}async unlink(e){switch(j.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(j.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(j.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},y=new rr;var R=class extends Error{constructor(e){super(e);}};var io=()=>no__default.default({level:"info",formatters:{level:e=>({level:e})}}),M=io();var ft=class extends R{constructor(e){super(`Failed to convert Zod schema to JSON Schema. This usually happens when using Zod v3 schemas with Zod v4. Make sure you're importing from 'zod' (v4) and not 'zod/v3'. Original error: ${e.message}`);}};var Le=class extends R{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var gt=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"?module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))):Zt("module").createRequire?.((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))??__filename)??Zt,pe=async o=>{let e=x.join(process.cwd(),"node_modules");if(!await y.exists(e))return o;let r=[];for(let s of o){let n=x.join(e,s);await y.exists(n)||r.push(s);}return r},U=async()=>await y.exists(x.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await y.exists(x.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await y.exists(x.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await y.exists(x.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await y.exists(x.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],D=async(o,e,t,r,s=true)=>{let n=Vr__namespace.createInterface({input:process.stdin,output:process.stdout}),i=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var ht=require('path'),no=require('pino'),ajv=require('ajv'),lo=require('fast-json-stringify'),child_process=require('child_process'),Vr=require('readline'),module$1=require('module'),Qo=require('crypto'),util=require('util'),zlib=require('zlib'),ot=require('fs'),stream=require('stream'),async_hooks=require('async_hooks'),http=require('http'),http2=require('http2'),https=require('https'),promises=require('stream/promises');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ht__default=/*#__PURE__*/_interopDefault(ht);var no__default=/*#__PURE__*/_interopDefault(no);var lo__default=/*#__PURE__*/_interopDefault(lo);var Vr__namespace=/*#__PURE__*/_interopNamespace(Vr);var Qo__default=/*#__PURE__*/_interopDefault(Qo);var ot__default=/*#__PURE__*/_interopDefault(ot);var Ks=Object.create;var mt=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var Vs=Object.getOwnPropertyNames;var Xs=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty;var Zt=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var Ys=(o,e)=>()=>(o&&(e=o(o=0)),e);var eo=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),to=(o,e)=>{for(var t in e)mt(o,t,{get:e[t],enumerable:true});},ro=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vs(e))!Zs.call(o,s)&&s!==t&&mt(o,s,{get:()=>e[s],enumerable:!(r=Wr(e,s))||r.enumerable});return o};var so=(o,e,t)=>(t=o!=null?Ks(Xs(o)):{},ro(mt(t,"default",{value:o,enumerable:true}),o));var P=(o,e,t,r)=>{for(var s=void 0,n=o.length-1,i;n>=0;n--)(i=o[n])&&(s=(i(e,t,s))||s);return s&&mt(e,t,s),s};var Kr={};to(Kr,{runtime:()=>j});var Yt,j,G=Ys(()=>{Yt=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},j=new Yt;});var ms=eo((Tt,dr)=>{(function(e,t){typeof Tt=="object"&&typeof dr=="object"?dr.exports=t():typeof define=="function"&&define.amd?define("cronstrue",[],t):typeof Tt=="object"?Tt.cronstrue=t():e.cronstrue=t();})(globalThis,()=>(()=>{var o={949:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.CronParser=void 0;var a=i(515),c=(function(){function d(l,p,m){p===void 0&&(p=true),m===void 0&&(m=false),this.expression=l,this.dayOfWeekStartIndexZero=p,this.monthStartIndexZero=m;}return d.prototype.parse=function(){var l,p,m=(l=this.expression)!==null&&l!==void 0?l:"";if(m==="@reboot")return p=["@reboot","","","","","",""],p;if(m.startsWith("@")){var f=this.parseSpecial(this.expression);p=this.extractParts(f);}else p=this.extractParts(this.expression);return this.normalize(p),this.validate(p),p},d.prototype.parseSpecial=function(l){var p={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},m=p[l];if(!m)throw new Error("Unknown special expression.");return m},d.prototype.extractParts=function(l){if(!this.expression)throw new Error("cron expression is empty");for(var p=l.trim().split(/[ ]+/),m=0;m<p.length;m++)if(p[m].includes(",")){var f=p[m].split(",").map(function(h){return h.trim()}).filter(function(h){return h!==""}).map(function(h){return isNaN(Number(h))?h:Number(h)}).filter(function(h){return h!==null&&h!==""});f.length===0&&f.push("*"),f.sort(function(h,g){return h!==null&&g!==null?h-g:0}),p[m]=f.map(function(h){return h!==null?h.toString():""}).join(",");}if(p.length<5)throw new Error("Expression has only ".concat(p.length," part").concat(p.length==1?"":"s",". At least 5 parts are required."));if(p.length==5)p.unshift(""),p.push("");else if(p.length==6){var u=/\d{4}$/.test(p[5])||p[4]=="?"||p[2]=="?";u?p.unshift(""):p.push("");}else if(p.length>7)throw new Error("Expression has ".concat(p.length," parts; too many!"));return p},d.prototype.normalize=function(l){var p=this;if(l[3]=l[3].replace("?","*"),l[5]=l[5].replace("?","*"),l[2]=l[2].replace("?","*"),l[0].indexOf("0/")==0&&(l[0]=l[0].replace("0/","*/")),l[1].indexOf("0/")==0&&(l[1]=l[1].replace("0/","*/")),l[2].indexOf("0/")==0&&(l[2]=l[2].replace("0/","*/")),l[3].indexOf("1/")==0&&(l[3]=l[3].replace("1/","*/")),l[4].indexOf("1/")==0&&(l[4]=l[4].replace("1/","*/")),l[6].indexOf("1/")==0&&(l[6]=l[6].replace("1/","*/")),l[5]=l[5].replace(/(^\d)|([^#/\s]\d)/g,function(S){var v=S.replace(/\D/,""),w=v;return p.dayOfWeekStartIndexZero?v=="7"&&(w="0"):w=(parseInt(v)-1).toString(),S.replace(v,w)}),l[5]=="L"&&(l[5]="6"),l[3]=="?"&&(l[3]="*"),l[3].indexOf("W")>-1&&(l[3].indexOf(",")>-1||l[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var m={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var f in m)l[5]=l[5].replace(new RegExp(f,"gi"),m[f].toString());l[4]=l[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(S){var v=S.replace(/\D/,""),w=v;return p.monthStartIndexZero&&(w=(parseInt(v)+1).toString()),S.replace(v,w)});var u={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var h in u)l[4]=l[4].replace(new RegExp(h,"gi"),u[h].toString());l[0]=="0"&&(l[0]=""),!/\*|\-|\,|\//.test(l[2])&&(/\*|\//.test(l[1])||/\*|\//.test(l[0]))&&(l[2]+="-".concat(l[2]));for(var g=0;g<l.length;g++)if(l[g].indexOf(",")!=-1&&(l[g]=l[g].split(",").filter(function(S){return S!==""}).join(",")||"*"),l[g]=="*/1"&&(l[g]="*"),l[g].indexOf("/")>-1&&!/^\*|\-|\,/.test(l[g])){var b=null;switch(g){case 4:b="12";break;case 5:b="6";break;case 6:b="9999";break;default:b=null;break}if(b!==null){var T=l[g].split("/");l[g]="".concat(T[0],"-").concat(b,"/").concat(T[1]);}}},d.prototype.validate=function(l){var p="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(l[0],p),this.validateOnlyExpectedCharactersFound(l[1],p),this.validateOnlyExpectedCharactersFound(l[2],p),this.validateOnlyExpectedCharactersFound(l[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(l[4],p),this.validateOnlyExpectedCharactersFound(l[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(l[6],p),this.validateAnyRanges(l);},d.prototype.validateAnyRanges=function(l){a.default.secondRange(l[0]),a.default.minuteRange(l[1]),a.default.hourRange(l[2]),a.default.dayOfMonthRange(l[3]),a.default.monthRange(l[4],this.monthStartIndexZero),a.default.dayOfWeekRange(l[5],this.dayOfWeekStartIndexZero);},d.prototype.validateOnlyExpectedCharactersFound=function(l,p){var m=l.match(new RegExp("[^".concat(p,"]+"),"gi"));if(m&&m.length)throw new Error("Expression contains invalid values: '".concat(m.toString(),"'"))},d})();n.CronParser=c;}),333:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.ExpressionDescriptor=void 0;var a=i(823),c=i(949),d=(function(){function l(p,m){if(this.expression=p,this.options=m,this.expressionParts=new Array(5),!this.options.locale&&l.defaultLocale&&(this.options.locale=l.defaultLocale),!l.locales[this.options.locale]){var f=Object.keys(l.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(f,"'.")),this.options.locale=f;}this.i18n=l.locales[this.options.locale],m.use24HourTimeFormat===void 0&&(m.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault());}return l.toString=function(p,m){var f=m===void 0?{}:m,u=f.throwExceptionOnParseError,h=u===void 0?true:u,g=f.verbose,b=g===void 0?false:g,T=f.dayOfWeekStartIndexZero,S=T===void 0?true:T,v=f.monthStartIndexZero,w=v===void 0?false:v,k=f.use24HourTimeFormat,E=f.locale,$=E===void 0?null:E,ce=f.logicalAndDayFields,le=ce===void 0?false:ce,Z={throwExceptionOnParseError:h,verbose:b,dayOfWeekStartIndexZero:S,monthStartIndexZero:w,use24HourTimeFormat:k,locale:$,logicalAndDayFields:le};Z.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Vt=new l(p,Z);return Vt.getFullDescription()},l.initialize=function(p,m){m===void 0&&(m="en"),l.specialCharacters=["/","-",",","*"],l.defaultLocale=m,p.load(l.locales);},l.prototype.getFullDescription=function(){var p,m,f="";try{var u=new c.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=u.parse(),this.expressionParts[0]==="@reboot")return ((m=(p=this.i18n).atReboot)===null||m===void 0?void 0:m.call(p))||"Run once, at startup";var h=this.getTimeOfDayDescription(),g=this.getDayOfMonthDescription(),b=this.getMonthDescription(),T=this.getDayOfWeekDescription(),S=this.getYearDescription();f+=h+g+T+b+S,f=this.transformVerbosity(f,!!this.options.verbose),f=f.charAt(0).toLocaleUpperCase()+f.substr(1);}catch(v){if(!this.options.throwExceptionOnParseError)f=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw "".concat(v)}return f},l.prototype.getTimeOfDayDescription=function(){var p=this.expressionParts[0],m=this.expressionParts[1],f=this.expressionParts[2],u="";if(!a.StringUtilities.containsAny(m,l.specialCharacters)&&!a.StringUtilities.containsAny(f,l.specialCharacters)&&!a.StringUtilities.containsAny(p,l.specialCharacters))u+=this.i18n.atSpace()+this.formatTime(f,m,p);else if(!p&&m.indexOf("-")>-1&&!(m.indexOf(",")>-1)&&!(m.indexOf("/")>-1)&&!a.StringUtilities.containsAny(f,l.specialCharacters)){var h=m.split("-");u+=a.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(f,h[0],""),this.formatTime(f,h[1],""));}else if(!p&&f.indexOf(",")>-1&&f.indexOf("-")==-1&&f.indexOf("/")==-1&&!a.StringUtilities.containsAny(m,l.specialCharacters)){var g=f.split(",");u+=this.i18n.at();for(var b=0;b<g.length;b++)u+=" ",u+=this.formatTime(g[b],m,""),b<g.length-2&&(u+=","),b==g.length-2&&(u+=this.i18n.spaceAnd());}else {var T=this.getSecondsDescription(),S=this.getMinutesDescription(),v=this.getHoursDescription();if(u+=T,u&&S&&(u+=", "),u+=S,S===v)return u;u&&v&&(u+=", "),u+=v;}return u},l.prototype.getSecondsDescription=function(){var p=this,m=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(f){return f},function(f){return a.StringUtilities.format(p.i18n.everyX0Seconds(f),f)},function(f){return p.i18n.secondsX0ThroughX1PastTheMinute()},function(f){return f=="0"?"":parseInt(f)<20?p.i18n.atX0SecondsPastTheMinute(f):p.i18n.atX0SecondsPastTheMinuteGt20()||p.i18n.atX0SecondsPastTheMinute(f)});return m},l.prototype.getMinutesDescription=function(){var p=this,m=this.expressionParts[0],f=this.expressionParts[2],u=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(h){return h},function(h){return a.StringUtilities.format(p.i18n.everyX0Minutes(h),h)},function(h){return p.i18n.minutesX0ThroughX1PastTheHour()},function(h){try{return h=="0"&&f.indexOf("/")==-1&&m==""?p.i18n.everyHour():parseInt(h)<20?p.i18n.atX0MinutesPastTheHour(h):p.i18n.atX0MinutesPastTheHourGt20()||p.i18n.atX0MinutesPastTheHour(h)}catch{return p.i18n.atX0MinutesPastTheHour(h)}});return u},l.prototype.getHoursDescription=function(){var p=this,m=this.expressionParts[2],f=0,u=[];m.split("/")[0].split(",").forEach(function(b){var T=b.split("-");T.length===2&&u.push({value:T[1],index:f+1}),f+=T.length;});var h=0,g=this.getSegmentDescription(m,this.i18n.everyHour(),function(b){var T=u.find(function(v){return v.value===b&&v.index===h}),S=T&&p.expressionParts[1]!=="0";return h++,S?p.formatTime(b,"59",""):p.formatTime(b,"0","")},function(b){return a.StringUtilities.format(p.i18n.everyX0Hours(b),b)},function(b){return p.i18n.betweenX0AndX1()},function(b){return p.i18n.atX0()});return g},l.prototype.getDayOfWeekDescription=function(){var p=this,m=this.i18n.daysOfTheWeek(),f=null;return this.expressionParts[5]=="*"?f="":f=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(u,h){var g=u;u.indexOf("#")>-1?g=u.substring(0,u.indexOf("#")):u.indexOf("L")>-1&&(g=g.replace("L",""));var b=parseInt(g),T=p.i18n.daysOfTheWeekInCase?p.i18n.daysOfTheWeekInCase(h)[b]:m[b];if(u.indexOf("#")>-1){var S=null,v=u.substring(u.indexOf("#")+1),w=u.substring(0,u.indexOf("#"));switch(v){case "1":S=p.i18n.first(w);break;case "2":S=p.i18n.second(w);break;case "3":S=p.i18n.third(w);break;case "4":S=p.i18n.fourth(w);break;case "5":S=p.i18n.fifth(w);break}T=S+" "+T;}return T},function(u){return parseInt(u)==1?"":a.StringUtilities.format(p.i18n.commaEveryX0DaysOfTheWeek(u),u)},function(u){var h=u.substring(0,u.indexOf("-")),g=p.expressionParts[3]!="*";return g?p.i18n.commaAndX0ThroughX1(h):p.i18n.commaX0ThroughX1(h)},function(u){var h=null;if(u.indexOf("#")>-1){var g=u.substring(u.indexOf("#")+1),b=u.substring(0,u.indexOf("#"));h=p.i18n.commaOnThe(g,b).trim()+p.i18n.spaceX0OfTheMonth();}else if(u.indexOf("L")>-1)h=p.i18n.commaOnTheLastX0OfTheMonth(u.replace("L",""));else {var T=p.expressionParts[3]!="*";T?p.options.logicalAndDayFields?h=p.i18n.commaOnlyOnX0(u):h=p.i18n.commaAndOnX0():h=p.i18n.commaOnlyOnX0(u);}return h}),f},l.prototype.getMonthDescription=function(){var p=this,m=this.i18n.monthsOfTheYear(),f=this.getSegmentDescription(this.expressionParts[4],"",function(u,h){return h&&p.i18n.monthsOfTheYearInCase?p.i18n.monthsOfTheYearInCase(h)[parseInt(u)-1]:m[parseInt(u)-1]},function(u){return parseInt(u)==1?"":a.StringUtilities.format(p.i18n.commaEveryX0Months(u),u)},function(u){return p.i18n.commaMonthX0ThroughMonthX1()||p.i18n.commaX0ThroughX1()},function(u){return p.i18n.commaOnlyInMonthX0?p.i18n.commaOnlyInMonthX0():p.i18n.commaOnlyInX0()});return f},l.prototype.getDayOfMonthDescription=function(){var p=this,m=null,f=this.expressionParts[3];switch(f){case "L":m=this.i18n.commaOnTheLastDayOfTheMonth();break;case "WL":case "LW":m=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var u=f.match(/(\d{1,2}W)|(W\d{1,2})/);if(u){var h=parseInt(u[0].replace("W","")),g=h==1?this.i18n.firstWeekday():a.StringUtilities.format(this.i18n.weekdayNearestDayX0(),h.toString());m=a.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),g);break}else {var b=f.match(/L-(\d{1,2})/);if(b){var T=b[1];m=a.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(T),T);break}else {if(f=="*"&&this.expressionParts[5]!="*")return "";m=this.getSegmentDescription(f,this.i18n.commaEveryDay(),function(S){return S=="L"?p.i18n.lastDay():p.i18n.dayX0?a.StringUtilities.format(p.i18n.dayX0(),S):S},function(S){return S=="1"?p.i18n.commaEveryDay():p.i18n.commaEveryX0Days(S)},function(S){return p.i18n.commaBetweenDayX0AndX1OfTheMonth(S)},function(S){return p.i18n.commaOnDayX0OfTheMonth(S)});}break}}return m},l.prototype.getYearDescription=function(){var p=this,m=this.getSegmentDescription(this.expressionParts[6],"",function(f){return /^\d+$/.test(f)?new Date(parseInt(f),1).getFullYear().toString():f},function(f){return a.StringUtilities.format(p.i18n.commaEveryX0Years(f),f)},function(f){return p.i18n.commaYearX0ThroughYearX1()||p.i18n.commaX0ThroughX1()},function(f){return p.i18n.commaOnlyInYearX0?p.i18n.commaOnlyInYearX0():p.i18n.commaOnlyInX0()});return m},l.prototype.getSegmentDescription=function(p,m,f,u,h,g){var b=null,T=p.indexOf("/")>-1,S=p.indexOf("-")>-1,v=p.indexOf(",")>-1;if(!p)b="";else if(p==="*")b=m;else if(!T&&!S&&!v)b=a.StringUtilities.format(g(p),f(p));else if(v){for(var w=p.split(","),k="",E=0;E<w.length;E++)if(E>0&&w.length>2&&(k+=",",E<w.length-1&&(k+=" ")),E>0&&w.length>1&&(E==w.length-1||w.length==2)&&(k+="".concat(this.i18n.spaceAnd()," ")),w[E].indexOf("/")>-1||w[E].indexOf("-")>-1){var $=w[E].indexOf("-")>-1&&w[E].indexOf("/")==-1,ce=this.getSegmentDescription(w[E],m,f,u,$?this.i18n.commaX0ThroughX1:h,g);$&&(ce=ce.replace(", ","")),k+=ce;}else T?k+=this.getSegmentDescription(w[E],m,f,u,h,g):k+=f(w[E]);T?b=k:b=a.StringUtilities.format(g(p),k);}else if(T){var w=p.split("/");if(b=a.StringUtilities.format(u(w[1]),w[1]),w[0].indexOf("-")>-1){var le=this.generateRangeSegmentDescription(w[0],h,f);le.indexOf(", ")!=0&&(b+=", "),b+=le;}else if(w[0].indexOf("*")==-1){var Z=a.StringUtilities.format(g(w[0]),f(w[0]));Z=Z.replace(", ",""),b+=a.StringUtilities.format(this.i18n.commaStartingX0(),Z);}}else S&&(b=this.generateRangeSegmentDescription(p,h,f));return b},l.prototype.generateRangeSegmentDescription=function(p,m,f){var u="",h=p.split("-"),g=f(h[0],1),b=f(h[1],2),T=m(p);return u+=a.StringUtilities.format(T,g,b),u},l.prototype.formatTime=function(p,m,f){var u=0,h=0,g=parseInt(p)+u,b=parseInt(m)+h;b>=60?(b-=60,g+=1):b<0&&(b+=60,g-=1),g>=24?g=g-24:g<0&&(g=24+g);var T="",S=false;this.options.use24HourTimeFormat||(S=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),T=S?"".concat(this.getPeriod(g)," "):" ".concat(this.getPeriod(g)),g>12&&(g-=12),g===0&&(g=12));var v="";return f&&(v=":".concat(("00"+f).substring(f.length))),"".concat(S?T:"").concat(("00"+g.toString()).substring(g.toString().length),":").concat(("00"+b.toString()).substring(b.toString().length)).concat(v).concat(S?"":T)},l.prototype.transformVerbosity=function(p,m){if(!m&&(p=p.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),p=p.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),p=p.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),p=p.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var f=0,u=Object.entries(this.i18n.conciseVerbosityReplacements());f<u.length;f++){var h=u[f],g=h[0],b=h[1];p=p.replace(new RegExp(g,"g"),b);}return p},l.prototype.getPeriod=function(p){return p>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},l.locales={},l})();n.ExpressionDescriptor=d;}),747:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.enLocaleLoader=void 0;var a=i(486),c=(function(){function d(){}return d.prototype.load=function(l){l.en=new a.en;},d})();n.enLocaleLoader=c;}),486:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.en=void 0;var i=(function(){function a(){}return a.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},a.prototype.atX0MinutesPastTheHourGt20=function(){return null},a.prototype.commaMonthX0ThroughMonthX1=function(){return null},a.prototype.commaYearX0ThroughYearX1=function(){return null},a.prototype.use24HourTimeFormatByDefault=function(){return false},a.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return "An error occurred when generating the expression description. Check the cron expression syntax."},a.prototype.everyMinute=function(){return "every minute"},a.prototype.everyHour=function(){return "every hour"},a.prototype.atSpace=function(){return "At "},a.prototype.everyMinuteBetweenX0AndX1=function(){return "Every minute between %s and %s"},a.prototype.at=function(){return "At"},a.prototype.spaceAnd=function(){return " and"},a.prototype.everySecond=function(){return "every second"},a.prototype.everyX0Seconds=function(){return "every %s seconds"},a.prototype.secondsX0ThroughX1PastTheMinute=function(){return "seconds %s through %s past the minute"},a.prototype.atX0SecondsPastTheMinute=function(){return "at %s seconds past the minute"},a.prototype.everyX0Minutes=function(){return "every %s minutes"},a.prototype.minutesX0ThroughX1PastTheHour=function(){return "minutes %s through %s past the hour"},a.prototype.atX0MinutesPastTheHour=function(){return "at %s minutes past the hour"},a.prototype.everyX0Hours=function(){return "every %s hours"},a.prototype.betweenX0AndX1=function(){return "between %s and %s"},a.prototype.atX0=function(){return "at %s"},a.prototype.commaEveryDay=function(){return ", every day"},a.prototype.commaEveryX0DaysOfTheWeek=function(){return ", every %s days of the week"},a.prototype.commaX0ThroughX1=function(){return ", %s through %s"},a.prototype.commaAndX0ThroughX1=function(){return ", %s through %s"},a.prototype.first=function(){return "first"},a.prototype.second=function(){return "second"},a.prototype.third=function(){return "third"},a.prototype.fourth=function(){return "fourth"},a.prototype.fifth=function(){return "fifth"},a.prototype.commaOnThe=function(){return ", on the "},a.prototype.spaceX0OfTheMonth=function(){return " %s of the month"},a.prototype.lastDay=function(){return "the last day"},a.prototype.commaOnTheLastX0OfTheMonth=function(){return ", on the last %s of the month"},a.prototype.commaOnlyOnX0=function(){return ", only on %s"},a.prototype.commaAndOnX0=function(){return ", and on %s"},a.prototype.commaEveryX0Months=function(){return ", every %s months"},a.prototype.commaOnlyInX0=function(){return ", only in %s"},a.prototype.commaOnTheLastDayOfTheMonth=function(){return ", on the last day of the month"},a.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return ", on the last weekday of the month"},a.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return ", %s days before the last day of the month"},a.prototype.firstWeekday=function(){return "first weekday"},a.prototype.weekdayNearestDayX0=function(){return "weekday nearest day %s"},a.prototype.commaOnTheX0OfTheMonth=function(){return ", on the %s of the month"},a.prototype.commaEveryX0Days=function(){return ", every %s days"},a.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return ", between day %s and %s of the month"},a.prototype.commaOnDayX0OfTheMonth=function(){return ", on day %s of the month"},a.prototype.commaEveryHour=function(){return ", every hour"},a.prototype.commaEveryX0Years=function(){return ", every %s years"},a.prototype.commaStartingX0=function(){return ", starting %s"},a.prototype.daysOfTheWeek=function(){return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},a.prototype.monthsOfTheYear=function(){return ["January","February","March","April","May","June","July","August","September","October","November","December"]},a.prototype.atReboot=function(){return "Run once, at startup"},a})();n.en=i;}),515:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true});function i(c,d){if(!c)throw new Error(d)}var a=(function(){function c(){}return c.secondRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var m=parseInt(l[p],10);i(m>=0&&m<=59,"seconds part must be >= 0 and <= 59");}},c.minuteRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var m=parseInt(l[p],10);i(m>=0&&m<=59,"minutes part must be >= 0 and <= 59");}},c.hourRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var m=parseInt(l[p],10);i(m>=0&&m<=23,"hours part must be >= 0 and <= 23");}},c.dayOfMonthRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var m=parseInt(l[p],10);i(m>=1&&m<=31,"DOM part must be >= 1 and <= 31");}},c.monthRange=function(d,l){for(var p=d.split(","),m=0;m<p.length;m++)if(!isNaN(parseInt(p[m],10))){var f=parseInt(p[m],10);i(f>=1&&f<=12,l?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12");}},c.dayOfWeekRange=function(d,l){for(var p=d.split(","),m=0;m<p.length;m++)if(!isNaN(parseInt(p[m],10))){var f=parseInt(p[m],10);i(f>=0&&f<=6,l?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7");}},c})();n.default=a;}),823:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.StringUtilities=void 0;var i=(function(){function a(){}return a.format=function(c){for(var d=[],l=1;l<arguments.length;l++)d[l-1]=arguments[l];return c.replace(/%s/g,function(p){for(var m=[],f=1;f<arguments.length;f++)m[f-1]=arguments[f];return d.shift()})},a.containsAny=function(c,d){return d.some(function(l){return c.indexOf(l)>-1})},a})();n.StringUtilities=i;})},e={};function t(s){var n=e[s];if(n!==void 0)return n.exports;var i=e[s]={exports:{}};return o[s](i,i.exports,t),i.exports}var r={};return (()=>{var s=r;Object.defineProperty(s,"__esModule",{value:true}),s.toString=void 0;var n=t(333),i=t(747);n.ExpressionDescriptor.initialize(new i.enLocaleLoader),s.default=n.ExpressionDescriptor;var a=n.ExpressionDescriptor.toString;s.toString=a;})(),r})());});var O=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var oo=o=>(e,t,r)=>{let s=O.get(e,t);return s||(s={middlewares:[]}),s.cacheConfig=o,O.set(e,t,s),r};G();G();var er=class{getCwd(){switch(j.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},L=new er;G();var tr=class{basename(e){switch(j.type){case "node":case "bun":case "deno":return ht__default.default.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(j.type){case "node":case "bun":case "deno":return ht__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(j.type){case "bun":case "node":case "deno":return ht__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(j.type){case "bun":case "node":case "deno":return ht__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},x=new tr;var rr=class{async glob(...e){let t=await import('fs/promises'),r=L.getCwd(),s=x.resolve(r,e[1]?.cwd??""),n=[];for await(let i of t.glob(...e)){if(typeof i=="string"){n.push(x.resolve(s,i));continue}i.isFile()&&n.push(x.resolve(s,i.name));}return n}async mkdir(e,t){switch(j.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(j.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(j.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.arrayBuffer());case "deno":let i=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(i):new Uint8Array(i)}}async writeFile(e,t){switch(j.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(j.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.size}}}async unlink(e){switch(j.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(j.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(j.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},y=new rr;var R=class extends Error{constructor(e){super(e);}};var io=()=>no__default.default({level:"info",formatters:{level:e=>({level:e})}}),M=io();var ft=class extends R{constructor(e){super(`Failed to convert Zod schema to JSON Schema. This usually happens when using Zod v3 schemas with Zod v4. Make sure you're importing from 'zod' (v4) and not 'zod/v3'. Original error: ${e.message}`);}};var Le=class extends R{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var gt=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"?module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))):Zt("module").createRequire?.((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))??__filename)??Zt,pe=async o=>{let e=x.join(process.cwd(),"node_modules");if(!await y.exists(e))return o;let r=[];for(let s of o){let n=x.join(e,s);await y.exists(n)||r.push(s);}return r},U=async()=>await y.exists(x.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await y.exists(x.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await y.exists(x.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await y.exists(x.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await y.exists(x.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],D=async(o,e,t,r,s=true)=>{let n=Vr__namespace.createInterface({input:process.stdin,output:process.stdout}),i=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
|
|
2
2
|
${i}
|
|
3
3
|
(y/n): `;return new Promise(c=>{n.question(a,d=>{if(n.close(),d.toLowerCase()==="y"||d.toLowerCase()==="yes"){child_process.execSync(o,r),c(true);return}c(false);});})};var H=class{static zodModule=null;static zodSchemaCache=new WeakSet;static load(){if(this.zodModule)return this.zodModule;try{return this.zodModule=gt("zod"),this.ensureZodV4(),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
|
|
4
|
-
Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new Le;if(!("toJSONSchema"in e))throw new Le}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new Le;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new ft(r):r}}};var yt=class extends R{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var I=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=gt("@sinclair/typebox"),this.typeboxModule}catch{throw new yt}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};function We(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let i=t[n];if(i&&typeof i=="object"&&!("$ref"in i)){let a=We(i);a!==i&&(s=true),r[n]=a;}else r[n]=i;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=We(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let i of r)if(i&&typeof i=="object"&&!("$ref"in i)){let a=We(i);a!==i&&(n=true),s.push(a);}else s.push(i);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let i in r){let a=r[i];if(a&&typeof a=="object"){let c=We(a);c!==a&&(n=true),s[i]=c;}else s[i]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var q=class{static ajv=new ajv.Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let n=We(e),i=lo__default.default(n,{ajv:this.ajv.opts});return r.set(t,i),i}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,n]of Object.entries(e)){let i=Number(s),a=null;if(H.isZodSchema(n)){let c=H.toJSONSchema(n);a=this.getOrCreateSerializer(c,"fast_stringify_zod");}else I.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"fast_stringify_json"));a&&r.set(i,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new ajv.Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var sr=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);q.storeJsonSchema(t,"serialize_zod"),q.getOrCompileValidator(t,"serialize_zod");}catch(t){M.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(I.isTypeBoxSchema(o)){try{q.storeJsonSchema(o,"serialize_typebox"),q.getOrCompileValidator(o,"serialize_typebox");}catch(t){M.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{q.storeJsonSchema(o,"serialize_json"),q.getOrCompileValidator(o,"serialize_json");}catch(t){M.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};q.storeJsonSchema(t,`serialize_primitive_${e}`),q.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){M.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},Zr=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);q.storeJsonSchema(t,"zod_schema"),q.getOrCompileValidator(t,"zod_schema");}catch(t){M.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(I.isTypeBoxSchema(o)){try{q.storeJsonSchema(o,"typebox_schema"),q.getOrCompileValidator(o,"typebox_schema");}catch(t){M.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{q.storeJsonSchema(o,"json_schema"),q.getOrCompileValidator(o,"json_schema");}catch(t){M.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};q.storeJsonSchema(t,`primitive_${e}`),q.getOrCompileValidator(t,`primitive_${e}`);}catch(t){M.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},Yr=(o,e)=>{o&&Zr(o),e&&Zr(e);},es=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,sr(r),H.isZodSchema(r))try{let n=H.toJSONSchema(r);q.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else I.isTypeBoxSchema(r)?q.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&q.getOrCreateSerializer(r,"fast_stringify_json");}return e};var ts=null;function rs(o){ts=o;}function ss(){return ts}var os=(o,e)=>async function(t,r,...s){try{if(e.headers){let n=t.validateHeaders(e.headers,!0);t.headers=n;}if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){let i=ss();return i?i(t,r,n):r.badRequest(n)}};var ho=util.promisify(zlib.gzip),fo=util.promisify(zlib.gunzip);function is(o){let{prefix:e,method:t,route:r,routeParams:s,body:n,bodyKeys:i,includeBody:a=true,query:c,queryKeys:d,includeQuery:p=false,headers:l,headerKeys:m,includeHeaders:f=false,fromRequestValue:u}=o,h=[e,"global"];if(h.push(t.toUpperCase(),go(r)),s&&Object.keys(s).length>0&&h.push(Ke(s)),p&&c){let g=or(c,d);Object.keys(g).length>0&&h.push("q:"+Ke(g));}if(a&&n!=null){let g=or(n,i);h.push("b:"+Ke(g));}if(f&&l){let g=or(l,m);Object.keys(g).length>0&&h.push("h:"+Ke(g));}return u!=null&&h.push("c:"+Ke(u)),h.join(":")}function or(o,e){if(!e||e.length===0)return o;let t={};for(let r of e)r in o&&(t[r]=o[r]);return t}function Ke(o){let e=Ve(o);return Qo.createHash("sha256").update(e).digest("hex").substring(0,32)}function Ve(o){return o===null?"null":o===void 0?"":typeof o!="object"?JSON.stringify(o):Array.isArray(o)?"["+o.map(r=>Ve(r)||"null").join(",")+"]":"{"+Object.keys(o).filter(r=>o[r]!==void 0).sort().map(r=>JSON.stringify(r)+":"+Ve(o[r])).join(",")+"}"}function go(o){return o.toLowerCase().replace(/\/+/g,"/").replace(/\/$/,"")}function nr(o){return `lock:${o}`}function ir(o,e){return `${o}:tag:${e}`}async function as(o){return ho(Buffer.from(o,"utf-8"))}async function cs(o){return (await fo(o)).toString("utf-8")}function vt(o){let e=o.include,t=true,r=false,s=false,n,i,a;return e&&(e.body===false?t=false:Array.isArray(e.body)?(t=true,n=e.body):e.body===true&&(t=true),e.body===void 0&&(t=false),e.query===true?r=true:Array.isArray(e.query)&&(r=true,i=e.query),e.headers===true?s=true:Array.isArray(e.headers)&&(s=true,a=e.headers)),{ttl:o.ttl,useCompression:o.useCompression,tags:o.tags,lockBehavior:o.lockBehavior,includeBody:t,includeQuery:r,includeHeaders:s,bodyKeys:n,queryKeys:i,headerKeys:a,fromRequest:e?.fromRequest}}var Ne={defaultTtl:300,compressionThreshold:1024,keyPrefix:"cache",enableStats:true,lockTimeout:5e3,lockBehavior:"wait"};var ls=50,ue="x-cache",ar=(s=>(s.Hit="HIT",s.Miss="MISS",s.Wait="WAIT",s.Bypass="BYPASS",s))(ar||{});var Xe=class{log=M.child({scope:"CacheService"});provider;options;stats={hits:0,misses:0,hitRate:0,invalidations:0};constructor(e,t){this.provider=e,this.options=t;}async get(e){try{let t=await this.provider.get(e);if(!t)return this.options.enableStats&&(this.stats.misses++,this.updateHitRate()),null;this.options.enableStats&&(this.stats.hits++,this.updateHitRate());let r=JSON.parse(t),s=r.data;return r.compressed&&(s=await cs(Buffer.from(r.data,"base64"))),JSON.parse(s)}catch(t){return this.log.error({error:t,key:e},"Cache get failed"),null}}async set(e,t,r,s){try{let n=Ve(t),i=s?.compressed&&n.length>this.options.compressionThreshold,a=n;i&&(a=(await as(n)).toString("base64"));let c={data:a,compressed:i??!1,createdAt:Date.now(),ttl:r};if(await this.provider.set(e,JSON.stringify(c),r),s?.tags?.length)for(let d of s.tags){let p=ir(this.options.keyPrefix,d);await this.provider.addToSet(p,[e],r+60);}}catch(n){this.log.error({error:n,key:e},"Cache set failed");}}async invalidate(e){if(!e.length)return 0;let t=0;try{for(let r of e){let s=ir(this.options.keyPrefix,r),n=await this.provider.getSetMembers(s);if(n.length>0){let i=await this.provider.delMany([...n,s]);t+=i-1;}}this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,tags:e},"Cache invalidate failed");}return t}async invalidateKey(e){try{if(await this.provider.del(e))return this.options.enableStats&&this.stats.invalidations++,!0}catch(t){this.log.error({error:t,key:e},"Cache invalidateKey failed");}return false}async invalidatePattern(e){let t=0;try{for await(let r of this.provider.scan(e))r.length>0&&(t+=await this.provider.delMany(r));this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,pattern:e},"Cache invalidatePattern failed");}return t}async acquireLock(e){try{let t=nr(e);return await this.provider.acquireLock(t,this.options.lockTimeout)}catch(t){return this.log.error({error:t,key:e},"Cache acquireLock failed"),true}}async releaseLock(e){try{let t=nr(e);await this.provider.releaseLock(t);}catch(t){this.log.warn({error:t,key:e},"Cache releaseLock failed");}}async waitForCache(e,t){let r=Date.now();for(;Date.now()-r<t;){let s=await this.get(e);if(s!==null)return s;await new Promise(n=>setTimeout(n,ls));}return null}getStats(){return {...this.stats}}getProvider(){return this.provider}async disconnect(){await this.provider.disconnect();}updateHitRate(){let e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0;}};var bt=null,cr={...Ne};function lr(o,e){return bt=new Xe(o,e),cr=e,bt}function Ze(){return bt}function wt(){return cr}function yo(){bt=null,cr={...Ne};}function St(o,e,t){let r=M.child({scope:"CacheMiddleware"});return async(s,n,i)=>{try{let a={};if(e.includeHeaders&&s.rawHeaders)if(e.headerKeys)for(let u of e.headerKeys){let h=s.rawHeaders.get(u);h&&(a[u]=h);}else s.rawHeaders.forEach((u,h)=>{a[h]=u;});let c=s.url,d=c.startsWith("http")?new URL(c).pathname:c.split("?")[0],p=e.fromRequest?await e.fromRequest(s):void 0,l=is({prefix:t.keyPrefix,method:s.method,route:d,routeParams:s.params,body:s.body,bodyKeys:e.bodyKeys,includeBody:e.includeBody,query:s.query,queryKeys:e.queryKeys,includeQuery:e.includeQuery,headers:a,headerKeys:e.headerKeys,includeHeaders:e.includeHeaders,fromRequestValue:p});r.debug({key:l},"Generated cache key");let m=await o.get(l);if(m!==null){n.setHeader(ue,"HIT"),n.json(m);return}let f=await o.acquireLock(l);if(!f){let u=e.lockBehavior??t.lockBehavior;if(!(await vo(u,o,l,t.lockTimeout,n)).continueToHandler)return}n.setHeader(ue,"MISS"),await i();try{if(n.responseStatus>=200&&n.responseStatus<300){let u=n.getBody(),h=typeof u=="string"?JSON.parse(u):u;await o.set(l,h,e.ttl,{compressed:e.useCompression,tags:e.tags}),r.debug({key:l,ttl:e.ttl},"Cached response");}}catch(u){r.error({error:u,key:l},"Failed to cache response");}finally{f&&await o.releaseLock(l);}}catch(a){return r.error({error:a},"Cache middleware error"),n.setHeader(ue,"BYPASS"),i()}}}async function vo(o,e,t,r,s){switch(o){case "bypass":return s.setHeader(ue,"BYPASS"),{continueToHandler:true};case "fail":return s.setHeader(ue,"BYPASS"),s.setHeader("Retry-After",String(Math.ceil(r/1e3))),s.status(503).json({error:"Service Unavailable",message:"Cache computation in progress"}),{continueToHandler:false};default:{s.setHeader(ue,"WAIT");let n=await e.waitForCache(t,r);return n!==null?(s.json(n),{continueToHandler:false}):{continueToHandler:true}}}}var ps=null;function ds(o){ps=o;}function us(){return ps}var xt=o=>async(e,t,r)=>{for(let s of o)if(!await s.manager.canAccess(s.scope,s.handler,e)){let i=us();return i?i(e,t):t.unauthorized({error:"Unauthorized"})}return r()};var Ie=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},pr=class o{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,n,i,a,c=false){e=e.toUpperCase();let d=t.split("?")[0];Yr(n?.body,n?.query);let p=es(a),l=n&&(n.body||n.query||n.headers||n.all),m=l?os(s,n):s,f=l?n:void 0,u=this.trees.get(e);u||(u=new Ie,this.trees.set(e,u));let h=d.replace(/^\/+|\/+$/g,""),g=h.length===0?[]:h.split("/"),b=true,P=[],S=u;for(let w of g){if(w==="*"){b=false,S.wildcardChild||(S.wildcardChild=new Ie),S=S.wildcardChild;break}if(w.startsWith(":")){b=false;let k=w.slice(1);P.push(k),S.paramChild||(S.paramChild={node:new Ie,name:k}),S=S.paramChild.node;continue}S.staticChildren.has(w)||S.staticChildren.set(w,new Ie),S=S.staticChildren.get(w);}if(S.middleware=r,S.handler=m,P.length>0&&(S.paramName=P.join(",")),p&&this.handlerResponseSchemas.set(s,p),b){let w="/"+h,k=`${e}:${w}`;this.staticRouteCache.set(k,{middleware:r,handler:m,params:{},responseSchemas:p});}else {let w="/"+h.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),k=`${e}:${w}`;this.staticRouteCache.delete(k);}let v=this.routes.findIndex(w=>w.method===e&&w.path===t);if(v!==-1){if(!c)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[v].middleware=r,this.routes[v].handler=m,this.routes[v].swaggerOptions=i,this.routes[v].responses=a,this.routes[v].responseSchemas=p,this.routes[v].validationSchemas=f;return}this.routes.push({method:e,path:t,middleware:r,handler:m,swaggerOptions:i,responses:a,responseSchemas:p,validationSchemas:f});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,i=this.staticRouteCache.get(n);if(i)return i;let a=this.trees.get(e);if(!a)return null;let c=r.replace(/^\/+|\/+$/g,""),d=c.length===0?[]:c.split("/"),p={},l=a;for(let f=0;f<d.length;f++){let u=d[f];if(l.staticChildren.has(u)){l=l.staticChildren.get(u);continue}if(l.paramChild){p[l.paramChild.name]=u,l=l.paramChild.node;continue}if(l.wildcardChild){p["*"]=d.slice(f).join("/"),l=l.wildcardChild;break}return null}if(!l.handler||!l.middleware)return null;let m=this.handlerResponseSchemas.get(l.handler);return {middleware:l.middleware,handler:l.handler,params:p,responseSchemas:m}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.policy){let i=(Array.isArray(r.policy)?r.policy:[r.policy]).map(a=>({scope:a.scope,handler:a.handler,manager:a.manager}));s.unshift(xt(i));}if(r.cache){let n=Ze();if(n){let i=vt(r.cache),a=St(n,i,wt());s.push(a);}}return {middlewares:s,handler:t,body:r.body,query:r.query,headers:r.headers,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:p,responses:l,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:p};this.addOrUpdate("GET",s,f,i,u,m,l);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:p,responses:l,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:p};this.addOrUpdate("POST",s,f,i,u,m,l);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:p,responses:l,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:p};this.addOrUpdate("PATCH",s,f,i,u,m,l);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:p,responses:l,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:p};this.addOrUpdate("PUT",s,f,i,u,m,l);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:p,responses:l,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:p};this.addOrUpdate("DELETE",s,f,i,u,m,l);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:p,responses:l,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:p};this.addOrUpdate("OPTIONS",s,f,i,u,m,l);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:p,responses:l,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:p};this.addOrUpdate("HEAD",s,f,i,u,m,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new o(i,[...this.middlewares,...s]);n?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.validationSchemas,c.swaggerOptions,c.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}},_=new pr;var ur=class o{static cronstrue=null;static async getCronstrue(){return this.cronstrue||(this.cronstrue=await Promise.resolve().then(()=>so(ms())).catch(()=>{throw new R("cronstrue not installed as a dependency, it is required in order to consult cron jobs in UI")})),this.cronstrue}async generate(){let e=await o.getCronstrue(),t=J.scheduledJobs,r=new Set,s=new Set,i=t.map(p=>{let l=e.default.toString(p.args[0])||"-",m=p.args[2]?.timezone||"System Default";return r.add(l),s.add(m),{name:p.name,schedule:p.args[0],frequency:l,timezone:m}}).map(p=>`
|
|
5
|
-
<tr data-name="${this.escapeHtml(
|
|
6
|
-
<td class="name">${this.escapeHtml(
|
|
7
|
-
<td class="schedule"><code>${this.escapeHtml(
|
|
8
|
-
<td class="frequency">${this.escapeHtml(
|
|
9
|
-
<td class="timezone">${this.escapeHtml(
|
|
10
|
-
</tr>`).join(""),a=Array.from(r).sort().map(
|
|
4
|
+
Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new Le;if(!("toJSONSchema"in e))throw new Le}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new Le;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new ft(r):r}}};var yt=class extends R{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var I=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=gt("@sinclair/typebox"),this.typeboxModule}catch{throw new yt}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};function We(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let i=t[n];if(i&&typeof i=="object"&&!("$ref"in i)){let a=We(i);a!==i&&(s=true),r[n]=a;}else r[n]=i;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=We(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let i of r)if(i&&typeof i=="object"&&!("$ref"in i)){let a=We(i);a!==i&&(n=true),s.push(a);}else s.push(i);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let i in r){let a=r[i];if(a&&typeof a=="object"){let c=We(a);c!==a&&(n=true),s[i]=c;}else s[i]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var q=class{static ajv=new ajv.Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let n=We(e),i=lo__default.default(n,{ajv:this.ajv.opts});return r.set(t,i),i}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,n]of Object.entries(e)){let i=Number(s),a=null;if(H.isZodSchema(n)){let c=H.toJSONSchema(n);a=this.getOrCreateSerializer(c,"fast_stringify_zod");}else I.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"fast_stringify_json"));a&&r.set(i,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new ajv.Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var sr=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);q.storeJsonSchema(t,"serialize_zod"),q.getOrCompileValidator(t,"serialize_zod");}catch(t){M.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(I.isTypeBoxSchema(o)){try{q.storeJsonSchema(o,"serialize_typebox"),q.getOrCompileValidator(o,"serialize_typebox");}catch(t){M.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{q.storeJsonSchema(o,"serialize_json"),q.getOrCompileValidator(o,"serialize_json");}catch(t){M.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};q.storeJsonSchema(t,`serialize_primitive_${e}`),q.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){M.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},Zr=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);q.storeJsonSchema(t,"zod_schema"),q.getOrCompileValidator(t,"zod_schema");}catch(t){M.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(I.isTypeBoxSchema(o)){try{q.storeJsonSchema(o,"typebox_schema"),q.getOrCompileValidator(o,"typebox_schema");}catch(t){M.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{q.storeJsonSchema(o,"json_schema"),q.getOrCompileValidator(o,"json_schema");}catch(t){M.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};q.storeJsonSchema(t,`primitive_${e}`),q.getOrCompileValidator(t,`primitive_${e}`);}catch(t){M.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},Yr=(o,e)=>{o&&Zr(o),e&&Zr(e);},es=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,sr(r),H.isZodSchema(r))try{let n=H.toJSONSchema(r);q.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else I.isTypeBoxSchema(r)?q.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&q.getOrCreateSerializer(r,"fast_stringify_json");}return e};var ts=null;function rs(o){ts=o;}function ss(){return ts}var os=(o,e)=>async function(t,r,...s){try{if(e.headers){let n=t.validateHeaders(e.headers,!0);t.headers=n;}if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){let i=ss();return i?i(t,r,n):r.badRequest(n)}};var ho=util.promisify(zlib.gzip),fo=util.promisify(zlib.gunzip);function is(o){let{prefix:e,method:t,route:r,routeParams:s,body:n,bodyKeys:i,includeBody:a=true,query:c,queryKeys:d,includeQuery:l=false,headers:p,headerKeys:m,includeHeaders:f=false,fromRequestValue:u}=o,h=[e,"global"];if(h.push(t.toUpperCase(),go(r)),s&&Object.keys(s).length>0&&h.push(Ke(s)),l&&c){let g=or(c,d);Object.keys(g).length>0&&h.push("q:"+Ke(g));}if(a&&n!=null){let g=or(n,i);h.push("b:"+Ke(g));}if(f&&p){let g=or(p,m);Object.keys(g).length>0&&h.push("h:"+Ke(g));}return u!=null&&h.push("c:"+Ke(u)),h.join(":")}function or(o,e){if(!e||e.length===0)return o;let t={};for(let r of e)r in o&&(t[r]=o[r]);return t}function Ke(o){let e=Ve(o);return Qo.createHash("sha256").update(e).digest("hex").substring(0,32)}function Ve(o){return o===null?"null":o===void 0?"":typeof o!="object"?JSON.stringify(o):Array.isArray(o)?"["+o.map(r=>Ve(r)||"null").join(",")+"]":"{"+Object.keys(o).filter(r=>o[r]!==void 0).sort().map(r=>JSON.stringify(r)+":"+Ve(o[r])).join(",")+"}"}function go(o){return o.toLowerCase().replace(/\/+/g,"/").replace(/\/$/,"")}function nr(o){return `lock:${o}`}function ir(o,e){return `${o}:tag:${e}`}async function as(o){return ho(Buffer.from(o,"utf-8"))}async function cs(o){return (await fo(o)).toString("utf-8")}function vt(o){let e=o.include,t=true,r=false,s=false,n,i,a;return e&&(e.body===false?t=false:Array.isArray(e.body)?(t=true,n=e.body):e.body===true&&(t=true),e.body===void 0&&(t=false),e.query===true?r=true:Array.isArray(e.query)&&(r=true,i=e.query),e.headers===true?s=true:Array.isArray(e.headers)&&(s=true,a=e.headers)),{ttl:o.ttl,useCompression:o.useCompression,tags:o.tags,lockBehavior:o.lockBehavior,includeBody:t,includeQuery:r,includeHeaders:s,bodyKeys:n,queryKeys:i,headerKeys:a,fromRequest:e?.fromRequest}}var Ne={defaultTtl:300,compressionThreshold:1024,keyPrefix:"cache",enableStats:true,lockTimeout:5e3,lockBehavior:"wait"};var ls=50,ue="x-cache",ar=(s=>(s.Hit="HIT",s.Miss="MISS",s.Wait="WAIT",s.Bypass="BYPASS",s))(ar||{});var Xe=class{log=M.child({scope:"CacheService"});provider;options;stats={hits:0,misses:0,hitRate:0,invalidations:0};constructor(e,t){this.provider=e,this.options=t;}async get(e){try{let t=await this.provider.get(e);if(!t)return this.options.enableStats&&(this.stats.misses++,this.updateHitRate()),null;this.options.enableStats&&(this.stats.hits++,this.updateHitRate());let r=JSON.parse(t),s=r.data;return r.compressed&&(s=await cs(Buffer.from(r.data,"base64"))),JSON.parse(s)}catch(t){return this.log.error({error:t,key:e},"Cache get failed"),null}}async set(e,t,r,s){try{let n=Ve(t),i=s?.compressed&&n.length>this.options.compressionThreshold,a=n;i&&(a=(await as(n)).toString("base64"));let c={data:a,compressed:i??!1,createdAt:Date.now(),ttl:r};if(await this.provider.set(e,JSON.stringify(c),r),s?.tags?.length)for(let d of s.tags){let l=ir(this.options.keyPrefix,d);await this.provider.addToSet(l,[e],r+60);}}catch(n){this.log.error({error:n,key:e},"Cache set failed");}}async invalidate(e){if(!e.length)return 0;let t=0;try{for(let r of e){let s=ir(this.options.keyPrefix,r),n=await this.provider.getSetMembers(s);if(n.length>0){let i=await this.provider.delMany([...n,s]);t+=i-1;}}this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,tags:e},"Cache invalidate failed");}return t}async invalidateKey(e){try{if(await this.provider.del(e))return this.options.enableStats&&this.stats.invalidations++,!0}catch(t){this.log.error({error:t,key:e},"Cache invalidateKey failed");}return false}async invalidatePattern(e){let t=0;try{for await(let r of this.provider.scan(e))r.length>0&&(t+=await this.provider.delMany(r));this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,pattern:e},"Cache invalidatePattern failed");}return t}async acquireLock(e){try{let t=nr(e);return await this.provider.acquireLock(t,this.options.lockTimeout)}catch(t){return this.log.error({error:t,key:e},"Cache acquireLock failed"),true}}async releaseLock(e){try{let t=nr(e);await this.provider.releaseLock(t);}catch(t){this.log.warn({error:t,key:e},"Cache releaseLock failed");}}async waitForCache(e,t){let r=Date.now();for(;Date.now()-r<t;){let s=await this.get(e);if(s!==null)return s;await new Promise(n=>setTimeout(n,ls));}return null}getStats(){return {...this.stats}}getProvider(){return this.provider}async disconnect(){await this.provider.disconnect();}updateHitRate(){let e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0;}};var bt=null,cr={...Ne};function lr(o,e){return bt=new Xe(o,e),cr=e,bt}function Ze(){return bt}function wt(){return cr}function yo(){bt=null,cr={...Ne};}function St(o,e,t){let r=M.child({scope:"CacheMiddleware"});return async(s,n,i)=>{try{let a={};if(e.includeHeaders&&s.rawHeaders)if(e.headerKeys)for(let u of e.headerKeys){let h=s.rawHeaders.get(u);h&&(a[u]=h);}else s.rawHeaders.forEach((u,h)=>{a[h]=u;});let c=s.url,d=c.startsWith("http")?new URL(c).pathname:c.split("?")[0],l=e.fromRequest?await e.fromRequest(s):void 0,p=is({prefix:t.keyPrefix,method:s.method,route:d,routeParams:s.params,body:s.body,bodyKeys:e.bodyKeys,includeBody:e.includeBody,query:s.query,queryKeys:e.queryKeys,includeQuery:e.includeQuery,headers:a,headerKeys:e.headerKeys,includeHeaders:e.includeHeaders,fromRequestValue:l});r.debug({key:p},"Generated cache key");let m=await o.get(p);if(m!==null){n.setHeader(ue,"HIT"),n.json(m);return}let f=await o.acquireLock(p);if(!f){let u=e.lockBehavior??t.lockBehavior;if(!(await vo(u,o,p,t.lockTimeout,n)).continueToHandler)return}n.setHeader(ue,"MISS"),await i();try{if(n.responseStatus>=200&&n.responseStatus<300){let u=n.getBody(),h=typeof u=="string"?JSON.parse(u):u;await o.set(p,h,e.ttl,{compressed:e.useCompression,tags:e.tags}),r.debug({key:p,ttl:e.ttl},"Cached response");}}catch(u){r.error({error:u,key:p},"Failed to cache response");}finally{f&&await o.releaseLock(p);}}catch(a){return r.error({error:a},"Cache middleware error"),n.setHeader(ue,"BYPASS"),i()}}}async function vo(o,e,t,r,s){switch(o){case "bypass":return s.setHeader(ue,"BYPASS"),{continueToHandler:true};case "fail":return s.setHeader(ue,"BYPASS"),s.setHeader("Retry-After",String(Math.ceil(r/1e3))),s.status(503).json({error:"Service Unavailable",message:"Cache computation in progress"}),{continueToHandler:false};default:{s.setHeader(ue,"WAIT");let n=await e.waitForCache(t,r);return n!==null?(s.json(n),{continueToHandler:false}):{continueToHandler:true}}}}var ps=null;function ds(o){ps=o;}function us(){return ps}var xt=o=>async(e,t,r)=>{for(let s of o)if(!await s.manager.canAccess(s.scope,s.handler,e)){let i=us();return i?i(e,t):t.unauthorized({error:"Unauthorized"})}return r()};var Ie=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},pr=class o{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,n,i,a,c=false){e=e.toUpperCase();let d=t.split("?")[0];Yr(n?.body,n?.query);let l=es(a),p=n&&(n.body||n.query||n.headers||n.all),m=p?os(s,n):s,f=p?n:void 0,u=this.trees.get(e);u||(u=new Ie,this.trees.set(e,u));let h=d.replace(/^\/+|\/+$/g,""),g=h.length===0?[]:h.split("/"),b=true,T=[],S=u;for(let w of g){if(w==="*"){b=false,S.wildcardChild||(S.wildcardChild=new Ie),S=S.wildcardChild;break}if(w.startsWith(":")){b=false;let k=w.slice(1);T.push(k),S.paramChild||(S.paramChild={node:new Ie,name:k}),S=S.paramChild.node;continue}S.staticChildren.has(w)||S.staticChildren.set(w,new Ie),S=S.staticChildren.get(w);}if(S.middleware=r,S.handler=m,T.length>0&&(S.paramName=T.join(",")),l&&this.handlerResponseSchemas.set(s,l),b){let w="/"+h,k=`${e}:${w}`;this.staticRouteCache.set(k,{middleware:r,handler:m,params:{},responseSchemas:l});}else {let w="/"+h.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),k=`${e}:${w}`;this.staticRouteCache.delete(k);}let v=this.routes.findIndex(w=>w.method===e&&w.path===t);if(v!==-1){if(!c)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[v].middleware=r,this.routes[v].handler=m,this.routes[v].swaggerOptions=i,this.routes[v].responses=a,this.routes[v].responseSchemas=l,this.routes[v].validationSchemas=f;return}this.routes.push({method:e,path:t,middleware:r,handler:m,swaggerOptions:i,responses:a,responseSchemas:l,validationSchemas:f});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,i=this.staticRouteCache.get(n);if(i)return i;let a=this.trees.get(e);if(!a)return null;let c=r.replace(/^\/+|\/+$/g,""),d=c.length===0?[]:c.split("/"),l={},p=a;for(let f=0;f<d.length;f++){let u=d[f];if(p.staticChildren.has(u)){p=p.staticChildren.get(u);continue}if(p.paramChild){l[p.paramChild.name]=u,p=p.paramChild.node;continue}if(p.wildcardChild){l["*"]=d.slice(f).join("/"),p=p.wildcardChild;break}return null}if(!p.handler||!p.middleware)return null;let m=this.handlerResponseSchemas.get(p.handler);return {middleware:p.middleware,handler:p.handler,params:l,responseSchemas:m}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.policy){let i=(Array.isArray(r.policy)?r.policy:[r.policy]).map(a=>({scope:a.scope,handler:a.handler,manager:a.manager}));s.unshift(xt(i));}if(r.cache){let n=Ze();if(n){let i=vt(r.cache),a=St(n,i,wt());s.push(a);}}return {middlewares:s,handler:t,body:r.body,query:r.query,headers:r.headers,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:l,responses:p,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:l};this.addOrUpdate("GET",s,f,i,u,m,p);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:l,responses:p,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:l};this.addOrUpdate("POST",s,f,i,u,m,p);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:l,responses:p,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:l};this.addOrUpdate("PATCH",s,f,i,u,m,p);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:l,responses:p,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:l};this.addOrUpdate("PUT",s,f,i,u,m,p);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:l,responses:p,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:l};this.addOrUpdate("DELETE",s,f,i,u,m,p);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:l,responses:p,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:l};this.addOrUpdate("OPTIONS",s,f,i,u,m,p);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:d,all:l,responses:p,swaggerOptions:m}=this.extractOptionsAndHandler(t,r),f=[...this.middlewares,...n],u={body:a,query:c,headers:d,all:l};this.addOrUpdate("HEAD",s,f,i,u,m,p);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new o(i,[...this.middlewares,...s]);n?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.validationSchemas,c.swaggerOptions,c.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}},_=new pr;var ur=class o{static cronstrue=null;static async getCronstrue(){return this.cronstrue||(this.cronstrue=await Promise.resolve().then(()=>so(ms())).catch(()=>{throw new R("cronstrue not installed as a dependency, it is required in order to consult cron jobs in UI")})),this.cronstrue}async generate(){let e=await o.getCronstrue(),t=J.scheduledJobs,r=new Set,s=new Set,i=t.map(l=>{let p=e.default.toString(l.args[0])||"-",m=l.args[2]?.timezone||"System Default";return r.add(p),s.add(m),{name:l.name,schedule:l.args[0],frequency:p,timezone:m}}).map(l=>`
|
|
5
|
+
<tr data-name="${this.escapeHtml(l.name.toLowerCase())}" data-frequency="${this.escapeHtml(l.frequency)}" data-timezone="${this.escapeHtml(l.timezone)}">
|
|
6
|
+
<td class="name">${this.escapeHtml(l.name)}</td>
|
|
7
|
+
<td class="schedule"><code>${this.escapeHtml(l.schedule)}</code></td>
|
|
8
|
+
<td class="frequency">${this.escapeHtml(l.frequency)}</td>
|
|
9
|
+
<td class="timezone">${this.escapeHtml(l.timezone)}</td>
|
|
10
|
+
</tr>`).join(""),a=Array.from(r).sort().map(l=>`<option value="${this.escapeHtml(l)}">${this.escapeHtml(l)}</option>`).join(""),c=Array.from(s).sort().map(l=>`<option value="${this.escapeHtml(l)}">${this.escapeHtml(l)}</option>`).join(""),d=t.length===0?'<tr><td colspan="4" class="empty-state">No cron jobs configured</td></tr>':"";return `<!DOCTYPE html>
|
|
11
11
|
<html lang="en">
|
|
12
12
|
<head>
|
|
13
13
|
<meta charset="UTF-8">
|
|
@@ -490,8 +490,8 @@ Zod is a peer dependency required when using Zod schemas for validation.`)}}stat
|
|
|
490
490
|
})();
|
|
491
491
|
</script>
|
|
492
492
|
</body>
|
|
493
|
-
</html>`}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},mr=new ur;var J=class{static scheduledJobs=[];static logger=M.child({scope:"CronService"});static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new R("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:L.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),M.error(s);});}));}},bo=o=>{J.globalErrorHandler=o.bind(J);},wo=async o=>{if(!o||o.path.length===0)throw new R("Cron UI path is required");let e=await mr.generate();_.addOrUpdate("GET",o.path,[],(t,r)=>{r.html(e);},void 0,void 0,void 0,true);};var So=(o,e)=>function(t,r,s){let n=s.value,i=async(...a)=>{let c=new t.constructor;return await n.apply(c,a)};return J.register(`${t.constructor.name}.${r}`,o,i,e),s};G();var hr=class{getCliArgs(){switch(j.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(j.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(s)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},fr=new hr;var Pt=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Rt=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),hs=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var ve=(o,e)=>{if(!o||typeof o!="string")return e;let t=o.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(s){let n=Number.parseFloat(s[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var xo=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:fs(r)}}return {name:o,value:true}},fs=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},be=()=>{let o=fr.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let n=xo(s);if(n){if(n.value===true&&r+1<o.length){let i=o[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=fs(i),r++);}if(n.name in t){let i=t[n.name];Array.isArray(i)?i.push(n.value):t[n.name]=[i,n.value];}else t[n.name]=n.value;}continue}e.push(s);}}return {args:e,flags:t}};var Ct=()=>fr.getCliArgs()[0]||null;var we="VALIDATION_ERROR";var gs=be().args.slice(1),B=o=>(e,t)=>{let r=Ct();if(!r||r!==e.commandName)return;let s=t;O.set(e,t,{type:"arg",name:s,description:o.description});let n=gs.length?gs.shift():o.defaultValue;if(o.required&&!n){let i=O.get(e,we);O.set(e,we,[...i||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&n&&(n=o.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var Y=o=>(e,t)=>{let r=Ct();if(!r||r!==e.commandName)return;let s=o.name||t,n=be().flags,i=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],a=[s,...i],c=o.defaultValue;for(let d of a){let p=[d,`-${d}`,`--${d}`];for(let l of p)if(l in n){let m=n[l];o.type==="list"?c=(Array.isArray(m)?m:[m]).map(u=>{let h=String(u);return o.parse?o.parse(h):h}):(c=m,o.type==="boolean"?c=!!c:o.type==="number"?c=Number(c):o.type==="string"&&(c=String(c)),o.parse&&(c=o.parse(c)));break}if(c!==o.defaultValue)break}if(O.set(e,t,{type:"flag",name:s,aliases:i||[],description:o.description}),o.required&&(o.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let p=O.get(e,we);O.set(e,we,[...p||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};Y.boolean=o=>Y({...o,type:"boolean"});Y.string=o=>Y({...o,type:"string"});Y.number=o=>Y({...o,type:"number"});Y.list=o=>Y({...o,type:"list"});Y.array=o=>Y({...o,type:"list"});var C=Y;var To=(o,e)=>t=>{let r=O.get(t.prototype,"__class__"),s=r?.middlewares||[],n=r?.policies||[],i=O.getAll(t.prototype),a=new t;if(i){for(let[c,d]of i.entries()){if(!d.route)continue;let p=t.prototype[c].bind(a),l=o?x.join(o,d.route.path):d.route.path,m=[...n,...d.policies||[]],f=m.length>0?[xt(m)]:[],u=[...s,...f,...d.middlewares||[]];if(d.cacheConfig){let h=Ze();if(h){let g=vt(d.cacheConfig),b=St(h,g,wt());u.push(b);}}_.addOrUpdate(d.route.method,l,u,p,{service:t.name.replace(/Controller$/,""),...e,...d.documentation});}O.clear(t.prototype);}};var Po=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"DELETE"},O.set(t,r,n),s};var Ro=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"GET"},O.set(t,r,n),s};var Co=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PATCH"},O.set(t,r,n),s};var Oo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"POST"},O.set(t,r,n),s};var Mo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PUT"},O.set(t,r,n),s};var jo=o=>(e,t,r)=>{if(typeof t>"u"){let n=O.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!o)throw new Error(`Middleware ${String(o)} not found, are you sure you defined it before using it?`);return Array.isArray(o)||(o=[o]),n.middlewares.push(...o),O.set(e.prototype,"__class__",n),e}let s=O.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(o)||(o=[o]),s.middlewares.push(...o),O.set(e,t,s),r};var Ot=(o,e,t=false)=>{if(!o(e)){if(t)throw new ajv.ValidationError(o.errors||[]);return e}return e};var Ye=new WeakMap,ys=new WeakSet,qo=o=>{let{jsonSchema:e,prefix:t}=vs(o);try{return q.getOrCompileValidator(e,t)}catch{return null}},vs=o=>H.isZodSchema(o)?{jsonSchema:H.toJSONSchema(o),prefix:"serialize_zod"}:I.isTypeBoxSchema(o)?{jsonSchema:o,prefix:"serialize_typebox"}:typeof o=="object"&&o!==null?{jsonSchema:o,prefix:"serialize_json"}:{jsonSchema:{type:typeof o},prefix:`serialize_primitive_${JSON.stringify(o)}`},Ao=(o,e)=>(t,r,s)=>{let n=O.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);n.documentation.responses[i]=o,n.serializeOptions[i]=e?.throwErrorOnValidationFail??false,O.set(t,r,n),sr(o);let{jsonSchema:a,prefix:c}=vs(o);q.getOrCreateSerializer(a,c);let d=Ye.get(s.value)||{};if(d[i]={name:r,schema:o,throwErrorOnValidationFail:e?.throwErrorOnValidationFail??false},Ye.set(s.value,d),!ys.has(s.value)){let p=s.value,l=async function(...f){let u=f[1];await p.apply(this,f);let h=u.responseStatus,g=Ye.get(l),b=g?.[h]?.schema,P=g?.[h]?.throwErrorOnValidationFail??false;if(!b)return;let S=u.getBody();if(P){let v=qo(b);if(v)try{await Ot(v,S,P);}catch(w){return M.error({error:w,body:S,statusCode:h,schemaDescription:typeof b=="object"&&b!==null?Object.keys(b).slice(0,5).join(", "):"unknown"},"Response validation failed in @serialize decorator"),u.status(500).json({error:"Internal Server Error",message:"Response validation failed"})}}u.json(S,b);};ys.add(l);let m=Ye.get(p);m&&Ye.set(l,m),s.value=l;}};var Se=o=>(e,t,r)=>{let s=r.value,n=O.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),o.body&&(n.documentation.requestBody=o.body),o.query&&(n.documentation.query=o.query),o.all&&(n.documentation.requestBody=o.all,n.documentation.query=o.all),O.set(e,t,n),r.value=async function(...i){let a=i[0],c=i[1];try{let d,p,l,m=o.throwOnValidationFail??!0;o.body&&(d=a.validate(o.body,m)),o.query&&(p=a.validateQuery(o.query,m)),o.all&&(l=a.validateAll(o.all,m));let f=[...i];return d!==void 0&&f.push(d),p!==void 0&&f.push(p),l!==void 0&&f.push(l),s.apply(this,f)}catch(d){return o.customError?c.status(o.customError.status||400).json({received:a.body,schema:o.body,error:d}):c.badRequest(d)}},r};Se.query=(o,e)=>Se({query:o,...e});Se.body=(o,e)=>Se({body:o,...e});Se.all=(o,e)=>Se({all:o,...e});var ko=Se;var gr=class{logger=M.child({scope:this.constructor.name})};var _o=o=>{if(!Buffer.isBuffer(o))return o;let e=o.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},Fe=class o{static subscriptions=[];static client=null;static connectionOptions={};static logger=M.child({scope:"MqttService"});static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new R("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,this.logger.info("Starting MQTT client"),this.subscriptions.length||this.logger.info("No MQTT subscriptions to register");let{host:r=process.env.MQTT_HOST||"localhost",port:s=Number(process.env.MQTT_PORT)||1883,protocol:n="mqtt",...i}=e,a=`${n}://${r}:${s}`;this.client=await t.connectAsync(a,i),this.logger.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,d)=>{this.handleMessage(c,d);}),this.client.on("disconnect",()=>{this.logger.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)this.logger.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){this.logger.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}this.logger.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let n=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${n}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(n){this.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(n);}}static globalErrorHandler(e){this.logger.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:L.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing MQTT handler: ${r}`),this.logger.error(s);});}));}subscribe(e,t){return function(r,s,n){let i=n.value;if(!i)return n;let a=async(c,d)=>{let p=new r.constructor,l=_o(d);if(i.length===1){await i.call(p,l);return}await i.call(p,c,l);};return o.register(`${r.constructor.name}.${s}`,e,a,t),n}}async unsubscribe(e){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("MQTT client is not connected. Call MqttService.connect() first.");try{await o.client.unsubscribeAsync(e),o.subscriptions=o.subscriptions.filter(t=>t.topic!==e),o.logger.debug(`Unsubscribed from topic: ${String(e)}`);}catch(t){throw o.logger.error(`Failed to unsubscribe from topic ${String(e)}: ${t.message}`),t}}async publish(e,t,r){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await o.client.publishAsync(e,s,r||{}),M.debug(`Published message to topic: ${String(e)}`);}catch(n){throw M.error(`Failed to publish to topic ${String(e)}: ${n.message}`),n}}static async disconnect(){if(this.client)return new Promise(e=>{let t=this.client;t?.end(false,{},()=>{M.info("MQTT client disconnected gracefully"),t?.emit("disconnect",{cmd:"disconnect"}),this.client=null,e();});})}},Ho=o=>{Fe.globalErrorHandler=o.bind(Fe);},$o=new Fe;var X=class extends R{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var yr=class{randomUUID(){return crypto.randomUUID()}},ee=new yr;var ne=class{static options={connection:{}}},bs=o=>{ne.options=o??{connection:{}};};var et=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),n=ee.randomUUID();return await s.add(e,t,{jobId:n,...ne.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=ne.options??{},n=await this.getBullMQClient(),i=new n.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,i);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),r=new t.Queue(e,{...ne.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let n=await this.getQueueWithConfig(e,s),i=ee.randomUUID(),a={jobId:i,...ne.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await n.add(e,t,a),{id:i}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let n=ne.options??{},{errorHandler:i}=n,a=await this.getBullMQClient(),c={...n,...r};delete c.errorHandler,delete c.defaultJobOptions;let d=new a.Worker(e,async p=>{try{await t(p.data);}catch(l){await i?.(p,l)??Promise.reject(l);}},c);this.workers.set(s,d);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),n={...ne.options||{connection:{}},...t},i=new s.Queue(e,n);this.queues.set(r,i);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var tt=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=ee.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(n=>{console.error("[MemoryPubSub] Fatal queue processing error:",n);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var te=class{static options={}},ws=o=>{te.options=o??{};};var rt=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let n=r||{},i=await s.send(e,t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=te.options;s.errorHandler&&r.on("error",s.errorHandler);let n=await r.work(e,async i=>{let a=Array.isArray(i)?i:[i];for(let c of a)await t(c.data);});this.workers.set(e,n);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:n}=te.options,i=s??n,a=new r(i);return te.options?.errorHandler&&a.on("error",te.options.errorHandler),await a.start(),this.boss=a,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let n=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,n);let i=r||{},a=await n.send(e,t,i);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let n=te.options;n.errorHandler&&s.on("error",n.errorHandler);let i=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async c=>{let d=Array.isArray(c)?c:[c];for(let p of d)await t(p.data);});this.workers.set(i,a);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),n=r.PgBoss.default??r.PgBoss,i=new n(e.connectionString);return te.options?.errorHandler&&i.on("error",te.options.errorHandler),await i.start(),this.bossInstances.set(t,i),i}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var me=class{static options={}},Ss=o=>{me.options=o??{};};var st=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:n}=await this.getSqsLib(),i=await this.resolveQueueUrl(e);if(!i)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new n({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:i,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=me.options,s=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let d=JSON.parse(c.Body||"{}");await t(d);}},i=s.Consumer.create(n),a=r.errorHandler;a&&(i.on("error",a),i.on("processing_error",a)),i.start(),this.consumers.set(e,i);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=me.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new X("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new X("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=me.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...n}=r??{},i=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),d=new a({...n,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await i.send(d)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=me.options,n=await this.getSqsConsumerLib(),i=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:i,handleMessage:async p=>{let l=JSON.parse(p.Body||"{}");await t(l);}},c=n.Consumer.create(a),d=s.errorHandler;d&&(c.on("error",d),c.on("processing_error",d)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var re=class{static map=new Map;static{this.map.set("bullmq",new et),this.map.set("sqs",new st),this.map.set("pgboss",new rt),this.map.set("memory",new tt);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var W=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=M.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,n){let i=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(i)&&this.logger.warn(`Queue handler for ${i} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(i,{name:e,topic:t,handler:r,provider:s,queueOptions:n});}static registerCustomQueue(e,t,r,s){let n=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(n)&&this.logger.warn(`Custom queue handler for ${n} already registered, overwriting previous handler`),this.customQueueSubscribers.set(n,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:n,provider:i,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let c=re.getProvider(i);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,n,a):await c.subscribe(s,n);}for(let{topic:r,handler:s,pubsub:n}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await n.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let n=await y.glob(s,{cwd:L.getCwd()});this.logger.info(`Pattern "${s}" matched ${n.length} file(s)`),r.push(...n);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(n=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(n),t.throwOnError)throw n});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var Mt=new WeakMap,xe=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=re.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}async unsubscribe(){await re.getProvider(this.provider).unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,n,i){let a=i.value,c=async d=>{let p=Mt.get(s.constructor);return p||(p=W.instanceFactory(s.constructor),Mt.set(s.constructor,p)),a.apply(p,[d])};return W.registerTypedQueue(`${s.constructor.name}.${String(n)}`,e,c,t,r),i}}async subscribeWithCallback(e){let t=re.getProvider(this.provider);if(this.queueOptions){await t.subscribeWithConfig(this.topic,e,this.queueOptions);return}await t.subscribe(this.topic,e);}},jt=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}async unsubscribe(){await this.pubsub.unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,n){let i=n.value,a=async c=>{let d=Mt.get(r.constructor);return d||(d=W.instanceFactory(r.constructor),Mt.set(r.constructor,d)),i.apply(d,[c])};return W.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),n}}};function Bo(o,e){return new xe(o,"sqs",e)}function Lo(o,e){return new xe(o,"bullmq",e)}function No(o,e){return new xe(o,"pgboss",e)}function vr(o){return new xe(o,"memory")}function Io(o,e){return new jt(o,e)}var Fo=o=>{let e=["bullmq","pgboss","sqs"];o.bullmq&&bs(o.bullmq),o.pgboss&&ws(o.pgboss),o.sqs&&Ss(o.sqs);for(let t of Object.keys(o)){let r=t;e.includes(r)||re.setProvider(r,o[r]);}};G();var br=class{exit(e){switch(j.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${j.type}`)}}},De=new br;var A=class{static flagsAndArgs={flags:be().flags,args:be().args.slice(1)};static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false,loggerPath:"src/logger.ts",allowUnknownFlags:true};static args=this.flagsAndArgs.args;static flags=this.flagsAndArgs.flags;static logger=M.child({scope:this.constructor.name});static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(d=>t.includes(d)))return;let s=this.commandName,n=this.description||"No description available",i=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:n,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(c),De.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:n,options:i,args:a,flags:c}=e,d={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},p=[`${d.title}${r}${d.reset}`,`${d.description}${s}${d.reset}`,"",`${d.subtitle}Usage:${d.reset}`,` ${d.code}${r}${d.reset} [options] [arguments]`,"",`${d.subtitle}Options:${d.reset}`,` ${d.flag}-h, --help${d.reset} Show this help message`,"",`${d.subtitle}Command Options:${d.reset}`,` ${d.flag}keepAlive${d.reset} ${i?.keepAlive??false?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,` ${d.flag}loggerPath${d.reset} ${i?.loggerPath??"src/logger.ts"}`,` ${d.flag}allowUnknownFlags${d.reset} ${i?.allowUnknownFlags??true?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,""];if(n){let u=Array.isArray(n)?n:[n];p.push(`${d.subtitle}Help:${d.reset}`),u.forEach(h=>{p.push(` ${d.description}${h}${d.reset}`);}),p.push("");}let l=O.getAll(t),m=l?Array.from(l.values()).filter(u=>u.type==="arg"):[],f=l?Array.from(l.values()).filter(u=>u.type==="flag"):[];return m.length&&(p.push(`${d.subtitle}Available Arguments:${d.reset}`),m.forEach(u=>{let h=u.required?` ${d.error}(required)${d.reset}`:"",g=u.description?` ${d.description}${u.description}${d.reset}`:"";p.push(` ${d.code}${u.name}${d.reset}${h}${g}`);}),p.push("")),f.length&&(p.push(`${d.subtitle}Available Flags:${d.reset}`),f.forEach(u=>{u.aliases&&!Array.isArray(u.aliases)&&(u.aliases=[u.aliases]);let h=u.aliases.length?` ${d.flag}(${u.aliases.join(", ")})${d.reset}`:"",g=u.required?` ${d.error}(required)${d.reset}`:"",b=u.description?` ${d.description}${u.description}${d.reset}`:"";p.push(` ${d.flag}--${u.name}${h}${d.reset}${g}${b}`);}),p.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(p.push(`${d.subtitle}Current Context:${d.reset}`),a?.length&&p.push(` ${d.info}Provided Arguments:${d.reset} ${d.code}${a.join(" ")}${d.reset}`),c&&Object.keys(c).length>0&&(p.push(` ${d.info}Provided Flags:${d.reset}`),Object.keys(c).forEach(u=>{let h=c[u],g=h!=null?` = ${d.code}${h}${d.reset}`:"";p.push(` ${d.flag}${u}${d.reset}${g}`);})),p.push("")),n&&(Array.isArray(n)?n.some(u=>u.includes("example")):n.includes("example"))&&(p.push(`${d.subtitle}Examples:${d.reset}`),(Array.isArray(n)?n.filter(h=>h.includes("example")):[n.split("example")[1].trim()]).forEach(h=>{p.push(` ${d.code}${h}${d.reset}`);}),p.push("")),p.join(`
|
|
494
|
-
`)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=O.getAll(e);if(s){for(let i of s.values())if(i.type==="flag"&&(r.add(`--${i.name}`),r.add(`-${i.name}`),r.add(i.name),i.aliases)){let a=Array.isArray(i.aliases)?i.aliases:[i.aliases];for(let c of a)r.add(`--${c}`),r.add(`-${c}`),r.add(c);}}let n=Object.keys(e.flags).filter(i=>!t.has(i)&&!r.has(i));if(n.length){let i={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",flag:"\x1B[0;35m"};console.error(`${i.title}\u274C Unknown Flags:${i.reset}`),console.error(""),n.forEach(a=>{console.error(` ${i.error}\u2022${i.reset} ${i.flag}${a}${i.reset}`);}),console.error(""),console.error(`${i.info}\u{1F4A1} Tip: Use --help for available flags${i.reset}`),De.exit(1);}};static validateContext=e=>{let t=Array.from(O.get(e,we)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((s,n)=>{let i=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,c=`${r.code}${s.name}${r.reset}`;console.error(` ${i} ${a} ${c}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),De.exit(1);}}};var K=class extends A{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,c,d]=await U();await D(`${a} ${c} esbuild ${d}`,a,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(a=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),r=ht__default.default.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(c=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});ot__default.default.existsSync(r)||ot__default.default.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&ot__default.default.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),ot__default.default.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=ht__default.default.join(this.output,"server.js"),i=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:n,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});i.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:i.errors},null,2)),process.exit(1)),i.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:i.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${n}`,output:n,assets:!!this.assets},null,2)),process.exit(0);}};
|
|
493
|
+
</html>`}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},mr=new ur;var J=class{static scheduledJobs=[];static logger=M.child({scope:"CronService"});static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new R("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:L.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),M.error(s);});}));}},bo=o=>{J.globalErrorHandler=o.bind(J);},wo=async o=>{if(!o||o.path.length===0)throw new R("Cron UI path is required");let e=await mr.generate();_.addOrUpdate("GET",o.path,[],(t,r)=>{r.html(e);},void 0,void 0,void 0,true);};var So=(o,e)=>function(t,r,s){let n=s.value,i=async(...a)=>{let c=new t.constructor;return await n.apply(c,a)};return J.register(`${t.constructor.name}.${r}`,o,i,e),s};G();var hr=class{getCliArgs(){switch(j.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(j.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(s)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},fr=new hr;var Pt=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Rt=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),hs=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var ve=(o,e)=>{if(!o||typeof o!="string")return e;let t=o.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(s){let n=Number.parseFloat(s[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var xo=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:fs(r)}}return {name:o,value:true}},fs=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},be=()=>{let o=fr.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let n=xo(s);if(n){if(n.value===true&&r+1<o.length){let i=o[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=fs(i),r++);}if(n.name in t){let i=t[n.name];Array.isArray(i)?i.push(n.value):t[n.name]=[i,n.value];}else t[n.name]=n.value;}continue}e.push(s);}}return {args:e,flags:t}};var Ct=()=>fr.getCliArgs()[0]||null;var we="VALIDATION_ERROR";var gs=be().args.slice(1),B=o=>(e,t)=>{let r=Ct();if(!r||r!==e.commandName)return;let s=t;O.set(e,t,{type:"arg",name:s,description:o.description});let n=gs.length?gs.shift():o.defaultValue;if(o.required&&!n){let i=O.get(e,we);O.set(e,we,[...i||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&n&&(n=o.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var Y=o=>(e,t)=>{let r=Ct();if(!r||r!==e.commandName)return;let s=o.name||t,n=be().flags,i=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],a=[s,...i],c=o.defaultValue;for(let d of a){let l=[d,`-${d}`,`--${d}`];for(let p of l)if(p in n){let m=n[p];o.type==="list"?c=(Array.isArray(m)?m:[m]).map(u=>{let h=String(u);return o.parse?o.parse(h):h}):(c=m,o.type==="boolean"?c=!!c:o.type==="number"?c=Number(c):o.type==="string"&&(c=String(c)),o.parse&&(c=o.parse(c)));break}if(c!==o.defaultValue)break}if(O.set(e,t,{type:"flag",name:s,aliases:i||[],description:o.description}),o.required&&(o.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let l=O.get(e,we);O.set(e,we,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};Y.boolean=o=>Y({...o,type:"boolean"});Y.string=o=>Y({...o,type:"string"});Y.number=o=>Y({...o,type:"number"});Y.list=o=>Y({...o,type:"list"});Y.array=o=>Y({...o,type:"list"});var C=Y;var To=(o,e)=>t=>{let r=O.get(t.prototype,"__class__"),s=r?.middlewares||[],n=r?.policies||[],i=O.getAll(t.prototype),a=new t;if(i){for(let[c,d]of i.entries()){if(!d.route)continue;let l=t.prototype[c].bind(a),p=o?x.join(o,d.route.path):d.route.path,m=[...n,...d.policies||[]],f=m.length>0?[xt(m)]:[],u=[...s,...f,...d.middlewares||[]];if(d.cacheConfig){let h=Ze();if(h){let g=vt(d.cacheConfig),b=St(h,g,wt());u.push(b);}}_.addOrUpdate(d.route.method,p,u,l,{service:t.name.replace(/Controller$/,""),...e,...d.documentation});}O.clear(t.prototype);}};var Po=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"DELETE"},O.set(t,r,n),s};var Ro=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"GET"},O.set(t,r,n),s};var Co=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PATCH"},O.set(t,r,n),s};var Oo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"POST"},O.set(t,r,n),s};var Mo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PUT"},O.set(t,r,n),s};var jo=o=>(e,t,r)=>{if(typeof t>"u"){let n=O.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!o)throw new Error(`Middleware ${String(o)} not found, are you sure you defined it before using it?`);return Array.isArray(o)||(o=[o]),n.middlewares.push(...o),O.set(e.prototype,"__class__",n),e}let s=O.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(o)||(o=[o]),s.middlewares.push(...o),O.set(e,t,s),r};var Ot=(o,e,t=false)=>{if(!o(e)){if(t)throw new ajv.ValidationError(o.errors||[]);return e}return e};var Ye=new WeakMap,ys=new WeakSet,qo=o=>{let{jsonSchema:e,prefix:t}=vs(o);try{return q.getOrCompileValidator(e,t)}catch{return null}},vs=o=>H.isZodSchema(o)?{jsonSchema:H.toJSONSchema(o),prefix:"serialize_zod"}:I.isTypeBoxSchema(o)?{jsonSchema:o,prefix:"serialize_typebox"}:typeof o=="object"&&o!==null?{jsonSchema:o,prefix:"serialize_json"}:{jsonSchema:{type:typeof o},prefix:`serialize_primitive_${JSON.stringify(o)}`},Ao=(o,e)=>(t,r,s)=>{let n=O.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);n.documentation.responses[i]=o,n.serializeOptions[i]=e?.throwErrorOnValidationFail??false,O.set(t,r,n),sr(o);let{jsonSchema:a,prefix:c}=vs(o);q.getOrCreateSerializer(a,c);let d=Ye.get(s.value)||{};if(d[i]={name:r,schema:o,throwErrorOnValidationFail:e?.throwErrorOnValidationFail??false},Ye.set(s.value,d),!ys.has(s.value)){let l=s.value,p=async function(...f){let u=f[1];await l.apply(this,f);let h=u.responseStatus,g=Ye.get(p),b=g?.[h]?.schema,T=g?.[h]?.throwErrorOnValidationFail??false;if(!b)return;let S=u.getBody();if(T){let v=qo(b);if(v)try{await Ot(v,S,T);}catch(w){return M.error({error:w,body:S,statusCode:h,schemaDescription:typeof b=="object"&&b!==null?Object.keys(b).slice(0,5).join(", "):"unknown"},"Response validation failed in @serialize decorator"),u.status(500).json({error:"Internal Server Error",message:"Response validation failed"})}}u.json(S,b);};ys.add(p);let m=Ye.get(l);m&&Ye.set(p,m),s.value=p;}};var Se=o=>(e,t,r)=>{let s=r.value,n=O.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),o.body&&(n.documentation.requestBody=o.body),o.query&&(n.documentation.query=o.query),o.all&&(n.documentation.requestBody=o.all,n.documentation.query=o.all),O.set(e,t,n),r.value=async function(...i){let a=i[0],c=i[1];try{let d,l,p,m=o.throwOnValidationFail??!0;o.body&&(d=a.validate(o.body,m)),o.query&&(l=a.validateQuery(o.query,m)),o.all&&(p=a.validateAll(o.all,m));let f=[...i];return d!==void 0&&f.push(d),l!==void 0&&f.push(l),p!==void 0&&f.push(p),s.apply(this,f)}catch(d){return o.customError?c.status(o.customError.status||400).json({received:a.body,schema:o.body,error:d}):c.badRequest(d)}},r};Se.query=(o,e)=>Se({query:o,...e});Se.body=(o,e)=>Se({body:o,...e});Se.all=(o,e)=>Se({all:o,...e});var ko=Se;var gr=class{logger=M.child({scope:this.constructor.name})};var _o=o=>{if(!Buffer.isBuffer(o))return o;let e=o.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},Fe=class o{static subscriptions=[];static client=null;static connectionOptions={};static logger=M.child({scope:"MqttService"});static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new R("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,this.logger.info("Starting MQTT client"),this.subscriptions.length||this.logger.info("No MQTT subscriptions to register");let{host:r=process.env.MQTT_HOST||"localhost",port:s=Number(process.env.MQTT_PORT)||1883,protocol:n="mqtt",...i}=e,a=`${n}://${r}:${s}`;this.client=await t.connectAsync(a,i),this.logger.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,d)=>{this.handleMessage(c,d);}),this.client.on("disconnect",()=>{this.logger.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)this.logger.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){this.logger.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}this.logger.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let n=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${n}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(n){this.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(n);}}static globalErrorHandler(e){this.logger.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:L.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing MQTT handler: ${r}`),this.logger.error(s);});}));}subscribe(e,t){return function(r,s,n){let i=n.value;if(!i)return n;let a=async(c,d)=>{let l=new r.constructor,p=_o(d);if(i.length===1){await i.call(l,p);return}await i.call(l,c,p);};return o.register(`${r.constructor.name}.${s}`,e,a,t),n}}async unsubscribe(e){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("MQTT client is not connected. Call MqttService.connect() first.");try{await o.client.unsubscribeAsync(e),o.subscriptions=o.subscriptions.filter(t=>t.topic!==e),o.logger.debug(`Unsubscribed from topic: ${String(e)}`);}catch(t){throw o.logger.error(`Failed to unsubscribe from topic ${String(e)}: ${t.message}`),t}}async publish(e,t,r){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await o.client.publishAsync(e,s,r||{}),M.debug(`Published message to topic: ${String(e)}`);}catch(n){throw M.error(`Failed to publish to topic ${String(e)}: ${n.message}`),n}}static async disconnect(){if(this.client)return new Promise(e=>{let t=this.client;t?.end(false,{},()=>{M.info("MQTT client disconnected gracefully"),t?.emit("disconnect",{cmd:"disconnect"}),this.client=null,e();});})}},Ho=o=>{Fe.globalErrorHandler=o.bind(Fe);},$o=new Fe;var X=class extends R{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var yr=class{randomUUID(){return crypto.randomUUID()}},ee=new yr;var ne=class{static options={connection:{}}},bs=o=>{ne.options=o??{connection:{}};};var et=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),n=ee.randomUUID();return await s.add(e,t,{jobId:n,...ne.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=ne.options??{},n=await this.getBullMQClient(),i=new n.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,i);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),r=new t.Queue(e,{...ne.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let n=await this.getQueueWithConfig(e,s),i=ee.randomUUID(),a={jobId:i,...ne.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await n.add(e,t,a),{id:i}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let n=ne.options??{},{errorHandler:i}=n,a=await this.getBullMQClient(),c={...n,...r};delete c.errorHandler,delete c.defaultJobOptions;let d=new a.Worker(e,async l=>{try{await t(l.data);}catch(p){await i?.(l,p)??Promise.reject(p);}},c);this.workers.set(s,d);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),n={...ne.options||{connection:{}},...t},i=new s.Queue(e,n);this.queues.set(r,i);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var tt=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=ee.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(n=>{console.error("[MemoryPubSub] Fatal queue processing error:",n);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var te=class{static options={}},ws=o=>{te.options=o??{};};var rt=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let n=r||{},i=await s.send(e,t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=te.options;s.errorHandler&&r.on("error",s.errorHandler);let n=await r.work(e,async i=>{let a=Array.isArray(i)?i:[i];for(let c of a)await t(c.data);});this.workers.set(e,n);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:n}=te.options,i=s??n,a=new r(i);return te.options?.errorHandler&&a.on("error",te.options.errorHandler),await a.start(),this.boss=a,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let n=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,n);let i=r||{},a=await n.send(e,t,i);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let n=te.options;n.errorHandler&&s.on("error",n.errorHandler);let i=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async c=>{let d=Array.isArray(c)?c:[c];for(let l of d)await t(l.data);});this.workers.set(i,a);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),n=r.PgBoss.default??r.PgBoss,i=new n(e.connectionString);return te.options?.errorHandler&&i.on("error",te.options.errorHandler),await i.start(),this.bossInstances.set(t,i),i}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var me=class{static options={}},Ss=o=>{me.options=o??{};};var st=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:n}=await this.getSqsLib(),i=await this.resolveQueueUrl(e);if(!i)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new n({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:i,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=me.options,s=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let d=JSON.parse(c.Body||"{}");await t(d);}},i=s.Consumer.create(n),a=r.errorHandler;a&&(i.on("error",a),i.on("processing_error",a)),i.start(),this.consumers.set(e,i);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=me.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new X("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new X("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=me.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...n}=r??{},i=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),d=new a({...n,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await i.send(d)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=me.options,n=await this.getSqsConsumerLib(),i=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:i,handleMessage:async l=>{let p=JSON.parse(l.Body||"{}");await t(p);}},c=n.Consumer.create(a),d=s.errorHandler;d&&(c.on("error",d),c.on("processing_error",d)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var re=class{static map=new Map;static{this.map.set("bullmq",new et),this.map.set("sqs",new st),this.map.set("pgboss",new rt),this.map.set("memory",new tt);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var W=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=M.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,n){let i=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(i)&&this.logger.warn(`Queue handler for ${i} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(i,{name:e,topic:t,handler:r,provider:s,queueOptions:n});}static registerCustomQueue(e,t,r,s){let n=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(n)&&this.logger.warn(`Custom queue handler for ${n} already registered, overwriting previous handler`),this.customQueueSubscribers.set(n,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:n,provider:i,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let c=re.getProvider(i);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,n,a):await c.subscribe(s,n);}for(let{topic:r,handler:s,pubsub:n}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await n.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let n=await y.glob(s,{cwd:L.getCwd()});this.logger.info(`Pattern "${s}" matched ${n.length} file(s)`),r.push(...n);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(n=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(n),t.throwOnError)throw n});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var Mt=new WeakMap,xe=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=re.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}async unsubscribe(){await re.getProvider(this.provider).unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,n,i){let a=i.value,c=async d=>{let l=Mt.get(s.constructor);return l||(l=W.instanceFactory(s.constructor),Mt.set(s.constructor,l)),a.apply(l,[d])};return W.registerTypedQueue(`${s.constructor.name}.${String(n)}`,e,c,t,r),i}}async subscribeWithCallback(e){let t=re.getProvider(this.provider);if(this.queueOptions){await t.subscribeWithConfig(this.topic,e,this.queueOptions);return}await t.subscribe(this.topic,e);}},jt=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}async unsubscribe(){await this.pubsub.unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,n){let i=n.value,a=async c=>{let d=Mt.get(r.constructor);return d||(d=W.instanceFactory(r.constructor),Mt.set(r.constructor,d)),i.apply(d,[c])};return W.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),n}}};function Bo(o,e){return new xe(o,"sqs",e)}function Lo(o,e){return new xe(o,"bullmq",e)}function No(o,e){return new xe(o,"pgboss",e)}function vr(o){return new xe(o,"memory")}function Io(o,e){return new jt(o,e)}var Fo=o=>{let e=["bullmq","pgboss","sqs"];o.bullmq&&bs(o.bullmq),o.pgboss&&ws(o.pgboss),o.sqs&&Ss(o.sqs);for(let t of Object.keys(o)){let r=t;e.includes(r)||re.setProvider(r,o[r]);}};G();var br=class{exit(e){switch(j.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${j.type}`)}}},De=new br;var A=class{static flagsAndArgs={flags:be().flags,args:be().args.slice(1)};static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false,loggerPath:"src/logger.ts",allowUnknownFlags:true};static args=this.flagsAndArgs.args;static flags=this.flagsAndArgs.flags;static logger=M.child({scope:this.constructor.name});static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(d=>t.includes(d)))return;let s=this.commandName,n=this.description||"No description available",i=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:n,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(c),De.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:n,options:i,args:a,flags:c}=e,d={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},l=[`${d.title}${r}${d.reset}`,`${d.description}${s}${d.reset}`,"",`${d.subtitle}Usage:${d.reset}`,` ${d.code}${r}${d.reset} [options] [arguments]`,"",`${d.subtitle}Options:${d.reset}`,` ${d.flag}-h, --help${d.reset} Show this help message`,"",`${d.subtitle}Command Options:${d.reset}`,` ${d.flag}keepAlive${d.reset} ${i?.keepAlive??false?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,` ${d.flag}loggerPath${d.reset} ${i?.loggerPath??"src/logger.ts"}`,` ${d.flag}allowUnknownFlags${d.reset} ${i?.allowUnknownFlags??true?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,""];if(n){let u=Array.isArray(n)?n:[n];l.push(`${d.subtitle}Help:${d.reset}`),u.forEach(h=>{l.push(` ${d.description}${h}${d.reset}`);}),l.push("");}let p=O.getAll(t),m=p?Array.from(p.values()).filter(u=>u.type==="arg"):[],f=p?Array.from(p.values()).filter(u=>u.type==="flag"):[];return m.length&&(l.push(`${d.subtitle}Available Arguments:${d.reset}`),m.forEach(u=>{let h=u.required?` ${d.error}(required)${d.reset}`:"",g=u.description?` ${d.description}${u.description}${d.reset}`:"";l.push(` ${d.code}${u.name}${d.reset}${h}${g}`);}),l.push("")),f.length&&(l.push(`${d.subtitle}Available Flags:${d.reset}`),f.forEach(u=>{u.aliases&&!Array.isArray(u.aliases)&&(u.aliases=[u.aliases]);let h=u.aliases.length?` ${d.flag}(${u.aliases.join(", ")})${d.reset}`:"",g=u.required?` ${d.error}(required)${d.reset}`:"",b=u.description?` ${d.description}${u.description}${d.reset}`:"";l.push(` ${d.flag}--${u.name}${h}${d.reset}${g}${b}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${d.subtitle}Current Context:${d.reset}`),a?.length&&l.push(` ${d.info}Provided Arguments:${d.reset} ${d.code}${a.join(" ")}${d.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${d.info}Provided Flags:${d.reset}`),Object.keys(c).forEach(u=>{let h=c[u],g=h!=null?` = ${d.code}${h}${d.reset}`:"";l.push(` ${d.flag}${u}${d.reset}${g}`);})),l.push("")),n&&(Array.isArray(n)?n.some(u=>u.includes("example")):n.includes("example"))&&(l.push(`${d.subtitle}Examples:${d.reset}`),(Array.isArray(n)?n.filter(h=>h.includes("example")):[n.split("example")[1].trim()]).forEach(h=>{l.push(` ${d.code}${h}${d.reset}`);}),l.push("")),l.join(`
|
|
494
|
+
`)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=O.getAll(e);if(s){for(let i of s.values())if(i.type==="flag"&&(r.add(`--${i.name}`),r.add(`-${i.name}`),r.add(i.name),i.aliases)){let a=Array.isArray(i.aliases)?i.aliases:[i.aliases];for(let c of a)r.add(`--${c}`),r.add(`-${c}`),r.add(c);}}let n=Object.keys(e.flags).filter(i=>!t.has(i)&&!r.has(i));if(n.length){let i={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",flag:"\x1B[0;35m"};console.error(`${i.title}\u274C Unknown Flags:${i.reset}`),console.error(""),n.forEach(a=>{console.error(` ${i.error}\u2022${i.reset} ${i.flag}${a}${i.reset}`);}),console.error(""),console.error(`${i.info}\u{1F4A1} Tip: Use --help for available flags${i.reset}`),De.exit(1);}};static validateContext=e=>{let t=Array.from(O.get(e,we)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((s,n)=>{let i=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,c=`${r.code}${s.name}${r.reset}`;console.error(` ${i} ${a} ${c}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),De.exit(1);}}};var K=class extends A{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,c,d]=await U();await D(`${a} ${c} esbuild ${d}`,a,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(a=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),r=ht__default.default.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(c=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});ot__default.default.existsSync(r)||ot__default.default.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&ot__default.default.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),ot__default.default.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=ht__default.default.join(this.output,"server.js"),i=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:n,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});i.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:i.errors},null,2)),process.exit(1)),i.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:i.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${n}`,output:n,assets:!!this.assets},null,2)),process.exit(0);}};P([C({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],K,"clearDist"),P([C({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],K,"entry"),P([C({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],K,"output"),P([C({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],K,"tsconfig"),P([C({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],K,"assets"),P([C({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],K,"format"),P([C({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],K,"packages"),P([C({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],K,"sourcemap");var Te=class extends A{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await J.massiveImportCronJobs(e);let t=J.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),J.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};P([B({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],Te,"pattern"),P([C.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],Te,"additionalPatterns");var Qe=class extends A{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){if(Pe.getCommand(this.name)){let s=Pe.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=x.join(this.path,`${this.name}.ts`),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
|
|
495
495
|
|
|
496
496
|
export default class extends Command {
|
|
497
497
|
static commandName = "${this.name}";
|
|
@@ -505,7 +505,7 @@ export default class extends Command {
|
|
|
505
505
|
static async handle(): Promise<void> {
|
|
506
506
|
// Implement your command logic here
|
|
507
507
|
}
|
|
508
|
-
}`}};
|
|
508
|
+
}`}};P([B({description:"The name of the command to generate",required:true})],Qe,"name");var Re=class extends A{static commandName="generate-controller";static description="Generate a new controller in the specified path";static help=["Generate a new controller in the specified path","Example: npx balda generate-controller user -p src/controllers"];static controllerName;static path;static async handle(){let e=this.getControllerTemplate(),t=`${this.controllerName.toLowerCase()}.ts`;this.path=x.join(this.path,t),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=Rt(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
|
|
509
509
|
|
|
510
510
|
@controller("/${hs(this.controllerName)}")
|
|
511
511
|
export default class ${e}Controller {
|
|
@@ -533,7 +533,7 @@ export default class ${e}Controller {
|
|
|
533
533
|
async destroy(req: Request, res: Response) {
|
|
534
534
|
return { message: \`Delete ${this.controllerName.toLowerCase()} with id \${req.params.id}\` };
|
|
535
535
|
}
|
|
536
|
-
}`}};
|
|
536
|
+
}`}};P([B({description:"The name of the controller to generate",required:true})],Re,"controllerName"),P([C({description:"The path to the controller to generate, default is src/controllers",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/controllers"})],Re,"path");var Ce=class extends A{static commandName="generate-cron";static description="Generate a new cron job in the specified path";static help=["Generate a new cron job in the specified path","Example: npx balda generate-cron my-cron -p src/cron"];static fileName;static path;static async handle(){let e=this.getCronTemplate();this.path=x.join(this.path,`${this.fileName}.ts`),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda";
|
|
537
537
|
|
|
538
538
|
export default class extends BaseCron {
|
|
539
539
|
@cron("* * * * *")
|
|
@@ -541,7 +541,7 @@ export default class extends BaseCron {
|
|
|
541
541
|
this.logger.info("Running cron job");
|
|
542
542
|
// Implement your cron job logic here
|
|
543
543
|
}
|
|
544
|
-
}`}};
|
|
544
|
+
}`}};P([B({description:"The name of the cron job file to generate",required:true})],Ce,"fileName"),P([C({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],Ce,"path");var Oe=class extends A{static commandName="generate-middleware";static description="Generate a new middleware in the specified path";static help=["Generate a new middleware in the specified path","Example: npx balda generate-middleware auth -p src/middlewares"];static middlewareName;static path;static async handle(){let e=this.getMiddlewareTemplate(),t=`${this.middlewareName.toLowerCase()}.ts`;this.path=x.join(this.path,t),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Middleware ${this.middlewareName} created successfully at ${this.path}`);}static getMiddlewareTemplate(){let e=Rt(this.middlewareName);return `import { defineMiddleware } from "balda";
|
|
545
545
|
import type { TypedMiddleware } from "balda";
|
|
546
546
|
|
|
547
547
|
/**
|
|
@@ -558,7 +558,7 @@ export const ${e}: TypedMiddleware<${e}Extension> = defineMiddleware<${e}Extensi
|
|
|
558
558
|
// Add your middleware logic here
|
|
559
559
|
return next();
|
|
560
560
|
},
|
|
561
|
-
);`}};
|
|
561
|
+
);`}};P([B({description:"The name of the middleware to generate",required:true})],Oe,"middlewareName"),P([C({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],Oe,"path");var Me=class extends A{static commandName="generate-mqtt";static description="Generate a new MQTT handler in the specified path";static help=["Generate a new MQTT handler in the specified path","Example: npx balda generate-mqtt temperature-handler -p src/mqtt"];static path;static topic;static async handle(){let e=this.topic.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getMqttTemplate(!!e);this.path=x.join(this.path,`${Pt(this.topic.replace(/\//g,"_"))}.ts`),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`MQTT handler for topic ${this.topic} created successfully at ${this.path}`);}static getMqttTemplate(e){return `import { BaseMqtt, mqtt } from "balda";
|
|
562
562
|
|
|
563
563
|
/**
|
|
564
564
|
* Define your MQTT topics interface for type safety
|
|
@@ -575,7 +575,7 @@ export default class extends BaseMqtt {
|
|
|
575
575
|
this.logger.info({ message }, "Message received");
|
|
576
576
|
// Implement your MQTT handler logic here
|
|
577
577
|
}
|
|
578
|
-
}`}};
|
|
578
|
+
}`}};P([C({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],Me,"path"),P([B({description:"The MQTT topic to subscribe to",required:true})],Me,"topic");var je=class extends A{static commandName="generate-plugin";static description="Generate a new plugin in the specified path";static help=["Generate a new plugin in the specified path","Example: npx balda generate-plugin my-plugin -p src/plugins"];static pluginName;static pluginPath;static async handle(){let e=this.getPluginTemplate();this.pluginPath=x.join(this.pluginPath,`${this.pluginName}.ts`),await y.exists(x.join(process.cwd(),this.pluginPath))||await y.mkdir(x.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`);}static getPluginTemplate(){return `import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
|
|
579
579
|
|
|
580
580
|
export default class extends BasePlugin {
|
|
581
581
|
async handle(): Promise<ServerRouteMiddleware> {
|
|
@@ -584,7 +584,7 @@ export default class extends BasePlugin {
|
|
|
584
584
|
await next();
|
|
585
585
|
};
|
|
586
586
|
}
|
|
587
|
-
}`}};
|
|
587
|
+
}`}};P([B({description:"The name of the plugin to generate",required:true})],je,"pluginName"),P([C({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],je,"pluginPath");var he=class extends A{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=x.join(this.path,`${Pt(this.queueName)}.ts`),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda";
|
|
588
588
|
|
|
589
589
|
export type Payload = {
|
|
590
590
|
// Add your payload here
|
|
@@ -603,24 +603,24 @@ export default class extends BaseQueue {
|
|
|
603
603
|
this.logger.info({ payload }, 'Payload received');
|
|
604
604
|
return Promise.resolve();
|
|
605
605
|
}
|
|
606
|
-
}`}};
|
|
606
|
+
}`}};P([B({description:"The name of the queue to generate",required:true})],he,"queueName"),P([C({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],he,"path"),P([C({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],he,"provider");var Q=class extends A{static commandName="generate-sdk";static description="Generate a TypeScript SDK from your server's OpenAPI specification";static help=["Generate a TypeScript SDK from your server's OpenAPI specification","This command imports your server instance, starts it if needed, downloads the OpenAPI spec, and generates an SDK","","Arguments:"," serverPath Path to the server instance file (default: test/server/instance.ts)","","Flags:"," -o, --output <path> Output directory for generated SDK (default: sdk)"," -s, --swagger-path <path> Swagger UI path on your server (default: /docs)"," -c, --client <type> HTTP client to use: axios or fetch (default: fetch)"," --unwrap-response-data Automatically unwrap response data property"," --single-http-client Generate single HTTP client instance"," --type-prefix <prefix> Add prefix to all generated types"," --type-suffix <suffix> Add suffix to all generated types"," --enum-names-as-values Use enum names as values"," --sort-types Sort types alphabetically","","Examples:"," npx balda generate-sdk"," npx balda generate-sdk src/server/index.ts -o ./client-sdk"," npx balda generate-sdk src/server.ts --client axios"," npx balda generate-sdk --unwrap-response-data --single-http-client"," npx balda generate-sdk --type-prefix Api --sort-types"];static serverPath;static outputPath;static swaggerPath;static httpClient;static unwrapResponseData;static singleHttpClient;static typePrefix;static typeSuffix;static enumNamesAsValues;static sortTypes;static async handle(){console.log(`
|
|
607
607
|
\u{1F680} Starting SDK generation...
|
|
608
608
|
`);let e="swagger-typescript-api",t=x.join(process.cwd(),"node_modules"),r=await y.exists(t),s=x.join(t,e);if(!(r?await y.exists(s):false)){console.log(`\u{1F4E6} ${e} not found. Installing as dev dependency...
|
|
609
609
|
`);let[v,w,k]=await U();if(!await D(`${v} ${w} ${e} ${k}`,v,[e],{stdio:"inherit"},true)){console.log(`\x1B[33m\u26A0\uFE0F SDK generation cancelled: swagger-typescript-api installation was skipped.\x1B[0m
|
|
610
610
|
`);return}console.log(`
|
|
611
611
|
\x1B[32m\u2705 ${e} installed successfully!\x1B[0m
|
|
612
612
|
`);}let i=x.resolve(process.cwd(),this.serverPath);if(!await y.exists(i)){console.error(`\x1B[31m\u274C Error: Server file not found at ${i}\x1B[0m
|
|
613
|
-
`);return}console.log(`\u{1F4C2} Loading server from: ${this.serverPath}`);let c;try{c=await import(`file://${i}`);}catch(v){console.error("\x1B[31m\u274C Error importing server module:\x1B[0m",v);return}let d=Object.keys(c),
|
|
614
|
-
`);break}}if(!
|
|
615
|
-
`);return}let
|
|
616
|
-
`),v();});}catch(k){w(k);}}).catch(v=>{console.error("Failed to start the server, continuing...");});else throw new Error("Server instance does not have a listen() method")}catch(v){console.error("\x1B[31m\u274C Error starting server:\x1B[0m",v);return}let h=this.swaggerPath??(typeof
|
|
617
|
-
`);}catch(v){if(console.error("\x1B[31m\u274C Error downloading OpenAPI spec:\x1B[0m",v),
|
|
618
|
-
`);try{await y.exists(S)||await y.mkdir(S,{recursive:!0});let v=["npx swagger-typescript-api generate",`--path="${
|
|
613
|
+
`);return}console.log(`\u{1F4C2} Loading server from: ${this.serverPath}`);let c;try{c=await import(`file://${i}`);}catch(v){console.error("\x1B[31m\u274C Error importing server module:\x1B[0m",v);return}let d=Object.keys(c),l=null;for(let v of d){let w=c[v];if("default"in w&&w.default&&(w=w.default),w&&"_brand"in w&&w._brand==="BaldaServer"&&typeof w=="object"&&"listen"in w){l=w,console.log(`\u2705 Found server instance in export: "${v}"
|
|
614
|
+
`);break}}if(!l){console.error(`\x1B[31m\u274C Error: No Server instance found in ${this.serverPath}\x1B[0m`),console.log(`\x1B[90mExpected exports: ${d.join(", ")}\x1B[0m
|
|
615
|
+
`);return}let p=false,m="";m="http://localhost:80";try{if(console.log(`\u{1F310} Starting server on ${m}...`),typeof l.listen=="function"&&!l.isListening)await new Promise((v,w)=>{try{l.listen(()=>{p=!0,console.log(`\u2705 Server started successfully!
|
|
616
|
+
`),v();});}catch(k){w(k);}}).catch(v=>{console.error("Failed to start the server, continuing...");});else throw new Error("Server instance does not have a listen() method")}catch(v){console.error("\x1B[31m\u274C Error starting server:\x1B[0m",v);return}let h=this.swaggerPath??(typeof l.serverOptions.swagger!="boolean"?l.serverOptions.swagger?.path:"/docs"),g=x.join(m,h??"/docs","/json");console.log(`\u{1F4E5} Downloading OpenAPI spec from: ${g}`);let b;try{let v=await globalThis.fetch(g);if(!v.ok)throw new Error(`Failed to fetch OpenAPI spec: ${v.status} ${v.statusText}`);b=await v.json(),console.log(`\u2705 OpenAPI spec downloaded successfully!
|
|
617
|
+
`);}catch(v){if(console.error("\x1B[31m\u274C Error downloading OpenAPI spec:\x1B[0m",v),p){let w=l;try{await w.close?.();}catch{}}return}let T=x.join(process.cwd(),".openapi-spec.json");try{await y.writeFile(T,new TextEncoder().encode(JSON.stringify(b,null,2)));}catch(v){if(console.error("\x1B[31m\u274C Error saving OpenAPI spec to file:\x1B[0m",v),p){let w=l;try{await w.close?.();}catch{}}return}let S=x.resolve(process.cwd(),this.outputPath);console.log(`\u{1F528} Generating SDK...
|
|
618
|
+
`);try{await y.exists(S)||await y.mkdir(S,{recursive:!0});let v=["npx swagger-typescript-api generate",`--path="${T}"`,`--output="${this.outputPath}"`,`--http-client ${this.httpClient}`,"--modular","--extract-request-params","--extract-request-body","--extract-response-body","--extract-response-error"];this.unwrapResponseData&&v.push("--unwrap-response-data"),this.singleHttpClient&&v.push("--single-http-client"),this.typePrefix&&v.push(`--type-prefix "${this.typePrefix}"`),this.typeSuffix&&v.push(`--type-suffix "${this.typeSuffix}"`),this.enumNamesAsValues&&v.push("--enum-names-as-values"),this.sortTypes&&v.push("--sort-types");let w=v.join(" ");child_process.execSync(w,{stdio:"inherit",cwd:process.cwd()}),console.log(`
|
|
619
619
|
\x1B[32m\u2705 SDK generated successfully!\x1B[0m`),console.log(`\x1B[32m\u{1F4C1} SDK location: ${S}\x1B[0m
|
|
620
|
-
`);}catch(v){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",v);}finally{try{await y.unlink(
|
|
620
|
+
`);}catch(v){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",v);}finally{try{await y.unlink(T);}catch{}if(p){let v=l;try{console.log("\u{1F6D1} Stopping server..."),await v.close?.(),console.log(`\u2705 Server stopped.
|
|
621
621
|
`);}catch{console.log(`\x1B[33m\u26A0\uFE0F Could not stop server gracefully.\x1B[0m
|
|
622
622
|
`);}}}console.log(`\x1B[32m\u2728 SDK generation complete!\x1B[0m
|
|
623
|
-
`);}};
|
|
623
|
+
`);}};P([B({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],Q,"serverPath"),P([C({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],Q,"outputPath"),P([C({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false})],Q,"swaggerPath"),P([C({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],Q,"httpClient"),P([C({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],Q,"unwrapResponseData"),P([C({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],Q,"singleHttpClient"),P([C({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],Q,"typePrefix"),P([C({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],Q,"typeSuffix"),P([C({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],Q,"enumNamesAsValues"),P([C({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],Q,"sortTypes");var ie=class extends A{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static mqtt;static cron;static graphql;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await U();if(["npm","yarn","pnpm"].includes(e)){let c=await pe(this.devDependencies);if(c.length&&(this.logger.info(`Found ${c.length} missing dev dependencies`),!await D(`${e} ${t} ${c.join(" ")} -${r}`,e,c,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}c.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let c=await pe(["mqtt"]);c.length&&(await D(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),c.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let c=await pe(["node-cron"]);c.length>0&&(await D(`${e} ${t} node-cron`,e,["node-cron"],{stdio:"inherit"},false)||(this.logger.info("node-cron installation cancelled by user. Skipping Cron scaffolding."),this.cron=false)),c.length||this.logger.info("node-cron package is already installed");}if(this.graphql&&["npm","yarn","pnpm"].includes(e)){let c=await pe(["@apollo/server","@graphql-tools/schema","graphql"]);c.length>0&&(await D(`${e} ${t} ${c.join(" ")}`,e,c,{stdio:"inherit"},false)||(this.logger.info("GraphQL installation cancelled by user. Skipping GraphQL scaffolding."),this.graphql=false)),c.length||this.logger.info("GraphQL packages are already installed");}let s=this.typescript?"ts":"js",n=this.getServerTemplate(),i=this.getIndexTemplate();y.exists(this.srcPath)||await y.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${s} file...`),await y.writeFile(`${this.srcPath}/server.${s}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${s} file...`),await y.writeFile(`${this.srcPath}/index.${s}`,new TextEncoder().encode(i));let a=this.getLoggerTemplate();if(this.logger.info(`Creating logger.${s} file...`),await y.writeFile(`${this.srcPath}/logger.${s}`,new TextEncoder().encode(a)),this.mqtt){let c=x.join(this.srcPath,"mqtt");await y.exists(c)||await y.mkdir(c,{recursive:true});let d=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${s} file...`),await y.writeFile(x.join(c,`mqtt.config.${s}`),new TextEncoder().encode(d));}if(this.cron){let c=x.join(this.srcPath,"cron");await y.exists(c)||await y.mkdir(c,{recursive:true});let d=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${s} file...`),await y.writeFile(x.join(c,`cron.config.${s}`),new TextEncoder().encode(d));}if(this.graphql){let c=x.join(this.srcPath,"graphql");await y.exists(c)||await y.mkdir(c,{recursive:true});let d=this.getGraphqlConfigTemplate();this.logger.info(`Creating graphql/graphql.config.${s} file...`),await y.writeFile(x.join(c,`graphql.config.${s}`),new TextEncoder().encode(d));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
|
|
624
624
|
import { logger } from "./logger.js";
|
|
625
625
|
|
|
626
626
|
const serverInstance = new Server({
|
|
@@ -690,7 +690,7 @@ import { CommandRegistry } from "../command_registry.js";
|
|
|
690
690
|
|
|
691
691
|
export const logger = pino({ level: "info" });
|
|
692
692
|
CommandRegistry.setLogger(logger);
|
|
693
|
-
`}};
|
|
693
|
+
`}};P([C.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],ie,"srcPath"),P([C.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],ie,"typescript"),P([C.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],ie,"mqtt"),P([C.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],ie,"cron"),P([C.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],ie,"graphql");var Ee=class extends A{static commandName="init-mailer";static description="Initialize mailer configuration with required dependencies";static help=["Initialize a mailer configuration file with basic setup","Automatically installs required packages for nodemailer and optional template engines","Supports Handlebars, EJS, Edge.js, Mustache, or custom adapters","Example: npx balda init-mailer -t handlebars -o src/mailer"];static templateEngine;static outputPath;static mailerDependencies={base:["nodemailer","@types/nodemailer"],handlebars:["handlebars","@types/handlebars"],ejs:["ejs","@types/ejs"],edge:["edge.js"],mustache:["mustache","@types/mustache"]};static async handle(){if(this.logger.info("Initializing mailer configuration..."),!["handlebars","ejs","edge","mustache","custom","none"].includes(this.templateEngine)){this.logger.error(`Invalid template engine: ${this.templateEngine}. Must be one of: handlebars, ejs, edge, mustache, custom, none`);return}let[e,t]=await U();if(["npm","yarn","pnpm"].includes(e)){let i=[...this.mailerDependencies.base,...this.templateEngine!=="none"&&this.templateEngine!=="custom"?this.mailerDependencies[this.templateEngine]||[]:[]],a=await pe(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for mailer`),!await D(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Mailer initialization aborted.");return}a.length===0&&this.logger.info("All mailer dependencies are already installed");}let r=this.getConfigTemplate(),s="mailer.config.ts",n=x.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(n,new TextEncoder().encode(r)),this.logger.info(`Mailer configuration initialized successfully at ${n}`),this.logger.info("Remember to update the configuration with your actual SMTP credentials"),this.templateEngine!=="none"&&this.logger.info(`Template engine '${this.templateEngine}' configured and ready to use`);}static getConfigTemplate(){let e=this.templateEngine!=="none";return `import { createTransport } from "nodemailer";
|
|
694
694
|
import { Mailer${e?`, ${this.getAdapterImport()}`:""} } from "balda";
|
|
695
695
|
|
|
696
696
|
/**
|
|
@@ -817,7 +817,7 @@ const adapter = new CustomAdapter();
|
|
|
817
817
|
* appName: "My App",
|
|
818
818
|
* },
|
|
819
819
|
* });
|
|
820
|
-
*`}};
|
|
820
|
+
*`}};P([C.string({description:"Template engine (handlebars, ejs, edge, mustache, custom, none) - optional",aliases:"t",name:"template",required:false,defaultValue:"none"})],Ee,"templateEngine"),P([C.string({description:"Output directory for mailer configuration, default is src/mailer",aliases:"o",name:"output",required:false,defaultValue:"src/mailer"})],Ee,"outputPath");var qe=class extends A{static commandName="init-queue";static description="Initialize queue provider configuration with required dependencies";static help=["Initialize a queue provider configuration file with basic credentials","Automatically installs required packages for the selected provider","Only scaffolds the connection, handlers should be created with generate-queue command","Example: npx balda init-queue -t bullmq -o src/queue"];static queueType;static outputPath;static queueDependencies={bullmq:["bullmq","ioredis"],sqs:["@aws-sdk/client-sqs","sqs-consumer"],pgboss:["pg-boss","pg"]};static async handle(){if(this.logger.info(`Initializing ${this.queueType} queue provider...`),!["bullmq","sqs","pgboss"].includes(this.queueType)){this.logger.error(`Invalid queue type: ${this.queueType}. Must be one of: bullmq, sqs, pgboss`);return}let[e,t]=await U();if(["npm","yarn","pnpm"].includes(e)){let i=this.queueDependencies[this.queueType],a=await pe(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await D(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}a.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),s=`${this.queueType}.config.ts`,n=x.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(n,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${n}`),this.logger.info("Remember to update the configuration with your actual credentials"),this.logger.info("Use 'npx balda generate-queue' to create queue handlers");}static getConfigTemplate(){return this.queueType==="bullmq"?this.getBullMQTemplate():this.queueType==="sqs"?this.getSQSTemplate():this.queueType==="pgboss"?this.getPGBossTemplate():""}static getBullMQTemplate(){return `import { defineBullMQConfiguration } from "balda";
|
|
821
821
|
|
|
822
822
|
// Configure BullMQ connection and default options
|
|
823
823
|
defineBullMQConfiguration({
|
|
@@ -986,18 +986,18 @@ definePGBossConfiguration({
|
|
|
986
986
|
* console.log("Processing:", payload);
|
|
987
987
|
* });
|
|
988
988
|
*/
|
|
989
|
-
`}};
|
|
989
|
+
`}};P([C.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],qe,"queueType"),P([C.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],qe,"outputPath");var Ue=class extends A{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=Qo__default.default.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=e==="sync"?"APP_PUBLIC_KEY":"APP_PUBLIC_KEY_ASYNC",n=e==="sync"?"APP_PRIVATE_KEY":"APP_PRIVATE_KEY_ASYNC";console.log(`
|
|
990
990
|
\u2728 Generated ${e==="sync"?"Sync":"Async"} Key Pair:
|
|
991
991
|
`),console.log(`\x1B[33mPublic Key (${s}):\x1B[0m`),console.log(`\x1B[32m${t}\x1B[0m`),console.log(`\x1B[33mPrivate Key (${n}):\x1B[0m`),console.log(`\x1B[32m${r}\x1B[0m`),await this.saveKeyToEnvFile(s,t),await this.saveKeyToEnvFile(n,r),console.log(`\x1B[90m\u{1F4A1} Keys saved to .env file as ${s} and ${n}\x1B[0m
|
|
992
992
|
`);}static async saveKeyToEnvFile(e,t){let r=ht__default.default.join(L.getCwd(),".env"),s=`${e}="${t}"`;if(ot__default.default.existsSync(r)){let n=ot__default.default.readFileSync(r,"utf-8"),i=new RegExp(`^${e}=.*$`,"m");if(i.test(n)){let a=n.replace(i,s);ot__default.default.writeFileSync(r,a),this.logger.info(`Updated ${e} in .env file`);return}ot__default.default.appendFileSync(r,`
|
|
993
993
|
${s}
|
|
994
994
|
`),this.logger.info(`Added ${e} to .env file`);return}ot__default.default.writeFileSync(r,`${s}
|
|
995
|
-
`),this.logger.info(`Created .env file with ${e}`);}};
|
|
995
|
+
`),this.logger.info(`Created .env file with ${e}`);}};P([C.string({aliases:["t"],name:"type",required:false,defaultValue:"sync",description:"Key type: sync or async (default: sync)"})],Ue,"type");var nt=class extends A{static commandName="list";static description="List all available commands";static help=["Display all registered Balda CLI commands with their descriptions","Example: npx balda list"];static async handle(){let e=Pe.getBuiltInCommands(),t=Pe.getUserDefinedCommands();if(console.log(`
|
|
996
996
|
\u2728 Available Balda Commands:
|
|
997
997
|
`),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
|
|
998
998
|
`);let r=this.groupByCategory(t);this.displayCategorizedCommands(r);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
|
|
999
999
|
`);let r=e.sort((n,i)=>n.commandName.localeCompare(i.commandName)),s=Math.max(...r.map(n=>n.commandName.length));for(let n of r){let i=n.commandName.padEnd(s+2),a=n.description||"No description available",c="";n.options?.deprecated&&(c=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${i}\x1B[0m ${a}${c}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
|
|
1000
|
-
`);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(c=>c&&c.commandName).sort((c,d)=>c.commandName.localeCompare(d.commandName));if(s.length===0)continue;let i={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${i}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...s.map(c=>c.commandName.length));for(let c of s){let d=c.commandName.padEnd(a+2),
|
|
1000
|
+
`);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(c=>c&&c.commandName).sort((c,d)=>c.commandName.localeCompare(d.commandName));if(s.length===0)continue;let i={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${i}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...s.map(c=>c.commandName.length));for(let c of s){let d=c.commandName.padEnd(a+2),l=c.description||"No description available",p="";c.options?.deprecated&&(p=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${d}\x1B[0m ${l}${p}`);}console.log("");}}};var Ae=class extends A{static commandName="queue-start";static description="Start queue workers to process jobs";static help=["Start queue workers to process jobs from registered queues","Loads queue handlers from specified patterns and starts processing","Example: npx balda queue-start","Example: npx balda queue-start src/queues/**/*.ts --patterns src/jobs/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting queue workers...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading queue handlers from patterns: ${e.join(", ")}`),await W.massiveImportQueues(e,{throwOnError:false});let t=W.typedQueueSubscribers.size,r=W.customQueueSubscribers.size,s=t+r;if(s===0){this.logger.warn("No queue handlers found. Make sure your queue handlers are decorated with @queue decorator");return}this.logger.info(`Found ${s} queue handler(s) (${t} typed, ${r} custom)`),W.run().then(()=>{this.logger.info("Queue workers started successfully. Press Ctrl+C to stop.");}).catch(n=>{this.logger.error("Error starting queue workers",n);});}};P([B({required:false,defaultValue:"src/queues/**/*.{ts,js}",description:"Primary glob pattern for queue handlers (default: src/queues/**/*.{ts,js})"})],Ae,"pattern"),P([C.list({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for queue handlers"})],Ae,"additionalPatterns");G();var ke=class extends A{static commandName="serve";static description="Run the server in dev mode with hot reload";static help=["This command is intended to be run from the root of the project","Bun and Deno have native dev hot reload","Runtime is automatically inferred","Node.js requires tsx to be installed for both typescript and javascript files","Node.js dev dependencies (tsx) are installed automatically if not detected"];static runtime=j.type;static options={keepAlive:true};static entry;static denoImportMap;static async handle(){if(this.runtime==="bun"){child_process.execSync(`bun run --watch ${this.entry}`,{stdio:"inherit",cwd:L.getCwd()});return}if(this.runtime==="deno"){let e="deno run --watch --unstable-sloppy-imports --allow-all";this.denoImportMap&&(e=`${e} --import-map ${this.denoImportMap}`),child_process.execSync(`${e} ${this.entry}`,{stdio:"inherit",cwd:L.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!ot__default.default.existsSync("node_modules/.bin/tsx")){let[r,s,n]=await U();if(!await D(`${r} ${s} tsx ${n}`,r,["tsx"],{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Cannot start dev server without tsx.");return}}let t=this.calledBy!=="node"?this.calledBy:"npx";child_process.execSync(`${t} tsx watch ${this.entry}`,{stdio:"inherit",cwd:process.cwd()});}};P([B({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],ke,"entry"),P([C.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],ke,"denoImportMap");var _e=class extends A{static commandName="init-storage";static description="Setup storage provider with required dependencies";static help=["Install dependencies and create storage configuration for a specific provider","Flags:"," -t, --type <provider> Storage provider type (s3, azure, local)"," -o, --output <path> Output directory for storage setup (default: src/storage/)","","Examples:"," npx balda setup:storage -t s3"," npx balda setup:storage --type azure --output src/config/"];static storageType;static outputPath;static async handle(){if(!this.storageType){console.error("\x1B[31m\u274C Error: Storage type is required. Use -t or --type flag.\x1B[0m"),console.log(`\x1B[90mExample: npx balda setup:storage -t s3\x1B[0m
|
|
1001
1001
|
`);return}this.outputPath||await y.mkdir(x.join(process.cwd(),this.outputPath),{recursive:true});let e=["s3","azure","local"];if(!e.includes(this.storageType)){console.error(`\x1B[31m\u274C Error: Invalid storage type '${this.storageType}'. Valid types: ${e.join(", ")}\x1B[0m
|
|
1002
1002
|
`);return}console.log(`
|
|
1003
1003
|
\u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
|
|
@@ -1087,16 +1087,16 @@ export const storage = new Storage(
|
|
|
1087
1087
|
defaultProvider: "local",
|
|
1088
1088
|
},
|
|
1089
1089
|
);
|
|
1090
|
-
`}[e]||""}};T([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],_e,"storageType"),T([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],_e,"outputPath");var Go=[je,Qe,Ce,Me,he,Re,Oe,Q,ie,Ee,qe,nt,K,ke,_e,Ue,Ae,Te],qt=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=M.child({scope:"CommandRegistry"});static setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),A.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||o.loggerPath;try{let r=await import(x.join(L.getCwd(),t));r.logger&&o.setLogger(r.logger);}catch{o.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return o.logger}setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),A.logger=e.child({scope:"Command"});}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){o.logger.info(`Loading commands from ${e}`);let t=await y.glob(e,{cwd:L.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{o.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let s=await import(r).then(n=>n.default?n.default:n).catch(n=>(o.logger.error(`Error loading command ${r}: ${n}`),null));s&&this.commands.set(s.commandName,s);}for(let r of Go)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Pe=qt.getInstance();function Jo(o){return o}function Sr(o,e){let t={...Ne,...e?.defaultTtl!==void 0&&{defaultTtl:e.defaultTtl},...e?.compressionThreshold!==void 0&&{compressionThreshold:e.compressionThreshold},...e?.keyPrefix!==void 0&&{keyPrefix:e.keyPrefix},...e?.enableStats!==void 0&&{enableStats:e.enableStats},...e?.lockTimeout!==void 0&&{lockTimeout:e.lockTimeout},...e?.lockBehavior!==void 0&&{lockBehavior:e.lockBehavior}};return lr(o,t),async(r,s,n)=>{await n();}}var it=class{store=new Map;sets=new Map;locks=new Map;async get(e){let t=this.store.get(e);return t?Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,r){this.store.set(e,{value:t,expiresAt:Date.now()+r*1e3});}async del(e){return this.store.delete(e)||this.sets.delete(e)}async delMany(e){let t=0;for(let r of e)(this.store.delete(r)||this.sets.delete(r))&&t++;return t}async addToSet(e,t,r){let s=this.sets.get(e);(!s||Date.now()>s.expiresAt)&&(s={members:new Set,expiresAt:r?Date.now()+r*1e3:Number.MAX_SAFE_INTEGER},this.sets.set(e,s));for(let n of t)s.members.add(n);r&&(s.expiresAt=Date.now()+r*1e3);}async getSetMembers(e){let t=this.sets.get(e);return t?Date.now()>t.expiresAt?(this.sets.delete(e),[]):Array.from(t.members):[]}async acquireLock(e,t){let r=this.locks.get(e);return r&&Date.now()<r?false:(this.locks.set(e,Date.now()+t),true)}async releaseLock(e){this.locks.delete(e);}async*scan(e){let t=Wo(e),r=[];for(let s of this.store.keys())if(t.test(s)){let n=this.store.get(s);Date.now()<=n.expiresAt&&(r.push(s),r.length>=100&&(yield [...r],r.length=0));}r.length>0&&(yield r);}async disconnect(){this.store.clear(),this.sets.clear(),this.locks.clear();}};function Wo(o){let e=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp("^"+e+"$")}var at=class{redis=null;options;constructor(e={}){this.options=e;}async getClient(){if(this.redis)return this.redis;let e;try{let{default:t}=await import('ioredis');e=t;}catch{throw new Error("ioredis is required for RedisCacheProvider. Install it with: npm install ioredis")}return this.options.url?this.redis=new e(this.options.url):this.redis=new e({host:this.options.host??"localhost",port:this.options.port??6379,password:this.options.password,db:this.options.db??0,keyPrefix:this.options.keyPrefix}),this.redis}async get(e){return (await this.getClient()).get(e)}async set(e,t,r){await(await this.getClient()).set(e,t,"EX",r);}async del(e){return await(await this.getClient()).del(e)>0}async delMany(e){return e.length===0?0:(await this.getClient()).del(...e)}async addToSet(e,t,r){if(t.length===0)return;let n=(await this.getClient()).pipeline();n.sadd(e,...t),r&&n.expire(e,r),await n.exec();}async getSetMembers(e){return (await this.getClient()).smembers(e)}async acquireLock(e,t){return await(await this.getClient()).set(e,"1","PX",t,"NX")==="OK"}async releaseLock(e){await(await this.getClient()).del(e);}async*scan(e){let t=await this.getClient(),r=this.options.keyPrefix||"",s=r+e,n="0";do{let[i,a]=await t.scan(n,"MATCH",s,"COUNT",100);n=i,a.length>0&&(yield r?a.map(c=>c.startsWith(r)?c.slice(r.length):c):a);}while(n!=="0")}async disconnect(){this.redis&&(await this.redis.quit(),this.redis=null);}};G();var ze=class{get(e){switch(j.type){case "node":case "bun":case "deno":return process.env[e];default:throw new Error(`Unsupported runtime: ${j.type}`)}}getEnvironment(){switch(j.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var Ko=new ze,N=o=>{let e=Ko.get("NODE_ENV")!=="production";return {code:o.name||"INTERNAL_ERROR",message:o.message,...e&&{stack:o.stack,cause:o.cause}}};var Ge=class extends R{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var z=class extends R{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var se=class{schemaOptions;apolloOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.apolloOptions=t.apolloOptions,this.isEnabled=t.isEnabled;}getSchemaOptions(){return this.schemaOptions}getApolloOptions(){return this.apolloOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},apolloOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),apolloOptions:this.resolveApolloOptions(e.apolloOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveApolloOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var fe=(o,e,t,r)=>{let s=o.length;if(s===0){let a=e(t,r);return a&&typeof a.then=="function"?a.then(c=>(c&&r.send(c),r)):(a&&r.send(a),r)}let n=0,i=async()=>{if(n>=s){let d=await e(t,r);return d&&r.send(d),r}let a=n++,c=o[a];await c(t,r,i);};return i().then(()=>r)},Vo=new Set(["post","put","patch"]),ae=o=>o?Vo.has(o.toLowerCase()):true,At=async(o,e,t,r,s)=>{try{let{HeaderMap:n}=await import('@apollo/server'),i=new n;e.headers.forEach((u,h)=>{i.set(h,u);});let c=(e.headers.get("content-type")??"").includes("application/json"),d="";if(t!=="GET"){let u=await e.text();d=c&&u?JSON.parse(u):u;}let p={method:t.toUpperCase(),headers:i,body:d,search:r?`?${r}`:""},l=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:p,context:async()=>s}),m={};for(let[u,h]of l.headers)m[u]=h;if(l.body.kind==="complete")return new globalThis.Response(l.body.string,{status:l.status??200,headers:m});let f=new ReadableStream({async start(u){if(l.body.kind==="chunked")for await(let h of l.body.asyncIterator)u.enqueue(new TextEncoder().encode(h));u.close();}});return new globalThis.Response(f,{status:l.status??200,headers:m})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},Ts=async(o,e,t,r,s,n,i)=>{try{let{HeaderMap:a}=await import('@apollo/server'),c=new a;for(let[h,g]of Object.entries(e))g!==void 0&&c.set(h,Array.isArray(g)?g.join(", "):g);let l=(c.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,m={method:t?.toUpperCase()??"POST",headers:c,body:l,search:s?`?${s}`:""},f=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:m,context:async()=>n}),u=f.status??200;f.body.kind==="complete"?await i(f.headers,u,f.body.string):await i(f.headers,u,f.body.asyncIterator);}catch{await i(new Map([["Content-Type","application/json"]]),500,JSON.stringify({errors:[{message:"Internal server error"}]}));}},ge=o=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(n=>setTimeout(n,10));},s=async()=>{try{let{ApolloServer:n}=await import('@apollo/server'),{makeExecutableSchema:i}=await import('@graphql-tools/schema'),a=o.getSchemaOptions(),c=o.getApolloOptions(),d=i({typeDefs:a.typeDefs,resolvers:a.resolvers}),p=new n({schema:d,...c});return await p.start(),{server:p,url:"/graphql"}}catch(n){throw n instanceof Error&&(n.message.includes("Cannot find module")||n.message.includes("Cannot find package"))?new Error("GraphQL is enabled but '@apollo/server' is not installed. Install it with: npm install @apollo/server @graphql-tools/schema graphql"):n}};return async()=>{if(!o.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var oe=class o{static fromRequest(e){let t=Object.assign(new o,{url:e.url,method:e.method,signal:e.signal,referrer:e.referrer,referrerPolicy:e.referrerPolicy,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,integrity:e.integrity,keepalive:e.keepalive});return t.#o=e.headers,t.#n=true,t.#t=e,t}toWebApi(){if(this.#t)return this.#t;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#r&&e){let t=stream.Readable.toWeb(this.#r);return this.#t=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.rawHeaders,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,duplex:"half"}),this.#t}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.rawHeaders,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive})}static toJSONSchemaWithPrefix(e){return H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"zod_schema"}:I.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"typebox_schema"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"json_schema"}:{jsonSchema:{type:typeof e},prefix:`primitive_${JSON.stringify(e)}`}}static getOrCompileSchema(e){let{jsonSchema:t,prefix:r}=this.toJSONSchemaWithPrefix(e);return q.storeJsonSchema(t,r),q.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return Ot(s,t,r)}#t;#r;#e;#a=false;#o;#n=false;#l;#p=false;url="";method="GET";get rawHeaders(){if(this.#n)return this.#o;if(this.#e){let e=this.#e,t={};if(this.#a)for(let r in e){if(r.charCodeAt(0)===58)continue;let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}else for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}this.#o=new Headers(t);}else this.#o=new Headers;return this.#n=true,this.#o}get headers(){return this.#p?this.#l:{}}set headers(e){this.#l=e,this.#p=true;}signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file(e){return this.files.find(t=>t.formName===e)??null}#u;#g=false;get cookies(){if(!this.#g)throw new Error("Cookie middleware is required. Register the cookie plugin to access request cookies.");return this.#u}set cookies(e){this.#u=e,this.#g=true;}cookie(e){return this.cookies[e]}timeout;#y;#v=false;get session(){if(!this.#v)throw new Error("Session middleware is required. Register the session plugin to access request session.");return this.#y}set session(e){this.#y=e,this.#v=true;}static _throwSaveSession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use saveSession.")};static _throwDestroySession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use destroySession.")};saveSession=o._throwSaveSession;destroySession=o._throwDestroySession;#m;#d=false;#c;get ip(){return this.#d?this.#m:(this.#d=true,this.#c&&(this.#m=this.#c(),this.#c=void 0),this.#m)}set ip(e){this.#m=e,this.#d=true,this.#c=void 0;}files=[];params={};#i;#s;#h=false;get query(){if(this.#h)return this.#i;if(!this.#s||this.#s==="")this.#i={};else if(this.#s.length<50&&!this.#s.includes("&")){let e=this.#s.indexOf("=");if(e===-1)this.#i={[this.#s]:""};else {let t=this.#s.slice(0,e),r=decodeURIComponent(this.#s.slice(e+1));this.#i={[t]:r};}}else this.#i=Object.fromEntries(new URLSearchParams(this.#s));return this.#h=true,this.#i}set query(e){this.#i=e,this.#h=true;}setQueryString(e){this.#s=e,this.#h=false,this.#i=void 0;}#f;get id(){return this.#f||(this.#f=ee.randomUUID()),this.#f}set id(e){this.#f=e;}validate(e,t=false){return o.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return o.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return o.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}validateHeaders(e,t=false){let r=this.#p?this.#l:this.#b();return o.compileAndValidate(e,r,t)}#b(){let e={},t=new Map;this.rawHeaders.forEach((r,s)=>{let n=s.toLowerCase(),i=t.get(n);i?i.push(r):t.set(n,[r]);});for(let[r,s]of t)e[r]=s.length===1?s[0]:s;return e}setIpExtractor(e){this.#d=false,this.#c=()=>{let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress};}setBunIpExtractor(e,t){this.#d=false,this.#c=()=>{let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0].trim():t.requestIP(e)?.address};}setDenoIpExtractor(e,t){this.#d=false,this.#c=()=>{let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0].trim():t.remoteAddr?.hostname};}setRawHeaders(e,t){this.#e=e,this.#a=t,this.#n=false,this.#o=void 0;}setNodeRequest(e){this.#r=e;}};G();var xr=class{file(e,t){switch(j.type){case "bun":case "node":return ot__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},kt=new xr;var Ps=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var Tr=(o,e)=>{let{source:t,path:r}=o,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),_.addOrUpdate("GET",`${s}/*`,[],async(n,i)=>Yo(n,i,t),{},{service:"StaticFiles",...e},void 0,true),async(n,i,a)=>a()};async function Yo(o,e,t){if(o.method!=="GET"&&o.method!=="HEAD")return e.status(405).json({...N(new Ge(o.url,o.method))});let r=o.params["*"]||"",s=x.join(t,r),n=x.resolve(L.getCwd(),s),i=x.resolve(L.getCwd(),t);if(!n.startsWith(i))return e.notFound({...N(new z(o.url,o.method))});try{if(!(await y.stat(n)).isFile)return e.notFound({...N(new z(o.url,o.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...N(new z(o.url,o.method))});throw d}let a=Pr(x.extName(n));e.setHeader("Content-Type",a);let c=kt.file(n);e.raw(c);}function Pr(o){return Ps.get(o)||"application/octet-stream"}var F=class{static toWebResponse(e){let t=e.getBody();return e.headers["Content-Type"]?.toLowerCase()==="application/json"?typeof t=="string"?new globalThis.Response(t,{status:e.responseStatus,headers:e.headers}):globalThis.Response.json(t,{status:e.responseStatus,headers:e.headers}):new globalThis.Response(t,{status:e.responseStatus,headers:e.headers})}responseStatus;headers;body;#t;#r;#e;constructor(e=200){this.responseStatus=e,this.headers={};}setRouteResponseSchemas(e){this.#r=e,this.#e=q.getOrCreateResponseSerializers(e)??void 0;}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers["Content-Type"]="text/plain";}json(e,t){if(this.body=e,this.headers["Content-Type"]="application/json",!t&&this.#e){let s=this.#e.get(this.responseStatus);if(s){this.#t=s;return}}let r=t??this.#r?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:n}=this.getJsonSchemaWithPrefix(r);this.#t=q.getOrCreateSerializer(s,n)??void 0;}}html(e){this.body=e,this.headers["Content-Type"]="text/html";}xml(e){this.body=e,this.headers["Content-Type"]="application/xml";}download(e){this.body=e,this.headers["Content-Type"]="application/octet-stream";}file(e,t){let r=x.extName(e),s=Pr(r);this.body=kt.file(e,t),this.headers["Content-Type"]=s;}ok(e){if(this.responseStatus=200,e!=null&&typeof e=="object"){this.json(e);return}this.send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.responseStatus=204,this.body="";}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.responseStatus=304,this.body="";}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers["Content-Type"]="text/event-stream",this.headers["Cache-Control"]="no-cache",this.headers.Connection="keep-alive",t?.customHeaders)for(let r in t.customHeaders)this.headers[r]=t.customHeaders[r];if(e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){if(this.#t&&typeof this.body=="object"&&this.body!==null)try{this.body=this.#t(this.body),this.#t=void 0;}catch(e){M.error({error:e,statusCode:this.responseStatus,contentType:this.headers["Content-Type"]},"Fast-json-stringify serialization failed, falling back to JSON.stringify"),this.#t=void 0;}return this.body}getJsonSchemaWithPrefix(e){return H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"fast_stringify_zod"}:I.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"fast_stringify_typebox"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof e},prefix:`fast_stringify_primitive_${JSON.stringify(e)}`}}};var de=class{constructor(e){this.response=e;}body(){let e=this.response.getBody();if(typeof e=="string"&&this.response.headers["Content-Type"]?.includes("json"))try{return JSON.parse(e)}catch{return e}return e}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let s in t){let n=r===""?s:`${r}.${s}`,i=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${s.length}`);for(let i of n){let a=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let n=`${r}[${s}]`,i=e[s],a=t[s];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let n=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var _t=class{server;logger=M.child({scope:"MockServer"});ensureGraphQLHandler;constructor(e){this.server=e,this.ensureGraphQLHandler=ge(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:n={},cookies:i={},ip:a}=r;this.validateOptions(r);let c=this.server.graphql.isEnabled,d=t.startsWith("/graphql");if(c&&d)return this.handleGraphQLRequest(e,t,r);let p=_.find(e.toUpperCase(),t);if(!p){let g=new F(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new de(g)}let l,m="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?l=JSON.stringify(r.body):l=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;m=`multipart/form-data; boundary=${g}`,l=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(m="application/x-www-form-urlencoded",l=new URLSearchParams(r.urlencoded).toString());let f=new URL(`http://${this.server.host}:${this.server.port}${t}`);f.search=new URLSearchParams(n).toString();let u=new globalThis.Request(f.toString(),{method:e.toUpperCase(),body:ae(e)?l:void 0,headers:{"content-type":m,...s}}),h=oe.fromRequest(u);h.query={...Object.fromEntries(f.searchParams.entries()),...n},h.params=p.params,h.cookies=i,h.ip=a;try{let g=await fe(p.middleware,p.handler,h,new F);return new de(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let b=new F(500);return b.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new de(b)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,s=[];for(let[c,d]of e.entries()){s.push(r.encode(`--${t}\r
|
|
1091
|
-
`));let
|
|
1092
|
-
`),s.push(r.encode(`${
|
|
1093
|
-
${
|
|
1090
|
+
`}[e]||""}};P([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],_e,"storageType"),P([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],_e,"outputPath");var Go=[je,Qe,Ce,Me,he,Re,Oe,Q,ie,Ee,qe,nt,K,ke,_e,Ue,Ae,Te],qt=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=M.child({scope:"CommandRegistry"});static setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),A.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||o.loggerPath;try{let r=await import(x.join(L.getCwd(),t));r.logger&&o.setLogger(r.logger);}catch{o.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return o.logger}setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),A.logger=e.child({scope:"Command"});}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){o.logger.info(`Loading commands from ${e}`);let t=await y.glob(e,{cwd:L.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{o.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let s=await import(r).then(n=>n.default?n.default:n).catch(n=>(o.logger.error(`Error loading command ${r}: ${n}`),null));s&&this.commands.set(s.commandName,s);}for(let r of Go)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Pe=qt.getInstance();function Jo(o){return o}function Sr(o,e){let t={...Ne,...e?.defaultTtl!==void 0&&{defaultTtl:e.defaultTtl},...e?.compressionThreshold!==void 0&&{compressionThreshold:e.compressionThreshold},...e?.keyPrefix!==void 0&&{keyPrefix:e.keyPrefix},...e?.enableStats!==void 0&&{enableStats:e.enableStats},...e?.lockTimeout!==void 0&&{lockTimeout:e.lockTimeout},...e?.lockBehavior!==void 0&&{lockBehavior:e.lockBehavior}};return lr(o,t),async(r,s,n)=>{await n();}}var it=class{store=new Map;sets=new Map;locks=new Map;async get(e){let t=this.store.get(e);return t?Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,r){this.store.set(e,{value:t,expiresAt:Date.now()+r*1e3});}async del(e){return this.store.delete(e)||this.sets.delete(e)}async delMany(e){let t=0;for(let r of e)(this.store.delete(r)||this.sets.delete(r))&&t++;return t}async addToSet(e,t,r){let s=this.sets.get(e);(!s||Date.now()>s.expiresAt)&&(s={members:new Set,expiresAt:r?Date.now()+r*1e3:Number.MAX_SAFE_INTEGER},this.sets.set(e,s));for(let n of t)s.members.add(n);r&&(s.expiresAt=Date.now()+r*1e3);}async getSetMembers(e){let t=this.sets.get(e);return t?Date.now()>t.expiresAt?(this.sets.delete(e),[]):Array.from(t.members):[]}async acquireLock(e,t){let r=this.locks.get(e);return r&&Date.now()<r?false:(this.locks.set(e,Date.now()+t),true)}async releaseLock(e){this.locks.delete(e);}async*scan(e){let t=Wo(e),r=[];for(let s of this.store.keys())if(t.test(s)){let n=this.store.get(s);Date.now()<=n.expiresAt&&(r.push(s),r.length>=100&&(yield [...r],r.length=0));}r.length>0&&(yield r);}async disconnect(){this.store.clear(),this.sets.clear(),this.locks.clear();}};function Wo(o){let e=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp("^"+e+"$")}var at=class{redis=null;options;constructor(e={}){this.options=e;}async getClient(){if(this.redis)return this.redis;let e;try{let{default:t}=await import('ioredis');e=t;}catch{throw new Error("ioredis is required for RedisCacheProvider. Install it with: npm install ioredis")}return this.options.url?this.redis=new e(this.options.url):this.redis=new e({host:this.options.host??"localhost",port:this.options.port??6379,password:this.options.password,db:this.options.db??0,keyPrefix:this.options.keyPrefix}),this.redis}async get(e){return (await this.getClient()).get(e)}async set(e,t,r){await(await this.getClient()).set(e,t,"EX",r);}async del(e){return await(await this.getClient()).del(e)>0}async delMany(e){return e.length===0?0:(await this.getClient()).del(...e)}async addToSet(e,t,r){if(t.length===0)return;let n=(await this.getClient()).pipeline();n.sadd(e,...t),r&&n.expire(e,r),await n.exec();}async getSetMembers(e){return (await this.getClient()).smembers(e)}async acquireLock(e,t){return await(await this.getClient()).set(e,"1","PX",t,"NX")==="OK"}async releaseLock(e){await(await this.getClient()).del(e);}async*scan(e){let t=await this.getClient(),r=this.options.keyPrefix||"",s=r+e,n="0";do{let[i,a]=await t.scan(n,"MATCH",s,"COUNT",100);n=i,a.length>0&&(yield r?a.map(c=>c.startsWith(r)?c.slice(r.length):c):a);}while(n!=="0")}async disconnect(){this.redis&&(await this.redis.quit(),this.redis=null);}};G();var ze=class{get(e){switch(j.type){case "node":case "bun":case "deno":return process.env[e];default:throw new Error(`Unsupported runtime: ${j.type}`)}}getEnvironment(){switch(j.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var Ko=new ze,N=o=>{let e=Ko.get("NODE_ENV")!=="production";return {code:o.name||"INTERNAL_ERROR",message:o.message,...e&&{stack:o.stack,cause:o.cause}}};var Ge=class extends R{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var z=class extends R{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var se=class{schemaOptions;apolloOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.apolloOptions=t.apolloOptions,this.isEnabled=t.isEnabled;}getSchemaOptions(){return this.schemaOptions}getApolloOptions(){return this.apolloOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},apolloOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),apolloOptions:this.resolveApolloOptions(e.apolloOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveApolloOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var fe=(o,e,t,r)=>{let s=o.length;if(s===0){let a=e(t,r);return a&&typeof a.then=="function"?a.then(c=>(c&&r.send(c),r)):(a&&r.send(a),r)}let n=0,i=async()=>{if(n>=s){let d=await e(t,r);return d&&r.send(d),r}let a=n++,c=o[a];await c(t,r,i);};return i().then(()=>r)},Vo=new Set(["post","put","patch"]),ae=o=>o?Vo.has(o.toLowerCase()):true,At=async(o,e,t,r,s)=>{try{let{HeaderMap:n}=await import('@apollo/server'),i=new n;e.headers.forEach((u,h)=>{i.set(h,u);});let c=(e.headers.get("content-type")??"").includes("application/json"),d="";if(t!=="GET"){let u=await e.text();d=c&&u?JSON.parse(u):u;}let l={method:t.toUpperCase(),headers:i,body:d,search:r?`?${r}`:""},p=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:l,context:async()=>s}),m={};for(let[u,h]of p.headers)m[u]=h;if(p.body.kind==="complete")return new globalThis.Response(p.body.string,{status:p.status??200,headers:m});let f=new ReadableStream({async start(u){if(p.body.kind==="chunked")for await(let h of p.body.asyncIterator)u.enqueue(new TextEncoder().encode(h));u.close();}});return new globalThis.Response(f,{status:p.status??200,headers:m})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},Ts=async(o,e,t,r,s,n,i)=>{try{let{HeaderMap:a}=await import('@apollo/server'),c=new a;for(let[h,g]of Object.entries(e))g!==void 0&&c.set(h,Array.isArray(g)?g.join(", "):g);let p=(c.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,m={method:t?.toUpperCase()??"POST",headers:c,body:p,search:s?`?${s}`:""},f=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:m,context:async()=>n}),u=f.status??200;f.body.kind==="complete"?await i(f.headers,u,f.body.string):await i(f.headers,u,f.body.asyncIterator);}catch{await i(new Map([["Content-Type","application/json"]]),500,JSON.stringify({errors:[{message:"Internal server error"}]}));}},ge=o=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(n=>setTimeout(n,10));},s=async()=>{try{let{ApolloServer:n}=await import('@apollo/server'),{makeExecutableSchema:i}=await import('@graphql-tools/schema'),a=o.getSchemaOptions(),c=o.getApolloOptions(),d=i({typeDefs:a.typeDefs,resolvers:a.resolvers}),l=new n({schema:d,...c});return await l.start(),{server:l,url:"/graphql"}}catch(n){throw n instanceof Error&&(n.message.includes("Cannot find module")||n.message.includes("Cannot find package"))?new Error("GraphQL is enabled but '@apollo/server' is not installed. Install it with: npm install @apollo/server @graphql-tools/schema graphql"):n}};return async()=>{if(!o.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var oe=class o{static fromRequest(e){let t=Object.assign(new o,{url:e.url,method:e.method,signal:e.signal,referrer:e.referrer,referrerPolicy:e.referrerPolicy,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,integrity:e.integrity,keepalive:e.keepalive});return t.#o=e.headers,t.#n=true,t.#t=e,t}toWebApi(){if(this.#t)return this.#t;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#r&&e){let t=stream.Readable.toWeb(this.#r);return this.#t=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.rawHeaders,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,duplex:"half"}),this.#t}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.rawHeaders,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive})}static toJSONSchemaWithPrefix(e){return H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"zod_schema"}:I.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"typebox_schema"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"json_schema"}:{jsonSchema:{type:typeof e},prefix:`primitive_${JSON.stringify(e)}`}}static getOrCompileSchema(e){let{jsonSchema:t,prefix:r}=this.toJSONSchemaWithPrefix(e);return q.storeJsonSchema(t,r),q.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return Ot(s,t,r)}#t;#r;#e;#a=false;#o;#n=false;#l;#p=false;url="";method="GET";get rawHeaders(){if(this.#n)return this.#o;if(this.#e){let e=this.#e,t={};if(this.#a)for(let r in e){if(r.charCodeAt(0)===58)continue;let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}else for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}this.#o=new Headers(t);}else this.#o=new Headers;return this.#n=true,this.#o}get headers(){return this.#p?this.#l:{}}set headers(e){this.#l=e,this.#p=true;}signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file(e){return this.files.find(t=>t.formName===e)??null}#u;#g=false;get cookies(){if(!this.#g)throw new Error("Cookie middleware is required. Register the cookie plugin to access request cookies.");return this.#u}set cookies(e){this.#u=e,this.#g=true;}cookie(e){return this.cookies[e]}timeout;#y;#v=false;get session(){if(!this.#v)throw new Error("Session middleware is required. Register the session plugin to access request session.");return this.#y}set session(e){this.#y=e,this.#v=true;}static _throwSaveSession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use saveSession.")};static _throwDestroySession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use destroySession.")};saveSession=o._throwSaveSession;destroySession=o._throwDestroySession;#m;#d=false;#c;get ip(){return this.#d?this.#m:(this.#d=true,this.#c&&(this.#m=this.#c(),this.#c=void 0),this.#m)}set ip(e){this.#m=e,this.#d=true,this.#c=void 0;}files=[];params={};#i;#s;#h=false;get query(){if(this.#h)return this.#i;if(!this.#s||this.#s==="")this.#i={};else if(this.#s.length<50&&!this.#s.includes("&")){let e=this.#s.indexOf("=");if(e===-1)this.#i={[this.#s]:""};else {let t=this.#s.slice(0,e),r=decodeURIComponent(this.#s.slice(e+1));this.#i={[t]:r};}}else this.#i=Object.fromEntries(new URLSearchParams(this.#s));return this.#h=true,this.#i}set query(e){this.#i=e,this.#h=true;}setQueryString(e){this.#s=e,this.#h=false,this.#i=void 0;}#f;get id(){return this.#f||(this.#f=ee.randomUUID()),this.#f}set id(e){this.#f=e;}validate(e,t=false){return o.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return o.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return o.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}validateHeaders(e,t=false){let r=this.#p?this.#l:this.#b();return o.compileAndValidate(e,r,t)}#b(){let e={},t=new Map;this.rawHeaders.forEach((r,s)=>{let n=s.toLowerCase(),i=t.get(n);i?i.push(r):t.set(n,[r]);});for(let[r,s]of t)e[r]=s.length===1?s[0]:s;return e}setIpExtractor(e){this.#d=false,this.#c=()=>{let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress};}setBunIpExtractor(e,t){this.#d=false,this.#c=()=>{let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0].trim():t.requestIP(e)?.address};}setDenoIpExtractor(e,t){this.#d=false,this.#c=()=>{let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0].trim():t.remoteAddr?.hostname};}setRawHeaders(e,t){this.#e=e,this.#a=t,this.#n=false,this.#o=void 0;}setNodeRequest(e){this.#r=e;}};G();var xr=class{file(e,t){switch(j.type){case "bun":case "node":return ot__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},kt=new xr;var Ps=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var Tr=(o,e)=>{let{source:t,path:r}=o,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),_.addOrUpdate("GET",`${s}/*`,[],async(n,i)=>Yo(n,i,t),{},{service:"StaticFiles",...e},void 0,true),async(n,i,a)=>a()};async function Yo(o,e,t){if(o.method!=="GET"&&o.method!=="HEAD")return e.status(405).json({...N(new Ge(o.url,o.method))});let r=o.params["*"]||"",s=x.join(t,r),n=x.resolve(L.getCwd(),s),i=x.resolve(L.getCwd(),t);if(!n.startsWith(i))return e.notFound({...N(new z(o.url,o.method))});try{if(!(await y.stat(n)).isFile)return e.notFound({...N(new z(o.url,o.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...N(new z(o.url,o.method))});throw d}let a=Pr(x.extName(n));e.setHeader("Content-Type",a);let c=kt.file(n);e.raw(c);}function Pr(o){return Ps.get(o)||"application/octet-stream"}var F=class{static toWebResponse(e){let t=e.getBody();return e.headers["Content-Type"]?.toLowerCase()==="application/json"?typeof t=="string"?new globalThis.Response(t,{status:e.responseStatus,headers:e.headers}):globalThis.Response.json(t,{status:e.responseStatus,headers:e.headers}):new globalThis.Response(t,{status:e.responseStatus,headers:e.headers})}responseStatus;headers;body;#t;#r;#e;constructor(e=200){this.responseStatus=e,this.headers={};}setRouteResponseSchemas(e){this.#r=e,this.#e=q.getOrCreateResponseSerializers(e)??void 0;}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers["Content-Type"]="text/plain";}json(e,t){if(this.body=e,this.headers["Content-Type"]="application/json",!t&&this.#e){let s=this.#e.get(this.responseStatus);if(s){this.#t=s;return}}let r=t??this.#r?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:n}=this.getJsonSchemaWithPrefix(r);this.#t=q.getOrCreateSerializer(s,n)??void 0;}}html(e){this.body=e,this.headers["Content-Type"]="text/html";}xml(e){this.body=e,this.headers["Content-Type"]="application/xml";}download(e){this.body=e,this.headers["Content-Type"]="application/octet-stream";}file(e,t){let r=x.extName(e),s=Pr(r);this.body=kt.file(e,t),this.headers["Content-Type"]=s;}ok(e){if(this.responseStatus=200,e!=null&&typeof e=="object"){this.json(e);return}this.send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.responseStatus=204,this.body="";}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.responseStatus=304,this.body="";}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers["Content-Type"]="text/event-stream",this.headers["Cache-Control"]="no-cache",this.headers.Connection="keep-alive",t?.customHeaders)for(let r in t.customHeaders)this.headers[r]=t.customHeaders[r];if(e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){if(this.#t&&typeof this.body=="object"&&this.body!==null)try{this.body=this.#t(this.body),this.#t=void 0;}catch(e){M.error({error:e,statusCode:this.responseStatus,contentType:this.headers["Content-Type"]},"Fast-json-stringify serialization failed, falling back to JSON.stringify"),this.#t=void 0;}return this.body}getJsonSchemaWithPrefix(e){return H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"fast_stringify_zod"}:I.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"fast_stringify_typebox"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof e},prefix:`fast_stringify_primitive_${JSON.stringify(e)}`}}};var de=class{constructor(e){this.response=e;}body(){let e=this.response.getBody();if(typeof e=="string"&&this.response.headers["Content-Type"]?.includes("json"))try{return JSON.parse(e)}catch{return e}return e}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let s in t){let n=r===""?s:`${r}.${s}`,i=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${s.length}`);for(let i of n){let a=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let n=`${r}[${s}]`,i=e[s],a=t[s];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let n=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var _t=class{server;logger=M.child({scope:"MockServer"});ensureGraphQLHandler;constructor(e){this.server=e,this.ensureGraphQLHandler=ge(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:n={},cookies:i={},ip:a}=r;this.validateOptions(r);let c=this.server.graphql.isEnabled,d=t.startsWith("/graphql");if(c&&d)return this.handleGraphQLRequest(e,t,r);let l=_.find(e.toUpperCase(),t);if(!l){let g=new F(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new de(g)}let p,m="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?p=JSON.stringify(r.body):p=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;m=`multipart/form-data; boundary=${g}`,p=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(m="application/x-www-form-urlencoded",p=new URLSearchParams(r.urlencoded).toString());let f=new URL(`http://${this.server.host}:${this.server.port}${t}`);f.search=new URLSearchParams(n).toString();let u=new globalThis.Request(f.toString(),{method:e.toUpperCase(),body:ae(e)?p:void 0,headers:{"content-type":m,...s}}),h=oe.fromRequest(u);h.query={...Object.fromEntries(f.searchParams.entries()),...n},h.params=l.params,h.cookies=i,h.ip=a;try{let g=await fe(l.middleware,l.handler,h,new F);return new de(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let b=new F(500);return b.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new de(b)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,s=[];for(let[c,d]of e.entries()){s.push(r.encode(`--${t}\r
|
|
1091
|
+
`));let l=`Content-Disposition: form-data; name="${c}"`,p="";if(d instanceof File&&(l+=`; filename="${d.name}"`,p=`Content-Type: ${d.type||"application/octet-stream"}\r
|
|
1092
|
+
`),s.push(r.encode(`${l}\r
|
|
1093
|
+
${p}\r
|
|
1094
1094
|
`)),d instanceof File){let m=await d.arrayBuffer();s.push(new Uint8Array(m)),s.push(r.encode(`\r
|
|
1095
1095
|
`));}else s.push(r.encode(`${String(d)}\r
|
|
1096
1096
|
`));}s.push(r.encode(`--${t}--\r
|
|
1097
|
-
`));let n=s.reduce((c,d)=>c+d.byteLength,0),i=new Uint8Array(n),a=0;for(let c of s)i.set(c,a),a+=c.byteLength;return i}async handleGraphQLRequest(e,t,r={}){let s=await this.ensureGraphQLHandler();if(!s){let
|
|
1098
|
-
`).find(le=>le.toLowerCase().startsWith("content-disposition:"));if(!v)continue;let w=v.match(/name="([^"]+)"/);if(!w)continue;let k=w[1],E=v.match(/filename="([^"]*)"/),$=E?E[1]:"";if(!!$){if(o?.maxFiles&&g.length>=o.maxFiles)return t.badRequest({...N(new R(`Too many files: Maximum ${o.maxFiles} files allowed`))});if(
|
|
1099
|
-
`).find(Ws=>Ws.toLowerCase().startsWith("content-type:")),Z=le?le.split(":")[1].trim():"application/octet-stream";if(o?.allowedMimeTypes&&!o.allowedMimeTypes.includes(Z))return t.badRequest({...N(new R(`Invalid file type: "${Z}" is not allowed. Allowed types: ${o.allowedMimeTypes.join(", ")}`))});let Vt=tn(Z),Xt=x.join(await Rs.tmpdir(),`${ee.randomUUID()}${Vt}`);await y.writeFile(Xt,S.data),s.push(Xt),g.push({formName:k,mimeType:Z,size:S.data.length,tmpPath:Xt,originalName:$});}else b[k]=new TextDecoder().decode(S.data);}e.files=g,e.body=b,e.bodyUsed=!0,await r(),await Ms(s);}catch(n){throw await Ms(s),n}},Ms=async o=>{await Promise.allSettled(o.map(e=>y.unlink(e)));};var tn=o=>({"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","application/pdf":".pdf","text/plain":".txt","application/json":".json","text/csv":".csv","application/octet-stream":".bin","application/x-www-form-urlencoded":".urlencoded","application/xml":".xml","application/yaml":".yaml","application/yml":".yml","application/csv":".csv","application/txt":".txt","application/markdown":".markdown"})[o.toLowerCase()]||".bin";var ct=class extends R{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var Es=100*1024,qs=o=>async(e,t,r)=>{if(!rn(e)||!ae(e.method)||e.bodyUsed)return r();let s=ve(o?.sizeLimit,Es)??Es,n=e.rawHeaders.get("content-length");if(n&&Number.parseInt(n)>s){let i={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...o?.customErrorMessage};return t.status(i.status).json({error:i.message})}if(e.body||e.bodyUsed)return r();try{let i=e.toWebApi();e.body=await i.json(),e.bodyUsed=!0;}catch(i){return i instanceof SyntaxError?t.badRequest({...N(new ct("Invalid JSON syntax"))}):t.badRequest({...N(new ct("Invalid request body encoding"))})}await r();};function rn(o){let e=sn(o);return e?on(e)==="application/json":false}function sn(o){let e=o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function on(o){let e=o.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var As=1024*1024,ks=o=>{let t={limit:ve(o?.limit,As)??As,extended:o?.extended??false,charset:o?.charset??"utf8",allowEmpty:o?.allowEmpty??true,parameterLimit:o?.parameterLimit??1e3};return async(r,s,n)=>{if(!(r.rawHeaders.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();let a=r.rawHeaders.get("content-length");if(a&&parseInt(a)>t.limit){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}try{await nn(r,t),await n();}catch(c){if(c instanceof Error&&c.message.includes("limit")){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw c}}};async function nn(o,e){if(o.body||o.bodyUsed)return;let r=await o.toWebApi().arrayBuffer();if(r.byteLength>e.limit)throw new Error(`Body size ${r.byteLength} exceeds limit ${e.limit}`);let n=new TextDecoder(e.charset).decode(r),i=an(n,e);o.body=i,o.bodyUsed=true;}function an(o,e){let t={},r=new URLSearchParams(o);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?cn(t,s,n):t[s]=n);return t}function cn(o,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(o[e]=t);return}let n=o,i=e.split("[")[0];if(r.includes(i))return;for(let c=0;c<s.length-1;c++){let d=s[c].slice(1,-1);if(r.includes(d))return;if(n[i]||(n[i]={}),d===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][d]||(n[i][d]={}),n=n[i][d];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(n)||(n=[]),n.push(t);return}n[a]=t;}}var ln=o=>(o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type"))?.split(";")[0]??null,_s=o=>{let e=o.json,t=o.urlencoded,r=o.fileParser;return async(s,n,i)=>{if(!ae(s.method)||s.bodyUsed)return i();let a=ln(s);if(a==="application/json"&&e)return qs(e)(s,n,i);if(a==="multipart/form-data"&&r)return js(r)(s,n,i);if(a==="application/x-www-form-urlencoded"&&t)return ks(t)(s,n,i);if(a?.includes("text/")){let c=new TextDecoder,d=s.toWebApi();s.body=c.decode(await d.arrayBuffer()),s.bodyUsed=true;}return !s.body&&!s.bodyUsed&&(s.body=await s.toWebApi().arrayBuffer()),i()}};var dn=1024,un=6,mn=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Or=o=>{let e=o?.threshold??dn,t=Math.max(0,Math.min(9,o?.level??un)),r=o?.filter??mn;return async(s,n,i)=>{if(!(s.rawHeaders.get("accept-encoding")||"").includes("gzip"))return i();let d=n.send.bind(n),p=n.text.bind(n),l=(m,f)=>{if(!fn(m,f,e,r))return m;let u=Hs(m);if(!u||u.length<e)return m;let h=zlib.gzipSync(u,{level:t});return n.setHeader("Content-Encoding","gzip"),n.setHeader("Content-Length",h.length.toString()),h};n.send=function(m){let f=n.headers["content-type"],u=l(m,f);return d(u)},n.json=function(m,f){let u=null;if(f){let{jsonSchema:b,prefix:P}=hn(f);u=q.getOrCreateSerializer(b,P);}let h=u&&typeof m=="object"&&m!==null?u(m):typeof m=="string"?m:JSON.stringify(m),g=l(h,"application/json");return g!==h?(n.setHeader("Content-Type","application/json"),d(g)):d(h)},n.text=function(m){let f=l(m,"text/plain");return f!==m?(n.setHeader("Content-Type","text/plain"),d(f)):p(m)},await i();}},hn=o=>H.isZodSchema(o)?{jsonSchema:H.toJSONSchema(o),prefix:"fast_stringify_zod"}:I.isTypeBoxSchema(o)?{jsonSchema:o,prefix:"fast_stringify_typebox"}:typeof o=="object"&&o!==null?{jsonSchema:o,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof o},prefix:`fast_stringify_primitive_${JSON.stringify(o)}`},fn=(o,e,t,r)=>{if(!o||!e)return false;let s=Hs(o);return !s||s.length<t?false:r.some(n=>n.test(e))},Hs=o=>typeof o=="string"?Buffer.from(o,"utf-8"):Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o):typeof o=="object"?Buffer.from(JSON.stringify(o),"utf-8"):null;var Mr=o=>{let e={secret:o?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...o?.defaults},parse:o?.parse??true,sign:o?.sign??false};return async(t,r,s)=>{if(e.parse){let n=gn(t.rawHeaders.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(n)){if(e.sign&&e.secret){let c=await bn(a,e.secret);c!==false&&(t.cookies[i]=c);continue}t.cookies[i]=a;}}r.cookie=(n,i,a)=>{$s(r,n,i,{...e.defaults,...a},e);},r.clearCookie=(n,i)=>{yn(r,n,{...e.defaults,...i});},await s();}};function gn(o){let e={};if(!o)return e;let t=o.split(";");for(let r of t){let[s,n]=r.trim().split("=");s&&n&&(e[decodeURIComponent(s)]=decodeURIComponent(n));}return e}async function $s(o,e,t,r,s){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),s.sign&&s.secret&&(n=await vn(n,s.secret));let i=o.headers["set-cookie"]||"",a=i?`${i}, ${n}`:n;o.setHeader("Set-Cookie",a);}function yn(o,e,t){let r={...t,expires:new Date(0),maxAge:0};$s(o,e,"",r,{secret:"",sign:false});}async function vn(o,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(o),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",n,s),a=new Uint8Array(i),c=Array.from(a).map(d=>d.toString(16).padStart(2,"0")).join("");return `${o}.${c}`}async function bn(o,e){let t=o.split(".");if(t.length!==2)return false;let[r,s]=t,n=new TextEncoder,i=n.encode(e),a=n.encode(r),c=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=await crypto.subtle.sign("HMAC",c,a),p=new Uint8Array(d),l=Array.from(p).map(m=>m.toString(16).padStart(2,"0")).join("");return s===l?r:false}var jr=o=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...o};return async(t,r,s)=>{let n=t.rawHeaders.get("origin")||"";if(t.method==="OPTIONS")return wn(t,r,e,n,s);Sn(t,r,e,n),await s();}};function wn(o,e,t,r,s){let n=Bs(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(Ls(e,t,n),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function Sn(o,e,t,r){let s=Bs(t,r);s&&Ls(e,t,s);}function Bs(o,e){if(typeof o.origin=="string")return o.origin;if(Array.isArray(o.origin)){let t=o.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function Ls(o,e,t){if(o.setHeader("Access-Control-Allow-Origin",t),e.credentials&&o.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;o.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;o.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;o.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&o.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function Ns(o,e=""){let t=new URL(o.url),r=Object.fromEntries(o.rawHeaders.entries()),n=o.rawHeaders.get("x-forwarded-proto")||t.protocol.replace(":","");return {body:o.body,query:o.query,params:o.params,cookies:o.cookies,session:o.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:o.method,ip:o.ip,headers:r,url:t.pathname,get(a){return o.rawHeaders.get(a.toLowerCase())??void 0},header(a){return o.rawHeaders.get(a.toLowerCase())??void 0},app:{},res:null,route:null,protocol:n,secure:n==="https",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:a=>o.params[a]??o.query[a],files:o.files,file:o.file,rawBody:o.body}}function Is(o){return {locals:{},headersSent:false,statusCode:o.responseStatus,status(t){return o.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!o.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return o.html(t),this}return o.send(t),this},json(t){return this.headersSent=true,o.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return o.status(n).setHeader("Location",s),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return o.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,n]of Object.entries(t))o.setHeader(s,n);else r!==void 0&&o.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return o.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,o.send(t??""),this},write(t){return M.warn({method:"write"},"res.write() is not fully supported in Express compatibility layer - responses will be buffered"),true},get(t){return o.headers[t]},getHeader(t){return o.headers[t]},removeHeader(t){return delete o.headers[t],this},append(t,r){let s=o.headers[t],n=Array.isArray(r)?r.join(", "):r;return o.setHeader(t,s?`${s}, ${n}`:n),this},cookie(t,r,s){return o.cookie?.(t,r,s),this},clearCookie(t,r){return o.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){throw new Error("format() is not supported in Express compatibility layer")},attachment(t){return t?o.setHeader("Content-Disposition",`attachment; filename="${t}"`):o.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){o.file(t);},download(t,r,s,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),o.file(t);},links(t){let r=Object.entries(t).map(([s,n])=>`<${n}>; rel="${s}"`).join(", ");return o.setHeader("Link",r),this},location(t){return o.setHeader("Location",t),this},vary(t){return o.setHeader("Vary",t),this},app:{},req:null}}function He(o,e=""){return async(t,r,s)=>{let n=Ns(t,e),i=Is(r);n.res=i,i.req=n;let a=false,c=3e4;await Promise.race([new Promise((d,p)=>{let l=m=>{if(a=true,m){p(m);return}d();};try{let m=o(n,i,l);m instanceof Promise&&m.catch(p);}catch(m){p(m);}}),new Promise(d=>{setTimeout(()=>{!a&&!i.headersSent&&M.warn({basePath:e,timeout:c},"Express middleware did not call next() within timeout and did not send response"),d();},c);})]),i.headersSent||await s();}}function Fs(o,e=""){return async(t,r)=>{let s=Ns(t,e),n=Is(r);s.res=n,n.req=s;let i=()=>{};try{await o(s,n,i);}catch(a){throw M.error({error:a,basePath:e},"Express handler threw an error"),a}}}function lt(o,e){let t=Er(o),r=e.stack;if(!r){M.warn({basePath:o},"Express router has no stack - routes may not be registered");return}for(let s of r)Ds(s,t);}function Ds(o,e){if(o.route){let t=Er(e+o.route.path),r=Object.keys(o.route.methods).filter(s=>o.route.methods[s]);for(let s of r){let n=o.route.stack.map(i=>i.handle);xn(s.toUpperCase(),t,n,e);}return}if(o.handle&&typeof o.handle=="function"){let t=o.path||"",r=Er(e+t),s=o.handle.stack;if(s&&Array.isArray(s)){for(let c of s)Ds(c,r);return}let n=r==="/"?"/*":`${r}/*`,i=He(o.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)_.addOrUpdate(c,n,[i],async()=>{},{},{excludeFromSwagger:true});}}function xn(o,e,t,r){let s=t.slice(0,-1).map(a=>He(a,r)),n=t[t.length-1],i=Fs(n,r);_.addOrUpdate(o,e,s,i,{},{excludeFromSwagger:true});}function Er(o){let e=o.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function qr(o){return {use(e,t){if(typeof e=="string"){let n=e,i=t,a=i.stack;if(a&&Array.isArray(a)){lt(n,i);return}o.use(He(i,n));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){lt("/",r);return}o.use(He(r));}}}var Ar=o=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...o};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n);}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let i=n.maxAge!==void 0?n.maxAge:15552e3,a=n.includeSubDomains!==void 0?n.includeSubDomains:true,c=n.preload!==void 0?n.preload:false,d=`max-age=${i}`;a!==false&&(d+="; includeSubDomains"),c&&(d+="; preload"),r.setHeader("Strict-Transport-Security",d);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await s();}};var kr=o=>{let e=M.child({scope:"LogMiddleware"});return async(t,r,s)=>{try{let n=t.body;(o?.logRequest??!0)&&e.info({type:"request",requestId:t.id,method:o?.requestPayload?.method??!0?t.method:void 0,url:o?.requestPayload?.url??!0?t.url:void 0,ip:o?.requestPayload?.ip??!0?t.ip:void 0,headers:o?.requestPayload?.headers??!0?t.headers:void 0,body:o?.requestPayload?.body??!1?Qs(n):void 0});let i=performance.now();await s();let c=performance.now()-i;(o?.logResponse??!0)&&e.info({type:"response",requestId:t.id,status:o?.responsePayload?.status??r.responseStatus,duration:`${c.toFixed(2)}ms`,body:o?.responsePayload?.body??!1?Qs(r.getBody()):void 0,headers:o?.responsePayload?.headers??!1?r.headers:void 0});}catch(n){throw e.error(n),n}}};function Qs(o){if(typeof o=="string"||o&&typeof o=="object"&&o.constructor===Object)return o}var Tn=["POST"],Pn="X-HTTP-Method-Override",Rn=["GET","POST","PUT","PATCH","DELETE"],_r=o=>{let e=(o?.methods??Tn).map(r=>r.toUpperCase()),t=o?.header??Pn;return async(r,s,n)=>{let i=r.method.toUpperCase();if(!e.includes(i))return n();let a=r.rawHeaders.get(t);if(!a)return n();let c=a.toUpperCase();if(!Rn.includes(c))return n();r.method=c,await n();}};var $t=class{storage=new Map;timers=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){let r=this.timers.get(e);r&&clearTimeout(r),this.storage.set(e,t);let s=setTimeout(()=>{this.storage.delete(e),this.timers.delete(e);},this.windowMs);this.timers.set(e,s);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){let t=this.timers.get(e);t&&clearTimeout(t),this.storage.delete(e),this.timers.delete(e);}};var Hr=(o,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...o},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new $t(r.windowMs):{get:r.get,set:r.set};return async(n,i,a)=>{let c=t.type==="ip"?n.ip:t.key(n),d=await s.get(c);return d>=t.limit?i.status(t.statusCode).json({message:t.message}):(await s.set(c,d+1),a())}};var Bt=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let s=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:s});}async destroy(e){this.store.delete(e);}};var $r=o=>{let e=o?.name??"sid",t=o?.ttl??3600*24,r=o?.store??new Bt,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...o?.cookie??{}};return async(n,i,a)=>{let d=n.cookies&&n.cookies[e],p=d?await r.get(d):void 0;(!d||!p)&&(d||=ee.randomUUID(),p||={},await r.set(d,p,t),i.cookie?.(e,d,s)),n.session=p,n.saveSession=async()=>r.set(d,p,t),n.destroySession=async()=>{await r.destroy(d),i.clearCookie?.(e,s);},await a(),await r.set(d,p,t);}};var Cn={json:"application/json","form-data":"multipart/form-data",urlencoded:"application/x-www-form-urlencoded",binary:"application/octet-stream",text:"text/plain","event-stream":"text/event-stream"};function Us(o){return o?Cn[o]??o:"application/json"}var Gs=o=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};o&&typeof o!="boolean"&&(e={...e,...o});let t=On(e),r=`${e.path}`,s=`${r}/json`,n;e.type==="rapidoc"?n=jn(s,e):e.type==="scalar"?n=En(s,e):e.type==="elements"?n=qn(s,e):e.type==="custom"?n=e.customUIGenerator(s,e):n=Mn(s,e),_.addOrUpdate("GET",r,[],(i,a)=>{a.html(n);},void 0,void 0,void 0,true),_.addOrUpdate("GET",s,[],(i,a)=>{a.json(t);},void 0,void 0,void 0,true);},ye=o=>o?o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):"";function $e(o){if(!o||typeof o!="object")return {type:"string"};let e="json_schema";H.isZodSchema(o)?e="zod_schema":I.isTypeBoxSchema(o)&&(e="typebox_schema");let t=q.getJsonSchema(o,e);if(t)return t;if(H.isZodSchema(o))try{let s=H.toJSONSchema(o);return q.storeJsonSchema(s,e),s}catch(s){return M.debug({error:s instanceof Error?s.message:String(s),schemaType:o?.constructor?.name||typeof o},"Failed to convert Zod schema to JSON Schema for Swagger documentation"),{type:"object"}}let r=o;return q.storeJsonSchema(r,e),r}function On(o){let e=_.getRoutes(),t={},r;if(o.models)if(Array.isArray(o.models))r=o.models.reduce((n,i,a)=>{let c=$e(i),d=c.$id||c.title||`Model${a}`;return n[d]=c,n},{});else {r={};for(let[n,i]of Object.entries(o.models))r[n]=$e(i);}let s={...o.components,securitySchemes:o.securitySchemes||{},schemas:r?{...o.components?.schemas||{},...r}:o.components?.schemas?{...o.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let a=n.method.toLowerCase(),c={summary:i?.name||`${a.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},d=[],p=n.validationSchemas?.query;if(p){let u=p;if(u.type==="object"&&u.shape)for(let[h,g]of Object.entries(u.shape))!g||typeof g!="object"||d.push({name:h,in:"query",required:Array.isArray(u.shape[h].required)?u.shape[h].required.includes(h):false,schema:$e(g)});}i&&i.params?d=d.concat(zs(n.path,i.params)):d=d.concat(zs(n.path));let l=n.validationSchemas?.headers;if(l){let u=l;if(u.type==="object"&&u.shape)for(let[h,g]of Object.entries(u.shape))!g||typeof g!="object"||d.push({name:h,in:"header",required:Array.isArray(u.shape[h].required)?u.shape[h].required.includes(h):false,schema:$e(g)});}d.length>0&&(c.parameters=d);let m=n.validationSchemas?.body||n.validationSchemas?.all;if(m){let u=Us(i?.bodyType);c.requestBody={content:{[u]:{schema:$e(m)}},required:true};}else if(i?.bodyType){let u=Us(i.bodyType);c.requestBody={content:{[u]:{schema:{type:"object"}}},required:true};}c.responses={};let f=n.responses;if(f)for(let[u,h]of Object.entries(f))c.responses[u]={description:`Response for ${u}`,content:{"application/json":{schema:$e(h)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let u=[];Array.isArray(i.security)||(i.security=[i.security]);for(let h of i.security)if(h.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:h.bearerFormat||"JWT",description:h.description}),u.push({bearer:[]});else if(h.type==="apiKey")s.securitySchemes[h.name]||(s.securitySchemes[h.name]={type:"apiKey",name:h.name,in:h.in,description:h.description}),u.push({[h.name]:[]});else if(h.type==="oauth2"){let g=h.name||"oauth2";s.securitySchemes[g]||(s.securitySchemes[g]={type:"oauth2",flows:h.flows,description:h.description}),u.push({[g]:[]});}else if(h.type==="openIdConnect"){let g=h.name||"openIdConnect";s.securitySchemes[g]||(s.securitySchemes[g]={type:"openIdConnect",openIdConnectUrl:h.openIdConnectUrl,description:h.description}),u.push({[g]:[]});}u.length&&(c.security=u);}else o.security&&(c.security=o.security);t[n.path][a]=c;}return {openapi:"3.0.0",info:{title:o.title,description:o.description,version:o.version,...o.info},servers:o.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:s,security:o.security||[],tags:o.tags?Object.entries(o.tags).map(([n,i])=>({name:n,...i})):[]}}function Mn(o,e){return `
|
|
1097
|
+
`));let n=s.reduce((c,d)=>c+d.byteLength,0),i=new Uint8Array(n),a=0;for(let c of s)i.set(c,a),a+=c.byteLength;return i}async handleGraphQLRequest(e,t,r={}){let s=await this.ensureGraphQLHandler();if(!s){let p=new F(500);return p.json({errors:[{message:"GraphQL handler not initialized"}]}),new de(p)}let{headers:n={},query:i={}}=r,a=new URL(`http://${this.server.host}:${this.server.port}${t}`);a.search=new URLSearchParams(i).toString();let c;r.body!==void 0&&ae(e)&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?c=JSON.stringify(r.body):c=r.body);let d=new globalThis.Request(a.toString(),{method:e.toUpperCase(),body:c,headers:{"content-type":"application/json",...n}}),l=oe.fromRequest(d);l.query={...Object.fromEntries(a.searchParams.entries()),...i};try{let{HeaderMap:p}=await import('@apollo/server'),m=new p;for(let[E,$]of Object.entries(n))$!==void 0&&m.set(E,Array.isArray($)?$.join(", "):String($));let u=(m.get("content-type")??"").includes("application/json"),h="";typeof c=="string"?h=c:c instanceof Uint8Array?h=new TextDecoder().decode(c):c&&typeof c=="object"&&(h=new TextDecoder().decode(new Uint8Array(c)));let g=u&&h?JSON.parse(h):h,b={method:e.toUpperCase(),headers:m,body:g,search:a.search},T=this.server.graphql.getApolloOptions(),S=T.context&&typeof T.context=="function"?await T.context({req:l}):{req:l},v=await s.server.executeHTTPGraphQLRequest({httpGraphQLRequest:b,context:async()=>S}),w=v.status??200,k=new F(w);for(let[E,$]of v.headers)k.setHeader(E,$);if(v.body.kind==="complete"){let E=v.body.string;try{k.json(JSON.parse(E));}catch{k.text(E);}}else {let E="";for await(let $ of v.body.asyncIterator)E+=$;try{k.json(JSON.parse(E));}catch{k.text(E);}}return new de(k)}catch(p){this.logger.error({error:p},`Error processing GraphQL request ${e} ${t}:`);let m=new F(500);return m.json({errors:[{message:"Internal server error"}]}),new de(m)}}validateOptions(e){let{body:t,formData:r,urlencoded:s}=e;if(t&&(r||s))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(s||t))throw new Error("Only one of formData, urlencoded can be provided");if(s&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var Je=new async_hooks.AsyncLocalStorage,Rr=o=>async(e,t,r)=>{let s={};for(let[n,i]of Object.entries(o))s[n]=i(e);Je.run(s,()=>{e.ctx=new Proxy({},{get(n,i){return Je.getStore()?.[i]},set(n,i,a){let c=Je.getStore();return c?(c[i]=a,true):false},ownKeys(){let n=Je.getStore();return n?Object.keys(n):[]},has(n,i){let a=Je.getStore();return a?i in a:false}}),r();});};var Ht=class extends R{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};G();var Cr=class{async tmpdir(){switch(j.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},Rs=new Cr;var Cs=1024*1024,Os=10*1024*1024,js=o=>async(e,t,r)=>{let s=[];try{let n=e.rawHeaders.get("content-type")??e.rawHeaders.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||e.body||e.bodyUsed)return r();let i=e.rawHeaders.get("content-length"),a=ve(o?.maxFileSize,Os)??Os;if(i&&parseInt(i)>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let c=n.match(/boundary=(.*)(;|$)/i);if(!c)return r();let d=c[1].replace(/(^\s*"?|"?\s*$)/g,""),l=new Uint8Array(await e.toWebApi().arrayBuffer());if(l.length>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let p=new TextEncoder().encode(`--${d}`),m=new Uint8Array([13,10,13,10]),f=[],u=(S,v,w=0)=>{e:for(let k=w;k<=S.length-v.length;k++){for(let E=0;E<v.length;E++)if(S[k+E]!==v[E])continue e;return k}return -1},h=u(l,p);for(;h!==-1&&(h+=p.length,!(l[h]===45&&l[h+1]===45));){l[h]===13&&l[h+1]===10&&(h+=2);let S=u(l,m,h);if(S===-1)break;let v=l.subarray(h,S),w=new TextDecoder().decode(v),k=S+m.length,E=u(l,p,k);if(E===-1)break;let $=E-1;l[$]===10&&$--,l[$]===13&&$--;let ce=l.subarray(k,$+1);f.push({headers:w,data:ce}),h=E;}let g=[],b={},T=ve(o?.maxFileSize,Cs)??Cs;for(let S of f){let v=S.headers.split(`\r
|
|
1098
|
+
`).find(le=>le.toLowerCase().startsWith("content-disposition:"));if(!v)continue;let w=v.match(/name="([^"]+)"/);if(!w)continue;let k=w[1],E=v.match(/filename="([^"]*)"/),$=E?E[1]:"";if(!!$){if(o?.maxFiles&&g.length>=o.maxFiles)return t.badRequest({...N(new R(`Too many files: Maximum ${o.maxFiles} files allowed`))});if(T&&S.data.length>T)return t.badRequest({...N(new Ht($,S.data.length,T))});let le=S.headers.split(`\r
|
|
1099
|
+
`).find(Ws=>Ws.toLowerCase().startsWith("content-type:")),Z=le?le.split(":")[1].trim():"application/octet-stream";if(o?.allowedMimeTypes&&!o.allowedMimeTypes.includes(Z))return t.badRequest({...N(new R(`Invalid file type: "${Z}" is not allowed. Allowed types: ${o.allowedMimeTypes.join(", ")}`))});let Vt=tn(Z),Xt=x.join(await Rs.tmpdir(),`${ee.randomUUID()}${Vt}`);await y.writeFile(Xt,S.data),s.push(Xt),g.push({formName:k,mimeType:Z,size:S.data.length,tmpPath:Xt,originalName:$});}else b[k]=new TextDecoder().decode(S.data);}e.files=g,e.body=b,e.bodyUsed=!0,await r(),await Ms(s);}catch(n){throw await Ms(s),n}},Ms=async o=>{await Promise.allSettled(o.map(e=>y.unlink(e)));};var tn=o=>({"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","application/pdf":".pdf","text/plain":".txt","application/json":".json","text/csv":".csv","application/octet-stream":".bin","application/x-www-form-urlencoded":".urlencoded","application/xml":".xml","application/yaml":".yaml","application/yml":".yml","application/csv":".csv","application/txt":".txt","application/markdown":".markdown"})[o.toLowerCase()]||".bin";var ct=class extends R{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var Es=100*1024,qs=o=>async(e,t,r)=>{if(!rn(e)||!ae(e.method)||e.bodyUsed)return r();let s=ve(o?.sizeLimit,Es)??Es,n=e.rawHeaders.get("content-length");if(n&&Number.parseInt(n)>s){let i={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...o?.customErrorMessage};return t.status(i.status).json({error:i.message})}if(e.body||e.bodyUsed)return r();try{let i=e.toWebApi();e.body=await i.json(),e.bodyUsed=!0;}catch(i){return i instanceof SyntaxError?t.badRequest({...N(new ct("Invalid JSON syntax"))}):t.badRequest({...N(new ct("Invalid request body encoding"))})}await r();};function rn(o){let e=sn(o);return e?on(e)==="application/json":false}function sn(o){let e=o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function on(o){let e=o.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var As=1024*1024,ks=o=>{let t={limit:ve(o?.limit,As)??As,extended:o?.extended??false,charset:o?.charset??"utf8",allowEmpty:o?.allowEmpty??true,parameterLimit:o?.parameterLimit??1e3};return async(r,s,n)=>{if(!(r.rawHeaders.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();let a=r.rawHeaders.get("content-length");if(a&&parseInt(a)>t.limit){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}try{await nn(r,t),await n();}catch(c){if(c instanceof Error&&c.message.includes("limit")){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw c}}};async function nn(o,e){if(o.body||o.bodyUsed)return;let r=await o.toWebApi().arrayBuffer();if(r.byteLength>e.limit)throw new Error(`Body size ${r.byteLength} exceeds limit ${e.limit}`);let n=new TextDecoder(e.charset).decode(r),i=an(n,e);o.body=i,o.bodyUsed=true;}function an(o,e){let t={},r=new URLSearchParams(o);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?cn(t,s,n):t[s]=n);return t}function cn(o,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(o[e]=t);return}let n=o,i=e.split("[")[0];if(r.includes(i))return;for(let c=0;c<s.length-1;c++){let d=s[c].slice(1,-1);if(r.includes(d))return;if(n[i]||(n[i]={}),d===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][d]||(n[i][d]={}),n=n[i][d];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(n)||(n=[]),n.push(t);return}n[a]=t;}}var ln=o=>(o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type"))?.split(";")[0]??null,_s=o=>{let e=o.json,t=o.urlencoded,r=o.fileParser;return async(s,n,i)=>{if(!ae(s.method)||s.bodyUsed)return i();let a=ln(s);if(a==="application/json"&&e)return qs(e)(s,n,i);if(a==="multipart/form-data"&&r)return js(r)(s,n,i);if(a==="application/x-www-form-urlencoded"&&t)return ks(t)(s,n,i);if(a?.includes("text/")){let c=new TextDecoder,d=s.toWebApi();s.body=c.decode(await d.arrayBuffer()),s.bodyUsed=true;}return !s.body&&!s.bodyUsed&&(s.body=await s.toWebApi().arrayBuffer()),i()}};var dn=1024,un=6,mn=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Or=o=>{let e=o?.threshold??dn,t=Math.max(0,Math.min(9,o?.level??un)),r=o?.filter??mn;return async(s,n,i)=>{if(!(s.rawHeaders.get("accept-encoding")||"").includes("gzip"))return i();let d=n.send.bind(n),l=n.text.bind(n),p=(m,f)=>{if(!fn(m,f,e,r))return m;let u=Hs(m);if(!u||u.length<e)return m;let h=zlib.gzipSync(u,{level:t});return n.setHeader("Content-Encoding","gzip"),n.setHeader("Content-Length",h.length.toString()),h};n.send=function(m){let f=n.headers["content-type"],u=p(m,f);return d(u)},n.json=function(m,f){let u=null;if(f){let{jsonSchema:b,prefix:T}=hn(f);u=q.getOrCreateSerializer(b,T);}let h=u&&typeof m=="object"&&m!==null?u(m):typeof m=="string"?m:JSON.stringify(m),g=p(h,"application/json");return g!==h?(n.setHeader("Content-Type","application/json"),d(g)):d(h)},n.text=function(m){let f=p(m,"text/plain");return f!==m?(n.setHeader("Content-Type","text/plain"),d(f)):l(m)},await i();}},hn=o=>H.isZodSchema(o)?{jsonSchema:H.toJSONSchema(o),prefix:"fast_stringify_zod"}:I.isTypeBoxSchema(o)?{jsonSchema:o,prefix:"fast_stringify_typebox"}:typeof o=="object"&&o!==null?{jsonSchema:o,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof o},prefix:`fast_stringify_primitive_${JSON.stringify(o)}`},fn=(o,e,t,r)=>{if(!o||!e)return false;let s=Hs(o);return !s||s.length<t?false:r.some(n=>n.test(e))},Hs=o=>typeof o=="string"?Buffer.from(o,"utf-8"):Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o):typeof o=="object"?Buffer.from(JSON.stringify(o),"utf-8"):null;var Mr=o=>{let e={secret:o?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...o?.defaults},parse:o?.parse??true,sign:o?.sign??false};return async(t,r,s)=>{if(e.parse){let n=gn(t.rawHeaders.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(n)){if(e.sign&&e.secret){let c=await bn(a,e.secret);c!==false&&(t.cookies[i]=c);continue}t.cookies[i]=a;}}r.cookie=(n,i,a)=>{$s(r,n,i,{...e.defaults,...a},e);},r.clearCookie=(n,i)=>{yn(r,n,{...e.defaults,...i});},await s();}};function gn(o){let e={};if(!o)return e;let t=o.split(";");for(let r of t){let[s,n]=r.trim().split("=");s&&n&&(e[decodeURIComponent(s)]=decodeURIComponent(n));}return e}async function $s(o,e,t,r,s){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),s.sign&&s.secret&&(n=await vn(n,s.secret));let i=o.headers["set-cookie"]||"",a=i?`${i}, ${n}`:n;o.setHeader("Set-Cookie",a);}function yn(o,e,t){let r={...t,expires:new Date(0),maxAge:0};$s(o,e,"",r,{secret:"",sign:false});}async function vn(o,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(o),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",n,s),a=new Uint8Array(i),c=Array.from(a).map(d=>d.toString(16).padStart(2,"0")).join("");return `${o}.${c}`}async function bn(o,e){let t=o.split(".");if(t.length!==2)return false;let[r,s]=t,n=new TextEncoder,i=n.encode(e),a=n.encode(r),c=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=await crypto.subtle.sign("HMAC",c,a),l=new Uint8Array(d),p=Array.from(l).map(m=>m.toString(16).padStart(2,"0")).join("");return s===p?r:false}var jr=o=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...o};return async(t,r,s)=>{let n=t.rawHeaders.get("origin")||"";if(t.method==="OPTIONS")return wn(t,r,e,n,s);Sn(t,r,e,n),await s();}};function wn(o,e,t,r,s){let n=Bs(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(Ls(e,t,n),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function Sn(o,e,t,r){let s=Bs(t,r);s&&Ls(e,t,s);}function Bs(o,e){if(typeof o.origin=="string")return o.origin;if(Array.isArray(o.origin)){let t=o.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function Ls(o,e,t){if(o.setHeader("Access-Control-Allow-Origin",t),e.credentials&&o.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;o.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;o.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;o.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&o.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function Ns(o,e=""){let t=new URL(o.url),r=Object.fromEntries(o.rawHeaders.entries()),n=o.rawHeaders.get("x-forwarded-proto")||t.protocol.replace(":","");return {body:o.body,query:o.query,params:o.params,cookies:o.cookies,session:o.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:o.method,ip:o.ip,headers:r,url:t.pathname,get(a){return o.rawHeaders.get(a.toLowerCase())??void 0},header(a){return o.rawHeaders.get(a.toLowerCase())??void 0},app:{},res:null,route:null,protocol:n,secure:n==="https",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:a=>o.params[a]??o.query[a],files:o.files,file:o.file,rawBody:o.body}}function Is(o){return {locals:{},headersSent:false,statusCode:o.responseStatus,status(t){return o.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!o.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return o.html(t),this}return o.send(t),this},json(t){return this.headersSent=true,o.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return o.status(n).setHeader("Location",s),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return o.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,n]of Object.entries(t))o.setHeader(s,n);else r!==void 0&&o.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return o.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,o.send(t??""),this},write(t){return M.warn({method:"write"},"res.write() is not fully supported in Express compatibility layer - responses will be buffered"),true},get(t){return o.headers[t]},getHeader(t){return o.headers[t]},removeHeader(t){return delete o.headers[t],this},append(t,r){let s=o.headers[t],n=Array.isArray(r)?r.join(", "):r;return o.setHeader(t,s?`${s}, ${n}`:n),this},cookie(t,r,s){return o.cookie?.(t,r,s),this},clearCookie(t,r){return o.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){throw new Error("format() is not supported in Express compatibility layer")},attachment(t){return t?o.setHeader("Content-Disposition",`attachment; filename="${t}"`):o.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){o.file(t);},download(t,r,s,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),o.file(t);},links(t){let r=Object.entries(t).map(([s,n])=>`<${n}>; rel="${s}"`).join(", ");return o.setHeader("Link",r),this},location(t){return o.setHeader("Location",t),this},vary(t){return o.setHeader("Vary",t),this},app:{},req:null}}function He(o,e=""){return async(t,r,s)=>{let n=Ns(t,e),i=Is(r);n.res=i,i.req=n;let a=false,c=3e4;await Promise.race([new Promise((d,l)=>{let p=m=>{if(a=true,m){l(m);return}d();};try{let m=o(n,i,p);m instanceof Promise&&m.catch(l);}catch(m){l(m);}}),new Promise(d=>{setTimeout(()=>{!a&&!i.headersSent&&M.warn({basePath:e,timeout:c},"Express middleware did not call next() within timeout and did not send response"),d();},c);})]),i.headersSent||await s();}}function Fs(o,e=""){return async(t,r)=>{let s=Ns(t,e),n=Is(r);s.res=n,n.req=s;let i=()=>{};try{await o(s,n,i);}catch(a){throw M.error({error:a,basePath:e},"Express handler threw an error"),a}}}function lt(o,e){let t=Er(o),r=e.stack;if(!r){M.warn({basePath:o},"Express router has no stack - routes may not be registered");return}for(let s of r)Ds(s,t);}function Ds(o,e){if(o.route){let t=Er(e+o.route.path),r=Object.keys(o.route.methods).filter(s=>o.route.methods[s]);for(let s of r){let n=o.route.stack.map(i=>i.handle);xn(s.toUpperCase(),t,n,e);}return}if(o.handle&&typeof o.handle=="function"){let t=o.path||"",r=Er(e+t),s=o.handle.stack;if(s&&Array.isArray(s)){for(let c of s)Ds(c,r);return}let n=r==="/"?"/*":`${r}/*`,i=He(o.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)_.addOrUpdate(c,n,[i],async()=>{},{},{excludeFromSwagger:true});}}function xn(o,e,t,r){let s=t.slice(0,-1).map(a=>He(a,r)),n=t[t.length-1],i=Fs(n,r);_.addOrUpdate(o,e,s,i,{},{excludeFromSwagger:true});}function Er(o){let e=o.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function qr(o){return {use(e,t){if(typeof e=="string"){let n=e,i=t,a=i.stack;if(a&&Array.isArray(a)){lt(n,i);return}o.use(He(i,n));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){lt("/",r);return}o.use(He(r));}}}var Ar=o=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...o};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n);}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let i=n.maxAge!==void 0?n.maxAge:15552e3,a=n.includeSubDomains!==void 0?n.includeSubDomains:true,c=n.preload!==void 0?n.preload:false,d=`max-age=${i}`;a!==false&&(d+="; includeSubDomains"),c&&(d+="; preload"),r.setHeader("Strict-Transport-Security",d);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await s();}};var kr=o=>{let e=M.child({scope:"LogMiddleware"});return async(t,r,s)=>{try{let n=t.body;(o?.logRequest??!0)&&e.info({type:"request",requestId:t.id,method:o?.requestPayload?.method??!0?t.method:void 0,url:o?.requestPayload?.url??!0?t.url:void 0,ip:o?.requestPayload?.ip??!0?t.ip:void 0,headers:o?.requestPayload?.headers??!0?t.headers:void 0,body:o?.requestPayload?.body??!1?Qs(n):void 0});let i=performance.now();await s();let c=performance.now()-i;(o?.logResponse??!0)&&e.info({type:"response",requestId:t.id,status:o?.responsePayload?.status??r.responseStatus,duration:`${c.toFixed(2)}ms`,body:o?.responsePayload?.body??!1?Qs(r.getBody()):void 0,headers:o?.responsePayload?.headers??!1?r.headers:void 0});}catch(n){throw e.error(n),n}}};function Qs(o){if(typeof o=="string"||o&&typeof o=="object"&&o.constructor===Object)return o}var Tn=["POST"],Pn="X-HTTP-Method-Override",Rn=["GET","POST","PUT","PATCH","DELETE"],_r=o=>{let e=(o?.methods??Tn).map(r=>r.toUpperCase()),t=o?.header??Pn;return async(r,s,n)=>{let i=r.method.toUpperCase();if(!e.includes(i))return n();let a=r.rawHeaders.get(t);if(!a)return n();let c=a.toUpperCase();if(!Rn.includes(c))return n();r.method=c,await n();}};var $t=class{storage=new Map;timers=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){let r=this.timers.get(e);r&&clearTimeout(r),this.storage.set(e,t);let s=setTimeout(()=>{this.storage.delete(e),this.timers.delete(e);},this.windowMs);this.timers.set(e,s);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){let t=this.timers.get(e);t&&clearTimeout(t),this.storage.delete(e),this.timers.delete(e);}};var Hr=(o,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...o},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new $t(r.windowMs):{get:r.get,set:r.set};return async(n,i,a)=>{let c=t.type==="ip"?n.ip:t.key(n),d=await s.get(c);return d>=t.limit?i.status(t.statusCode).json({message:t.message}):(await s.set(c,d+1),a())}};var Bt=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let s=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:s});}async destroy(e){this.store.delete(e);}};var $r=o=>{let e=o?.name??"sid",t=o?.ttl??3600*24,r=o?.store??new Bt,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...o?.cookie??{}};return async(n,i,a)=>{let d=n.cookies&&n.cookies[e],l=d?await r.get(d):void 0;(!d||!l)&&(d||=ee.randomUUID(),l||={},await r.set(d,l,t),i.cookie?.(e,d,s)),n.session=l,n.saveSession=async()=>r.set(d,l,t),n.destroySession=async()=>{await r.destroy(d),i.clearCookie?.(e,s);},await a(),await r.set(d,l,t);}};var Cn={json:"application/json","form-data":"multipart/form-data",urlencoded:"application/x-www-form-urlencoded",binary:"application/octet-stream",text:"text/plain","event-stream":"text/event-stream"};function Us(o){return o?Cn[o]??o:"application/json"}var Gs=o=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};o&&typeof o!="boolean"&&(e={...e,...o});let t=On(e),r=`${e.path}`,s=`${r}/json`,n;e.type==="rapidoc"?n=jn(s,e):e.type==="scalar"?n=En(s,e):e.type==="elements"?n=qn(s,e):e.type==="custom"?n=e.customUIGenerator(s,e):n=Mn(s,e),_.addOrUpdate("GET",r,[],(i,a)=>{a.html(n);},void 0,void 0,void 0,true),_.addOrUpdate("GET",s,[],(i,a)=>{a.json(t);},void 0,void 0,void 0,true);},ye=o=>o?o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):"";function $e(o){if(!o||typeof o!="object")return {type:"string"};let e="json_schema";H.isZodSchema(o)?e="zod_schema":I.isTypeBoxSchema(o)&&(e="typebox_schema");let t=q.getJsonSchema(o,e);if(t)return t;if(H.isZodSchema(o))try{let s=H.toJSONSchema(o);return q.storeJsonSchema(s,e),s}catch(s){return M.debug({error:s instanceof Error?s.message:String(s),schemaType:o?.constructor?.name||typeof o},"Failed to convert Zod schema to JSON Schema for Swagger documentation"),{type:"object"}}let r=o;return q.storeJsonSchema(r,e),r}function On(o){let e=_.getRoutes(),t={},r;if(o.models)if(Array.isArray(o.models))r=o.models.reduce((n,i,a)=>{let c=$e(i),d=c.$id||c.title||`Model${a}`;return n[d]=c,n},{});else {r={};for(let[n,i]of Object.entries(o.models))r[n]=$e(i);}let s={...o.components,securitySchemes:o.securitySchemes||{},schemas:r?{...o.components?.schemas||{},...r}:o.components?.schemas?{...o.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let a=n.method.toLowerCase(),c={summary:i?.name||`${a.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},d=[],l=n.validationSchemas?.query;if(l){let u=l;if(u.type==="object"&&u.shape)for(let[h,g]of Object.entries(u.shape))!g||typeof g!="object"||d.push({name:h,in:"query",required:Array.isArray(u.shape[h].required)?u.shape[h].required.includes(h):false,schema:$e(g)});}i&&i.params?d=d.concat(zs(n.path,i.params)):d=d.concat(zs(n.path));let p=n.validationSchemas?.headers;if(p){let u=p;if(u.type==="object"&&u.shape)for(let[h,g]of Object.entries(u.shape))!g||typeof g!="object"||d.push({name:h,in:"header",required:Array.isArray(u.shape[h].required)?u.shape[h].required.includes(h):false,schema:$e(g)});}d.length>0&&(c.parameters=d);let m=n.validationSchemas?.body||n.validationSchemas?.all;if(m){let u=Us(i?.bodyType);c.requestBody={content:{[u]:{schema:$e(m)}},required:true};}else if(i?.bodyType){let u=Us(i.bodyType);c.requestBody={content:{[u]:{schema:{type:"object"}}},required:true};}c.responses={};let f=n.responses;if(f)for(let[u,h]of Object.entries(f))c.responses[u]={description:`Response for ${u}`,content:{"application/json":{schema:$e(h)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let u=[];Array.isArray(i.security)||(i.security=[i.security]);for(let h of i.security)if(h.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:h.bearerFormat||"JWT",description:h.description}),u.push({bearer:[]});else if(h.type==="apiKey")s.securitySchemes[h.name]||(s.securitySchemes[h.name]={type:"apiKey",name:h.name,in:h.in,description:h.description}),u.push({[h.name]:[]});else if(h.type==="oauth2"){let g=h.name||"oauth2";s.securitySchemes[g]||(s.securitySchemes[g]={type:"oauth2",flows:h.flows,description:h.description}),u.push({[g]:[]});}else if(h.type==="openIdConnect"){let g=h.name||"openIdConnect";s.securitySchemes[g]||(s.securitySchemes[g]={type:"openIdConnect",openIdConnectUrl:h.openIdConnectUrl,description:h.description}),u.push({[g]:[]});}u.length&&(c.security=u);}else o.security&&(c.security=o.security);t[n.path][a]=c;}return {openapi:"3.0.0",info:{title:o.title,description:o.description,version:o.version,...o.info},servers:o.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:s,security:o.security||[],tags:o.tags?Object.entries(o.tags).map(([n,i])=>({name:n,...i})):[]}}function Mn(o,e){return `
|
|
1100
1100
|
<!DOCTYPE html>
|
|
1101
1101
|
<html lang="en">
|
|
1102
1102
|
<head>
|
|
@@ -1226,6 +1226,6 @@ ${l}\r
|
|
|
1226
1226
|
<script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
|
|
1227
1227
|
</body>
|
|
1228
1228
|
</html>
|
|
1229
|
-
`}function zs(o,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(o))!==null;){let n=s[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=$e(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var Br=o=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},o.ms);try{await r();}finally{clearTimeout(s);}};var Lr=o=>{let e=o?.header??"x-forwarded-for",t=o?.trust??true,r=o?.hop??"first";return async(s,n,i)=>{if(!t)return i();let a=s.rawHeaders.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(d=>d.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return i()}};var Lt=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=ge(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},n=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,c)=>{let d=a.url,p=d.indexOf("://")+3,l=d.indexOf("/",p),m=l===-1?"/":d.slice(l),f=m.indexOf("?"),u=f===-1?m:m.slice(0,f),h=f===-1?"":m.slice(f+1),g=_.find(a.method,u),b=oe.fromRequest(a);if(b.params=g?.params??{},b.setQueryString(h),b.setBunIpExtractor(a,c),await t?.call(this,b,c),n&&u.startsWith(i)){let v=await this.ensureGraphQLHandler();if(v){let w=b.toWebApi();return At(v.server,w,a.method,h,{req:b,server:c})}}if(r&&b.rawHeaders.get("upgrade")==="websocket"){let v=b.toWebApi();if(c.upgrade(v,{data:{}}))return}let P=new F;return g?.responseSchemas&&P.setRouteResponseSchemas(g.responseSchemas),await fe(g?.middleware??[],g?.handler??((v,w)=>{w.notFound({...N(new z(v.url,v.method))});}),b,P),F.toWebResponse(P)},...r?{websocket:r}:{},...s}),this.url=this.runtimeServer.url.toString();}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Nt=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=ge(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,n="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let c=i.url,d=c.indexOf("://")+3,p=c.indexOf("/",d),l=p===-1?"/":c.slice(p),m=l.indexOf("?"),f=m===-1?l:l.slice(0,m),u=m===-1?"":l.slice(m+1),h=_.find(i.method,f),g=oe.fromRequest(i);if(g.params=h?.params??{},g.setQueryString(u),g.setDenoIpExtractor(i,a),await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&f.startsWith(n)){let v=await this.ensureGraphQLHandler();if(v){let w=g.toWebApi();return At(v.server,w,i.method,u,{req:g,info:a})}}if(g.rawHeaders.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let v=g.toWebApi(),{socket:w,response:k}=Deno.upgradeWebSocket(v);return this.tapOptions?.deno?.websocket?.open&&(w.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(w)),this.tapOptions?.deno?.websocket?.message&&(w.onmessage=E=>{this.tapOptions?.deno?.websocket?.message?.(w,E.data);}),this.tapOptions?.deno?.websocket?.close&&(w.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(w)),k}let P=new F;return h?.responseSchemas&&P.setRouteResponseSchemas(h.responseSchemas),await fe(h?.middleware??[],h?.handler??((v,w)=>{w.notFound({...N(new z(v.url,v.method))});}),g,P),F.toWebResponse(P)},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Ln=async(o,e)=>{let t=stream.Readable.fromWeb(o);return promises.pipeline(t,e)},It=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=ge(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure";let r=this.graphql.isEnabled,s="/graphql";this.runtimeServer=this.createServer(async(n,i)=>{if(this.tapOptions&&this.tapOptions.node){let h=this.tapOptions.node;await h?.(n);}let a=n.url,c=a.indexOf("?"),d=c===-1?a:a.slice(0,c),p=c===-1?"":a.slice(c+1);if(r&&d.startsWith(s)){let h=await this.ensureGraphQLHandler();if(h){let g=ae(n.method)?await this.readRequestBody(n):"";await Ts(h.server,n.headers,n.method??"POST",g,p,{req:n},async(b,P,S)=>{for(let[v,w]of b)i.setHeader(v,w);if(i.statusCode=P,typeof S=="string")i.end(S);else {for await(let v of S)i.write(v);i.end();}});return}}let l=_.find(n.method,d),m=new oe;m.url=`${this.url}${a}`,m.method=n.method,ae(n.method)&&m.setNodeRequest(n),m.setRawHeaders(n.headers,this.needsHeaderFiltering),m.setIpExtractor(n),m.setQueryString(p),m.params=l?.params??{};let f=new F;f.nodeResponse=i,l?.responseSchemas&&f.setRouteResponseSchemas(l.responseSchemas);let u=fe(l?.middleware??[],l?.handler??((h,g)=>{g.notFound({...N(new z(h.url,h.method))});}),m,f);u instanceof F?this.writeResponse(u,i):u.then(h=>this.writeResponse(h,i));});}listen(){this.runtimeServer.listen(this.port,this.host);}writeResponse(e,t){if(t.headersSent||t.writableEnded)return;let r=e.getBody();if(r instanceof ReadableStream){t.writeHead(e.responseStatus,e.headers),Ln(r,t);return}t.writeHead(e.responseStatus,e.headers),r instanceof Buffer||r instanceof Uint8Array||typeof r=="string"?t.end(r):e.headers["Content-Type"]==="application/json"?t.end(typeof r=="string"?r:JSON.stringify(r)):t.end(r!=null?String(r):void 0);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let n=e[s];n!==void 0&&(t[s]=Array.isArray(n)?n.join(", "):n);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var Ft=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}set port(e){this.server.port=e;}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Lt(e);if(e?.runtime==="node")return new It(e);if(e?.runtime==="deno")return new Nt(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};G();var Dt=class{_brand="BaldaServer";#t=new ze;serverOptions;router=_;logger;isListening;isProduction;graphql;#r;#e;#a=[];#o=["node_modules"];#n;#l;#p=[];#u=[];constructor(e){this.#r=false,this.logger=(e?.logger??M).child({scope:"Balda"}),this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.#t.get("PORT"))??80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal},e?.ajvInstance&&q.setGlobalInstance(e.ajvInstance),this.#l=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new se(this.serverOptions.graphql),this.#e=new Ft({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:j.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#l,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}get host(){return this.#e.host}get routes(){return _.getRoutes()||[]}get fs(){return y}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}getNodeServer(){if(j.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(j.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(j.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){De.exit(e);}on(e,t){switch(j.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${j.type}, only node, bun and deno are supported`)}}once(e,t){switch(j.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${j.type}, only node, bun and deno are supported`)}}use(...e){this.#a.push(...e);}useExpress(e,t){qr(this).use(e,t);}expressMiddleware(e){return He(e)}mountExpressRouter(e,t){lt(e,t);}setErrorHandler(e){this.#a.unshift(async(t,r,s)=>{try{await s();}catch(n){await e?.(t,r,s,n);}});}setNotFoundHandler(e){this.#n=e?.bind(this);}setValidationErrorHandler(e){rs(e);}setPolicyErrorHandler(e){ds(e);}beforeStart(e){this.#p.push(e);}beforeClose(e){this.#u.push(e);}listen(e,t){if(typeof e=="number"&&(this.#e.port=e),this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let r={port:this.port,host:this.host,url:this.url};this.bootstrap().then(async()=>{for(let s of this.#p)await s();this.#e.listen(),this.isListening=true,e&&typeof e=="function"&&e(r),t?.({...r,error:void 0});}).catch(s=>{t?.({...r,error:s});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e({port:this.port,host:this.host,url:this.url});});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{for(let e of this.#u)await e();await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}async getMockServer(e){return await this.bootstrap(e),new _t(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>y.glob(s,{cwd:L.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#o.some(n=>s.includes(n))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(n=>{this.logger.error(`Error importing controller ${s}: ${n}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(_s(r));break;case "cors":this.use(jr(r));break;case "static":this.use(Tr(r));break;case "helmet":this.use(Ar(r));break;case "cookie":this.use(Mr(r));break;case "methodOverride":this.use(_r(r));break;case "compression":this.use(Or(r));break;case "log":this.use(kr(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:n}=r;this.use(Hr(s,n));break;case "trustProxy":this.use(Lr(r));break;case "timeout":this.use(Br(r));break;case "session":this.use($r(r));break;case "asyncLocalStorage":this.use(Rr(r));break;case "cache":{let i=r,a;i.provider&&typeof i.provider=="object"&&"get"in i.provider?a=i.provider:i.provider==="redis"?a=new at(i.redis):a=new it,this.use(Sr(a,i));break}default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#r||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.swagger&&Gs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#a.length&&_.applyGlobalMiddlewaresToAllRoutes(this.#a),this.#r=true);}handleNotFound=(e,t)=>{if(this.#n){this.#n(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],n=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=_.find(a,r);c&&c.handler!==this.handleNotFound&&n.push(a);}if(n.length){t.setHeader("Allow",n.join(", "));let a=new Ge(r,e.method);t.methodNotAllowed({...N(a)});return}let i=new z(r,e.method);t.notFound({...N(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)_.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true},void 0,true);}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var Nr=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),n=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},n,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(i));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,a]=n,c=this.decodeBase64(i),d=this.decodeBase64(a),p=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),l=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},p,this.KEY_LENGTH),m=new Uint8Array(l);if(m.length!==d.length)return !1;let f=0;for(let u=0;u<m.length;u++)f|=m[u]^d[u];return f===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return s}},Nn=new Nr;var Js=()=>{let o=q.getCacheStats(),e=o.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:o.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:o.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},In=()=>{let o=Js();M.info({validators:o.validators.size,totalSchemaRefs:o.totalSchemaReferences,memoryEstimate:o.memoryEstimate.total},"Schema cache metrics");},Fn=()=>{q.clearAllCaches(),M.debug("All schema caches cleared");};var V=class extends R{constructor(e){super(`File not found: ${e}`);}};var Ir=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new V(e);let n=t;if(n==="stream")return stream.Readable.toWeb(s.readableStreamBody);let i=[];for await(let c of s.readableStreamBody)i.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(i);switch(n){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new R("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new V(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),n=t;await s.upload(n,n.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new R("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new R("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Fr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new R("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await y.exists(r))return [];let n=[];return await this.listFilesRecursively(r,t,n),n}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await y.exists(r))throw new V(e);switch(t){case "raw":return await y.readFile(r);case "text":return await y.readFile(r,{encoding:"utf8"});case "stream":return await y.streamFile(r);default:throw new R("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),n=x.join(s,"..");await y.mkdir(n,{recursive:true}),await y.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await y.exists(t)&&await y.unlink(t);}async listFilesRecursively(e,t,r){let s=await y.stat(e);if(s.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!s.isDirectory)return;let n=await this.readDirectory(e);for(let i of n){let a=x.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(G(),Kr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new R("Unsupported runtime")}}async ensureDirectoryExists(){if(await y.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await y.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};G();var Dr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=j.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:n}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:n,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new R("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new V(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new R("Invalid return type")}}catch(s){throw s instanceof V?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new V(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new V(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new R("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new V(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Qr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var Qt=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await y.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new R("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var Ut=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new R("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var zt=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await y.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new R("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var Gt=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new R("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var Jt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,n)=>{let i=t[s];return i===void 0?r:n&&this.helpers.has(n)?this.helpers.get(n)(i):String(i)})}async renderFromFile(e,t){let r=await y.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var pt=class extends R{constructor(e){super(e),this.name="MailerError";}},dt=class extends pt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},Wt=class extends pt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},Kt=class extends pt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var ut=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,n=s.build();return s.hasTemplate()?this.sendWithTemplate(n):this.sendDirect(n)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new Wt;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var Ur=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new Kt(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new ut(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new dt(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,n=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:n,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=vr("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let n=s;n.isFilePath?r.templateFile(n.template,n.data):r.template(n.template,n.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new dt(String(this.defaultProvider));return e}};var zr=class{};var Gr=o=>(e,t)=>(r,s,n)=>{let i={scope:e,handler:t,manager:o};if(typeof s>"u"){let c=O.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),O.set(r.prototype,"__class__",c),r}let a=O.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),O.set(r,s,a),n};var Jr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Gr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new R(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var jg=_,Eg=Dt;
|
|
1229
|
+
`}function zs(o,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(o))!==null;){let n=s[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=$e(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var Br=o=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},o.ms);try{await r();}finally{clearTimeout(s);}};var Lr=o=>{let e=o?.header??"x-forwarded-for",t=o?.trust??true,r=o?.hop??"first";return async(s,n,i)=>{if(!t)return i();let a=s.rawHeaders.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(d=>d.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return i()}};var Lt=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},n=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,c)=>{let d=a.url,l=d.indexOf("://")+3,p=d.indexOf("/",l),m=p===-1?"/":d.slice(p),f=m.indexOf("?"),u=f===-1?m:m.slice(0,f),h=f===-1?"":m.slice(f+1),g=_.find(a.method,u),b=oe.fromRequest(a);if(b.params=g?.params??{},b.setQueryString(h),b.setBunIpExtractor(a,c),await t?.call(this,b,c),n&&u.startsWith(i)){let v=await this.ensureGraphQLHandler();if(v){let w=b.toWebApi();return At(v.server,w,a.method,h,{req:b,server:c})}}if(r&&b.rawHeaders.get("upgrade")==="websocket"){let v=b.toWebApi();if(c.upgrade(v,{data:{}}))return}let T=new F;return g?.responseSchemas&&T.setRouteResponseSchemas(g.responseSchemas),await fe(g?.middleware??[],g?.handler??((v,w)=>{w.notFound({...N(new z(v.url,v.method))});}),b,T),F.toWebResponse(T)},...r?{websocket:r}:{},...s});}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Nt=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,n="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let c=i.url,d=c.indexOf("://")+3,l=c.indexOf("/",d),p=l===-1?"/":c.slice(l),m=p.indexOf("?"),f=m===-1?p:p.slice(0,m),u=m===-1?"":p.slice(m+1),h=_.find(i.method,f),g=oe.fromRequest(i);if(g.params=h?.params??{},g.setQueryString(u),g.setDenoIpExtractor(i,a),await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&f.startsWith(n)){let v=await this.ensureGraphQLHandler();if(v){let w=g.toWebApi();return At(v.server,w,i.method,u,{req:g,info:a})}}if(g.rawHeaders.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let v=g.toWebApi(),{socket:w,response:k}=Deno.upgradeWebSocket(v);return this.tapOptions?.deno?.websocket?.open&&(w.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(w)),this.tapOptions?.deno?.websocket?.message&&(w.onmessage=E=>{this.tapOptions?.deno?.websocket?.message?.(w,E.data);}),this.tapOptions?.deno?.websocket?.close&&(w.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(w)),k}let T=new F;return h?.responseSchemas&&T.setRouteResponseSchemas(h.responseSchemas),await fe(h?.middleware??[],h?.handler??((v,w)=>{w.notFound({...N(new z(v.url,v.method))});}),g,T),F.toWebResponse(T)},...r});}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Ln=async(o,e)=>{let t=stream.Readable.fromWeb(o);return promises.pipeline(t,e)},It=class{port;host;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=ge(this.graphql),this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure",this.createServerWithHandler();}get url(){return `${this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http"}://${this.host}:${this.port}`}createServerWithHandler(){let e=this.graphql.isEnabled,t="/graphql";this.runtimeServer=this.createServer(async(r,s)=>{if(this.tapOptions&&this.tapOptions.node){let f=this.tapOptions.node;await f?.(r);}let n=r.url,i=n.indexOf("?"),a=i===-1?n:n.slice(0,i),c=i===-1?"":n.slice(i+1);if(e&&a.startsWith(t)){let f=await this.ensureGraphQLHandler();if(f){let u=ae(r.method)?await this.readRequestBody(r):"";await Ts(f.server,r.headers,r.method??"POST",u,c,{req:r},async(h,g,b)=>{for(let[T,S]of h)s.setHeader(T,S);if(s.statusCode=g,typeof b=="string")s.end(b);else {for await(let T of b)s.write(T);s.end();}});return}}let d=_.find(r.method,a),l=new oe;l.url=`${this.url}${n}`,l.method=r.method,ae(r.method)&&l.setNodeRequest(r),l.setRawHeaders(r.headers,this.needsHeaderFiltering),l.setIpExtractor(r),l.setQueryString(c),l.params=d?.params??{};let p=new F;p.nodeResponse=s,d?.responseSchemas&&p.setRouteResponseSchemas(d.responseSchemas);let m=fe(d?.middleware??[],d?.handler??((f,u)=>{u.notFound({...N(new z(f.url,f.method))});}),l,p);m instanceof F?this.writeResponse(m,s):m.then(f=>this.writeResponse(f,s));});}listen(){this.runtimeServer.listen(this.port,this.host);}writeResponse(e,t){if(t.headersSent||t.writableEnded)return;let r=e.getBody();if(r instanceof ReadableStream){t.writeHead(e.responseStatus,e.headers),Ln(r,t);return}t.writeHead(e.responseStatus,e.headers),r instanceof Buffer||r instanceof Uint8Array||typeof r=="string"?t.end(r):e.headers["Content-Type"]==="application/json"?t.end(typeof r=="string"?r:JSON.stringify(r)):t.end(r!=null?String(r):void 0);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let n=e[s];n!==void 0&&(t[s]=Array.isArray(n)?n.join(", "):n);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var Ft=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}set port(e){this.server.port=e;}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Lt(e);if(e?.runtime==="node")return new It(e);if(e?.runtime==="deno")return new Nt(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};G();var Dt=class{_brand="BaldaServer";#t=new ze;serverOptions;router=_;logger;isListening;isProduction;graphql;#r;#e;#a=[];#o=["node_modules"];#n;#l;#p=[];#u=[];constructor(e){this.#r=false,this.logger=(e?.logger??M).child({scope:"Balda"}),this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:(e?.port??Number(this.#t.get("PORT")||"80"))||80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal},e?.ajvInstance&&q.setGlobalInstance(e.ajvInstance),this.#l=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new se(this.serverOptions.graphql),this.#e=new Ft({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:j.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#l,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}set port(e){if(this.isListening)throw new Error("Cannot change port while server is listening, please call `.close()` before changing the port");this.#e.port=e;}get host(){return this.#e.host}get routes(){return _.getRoutes()||[]}get fs(){return y}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}getNodeServer(){if(j.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(j.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(j.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){De.exit(e);}on(e,t){switch(j.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${j.type}, only node, bun and deno are supported`)}}once(e,t){switch(j.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${j.type}, only node, bun and deno are supported`)}}use(...e){this.#a.push(...e);}useExpress(e,t){qr(this).use(e,t);}expressMiddleware(e){return He(e)}mountExpressRouter(e,t){lt(e,t);}setErrorHandler(e){this.#a.unshift(async(t,r,s)=>{try{await s();}catch(n){await e?.(t,r,s,n);}});}setNotFoundHandler(e){this.#n=e?.bind(this);}setValidationErrorHandler(e){rs(e);}setPolicyErrorHandler(e){ds(e);}beforeStart(e){this.#p.push(e);}beforeClose(e){this.#u.push(e);}listen(e,t){let r=typeof e=="function"?e:t;if(typeof e=="number"&&Number.isFinite(e)&&(this.port=e),this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let s={port:this.port,host:this.host,url:this.url};this.bootstrap().then(async()=>{for(let n of this.#p)await n();this.#e.listen(),this.isListening=true,r?.({...s,error:void 0});}).catch(n=>{r?.({...s,error:n});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e({port:this.port,host:this.host,url:this.url});});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{for(let e of this.#u)await e();await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}async getMockServer(e){return await this.bootstrap(e),new _t(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>y.glob(s,{cwd:L.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#o.some(n=>s.includes(n))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(n=>{this.logger.error(`Error importing controller ${s}: ${n}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(_s(r));break;case "cors":this.use(jr(r));break;case "static":this.use(Tr(r));break;case "helmet":this.use(Ar(r));break;case "cookie":this.use(Mr(r));break;case "methodOverride":this.use(_r(r));break;case "compression":this.use(Or(r));break;case "log":this.use(kr(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:n}=r;this.use(Hr(s,n));break;case "trustProxy":this.use(Lr(r));break;case "timeout":this.use(Br(r));break;case "session":this.use($r(r));break;case "asyncLocalStorage":this.use(Rr(r));break;case "cache":{let i=r,a;i.provider&&typeof i.provider=="object"&&"get"in i.provider?a=i.provider:i.provider==="redis"?a=new at(i.redis):a=new it,this.use(Sr(a,i));break}default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#r||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.swagger&&Gs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#a.length&&_.applyGlobalMiddlewaresToAllRoutes(this.#a),this.#r=true);}handleNotFound=(e,t)=>{if(this.#n){this.#n(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],n=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=_.find(a,r);c&&c.handler!==this.handleNotFound&&n.push(a);}if(n.length){t.setHeader("Allow",n.join(", "));let a=new Ge(r,e.method);t.methodNotAllowed({...N(a)});return}let i=new z(r,e.method);t.notFound({...N(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)_.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true},void 0,true);}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var Nr=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),n=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},n,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(i));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,a]=n,c=this.decodeBase64(i),d=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),p=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),m=new Uint8Array(p);if(m.length!==d.length)return !1;let f=0;for(let u=0;u<m.length;u++)f|=m[u]^d[u];return f===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return s}},Nn=new Nr;var Js=()=>{let o=q.getCacheStats(),e=o.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:o.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:o.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},In=()=>{let o=Js();M.info({validators:o.validators.size,totalSchemaRefs:o.totalSchemaReferences,memoryEstimate:o.memoryEstimate.total},"Schema cache metrics");},Fn=()=>{q.clearAllCaches(),M.debug("All schema caches cleared");};var V=class extends R{constructor(e){super(`File not found: ${e}`);}};var Ir=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new V(e);let n=t;if(n==="stream")return stream.Readable.toWeb(s.readableStreamBody);let i=[];for await(let c of s.readableStreamBody)i.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(i);switch(n){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new R("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new V(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),n=t;await s.upload(n,n.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new R("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new R("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Fr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new R("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await y.exists(r))return [];let n=[];return await this.listFilesRecursively(r,t,n),n}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await y.exists(r))throw new V(e);switch(t){case "raw":return await y.readFile(r);case "text":return await y.readFile(r,{encoding:"utf8"});case "stream":return await y.streamFile(r);default:throw new R("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),n=x.join(s,"..");await y.mkdir(n,{recursive:true}),await y.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await y.exists(t)&&await y.unlink(t);}async listFilesRecursively(e,t,r){let s=await y.stat(e);if(s.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!s.isDirectory)return;let n=await this.readDirectory(e);for(let i of n){let a=x.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(G(),Kr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new R("Unsupported runtime")}}async ensureDirectoryExists(){if(await y.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await y.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};G();var Dr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=j.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:n}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:n,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new R("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new V(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new R("Invalid return type")}}catch(s){throw s instanceof V?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new V(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new V(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new R("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new V(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new R("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Qr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var Qt=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await y.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new R("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var Ut=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new R("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var zt=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await y.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new R("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var Gt=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new R("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var Jt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,n)=>{let i=t[s];return i===void 0?r:n&&this.helpers.has(n)?this.helpers.get(n)(i):String(i)})}async renderFromFile(e,t){let r=await y.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var pt=class extends R{constructor(e){super(e),this.name="MailerError";}},dt=class extends pt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},Wt=class extends pt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},Kt=class extends pt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var ut=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,n=s.build();return s.hasTemplate()?this.sendWithTemplate(n):this.sendDirect(n)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new Wt;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var Ur=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new Kt(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new ut(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new dt(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,n=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:n,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=vr("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let n=s;n.isFilePath?r.templateFile(n.template,n.data):r.template(n.template,n.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new dt(String(this.defaultProvider));return e}};var zr=class{};var Gr=o=>(e,t)=>(r,s,n)=>{let i={scope:e,handler:t,manager:o};if(typeof s>"u"){let c=O.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),O.set(r.prototype,"__class__",c),r}let a=O.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),O.set(r,s,a),n};var Jr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Gr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new R(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var jg=_,Eg=Dt;
|
|
1230
1230
|
exports.AzureBlobStorageProvider=Ir;exports.BaseCron=gr;exports.BasePlugin=zr;exports.BullMQPubSub=et;exports.CACHE_STATUS_HEADER=ue;exports.CacheService=Xe;exports.CacheStatus=ar;exports.Command=A;exports.CommandRegistry=qt;exports.CronService=J;exports.CustomAdapter=Jt;exports.DEFAULT_CACHE_OPTIONS=Ne;exports.EdgeAdapter=Ut;exports.EjsAdapter=Gt;exports.GraphQL=se;exports.HandlebarsAdapter=Qt;exports.LocalStorageProvider=Fr;exports.MailOptionsBuilder=Be;exports.MailProvider=ut;exports.Mailer=Ur;exports.MemoryCacheProvider=it;exports.MemoryPubSub=tt;exports.MqttService=Fe;exports.MustacheAdapter=zt;exports.PGBossPubSub=rt;exports.PolicyManager=Jr;exports.QueueManager=re;exports.QueueService=W;exports.RedisCacheProvider=at;exports.S3StorageProvider=Dr;exports.SQSPubSub=st;exports.Server=Dt;exports.Storage=Qr;exports.arg=B;exports.asyncLocalStorage=Rr;exports.asyncStorage=Je;exports.bullmqQueue=Lo;exports.cache=oo;exports.cacheMiddleware=Sr;exports.clearAllSchemaCaches=Fn;exports.commandRegistry=Pe;exports.compression=Or;exports.controller=To;exports.cookie=Mr;exports.cors=jr;exports.createExpressAdapter=qr;exports.createPolicyDecorator=Gr;exports.createQueue=Io;exports.cron=So;exports.cronUIInstance=mr;exports.cronUi=wo;exports.default=Eg;exports.defineMiddleware=Jo;exports.defineQueueConfiguration=Fo;exports.del=Po;exports.expressHandler=Fs;exports.expressMiddleware=He;exports.flag=C;exports.get=Ro;exports.getCacheService=Ze;exports.getSchemaCacheMetrics=Js;exports.hash=Nn;exports.helmet=Ar;exports.initCacheService=lr;exports.log=kr;exports.logSchemaCacheMetrics=In;exports.logger=M;exports.memoryQueue=vr;exports.methodOverride=_r;exports.middleware=jo;exports.mountExpressRouter=lt;exports.mqtt=$o;exports.patch=Co;exports.pgbossQueue=No;exports.post=Oo;exports.put=Mo;exports.rateLimiter=Hr;exports.resetCacheService=yo;exports.router=jg;exports.serialize=Ao;exports.serveStatic=Tr;exports.session=$r;exports.setCronGlobalErrorHandler=bo;exports.setMqttGlobalErrorHandler=Ho;exports.sqsQueue=Bo;exports.timeoutMw=Br;exports.trustProxy=Lr;exports.validate=ko;//# sourceMappingURL=index.cjs.map
|
|
1231
1231
|
//# sourceMappingURL=index.cjs.map
|