UNPKG

@lunoxjs/core

Version:
6 lines (5 loc) 32.6 kB
var Ge=Object.defineProperty;var a=(r,e)=>Ge(r,"name",{value:e,configurable:!0});import{a as P,p as U,n as k,c as $,b as D,r as oe,o as V,s as ce,d as x,e as K,f as N,g as le,h as ze,t as L,i as A,q as pe,j as de,k as he,l as ue,m as _,u as T,v as me,w as ge}from"./ViewFactory-bbd4d106.mjs";import{E as Br,z as qr,B as Jr,y as Gr,x as zr,A as Wr,C as Xr}from"./ViewFactory-bbd4d106.mjs";import{StorageManager as We}from"@kodepandai/flydrive";import u from"path";import{STATUS_CODES as Xe}from"http";import fe from"sirv";import d from"fs";import Qe from"polka";import E from"crypto";import Ye from"hash-equals";import{pathToFileURL as O}from"url";import{AsyncLocalStorage as Ze}from"async_hooks";import et from"formidable";import ye from"express-session";import{Command as tt}from"commander";import{cyanBright as st,bgRed as ve,whiteBright as be,yellow as rt,blue as at}from"colorette";import{exit as we}from"process";import{spawn as it}from"child_process";import nt from"repl";import"pluralize";import"dotenv";import"@kodepandai/node-input-validator";import"cookie";var ot=Object.defineProperty,ct=a((r,e)=>ot(r,"name",{value:e,configurable:!0}),"r$j");const lt=ct(r=>class extends r{static rememberTokenName="remember_token";password;getAuthPassword(){return this.password}getAuthIdentifierName(){return this.constructor.primaryKey}getAuthIdentifier(){const e=this.getAuthIdentifierName()||"id";return this[e]}getRememberToken(){if(this.getRememberTokenName())return this[this.getRememberTokenName()]}setRememberToken(e){this.getRememberTokenName()&&(this[this.getRememberTokenName()]=e)}getRememberTokenName(){return this.constructor.rememberTokenName}},"AuthenticatableTrait");var pt=Object.defineProperty,dt=a((r,e)=>pt(r,"name",{value:e,configurable:!0}),"r$i");let $e=a(class extends P{async register(){this.app.singleton(U.symbol,()=>new U(this.app))}},"o");dt($e,"AuthServiceProvider");var ht=Object.defineProperty,ut=a((r,e)=>ht(r,"name",{value:e,configurable:!0}),"t$7");let M=a(class extends We{static symbol=Symbol("FilesystemManager");app;constructor(e){super(config("filesystems")),this.app=e}isUsingS3(){const e=config("filesystems").disks;for(const t in e)if(e[t].driver=="s3")return!0;return!1}async registerS3Driver(){this.registerDriver("s3",(await import("@kodepandai/flydrive-s3")).AmazonWebServicesS3Storage)}},"e");ut(M,"FilesystemManager");var mt=Object.defineProperty,gt=a((r,e)=>mt(r,"name",{value:e,configurable:!0}),"a$g");let Se=a(class extends ${static getFacadeAccessor(){return M.symbol}},"r");gt(Se,"Storage");var H=k(Se),ft=Object.defineProperty,yt=a((r,e)=>ft(r,"name",{value:e,configurable:!0}),"r$g");let ke=a(class extends P{async register(){this.app.singleton(M.symbol,()=>new M(this.app))}async boot(){H.isUsingS3()&&H.registerS3Driver()}},"t");yt(ke,"FilesystemServiceProvider");const vt={async handleNative(r,e,t){const s=D.getConfig();return ye({store:await D.getStore(ye),name:s.cookie,secret:env("APP_KEY","secret"),resave:!1,saveUninitialized:!1,unset:"destroy",cookie:{httpOnly:s.http_only,maxAge:s.lifetime*60*1e3,path:s.path,secure:s.secure,sameSite:s.same_site==null?void 0:s.same_site}})(r,e,t)}};var bt=Object.defineProperty,wt=a((r,e)=>bt(r,"name",{value:e,configurable:!0}),"c$3");let Ce=a(class{instances={};bindings={};bind(e,t,s=!1){this.bindings[e]={concrete:t,shared:s}}singleton(e,t){this.bind(e,t,!0)}build(e,t={}){const s=this.bindings[e].concrete;let i=null;return is_class(s)?(i=Reflect.construct(s,[]),Object.keys(t).forEach(o=>{Reflect.set(i,o,t[o])})):i=s(),this.bindings[e].shared&&(this.instances[e]=i),i}make(e,t={}){try{return this.instances[e]&&Object.keys(t).length==0?this.instances[e]:this.build(e,t)}catch(s){let i="";throw s instanceof Error&&(i=s.message),new Error(`cannot resolve "${e.toString()}": ${i}`)}}instance(e,t){return this.instances[e]=t,t}},"o");wt(Ce,"Container");var $t=Object.defineProperty,St=a((r,e)=>$t(r,"name",{value:e,configurable:!0}),"r$f");let B=a(class extends P{async register(){this.app.singleton(oe.symbol,()=>new oe)}},"s");St(B,"RoutingServiceProvider");var kt=Object.defineProperty,Ct=a((r,e)=>kt(r,"name",{value:e,configurable:!0}),"n$6");let Pe=a(class extends Ce{_basePath;isBooted=!1;config;responseRenderers=[];isRunningInConsole=null;constructor(e=null){super(),global.app=(t=null,s={})=>t&&(typeof t=="string"||typeof t=="symbol")?this.make(t,s):this,this.setBasePath(e),this.registerBaseServiceProviders()}setBasePath(e){return this._basePath=e?.replace(new RegExp(`${u.sep}$`),"")||process.cwd(),this.bindPaths(),this._basePath}basePath(e=""){return u.join(this._basePath,e)}configPath(e=""){return u.join(this._basePath,"config",e)}storagePath(e=""){return u.join(process.cwd(),"storage",e)}bindPaths(){this.instance("path.basePath",this.basePath()),this.instance("path.configPath",this.configPath())}async bootstrapWith(e){for(let t=0;t<e.length;t++)await new e[t]().bootstrap(this)}async register(e){await e.register()}async registerConfiguredProviders(){const e=this.config.get("app.providers")||[];for(let t=0;t<e.length;t++)await this.register(new e[t](this))}async boot(){if(this.isBooted)return;const e=this.config.get("app.providers")||[];for(let t=0;t<e.length;t++)await new e[t](this).boot();this.isBooted=!0}async registerBaseServiceProviders(){await this.register(new B(this))}abort(e,t="",s={}){throw e==404?new V(t):new ce(e,t,null,s)}runningInConsole(){return this.isRunningInConsole==null&&(this.isRunningInConsole=env("APP_RUNNING_IN_CONSOLE")),this.isRunningInConsole}runingUnitTests(){return this.config.get("app.env")=="testing"}},"o");Ct(Pe,"Application");var Pt=Object.defineProperty,xt=a((r,e)=>Pt(r,"name",{value:e,configurable:!0}),"r$e");let xe=a(class extends x{validator=null;rules(){return{}}messages(){return{}}setValidator(e){return this.validator=e,this}attributes(){return{}}validateForm(){return this.getValidatorInstance().validate()}createDefaultValidator(e){return e.make(this.all(),this.rules(),this.messages(),this.attributes())}getValidatorInstance(){if(this.validator)return this.validator;const e=this.app.make(K.symbol),t=this.createDefaultValidator(e);return this.setValidator(t),this.validator}},"e");xt(xe,"FormRequest");var Et=Object.defineProperty,Ot=a((r,e)=>Et(r,"name",{value:e,configurable:!0}),"t$4");let C=a(class extends N{},"o");Ot(C,"DecryptException");var At=Object.defineProperty,Rt=a((r,e)=>At(r,"name",{value:e,configurable:!0}),"h$2");let f=a(class v{static symbol=Symbol("Encrypter");key;cipher;static supportedCiphers={"aes-128-cbc":{size:16,aead:!1},"aes-256-cbc":{size:32,aead:!1},"aes-128-gcm":{size:16,aead:!0},"aes-256-gcm":{size:32,aead:!0}};constructor(e,t="aes-128-cbc"){if(!v.supported(e,t)){const s=Object.keys(v.supportedCiphers).join(", ");throw new N(`Unsupported cipher or incorrect key length. Supported ciphers are: ${s}.`)}this.key=e,this.cipher=t}getKey(){return this.key}static supported(e,t){return v.supportedCiphers[t]?e.length===v.supportedCiphers[t].size:!1}static generateKey(e){return E.randomBytes(v.supportedCiphers[e].size||32)}encrypt(e,t=!0){const s=t?JSON.stringify(e):e;try{const i=E.randomBytes(E.getCipherInfo(this.cipher)?.ivLength),o=v.base64Encode(i),c=E.createCipheriv(this.cipher,this.key,i);let n=c.update(s,"utf8","base64");n+=c.final("base64");const l=this.hash(o,n),p=JSON.stringify({iv:o,value:n,mac:l});return v.base64Encode(p)}catch{throw new Error("Cannot encrypt data provided !")}}encryptString(e){return this.encrypt(e,!1)}decrypt(e,t=!0){const s=this.getJsonPayload(e),i=v.base64Decode(s.iv),o=E.createDecipheriv(this.cipher,this.key,i);let c=o.update(s.value,"base64","utf8");return c+=o.final("utf8"),t?JSON.parse(c):c}decryptString(e){return this.decrypt(e,!1)}hash(e,t){if(!e)throw new Error("Iv is not defined !");if(!t)throw new Error("Value is not defined !");const s=String(e)+String(t);return this.hashHmac("sha256",s,this.key)}hashHmac(e,t,s){const i=E.createHmac(e,s);return i.update(t),i.digest("hex")}getJsonPayload(e){let t={};try{t=JSON.parse(v.base64Decode(e).toString())}catch{throw new C("Payload cannot be parsed !")}if(!this.isValidPayload(t))throw new C("Payload is not valid !");if(!this.isValidMac(t))throw new C("Mac is not valid !");return t}isValidPayload(e){return e.hasOwnProperty("iv")&&e.hasOwnProperty("value")&&e.hasOwnProperty("mac")}isValidMac(e){return this.hash(e.iv,e.value)===e.mac}static hashEquals(e,t){return Ye(e,t)}static base64Encode(e){return typeof e=="string"&&(e=Buffer.from(e)),e.toString("base64")}static base64Decode(e){return Buffer.from(e,"base64")}},"r");Rt(f,"Encrypter");var jt=Object.defineProperty,Ft=a((r,e)=>jt(r,"name",{value:e,configurable:!0}),"e$5");let Ee=a(class extends ${static getFacadeAccessor(){return f.symbol}},"t");Ft(Ee,"Crypt");var Oe=k(Ee),Nt=Object.defineProperty,Ae=a((r,e)=>Nt(r,"name",{value:e,configurable:!0}),"o$9");class q extends ze{routes;prefixStack;middlewareStack;deep;calledAction;static macros={};constructor(){super(),this.routes=[],this.prefixStack=[],this.middlewareStack=[],this.calledAction="",this.deep=0}addRoutes=e=>(t,s,i={})=>{let o=[];if(Array.isArray(s)){const[c,n]=s,l=new c;s=Ae((p,...h)=>l.callAction(n,[p,...h]),"action"),o=l.getMiddleware().filter(p=>this.methodIncludedByOptions(n,p.options)).map(p=>p.middleware)}return this.routes.push({prefix:this.prefixStack.join(""),uri:this.prefixStack.join("")+t,method:e,action:s,middleware:this.flattenMiddleware(this.middlewareStack),controllerMiddleware:this.flattenMiddleware(o),...i}),this.calledAction="addRoutes",this};get=this.addRoutes("get");post=this.addRoutes("post");delete=this.addRoutes("delete");patch=this.addRoutes("patch");put=this.addRoutes("put");all=this.addRoutes("all");getRoutes(){return this.routes}prefix(e){return this.prefixStack.push(e),this.calledAction="prefix",this}middleware(e){return this.middlewareStack.push(e),this.calledAction=="addRoutes"&&(this.routes[this.routes.length-1].middleware=this.flattenMiddleware(this.middlewareStack),this.middlewareStack.pop()),this.calledAction="middleware",this}async group(e){this.deep++,this.deep>this.middlewareStack.length&&this.middlewareStack.push(null),typeof e=="string"?app().runingUnitTests()?await import(O(e).href):await import(O(e+".mjs").href):typeof e=="function"&&await e(),this.middlewareStack.pop(),this.prefixStack.pop(),this.calledAction="group",this.deep--}flattenMiddleware(e){return e.reduce((t,s)=>s==null?t:Array.isArray(s)?[...t,...s]:[...t,s],[])}facadeCalled(){this.calledAction=""}methodIncludedByOptions(e,t){return t.only.includes(e)&&!t.except.includes(e)||!t.except.includes(e)&&t.only.length==0}}a(q,"Router"),Ae(q,"Router");var Re=le(q),_t=Object.defineProperty,Tt=a((r,e)=>_t(r,"name",{value:e,configurable:!0}),"r$c");let je=a(class extends ${static getFacadeAccessor(){return Re}},"t");Tt(je,"Route");var Fe=k(je),Mt=Object.defineProperty,It=a((r,e)=>Mt(r,"name",{value:e,configurable:!0}),"r$b");let R=a(class{static symbol=Symbol("config");items={};constructor(e){this.items=e}has(e){return Object.keys(this.items).includes(e)}get(e="",t){return e.split(".").reduce((s,i)=>s?.[i],this.items)||t||null}all(){return this.items}set(e,t){let s=this.items;const i=e.split("."),o=i.length;for(let c=0;c<o-1;c++){const n=i[c];s[n]||(s[n]={}),s=s[n]}s[i[o-1]]=t}},"a");It(R,"Repository");var Ut=Object.defineProperty,Dt=a((r,e)=>Ut(r,"name",{value:e,configurable:!0}),"o$8");let Ne=a(class extends ${static getFacadeAccessor(){return R.symbol}},"r");Dt(Ne,"Config");var Vt=k(Ne),Kt=Object.defineProperty,Lt=a((r,e)=>Kt(r,"name",{value:e,configurable:!0}),"e$4");let _e=a(class extends ${static getFacadeAccessor(){return Ze}},"o");Lt(_e,"Als");var j=k(_e),Ht=Object.defineProperty,Bt=a((r,e)=>Ht(r,"name",{value:e,configurable:!0}),"p$8");let J=a(class{async bootstrap(e){await e.boot()}},"a");Bt(J,"BootProviders");var qt=Object.defineProperty,Jt=a((r,e)=>qt(r,"name",{value:e,configurable:!0}),"p$7");let G=a(class{async bootstrap(e){e.singleton(R.symbol,R);const t=e.make(R.symbol,{items:{}});global.config=(s,i)=>t.get(s,i),e.config=t,await this.loadConfigurations(e,t)}async getConfigurationFiles(e){const t=e.make("path.configPath");d.existsSync(t)||d.mkdirSync(t);const s=(await walkDir(t)).map(i=>i.replace(t+u.sep,""));if(!(s.includes("app.mjs")||s.includes("app.ts")))throw new Error('unable to load "app": configuration file');return s}async loadConfigurations(e,t){const s=e.make("path.configPath"),i=await this.getConfigurationFiles(e);await Promise.all(i.map(async o=>{t.set(o.replace(".mjs","").replace(".ts","").replace(u.sep,"."),(await import(O(u.join(s,o)).href)).default||{})}))}},"c");Jt(G,"LoadConfiguration");var Gt=Object.defineProperty,zt=a((r,e)=>Gt(r,"name",{value:e,configurable:!0}),"r$8");let z=a(class{async bootstrap(e){e.singleton(L.symbol,L),global.env=(t,s=null)=>e.make(L.symbol).get(t,s)}},"n");zt(z,"LoadEnvirontmentVariabel");var Wt=Object.defineProperty,Xt=a((r,e)=>Wt(r,"name",{value:e,configurable:!0}),"p$6");let W=a(class{async bootstrap(e){$.setApplicationFacade(e)}},"a");Xt(W,"RegisterFacades");var Qt=Object.defineProperty,Yt=a((r,e)=>Qt(r,"name",{value:e,configurable:!0}),"p$5");let X=a(class{async bootstrap(e){await e.registerConfiguredProviders()}},"r");Yt(X,"RegisterProviders");var Zt=Object.defineProperty,es=a((r,e)=>Zt(r,"name",{value:e,configurable:!0}),"p$4");let Q=a(class{async bootstrap(e){e.singleton(A.symbol,A)}},"a");es(Q,"HandleException");var ts=Object.defineProperty,ss=a((r,e)=>ts(r,"name",{value:e,configurable:!0}),"n$3");class I{file;constructor(e){this.file=e}path(){return this.failIfArray("path"),this.file.filepath}getClientOriginalExtension(){return this.failIfArray("getClientOriginalExtension"),u.extname(this.file.originalFilename||"")}getClientOriginalName(){return this.failIfArray("getClientOriginalName"),this.file.originalFilename}getClientMimeType(){return this.failIfArray("getClientMimeType"),this.file.mimetype}move(e,t=null){d.existsSync(e)||d.mkdirSync(e),Array.isArray(this.file)?this.file.forEach(s=>{this.moveFile(s,e,t)}):this.moveFile(this.file,e,t)}failIfArray(e){if(Array.isArray(this.file))throw new Error(`Cannot call method '${e}' on Array`)}moveFile(e,t,s=null){const i=e.filepath,o=u.join(t,s||e.originalFilename||"");d.renameSync(i,o),d.chmodSync(o,438)}}a(I,"f"),ss(I,"UploadedFile");var rs=Object.defineProperty,Te=a((r,e)=>rs(r,"name",{value:e,configurable:!0}),"y");class Y{app;middleware=[];middlewareGroups={};routeMiddleware={};bootstrappers=[z,G,Q,W,X,J];constructor(e){this.app=e}async start(){const e=Qe({onError:async(n,l,p)=>{this.reportException(n);const h=await this.renderException(l._httpRequest,n);return this.send(p,h.getStatus(),h.getOriginal(),h.headers)},onNoMatch:()=>{throw new V("Not Found")}}),t=e.parse;e.parse=n=>{const l=t(n);return n.method?.toLocaleLowerCase()=="get"||l.query?._method&&(n.method=l.query._method.toUpperCase()),l},this.app.instance("server",e),this.app.bind(x.symbol,()=>j.getStore()?.get(x.symbol)),await this.app.bootstrapWith(this.bootstrappers),e.use((n,l,p)=>{j.run(new Map,()=>{try{const h=new x(this.app,n),g=pe.make({}).setServerResponse(l);if(n._httpRequest=h,l._httpResponse=g,j.getStore()?.set(x.symbol,h),n.method.toLowerCase()=="get")return p();as(n,h).then(()=>{p()}).catch(b=>{p(b)})}catch(h){throw j.getStore()?.clear(),h}})});const s=this.middleware.map(n=>this.handleMiddleware(n));s.length>0&&e.use(...s);const i=env("PORT")||8e3,o=Fe.getRoutes();if(await Promise.all(o.map(n=>{n.middleware=[...n.middleware,...n.controllerMiddleware];const l=n.middleware.reduce((p,h)=>(typeof h=="string"&&this.middlewareGroups[h]?p=[...p,...this.middlewareGroups[h].map(g=>this.handleMiddleware(g))]:p=[...p,this.handleMiddleware(h)],p),[]);e[n.method](n.uri,(p,h,g)=>(p._httpRequest.setRouter(n),g()),...l,async(p,h)=>{let g=p._httpRequest,b=h._httpResponse,y=await n.action(g,...Object.values(p.params));for(let m=0;m<this.app.responseRenderers.length;m++)y instanceof this.app.responseRenderers[m]&&(y=await y.render(g));y instanceof de&&(g=y.setRequest(g));const ne=n.middleware.reduce((m,S)=>(typeof S=="string"&&this.middlewareGroups[S]?m=[...m,...this.middlewareGroups[S].map(Je=>this.handleMiddleware(Je,!0))]:m=[...m,this.handleMiddleware(S,!0)],m),[]).filter(m=>m!=null).reverse();for(let m=0;m<=ne.length;m++){const S=ne[m];typeof S=="function"&&(b=await S(b,g))}return y instanceof he?(await g.session().save(),b.mergeResponse(y),b.setCookiesToHeaders(),this.send(h,b.getStatus(),b.getOriginal(),b.headers)):["object","number","boolean"].includes(typeof y)?h.end(JSON.stringify(y)):h.end(y)})})),process.env.NODE_ENV!="production"&&config("view.engine")&&!this.app.runingUnitTests()){const{createServer:n}=(await import("vite")).default,l=await n({server:{middlewareMode:"ssr",watch:{usePolling:!0,interval:5e3}}});this.app.instance("vite",l),e.use(l.middlewares)}else if(d.existsSync(base_path("client"))){const n=base_path("client"),l=fe(n,{maxAge:31536e3,immutable:!0});e.use(l)}const c=fe(base_path("public"),{maxAge:331536e3,dev:process.env.NODE_ENV!="production"});return e.use(c),this.app.runingUnitTests()||e.listen(i,()=>process.env.NODE_ENV!="production"?console.log("Starting development server: http://localhost:"+i):console.log("Starting server: http://localhost:"+i)),this.app}handleMiddleware(e,t=!1){let s=typeof e=="string"?this.routeMiddleware[e]:e;return is_class(s)&&(s=new s),t?s.handleAfter?.bind(s):s.handleNative?s.handleNative?.bind(s):async(i,o,c)=>{try{const n=s.handle?.bind(s);if(n){const l=await n(i._httpRequest,()=>o._httpResponse);o._httpResponse=l}return c()}catch(n){if(n instanceof Error)return c(n)}}}send(e,t=200,s="",i={}){const o="content-type",c="application/octet-stream";let n;const l={};for(n in i)typeof i[n]!="function"&&(l[n.toLowerCase()]=i[n]);let p=l[o]||e.getHeader(o);if(s&&typeof s.pipe=="function")return e.setHeader(o,p||c),s.pipe(e);s instanceof Buffer?p=p||c:typeof s=="object"?(s=JSON.stringify(s),p=p||"application/json;charset=utf-8"):s=s||Xe[t],l[o]=p||"text/html;charset=utf-8",l["content-length"]=Buffer.byteLength(s),e.writeHead(t,l),e.end(s)}reportException(e){return typeof e=="string"&&(e=new Error(e)),this.app.make(A.symbol).report(e)}async renderException(e,t){return typeof t=="string"&&(t=new Error(t)),await this.app.make(A.symbol).render(e,t)}}a(Y,"b"),Te(Y,"Kernel");const as=Te((r,e)=>new Promise((t,s)=>{et({multiples:!0}).parse(r,(i,o,c)=>{i&&s(i),e.files=Object.keys(c).reduce((n,l)=>(n[l]=new I(c[l]),n),{}),e.merge({...o,...e.files}),t()})}),"parseFormData");var is=Object.defineProperty,ns=a((r,e)=>is(r,"name",{value:e,configurable:!0}),"o$6");let Z=a(class extends Error{constructor(e="No application encryption key has been specified."){super(e)}},"s");ns(Z,"MissingAppKeyException");var os=Object.defineProperty,cs=a((r,e)=>os(r,"name",{value:e,configurable:!0}),"p$3");let Me=a(class extends P{async register(){this.app.singleton(f.symbol,()=>{const e=this.app.config.get("app");return new f(this.parseKey(e),e.cipher)})}parseKey(e){const t=this.key(e);return t.includes("base64:")?f.base64Decode(t.substring(7)):f.base64Decode(t)}key(e){if(!e.key)throw new Z;return e.key}},"i");cs(Me,"EncryptionServiceProvider");var ls=Object.defineProperty,ps=a((r,e)=>ls(r,"name",{value:e,configurable:!0}),"a$6");let F=a(class ie{static create(e,t){return Oe.hashHmac("sha1",e+"v2",t)+"|"}static validate(e,t,s){return t.startsWith(ie.create(e,s))?ie.remove(t):null}static remove(e){return e.slice(41)}},"r");ps(F,"CookieValuePrefix");var ds=Object.defineProperty,hs=a((r,e)=>ds(r,"name",{value:e,configurable:!0}),"i$5");let Ie=a(class{app;encrypter;except=[];addHttpCookie=!0;constructor(){this.app=app(),this.encrypter=app(f.symbol)}async handle(e,t){if(this.isReading(e)||this.runningUnitTests()||this.inExceptArray(e)||this.tokensMatch(e)){const s=t(e);return this.shouldAddXsrfTokenCookie()&&this.addCookieToResponse(e,s),s}throw new ue("CSRF token mismatch.")}isReading(e){return["HEAD","GET","OPTIONS"].includes(e.method())}runningUnitTests(){return this.app.runningInConsole()&&this.app.runingUnitTests()}inExceptArray(e){return this.except.some(t=>(t!=="/"&&(t=t.replace(/^\/|\/$/g,"")),!!e.is(t)))}tokensMatch(e){const t=this.getTokenFromRequest(e);return typeof t=="string"&&f.hashEquals(e.session().token(),t)}getTokenFromRequest(e){let t=e.input("_token")||e.header("X-CSRF-TOKEN");const s=e.header("X-XSRF-TOKEN");if(!t&&s)try{t=F.remove(this.encrypter.decrypt(s,!1))}catch(i){i instanceof C&&(t="")}return t}shouldAddXsrfTokenCookie(){return this.addHttpCookie}addCookieToResponse(e,t){const s=this.app.config.get("session");t.headers.setCookie(this.newCookie(e,s))}newCookie(e,t){return new _("XSRF-TOKEN",e.session().token(),_.getExpiresTimeFromLifeTime(t.lifetime),t.path,t.domain,t.secure,!1,!1,t.same_site)}},"p");hs(Ie,"VerifyCsrfToken");var us=Object.defineProperty,ms=a((r,e)=>us(r,"name",{value:e,configurable:!0}),"r$4");let Ue=a(class{options={only:[],except:[]};constructor(e){this.options=e}only(e){return this.options.only=T.wrap(e),this}except(e){return this.options.except=T.wrap(e),this}},"s");ms(Ue,"ControllerMiddlewareOptions");var gs=Object.defineProperty,fs=a((r,e)=>gs(r,"name",{value:e,configurable:!0}),"i$4");let De=a(class{middlewares=[];callAction(e,t){if(!get_class_methods(this).includes(e))throw new me(`Method ${this.constructor.name}.${e} does not exist.`);return this[e](...t)}middleware(e){const t={except:[],only:[]};return T.wrap(e).forEach(s=>{this.middlewares.push({middleware:s,options:t})}),new Ue(t)}getMiddleware(){return this.middlewares}},"d");fs(De,"Controller");const ys={name:"mimes",passes:async(r,e)=>{if(!r||r.length==0)throw new Error("Invalid rule args, the usage must be mime:a,b,c");if(e instanceof I){let t=!1;return r.forEach(s=>{e.getClientMimeType()?.includes(s)&&(t=!0)}),t}return!1},message:"The :attr must be a file of type: :args."};var vs=Object.defineProperty,bs=a((r,e)=>vs(r,"name",{value:e,configurable:!0}),"o$4");let Ve=a(class extends P{async register(){this.app.singleton(K.symbol,()=>new K(this.app))}async boot(){ge.extend(ys)}},"e");bs(Ve,"ValidationServiceProvider");var ws=Object.defineProperty,$s=a((r,e)=>ws(r,"name",{value:e,configurable:!0}),"l$1");class w{lunox;SUCCESS=0;FAILURE=1;INVALID=2;signature="";description="";args={};opts={};async handle(){return this.SUCCESS}getSignature(){return this.signature.replace(/\s\s+/g," ")}getDescription(){return this.description}setArguments(e){this.args=e}setOptions(e){this.opts=e}setLunox(e){this.lunox=e}arguments(){return this.args}argument(e){return this.args[e]}options(){return this.opts}option(e){return this.opts[e]}info(e){console.log(st(e))}line(e){console.log(e)}error(e){console.log(ve(be(e)))}newLine(e=1){for(let t=0;t<e;t++)console.log("")}comment(e){console.log(rt(e))}async tryCommand(e,t,s){try{await t()}catch(i){s(i)}}shellExec(e,t=!1){const s=it(e,{shell:!0});let i="",o="";return new Promise((c,n)=>{s.stderr.setEncoding("utf-8"),s.stdout.setEncoding("utf-8"),s.stdout.on("data",l=>{t&&this.line(l),i+=l}),s.stderr.on("data",l=>{t&&this.comment(l),o+=l}),s.on("close",l=>{if(l===0){const p=i.split(` `);p[p.length-1]==""&&p.pop(),this.line(p.join(` `)),c()}else this.error(o),n(o)}),s.on("error",n)})}}a(w,"g"),$s(w,"Command");var Ss=Object.defineProperty,ks=a((r,e)=>Ss(r,"name",{value:e,configurable:!0}),"e$1");let Ke=a(class extends w{signature="make:command {name : name of command}";description="create new artisan command";async handle(){this.info("making artisan command...");const e=this.argument("name");if(d.existsSync(u.join(base_path("../app/Console/Command"),e+".ts")))return this.error("console command already exists!"),this.FAILURE;const t=d.readFileSync(stub_path("command"),{encoding:"utf-8"}).replace(/#CommandName/g,e);return d.writeFileSync(u.join(base_path("../app/Console/Command"),e+".ts"),t),this.comment(`created artisan command ${e}`),this.SUCCESS}},"o");ks(Ke,"MakeCommand");var Cs=Object.defineProperty,Ps=a((r,e)=>Cs(r,"name",{value:e,configurable:!0}),"i$3");let Le=a(class extends w{signature="make:middleware {name : name of middleware}";description="create new middleware";async handle(){this.info("making middleware...");const e=this.argument("name");if(d.existsSync(u.join(base_path("../app/Middleware"),e+".ts")))return this.error("console command already exists!"),this.FAILURE;const t=d.readFileSync(stub_path("middleware"),{encoding:"utf-8"}).replace(/#MiddlewareName/g,e);return d.writeFileSync(u.join(base_path("../app/Middleware"),e+".ts"),t),this.comment(`created middleware file ${e}`),this.SUCCESS}},"d");Ps(Le,"MakeMiddlewareCommand");var xs=Object.defineProperty,Es=a((r,e)=>xs(r,"name",{value:e,configurable:!0}),"s");let He=a(class extends w{signature="make:provider {name : name of the class}";description="create a new service provider class";async handle(){this.info("making provider...");const e=this.argument("name");if(d.existsSync(u.join(base_path("../app/Providers"),e+".ts")))return this.error("provider class already exists!"),this.FAILURE;const t=d.readFileSync(stub_path("provider"),{encoding:"utf-8"}).replace(/#ProviderName/g,e);return d.writeFileSync(u.join(base_path("../app/Providers"),e+".ts"),t),this.comment(`created provider ${e}`),this.SUCCESS}},"a");Es(He,"MakeProviderCommand");var Os=Object.defineProperty,As=a((r,e)=>Os(r,"name",{value:e,configurable:!0}),"r$2");class ee extends w{signature="make:controller {name : name of controller} {--L|lite}";description="create a new controller file";async handle(){this.info("making controller...");const e=this.argument("name");if(d.existsSync(u.join(base_path("../app/Http/Controllers"),e+".ts")))return this.error("controller already exists!"),this.FAILURE;const t=this.option("lite")?"controller_lite":"controller",s=d.readFileSync(stub_path(t),{encoding:"utf-8"}).replace(/#ControllerName/g,e);return d.writeFileSync(u.join(base_path("../app/Http/Controllers"),e+".ts"),s),this.comment(`created controller ${e}`),this.SUCCESS}}a(ee,"l"),As(ee,"MakeControllerCommand");var Rs=Object.defineProperty,js=a((r,e)=>Rs(r,"name",{value:e,configurable:!0}),"r$1");let Be=a(class extends w{signature=`key:generate {--show : Display the key instead of modifying files} {--force : Force the operation to run when in production}`;description="Set the application key";async handle(){const e=this.generateRandomKey();return this.option("show")?(this.comment(e),this.SUCCESS):(this.setKeyInEnvironmentFile(e),this.info("Application key set successfully."),this.lunox.config.set("app.key",e),this.SUCCESS)}generateRandomKey(){return"base64:"+f.base64Encode(f.generateKey(this.lunox.config.get("app.cipher")))}setKeyInEnvironmentFile(e){const t=u.join(process.cwd(),".env");d.existsSync(t)||this.shellExec("cp .env.example .env");let s=d.readFileSync(u.join(process.cwd(),".env"),"utf-8");s=s.replace(/APP_KEY=?.+/m,"APP_KEY="+e),d.writeFileSync(t,s,"utf-8")}},"p");js(Be,"KeyGenerateCommand");var Fs=Object.defineProperty,Ns=a((r,e)=>Fs(r,"name",{value:e,configurable:!0}),"i$1");let qe=a(class extends w{signature="tinker";description="Interact with your application";shell;async handle(){return this.shell=nt.start(),this.shell.context.use=this.loadModule.bind(this),this.SUCCESS}async loadModule(e){if(e.includes("app")){e=u.join(this.lunox.basePath(),e);const t=(await import(O(e+".mjs").href)).default;this.shell.context[e.split(u.sep).pop()]=t}else{const t=(await import(O(lunox_path("index.mjs")).href))[e];t instanceof $?this.shell.context[e]=k(t):this.shell.context[e]=t}}},"n");Ns(qe,"TinkerCommand");var _s=Object.defineProperty,Ts=a((r,e)=>_s(r,"name",{value:e,configurable:!0}),"m");class te{app;program;bootstrappers=[z,G,Q,W,X,J];constructor(e){this.app=e,this.program=new tt,process.env.APP_RUNNING_IN_CONSOLE="true"}async handle(){const e=JSON.parse(d.readFileSync(get_current_dir(import.meta.url)+"/../package.json",{encoding:"utf-8"})).version;let t=[];try{t=JSON.parse(process.env.npm_config_argv).original.slice(2)}catch{t=process.argv.slice(2)}await this.app.bootstrapWith(this.bootstrappers),await this.builtinCommands(),await this.commands(),this.app.instances._commands&&await Promise.all(this.app.instances._commands.map(s=>{const i=new s;this.registerCommand(i)})),this.program.version(at("Lunox Framework ")+"version "+e),this.program.description("Laravel-Flavoured NodeJs framework"),this.program.showHelpAfterError(!0),this.program.parse(process.argv.slice(0,2).concat(t))}async builtinCommands(){const e=[Be,Ke,ee,Le,He,qe];await Promise.all(e.map(t=>{const s=new t;this.registerCommand(s)}))}async commands(){}async load(e){const t=await walkDir(e);await Promise.all(t.map(async s=>{const i=(await import(O(s).href)).default,o=new i;this.registerCommand(o)}))}registerCommand(e){const t=e.getSignature().match(/(?<=\{)(.*?)(?=})/g)||[],s=this.program.command(e.getSignature().split(" ")[0]).description(e.getDescription()).action(async()=>{const i=t.filter(c=>!(c.startsWith("--")||c.startsWith("-"))).map(c=>c.replace("?","")),o=s.args.reduce((c,n,l)=>(i.length>0&&(c[i[l].split(" : ")[0]]=n),c),{});e.setArguments(o),e.setOptions(s.opts()),e.setLunox(this.app);try{const c=await e.handle();c>0&&we(c)}catch(c){c instanceof Error?console.log(ve(be(c.message))):console.log(c),c instanceof N||we(1)}});t.forEach(i=>{let o="";if(i.split(" : ").length==2&&(o=i.split(" : ")[1],i=i.split(" : ")[0]),i.startsWith("--")||i.startsWith("-")){if(i.split("=").length==2){const[c,n]=i.split("=");return n==""?s.option(`${c} <value>`,o):s.option(`${c} <value>`,o,`${n}`)}if(i.split("|").length==2){const[c,n]=i.replace(/-/g,"").split("|");return s.option(["-"+c,"--"+n].join(", "),o)}return s.option(i,o)}return i.split("").pop()=="?"?s.argument(`[${i}]`,o):s.argument(`<${i}>`,o)}),s.showHelpAfterError()}}a(te,"c"),Ts(te,"Kernel");var Ms=Object.defineProperty,Is=a((r,e)=>Ms(r,"name",{value:e,configurable:!0}),"o$1");class se{async handleAfter(e,t){return t.cookieJar.getQueuedCookies().forEach(s=>{e.headers.setCookie(s)}),e}}a(se,"r"),Is(se,"AddQueuedCookiesToResponse");var Us=Object.defineProperty,Ds=a((r,e)=>Us(r,"name",{value:e,configurable:!0}),"n");class re{constructor(e=app(f.symbol)){this.encrypter=e}except=[];async handle(e,t){return t(this.decrypt(e))}async handleAfter(e){return this.encrypt(e)}decrypt(e){const t=e.cookies;for(const s in t){const i=t[s];if(!this.isDisabled(s))try{const o=this.decryptCookie(i);e.cookies.set(s,this.validateValue(s,o))}catch(o){if(o instanceof C)e.cookies.set(s,null);else throw o}}return e}encrypt(e){return e.headers.getCookies().forEach(t=>{this.isDisabled(t.getName())||e.headers.setCookie(this.duplicate(t,this.encrypter.encrypt(F.create(t.getName(),this.encrypter.getKey())+t.getValue(),!1)))}),e}isDisabled(e){return this.except.push(config("session.cookie")),this.except.includes(e)}decryptCookie(e){return this.encrypter.decrypt(e,!1)}validateValue(e,t){return F.validate(e,t,this.encrypter.getKey())}duplicate(e,t){return new _(e.getName(),t,e.getExpiresTime(),e.getPath(),e.getDomain(),e.isSecure(),e.isHttpOnly(),e.isRaw(),e.getSameSite())}}a(re,"o"),Ds(re,"EncryptCookie");var Vs=Object.defineProperty,Ks=a((r,e)=>Vs(r,"name",{value:e,configurable:!0}),"e");class ae{app;static make(){const e=new this;return beforeAll(async()=>{await e.setUp();const{agent:t}=await import("supertest");global.agent=t(e.app.make("server").handler)}),afterAll(()=>e.tearDown()),e}async setUp(){if(!this.app)return await this.refreshApplication()}async refreshApplication(){try{this.app=await this.createApplication()}catch(e){console.log("fail to create application",e)}}tearDown(){}}a(ae,"p"),Ks(ae,"TestCase");export{se as AddQueuedCookiesToResponse,j as Als,Pe as Application,T as Arr,U as AuthManager,$e as AuthServiceProvider,lt as AuthenticatableTrait,me as BadMethodCallException,w as Command,Vt as Config,te as ConsoleKernel,De as Controller,_ as Cookie,F as CookieValuePrefix,Oe as Crypt,C as DecryptException,re as EncryptCookie,f as Encrypter,Me as EncryptionServiceProvider,Br as Env,qr as ExtendedFacade,$ as Facade,ke as FilesystemServiceProvider,xe as FormRequest,A as Handler,ce as HttpException,he as HttpResponse,Y as Kernel,Z as MissingAppKeyException,V as NotFoundHttpException,de as RedirectResponse,x as Request,pe as Response,Fe as Route,Re as Router,B as RoutingServiceProvider,N as RuntimeException,P as ServiceProvider,D as SessionManager,Jr as SessionServiceProvider,vt as StartSession,H as Storage,Gr as Str,ae as TestCase,ue as TokenMismatchException,zr as Traitable,Wr as ValidationException,Ve as ValidationServiceProvider,ge as Validator,Ie as VerifyCsrfToken,Xr as ViewFactory,k as useFacade,le as useMagic};