@andrewcaires/express 1.2.9 → 2.0.1

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/dist/index.cjs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v1.2.9
3
- * Decorators for express
2
+ * @andrewcaires/express v2.0.1
3
+ * Decorators for express
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- "use strict";var e=require("@andrewcaires/node"),t=require("@andrewcaires/utils.js"),s=require("compression"),r=require("cookie-parser"),o=require("cors"),i=require("express"),n=require("express-session"),a=require("fs"),p=require("http"),h=require("https"),u=require("net"),l=require("path"),d=require("request-ip"),E=require("@andrewcaires/decorator"),c=require("multer");function _(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var T=_(p),O=_(h);function v(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{p(r.next(e))}catch(e){i(e)}}function a(e){try{p(r.throw(e))}catch(e){i(e)}}function p(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}p((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class R{}R.CONTINUE=100,R.SWITCHING_PROTOCOLS=101,R.PROCESSING=102,R.OK=200,R.CREATED=201,R.ACCEPTED=202,R.NON_AUTHORITATIVE_INFORMATION=203,R.NO_CONTENT=204,R.RESET_CONTENT=205,R.PARTIAL_CONTENT=206,R.MULTI_STATUS=207,R.ALREADY_REPORTED=208,R.IM_USED=226,R.MULTIPLE_CHOICES=300,R.MOVED_PERMANENTLY=301,R.FOUND=302,R.SEE_OTHER=303,R.NOT_MODIFIED=304,R.USE_PROXY=305,R.TEMPORARY_REDIRECT=307,R.PERMANENT_REDIRECT=308,R.BAD_REQUEST=400,R.UNAUTHORIZED=401,R.PAYMENT_REQUIRED=402,R.FORBIDDEN=403,R.NOT_FOUND=404,R.METHOD_NOT_ALLOWED=405,R.NOT_ACCEPTABLE=406,R.PROXY_AUTHENTICATION_REQUIRED=407,R.REQUEST_TIMEOUT=408,R.CONFLICT=409,R.GONE=410,R.LENGTH_REQUIRED=411,R.PRECONDITION_FAILED=412,R.PAYLOAD_TOO_LARGE=413,R.REQUEST_URI_TOO_LONG=414,R.UNSUPPORTED_MEDIA_TYPE=415,R.REQUESTED_RANGE_NOT_SATISFIABLE=416,R.EXPECTATION_FAILED=417,R.IM_A_TEAPOT=418,R.MISDIRECTED_REQUEST=421,R.UNPROCESSABLE_ENTITY=422,R.LOCKED=423,R.FAILED_DEPENDENCY=424,R.UPGRADE_REQUIRED=426,R.PRECONDITION_REQUIRED=428,R.TOO_MANY_REQUESTS=429,R.REQUEST_HEADER_FIELDS_TOO_LARGE=431,R.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,R.UNAVAILABLE_FOR_LEGAL_REASONS=451,R.CLIENT_CLOSED_REQUEST=499,R.INTERNAL_SERVER_ERROR=500,R.NOT_IMPLEMENTED=501,R.BAD_GATEWAY=502,R.SERVICE_UNAVAILABLE=503,R.GATEWAY_TIMEOUT=504,R.HTTP_VERSION_NOT_SUPPORTED=505,R.VARIANT_ALSO_NEGOCIATES=506,R.INSUFFICIENT_STORAGE=507,R.LOOP_DETECTED=508,R.NOT_EXTENDED=510,R.NETWORK_AUTHENTICATION_REQUIRED=511,R.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class m{constructor(e,t,s,r,o){this.req=e,this.res=t,this.next=s,this.app=r,this.controller=o}cache(e){const s=[];e.private?s.push("private"):e.public&&s.push("public"),e.noStore&&(e.noCache=!0,s.push("no-store")),e.noCache&&(e.maxAge=0,delete e.sMaxAge,s.push("no-cache")),e.noTransform&&s.push("no-transform"),e.proxyRevalidate&&s.push("proxy-revalidate"),e.mustRevalidate?s.push("must-revalidate"):e.noCache||(t.isNumber(e.staleIfError)&&s.push(`stale-if-error=${e.staleIfError}`),t.isNumber(e.staleWhileRevalidate)&&s.push(`stale-while-revalidate=${e.staleWhileRevalidate}`)),t.isNumber(e.maxAge)&&s.push(`max-age=${e.maxAge}`),t.isNumber(e.sMaxAge)&&s.push(`s-maxage=${e.sMaxAge}`),s.length&&(this.res.setHeader("Cache-Control",s.join(",")),e.noCache&&t.forEachKey({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}close(e){this.res.headersSent||this.res.json(e||this.storage)}destroy(e){var t;e&&this.error(e.message),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){this.send(R.INTERNAL_SERVER_ERROR,{message:e})}file(e){this.res.headersSent||(this.status(R.OK),this.res.sendFile(l.resolve(e)))}getIp(){return d.getClientIp(this.req)||"0.0.0.0"}json(e){this.send(R.OK,e)}notFound(e){this.send(R.NOT_FOUND,{message:e})}prepare(e,t){this.res.headersSent||(this.status(e),this.storage=t)}send(e,t){this.res.headersSent||(this.status(e),this.res.json(t))}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.send(R.OK,{message:e})}unauthorized(e){this.send(R.UNAUTHORIZED,{message:e})}validation(e){this.send(R.BAD_REQUEST,{message:e})}}class x{static extends(e){return E.metadata(x.EXTENDS,e,[])}static middleware(e){return E.metadata(x.MIDDLEWARE,e,[])}static parameters(e){return E.metadata(x.PARAMETERS,e,[])}static path(e,t){return E.metadata(x.PATH,e,t)}static routers(e){return E.metadata(x.ROUTERS,e,[])}}x.EXTENDS=Symbol("EXTENDS"),x.MIDDLEWARE=Symbol("MIDDLEWARE"),x.PARAMETERS=Symbol("PARAMETERS"),x.PATH=Symbol("PATH"),x.ROUTERS=Symbol("ROUTERS");class A extends t.EventEmitter{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(e,p){var h,u;super(),this._app=i(),this._options={},this._base=i.Router(),this._router=i.Router(),this._controllers=[],this._controllers.push(...e.map(e=>t.isConstructor(e)?new e:e)),this._options=t.merge({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=p?p:{}),this._app.use(i.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(i.urlencoded({extended:!0})),this._options.cross&&this._app.use(o(t.isObject(this._options.cross)?this._options.cross:{})),this._app.use(s(this._options.compression)),this._app.use(r(null===(h=this._options.cookie)||void 0===h?void 0:h.secret,this._options.cookie)),this._app.use(n(this._options.session)),this.init(),this._app.use(this._router);const d=(null===(u=this._options.path)||void 0===u?void 0:u.length)?this._options.path:"/";if(this._app.use(d,this._base),this._app.all(d+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(R.NOT_FOUND),t.json({message:"INVALID API"}))}),this._options.public){const e=l.resolve(this._options.public);a.existsSync(e)&&this._app.use(i.static(e)),this._app.get("*path",(t,s)=>{a.existsSync(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(R.NOT_FOUND),s.json({message:'FILE "index.html" NOT FOUND'}))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(R.NOT_FOUND),t.json({message:"INVALID API"}))});this._controllers.forEach(e=>{const s=i.Router(),r=this._middlewares(e),o=x.parameters(e);this._extends(e).forEach(e=>{r.push(...this._middlewares(e)),o.push(...x.parameters(e))}),x.routers(e).forEach(i=>{const n=i.propertyKey.toString();if(t.isFunction(e[n])){if(!t.isFunction(s[i.method]))return this._notFound(i.method);const a=this._handles(e,n,r,o);return s[i.method](i.path,...a,(s,r,i)=>v(this,void 0,void 0,function*(){const a=new m(s,r,i,this,e),p=this._args(a,this._indexes(n,o)),h=yield e[n](...p);a.close(t.isArray(h)||t.isObject(h)?h:void 0)}))}this._notFound(`${e.name}.${n}`)}),this._extends(e).forEach(i=>{x.routers(i).forEach(i=>{const n=i.propertyKey.toString();if(t.isFunction(e[n])){if(!t.isFunction(s[i.method]))return this._notFound(i.method);const a=this._handles(e,n,r,o);return s[i.method](i.path,...a,(s,r,i)=>v(this,void 0,void 0,function*(){const a=new m(s,r,i,this,e),p=this._args(a,this._indexes(n,o)),h=yield e[n](...p);a.close(t.isArray(h)||t.isObject(h)?h:void 0)}))}this._notFound(`${e.constructor.name}.${n}`)})}),this._base.use(x.path(e,"/"),s)})}init(){}error(t,s){e.Log.error(t)}log(t,s){e.Log.info(t)}_args(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_handles(e,s,r,o){return r.filter(e=>e.propertyKey==s).map(s=>{if(s.callback!=t.noop){const r=this._indexes(s.method,o);return(o,i,n)=>v(this,void 0,void 0,function*(){const a=new m(o,i,n,this,e),p=t.isFunction(s.argument)?s.argument(a):s.argument,h=yield s.callback.call(e,...this._args(a,r,p));(t.isArray(h)||t.isObject(h))&&a.close(h)})}this._notFound(s.method)}).filter(t.isFunction)}_extends(e){return x.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...x.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return v(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=T.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=T.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(R.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()}),t=O.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new u.Server(s=>{s.once("data",r=>{s.pause(),s.unshift(r),(22===r[0]?t:e).emit("connection",s),process.nextTick(()=>s.resume())})}).listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t}this._server||(443==this._options.port&&e.listen(80,()=>this.log(this._port(80),"express")),t.listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t)}})}}var N;exports.Methods=void 0,(N=exports.Methods||(exports.Methods={})).ALL="all",N.GET="get",N.POST="post",N.PUT="put",N.HEAD="head",N.DELETE="delete",N.OPTIONS="options",N.PATCH="patch";const I=e=>t=>(s,r)=>{x.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},S=I(exports.Methods.ALL),D=I(exports.Methods.DELETE),g=I(exports.Methods.GET),y=I(exports.Methods.HEAD),f=I(exports.Methods.OPTIONS),L=I(exports.Methods.PATCH),C=I(exports.Methods.POST),U=I(exports.Methods.PUT),P=e=>t=>(s,r,o)=>{x.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},F=P(({app:e})=>e),M=P(({argument:e})=>e),b=(e,s)=>t.isUndefined(s)?e:e[s],k=P(({ctx:e,key:t})=>{var s,r;return b(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{},t)}),q=P(({ctx:e,key:t})=>{var s,r;return b(null!==(r=null===(s=e.req)||void 0===s?void 0:s.cookies)&&void 0!==r?r:{},t)}),w=P(({ctx:e})=>e),j=P(({ctx:e})=>{var t,s;return null!==(s=null===(t=e.req)||void 0===t?void 0:t.files)&&void 0!==s?s:{}}),H=P(({ctx:e,key:t})=>{var s,r;return b(null!==(r=null===(s=e.req)||void 0===s?void 0:s.headers)&&void 0!==r?r:{},t)}),G=P(({ctx:e,key:t})=>{var s,r;return b(null!==(r=null===(s=e.req)||void 0===s?void 0:s.params)&&void 0!==r?r:{},t)}),K=P(({ctx:e,key:t})=>{var s,r,o;return String(null!==(o=b(null!==(r=null===(s=e.req)||void 0===s?void 0:s.query)&&void 0!==r?r:{},t))&&void 0!==o?o:"")}),Q=P(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),$=(e,s)=>(r,o)=>{const i=t.uuidv7();w()(r,i,0),x.middleware(r).push({method:i,argument:s,propertyKey:o,callback:e})},Y=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},V=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},W=(e,s)=>{const r=t.uuidv7()+"."+s;return a.existsSync(l.join(e,r))?W(e,s):r};exports.All=S,exports.App=F,exports.Application=A,exports.Argument=M,exports.Body=k,exports.Cache=e=>(t,s,r)=>{$(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},exports.Context=m,exports.Controller=e=>t=>{x.path(t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=q,exports.Ctx=w,exports.Delete=D,exports.Extends=e=>t=>{x.extends(t).push(e)},exports.Files=j,exports.Get=g,exports.Head=y,exports.Headers=H,exports.Metadata=x,exports.Middleware=(e,s)=>(r,o)=>{let i=t.noop;if(t.isString(o)){const s=r;t.isFunction(s[e])&&(i=s[e])}x.middleware(r).push({method:e,argument:s,propertyKey:o,callback:i})},exports.Options=f,exports.Params=G,exports.Parse=e=>{const s=t.Validation.object(t.isFunction(e)?e(t.Validation):e).parse();return(e,t,r)=>{$(e=>v(void 0,void 0,void 0,function*(){const{error:t,message:r,value:o}=yield s.validateAsync(e.req.body);if(t)return e.validation(null!=r?r:t);e.req.body=o,e.next()}))(e,t,r)}},exports.Patch=L,exports.Post=C,exports.Put=U,exports.Query=K,exports.Session=Q,exports.Status=R,exports.Upload=e=>{const s=t.merge({},e),r=c.diskStorage({destination(e,t,r){var o;const i=V(s,t.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,t,r){var o;const i=V(s,t.fieldname);r(null,W(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",Y(t.originalname)))}}),o=Math.max(...Object.values(s).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),i=c({storage:r,fileFilter(e,t,r){var o;const i=V(s,t.fieldname);return i?((e,t)=>!t.length||t.includes(Y(e.originalname))||t.includes(e.mimetype.toLowerCase()))(t,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${t.fieldname}"`)):r(new Error(`UPLOAD FIELD "${t.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*o*1024}}).fields(Object.keys(s).map(e=>{var t,r;return{name:e,maxCount:null!==(r=null===(t=s[e])||void 0===t?void 0:t.count)&&void 0!==r?r:1}}));return(e,t,s)=>{$(e=>{i(e.req,e.res,t=>{if(t)return"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t);e.next()})})(e,t,s)}},exports.Use=$,exports.methodFactory=I,exports.parameterFactory=P;
7
+ "use strict";var e=require("@andrewcaires/decorator"),t=require("@andrewcaires/node"),s=require("@andrewcaires/utils.js"),r=require("compression"),o=require("cookie-parser"),i=require("cors"),n=require("express"),a=require("express-session"),p=require("fs"),u=require("http"),l=require("https"),h=require("net"),d=require("path"),E=require("request-ip"),c=require("multer");function _(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var T=_(u),O=_(l);function v(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{p(r.next(e))}catch(e){i(e)}}function a(e){try{p(r.throw(e))}catch(e){i(e)}}function p(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}p((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class R{}R.CONTINUE=100,R.SWITCHING_PROTOCOLS=101,R.PROCESSING=102,R.OK=200,R.CREATED=201,R.ACCEPTED=202,R.NON_AUTHORITATIVE_INFORMATION=203,R.NO_CONTENT=204,R.RESET_CONTENT=205,R.PARTIAL_CONTENT=206,R.MULTI_STATUS=207,R.ALREADY_REPORTED=208,R.IM_USED=226,R.MULTIPLE_CHOICES=300,R.MOVED_PERMANENTLY=301,R.FOUND=302,R.SEE_OTHER=303,R.NOT_MODIFIED=304,R.USE_PROXY=305,R.TEMPORARY_REDIRECT=307,R.PERMANENT_REDIRECT=308,R.BAD_REQUEST=400,R.UNAUTHORIZED=401,R.PAYMENT_REQUIRED=402,R.FORBIDDEN=403,R.NOT_FOUND=404,R.METHOD_NOT_ALLOWED=405,R.NOT_ACCEPTABLE=406,R.PROXY_AUTHENTICATION_REQUIRED=407,R.REQUEST_TIMEOUT=408,R.CONFLICT=409,R.GONE=410,R.LENGTH_REQUIRED=411,R.PRECONDITION_FAILED=412,R.PAYLOAD_TOO_LARGE=413,R.REQUEST_URI_TOO_LONG=414,R.UNSUPPORTED_MEDIA_TYPE=415,R.REQUESTED_RANGE_NOT_SATISFIABLE=416,R.EXPECTATION_FAILED=417,R.IM_A_TEAPOT=418,R.MISDIRECTED_REQUEST=421,R.UNPROCESSABLE_ENTITY=422,R.LOCKED=423,R.FAILED_DEPENDENCY=424,R.UPGRADE_REQUIRED=426,R.PRECONDITION_REQUIRED=428,R.TOO_MANY_REQUESTS=429,R.REQUEST_HEADER_FIELDS_TOO_LARGE=431,R.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,R.UNAVAILABLE_FOR_LEGAL_REASONS=451,R.CLIENT_CLOSED_REQUEST=499,R.INTERNAL_SERVER_ERROR=500,R.NOT_IMPLEMENTED=501,R.BAD_GATEWAY=502,R.SERVICE_UNAVAILABLE=503,R.GATEWAY_TIMEOUT=504,R.HTTP_VERSION_NOT_SUPPORTED=505,R.VARIANT_ALSO_NEGOCIATES=506,R.INSUFFICIENT_STORAGE=507,R.LOOP_DETECTED=508,R.NOT_EXTENDED=510,R.NETWORK_AUTHENTICATION_REQUIRED=511,R.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class x extends Error{constructor(e,t=R.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class N extends x{constructor(e){super(e,R.UNPROCESSABLE_ENTITY)}}class A{constructor(e,t,s,r,o){this.req=e,this.res=t,this.next=s,this.app=r,this.controller=o}cache(e){const t=[];e.private?t.push("private"):e.public&&t.push("public"),e.noStore&&(e.noCache=!0,t.push("no-store")),e.noCache&&(e.maxAge=0,delete e.sMaxAge,t.push("no-cache")),e.noTransform&&t.push("no-transform"),e.proxyRevalidate&&t.push("proxy-revalidate"),e.mustRevalidate?t.push("must-revalidate"):e.noCache||(s.isNumber(e.staleIfError)&&t.push(`stale-if-error=${e.staleIfError}`),s.isNumber(e.staleWhileRevalidate)&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`)),s.isNumber(e.maxAge)&&t.push(`max-age=${e.maxAge}`),s.isNumber(e.sMaxAge)&&t.push(`s-maxage=${e.sMaxAge}`),t.length&&(this.res.setHeader("Cache-Control",t.join(",")),e.noCache&&s.forEachKey({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}close(e){this.res.headersSent||this.res.json(e||this.storage)}cookie(e,t,r){s.isUndefined(t)?this.res.clearCookie(e):this.res.cookie(e,t,null!=r?r:{})}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){var t;let s=null!==(t=e.toString())&&void 0!==t?t:"",r=R.INTERNAL_SERVER_ERROR;e instanceof Error&&(s=e.message,e instanceof x&&(r=e.status)),this.send(r,{error:s})}file(e){this.res.headersSent||(this.status(R.OK),this.res.sendFile(d.resolve(e)))}getIp(){return E.getClientIp(this.req)||"0.0.0.0"}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}json(e){this.send(R.OK,e)}prepare(e,t){this.res.headersSent||(this.status(e),this.storage=t)}send(e,t){this.res.headersSent||(this.status(e),this.res.json(t))}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.send(R.OK,{message:e})}}class m{static extends(t){return e.metadata(m.EXTENDS,t,[])}static middleware(t){return e.metadata(m.MIDDLEWARE,t,[])}static parameters(t){return e.metadata(m.PARAMETERS,t,[])}static path(t,s){return e.metadata(m.PATH,t,s)}static routers(t){return e.metadata(m.ROUTERS,t,[])}}m.EXTENDS=Symbol("EXTENDS"),m.MIDDLEWARE=Symbol("MIDDLEWARE"),m.PARAMETERS=Symbol("PARAMETERS"),m.PATH=Symbol("PATH"),m.ROUTERS=Symbol("ROUTERS");class I extends s.EventEmitter{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(t,u){var l,h;super(),this._app=n(),this._options={},this._base=n.Router(),this._router=n.Router(),this._controllers=[],this._controllers.push(...t.map(t=>s.isConstructor(t)?new t(...e.getInjectionArgs(t)):t)),this._options=s.merge({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=u?u:{}),this._app.use(n.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(n.urlencoded({extended:!0})),this._options.cross&&this._app.use(i(s.isObject(this._options.cross)?this._options.cross:{})),this._app.use(r(this._options.compression)),this._app.use(o(null===(l=this._options.cookie)||void 0===l?void 0:l.secret,this._options.cookie)),this._app.use(a(this._options.session)),this.init(),this._app.use(this._router);const E=(null===(h=this._options.path)||void 0===h?void 0:h.length)?this._options.path:"/";if(this._app.use(E,this._base),this._app.all(E+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(R.NOT_FOUND),t.json({message:"INVALID API"}))}),this._options.public){const e=d.resolve(this._options.public);p.existsSync(e)&&this._app.use(n.static(e)),this._app.get("*path",(t,s)=>{p.existsSync(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(R.NOT_FOUND),s.json({message:'FILE "index.html" NOT FOUND'}))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(R.NOT_FOUND),t.json({message:"INVALID API"}))});this._controllers.forEach(e=>{const t=n.Router(),r=this._middlewares(e),o=m.parameters(e);this._extends(e).forEach(e=>{r.push(...this._middlewares(e)),o.push(...m.parameters(e))}),m.routers(e).forEach(i=>{const n=i.propertyKey.toString();if(s.isFunction(e[n])){if(!s.isFunction(t[i.method]))return this._notFound(i.method);const a=this._handles(e,n,r,o);return t[i.method](i.path,...a,(t,r,i)=>v(this,void 0,void 0,function*(){const a=new A(t,r,i,this,e),p=this._args(a,this._indexes(n,o)),u=yield e[n](...p);a.close(s.isArray(u)||s.isObject(u)?u:void 0)}))}this._notFound(`${e.name}.${n}`)}),this._extends(e).forEach(i=>{m.routers(i).forEach(i=>{const n=i.propertyKey.toString();if(s.isFunction(e[n])){if(!s.isFunction(t[i.method]))return this._notFound(i.method);const a=this._handles(e,n,r,o);return t[i.method](i.path,...a,(t,r,i)=>v(this,void 0,void 0,function*(){const a=new A(t,r,i,this,e),p=this._args(a,this._indexes(n,o)),u=yield e[n](...p);a.close(s.isArray(u)||s.isObject(u)?u:void 0)}))}this._notFound(`${e.constructor.name}.${n}`)})}),this._base.use(m.path(e,"/"),t)})}init(){}error(e,s){t.Log.error(e)}log(e,s){t.Log.info(e)}_args(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_handles(e,t,r,o){return r.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=s.noop){const r=this._indexes(t.method,o);return(o,i,n)=>v(this,void 0,void 0,function*(){const a=new A(o,i,n,this,e),p=s.isFunction(t.argument)?t.argument(a):t.argument,u=yield t.callback.call(e,...this._args(a,r,p));(s.isArray(u)||s.isObject(u))&&a.close(u)})}this._notFound(t.method)}).filter(s.isFunction)}_extends(e){return m.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...m.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return v(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=T.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=T.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(R.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()}),t=O.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new h.Server(s=>{s.once("data",r=>{s.pause(),s.unshift(r),(22===r[0]?t:e).emit("connection",s),process.nextTick(()=>s.resume())})}).listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t}this._server||(443==this._options.port&&e.listen(80,()=>this.log(this._port(80),"express")),t.listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t)}})}}var S;exports.Methods=void 0,(S=exports.Methods||(exports.Methods={})).ALL="all",S.GET="get",S.POST="post",S.PUT="put",S.HEAD="head",S.DELETE="delete",S.OPTIONS="options",S.PATCH="patch";const D=e=>t=>(s,r)=>{m.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},g=D(exports.Methods.ALL),f=D(exports.Methods.DELETE),y=D(exports.Methods.GET),L=D(exports.Methods.HEAD),U=D(exports.Methods.OPTIONS),C=D(exports.Methods.PATCH),P=D(exports.Methods.POST),F=D(exports.Methods.PUT),M=e=>t=>(s,r,o)=>{m.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},b=M(({app:e})=>e),k=M(({argument:e})=>e),q=(e,t)=>s.isUndefined(t)?e:e[t],w=M(({ctx:e,key:t})=>{var s,r;return q(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{},t)}),j=M(({ctx:e,key:t})=>{var s,r;return q(null!==(r=null===(s=e.req)||void 0===s?void 0:s.cookies)&&void 0!==r?r:{},t)}),H=M(({ctx:e})=>e),$=M(({ctx:e})=>{var t,s;return null!==(s=null===(t=e.req)||void 0===t?void 0:t.files)&&void 0!==s?s:{}}),G=M(({ctx:e,key:t})=>{var s,r;return q(null!==(r=null===(s=e.req)||void 0===s?void 0:s.headers)&&void 0!==r?r:{},t)}),V=M(({ctx:e,key:t})=>{var s,r;return q(null!==(r=null===(s=e.req)||void 0===s?void 0:s.params)&&void 0!==r?r:{},t)}),K=M(({ctx:e,key:t})=>{var s,r,o;return String(null!==(o=q(null!==(r=null===(s=e.req)||void 0===s?void 0:s.query)&&void 0!==r?r:{},t))&&void 0!==o?o:"")}),Y=M(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),Q=(e,t)=>(r,o)=>{const i=s.uuidv7();H()(r,i,0),m.middleware(r).push({method:i,argument:t,propertyKey:o,callback:e})},W=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},B=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},X=(e,t)=>{const r=s.uuidv7()+"."+t;return p.existsSync(d.join(e,r))?X(e,t):r};exports.All=g,exports.App=b,exports.Application=I,exports.Argument=k,exports.Body=w,exports.Cache=e=>(t,s,r)=>{Q(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},exports.Context=A,exports.Controller=e=>t=>{m.path(t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=j,exports.Ctx=H,exports.Delete=f,exports.Extends=e=>t=>{m.extends(t).push(e)},exports.Files=$,exports.Get=y,exports.Head=L,exports.Headers=G,exports.InternalServerError=class extends x{constructor(e="Internal server error"){super(e,R.INTERNAL_SERVER_ERROR)}},exports.Metadata=m,exports.Middleware=(e,t)=>(r,o)=>{let i=s.noop;if(s.isString(o)){const t=r;s.isFunction(t[e])&&(i=t[e])}m.middleware(r).push({method:e,argument:t,propertyKey:o,callback:i})},exports.NotFoundError=class extends x{constructor(e="Record not found"){super(e,R.NOT_FOUND)}},exports.Options=U,exports.Params=V,exports.Parse=e=>{const t=s.Validation.object(s.isFunction(e)?e(s.Validation):e).parse();return(e,s,r)=>{Q(e=>v(void 0,void 0,void 0,function*(){var s,r;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{});if(o)return e.error(new N(null!=i?i:o));e.req.body=n,e.next()}))(e,s,r)}},exports.Patch=C,exports.Post=P,exports.Put=F,exports.Query=K,exports.ResponseError=x,exports.Session=Y,exports.Status=R,exports.UnauthorizedError=class extends x{constructor(e="Unauthorized"){super(e,R.UNAUTHORIZED)}},exports.Upload=e=>{const t=s.merge({},e),r=c.diskStorage({destination(e,s,r){var o;const i=B(t,s.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,s,r){var o;const i=B(t,s.fieldname);r(null,X(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",W(s.originalname)))}}),o=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),i=c({storage:r,fileFilter(e,s,r){var o;const i=B(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(W(e.originalname))||t.includes(e.mimetype.toLowerCase()))(s,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${s.fieldname}"`)):r(new Error(`UPLOAD FIELD "${s.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*o*1024}}).fields(Object.keys(t).map(e=>{var s,r;return{name:e,maxCount:null!==(r=null===(s=t[e])||void 0===s?void 0:s.count)&&void 0!==r?r:1}}));return(e,t,s)=>{Q(e=>{i(e.req,e.res,t=>{if(t)return"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t);e.next()})})(e,t,s)}},exports.Use=Q,exports.ValidationError=N,exports.methodFactory=D,exports.parameterFactory=M;
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  /*!
2
- * @andrewcaires/express v1.2.9
3
- * Decorators for express
2
+ * @andrewcaires/express v2.0.1
3
+ * Decorators for express
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
7
  import { TypeAnyObject, TypeAnyFunction, Validation, TypeObject, ValidationBase, EventEmitter, TypeAnyConstructor } from '@andrewcaires/utils.js';
8
- import { Request, Response, NextFunction, Express, Router } from 'express';
8
+ import { Request, Response, NextFunction, CookieOptions, Express, Router } from 'express';
9
9
  import * as http from 'http';
10
10
  import * as https from 'https';
11
11
  import { OptionsJson } from 'body-parser';
@@ -24,18 +24,17 @@ declare class Context<T = any, A = Application> {
24
24
  constructor(req: Request, res: Response, next: NextFunction, app: A, controller: T);
25
25
  cache(options: ICache): void;
26
26
  close(value?: TypeAnyObject): void;
27
+ cookie(key: string, value?: string, options?: CookieOptions): void;
27
28
  destroy(error?: Error): void;
28
- error(message: string): void;
29
+ error(error: string | Error): void;
29
30
  file(path: string): void;
30
31
  getIp(): string;
32
+ getUrl(): string;
31
33
  json(value?: TypeAnyObject | Array<TypeAnyObject>): void;
32
- notFound(message: string): void;
33
34
  prepare(status: number, value: TypeAnyObject | Array<TypeAnyObject>): void;
34
35
  send(status: number, value?: TypeAnyObject | Array<TypeAnyObject>): void;
35
36
  status(value?: number): number;
36
37
  success(message: string): void;
37
- unauthorized(message: string): void;
38
- validation(message: string): void;
39
38
  }
40
39
 
41
40
  interface IArgs {
@@ -145,6 +144,251 @@ interface IUse {
145
144
  propertyKey: string | symbol;
146
145
  }
147
146
 
147
+ interface ExternalDocumentationObject {
148
+ description?: string;
149
+ url: string;
150
+ }
151
+
152
+ interface ExampleObject {
153
+ summary?: string;
154
+ description?: string;
155
+ value?: any;
156
+ externalValue?: string;
157
+ }
158
+
159
+ interface HeaderObject extends Omit<ParameterObject, "name" | "in"> {
160
+ }
161
+
162
+ interface ReferenceObject {
163
+ $ref: string;
164
+ }
165
+
166
+ interface EncodingObject {
167
+ contentType?: string;
168
+ headers?: Record<string, HeaderObject | ReferenceObject>;
169
+ style?: string;
170
+ explode?: boolean;
171
+ allowReserved?: boolean;
172
+ }
173
+
174
+ interface SchemaObject {
175
+ $id?: string;
176
+ $schema?: string;
177
+ $ref?: string;
178
+ $comment?: string;
179
+ type?: string | Array<string>;
180
+ enum?: Array<any>;
181
+ const?: any;
182
+ format?: string;
183
+ default?: any;
184
+ examples?: Array<any>;
185
+ properties?: Record<string, SchemaObject>;
186
+ required?: Array<string>;
187
+ additionalProperties?: boolean | SchemaObject;
188
+ patternProperties?: Record<string, SchemaObject>;
189
+ propertyNames?: SchemaObject;
190
+ items?: SchemaObject | Array<SchemaObject>;
191
+ minItems?: number;
192
+ maxItems?: number;
193
+ uniqueItems?: boolean;
194
+ minimum?: number;
195
+ maximum?: number;
196
+ exclusiveMinimum?: number;
197
+ exclusiveMaximum?: number;
198
+ multipleOf?: number;
199
+ minLength?: number;
200
+ maxLength?: number;
201
+ pattern?: string;
202
+ allOf?: Array<SchemaObject>;
203
+ anyOf?: Array<SchemaObject>;
204
+ oneOf?: Array<SchemaObject>;
205
+ not?: SchemaObject;
206
+ if?: SchemaObject;
207
+ then?: SchemaObject;
208
+ else?: SchemaObject;
209
+ readOnly?: boolean;
210
+ writeOnly?: boolean;
211
+ deprecated?: boolean;
212
+ nullable?: boolean;
213
+ description?: string;
214
+ title?: string;
215
+ }
216
+
217
+ interface MediaTypeObject {
218
+ schema?: SchemaObject;
219
+ example?: any;
220
+ examples?: Record<string, ExampleObject | ReferenceObject>;
221
+ encoding?: Record<string, EncodingObject>;
222
+ }
223
+
224
+ interface ParameterObject {
225
+ name: string;
226
+ in: "query" | "header" | "path" | "cookie";
227
+ description?: string;
228
+ required?: boolean;
229
+ deprecated?: boolean;
230
+ allowEmptyValue?: boolean;
231
+ style?: string;
232
+ explode?: boolean;
233
+ allowReserved?: boolean;
234
+ schema?: SchemaObject;
235
+ example?: any;
236
+ examples?: Record<string, ExampleObject | ReferenceObject>;
237
+ content?: Record<string, MediaTypeObject>;
238
+ }
239
+
240
+ interface RequestBodyObject {
241
+ description?: string;
242
+ content: Record<string, MediaTypeObject>;
243
+ required?: boolean;
244
+ }
245
+
246
+ interface ServerVariableObject {
247
+ enum?: Array<string>;
248
+ default: string;
249
+ description?: string;
250
+ }
251
+
252
+ interface ServerObject {
253
+ url: string;
254
+ description?: string;
255
+ variables?: Record<string, ServerVariableObject>;
256
+ }
257
+
258
+ interface LinkObject {
259
+ operationRef?: string;
260
+ operationId?: string;
261
+ parameters?: Record<string, any>;
262
+ requestBody?: any;
263
+ description?: string;
264
+ server?: ServerObject;
265
+ }
266
+
267
+ interface ResponseObject {
268
+ description: string;
269
+ headers?: Record<string, HeaderObject | ReferenceObject>;
270
+ content?: Record<string, MediaTypeObject>;
271
+ links?: Record<string, LinkObject | ReferenceObject>;
272
+ }
273
+
274
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
275
+
276
+ type SecurityRequirementObject = Record<string, Array<string>>;
277
+
278
+ interface OperationObject {
279
+ tags?: Array<string>;
280
+ summary?: string;
281
+ description?: string;
282
+ externalDocs?: ExternalDocumentationObject;
283
+ operationId?: string;
284
+ parameters?: Array<ParameterObject | ReferenceObject>;
285
+ requestBody?: RequestBodyObject | ReferenceObject;
286
+ responses: ResponsesObject;
287
+ callbacks?: Record<string, CallbackObject | ReferenceObject>;
288
+ deprecated?: boolean;
289
+ security?: Array<SecurityRequirementObject>;
290
+ servers?: Array<ServerObject>;
291
+ }
292
+
293
+ interface PathItemObject {
294
+ $ref?: string;
295
+ summary?: string;
296
+ description?: string;
297
+ get?: OperationObject;
298
+ put?: OperationObject;
299
+ post?: OperationObject;
300
+ delete?: OperationObject;
301
+ options?: OperationObject;
302
+ head?: OperationObject;
303
+ patch?: OperationObject;
304
+ trace?: OperationObject;
305
+ servers?: Array<ServerObject>;
306
+ parameters?: Array<ParameterObject | ReferenceObject>;
307
+ }
308
+
309
+ type CallbackObject = Record<string, PathItemObject>;
310
+
311
+ interface OAuthFlowObject {
312
+ authorizationUrl?: string;
313
+ tokenUrl?: string;
314
+ refreshUrl?: string;
315
+ scopes: Record<string, string>;
316
+ }
317
+
318
+ interface OAuthFlowsObject {
319
+ implicit?: OAuthFlowObject;
320
+ password?: OAuthFlowObject;
321
+ clientCredentials?: OAuthFlowObject;
322
+ authorizationCode?: OAuthFlowObject;
323
+ }
324
+
325
+ interface SecuritySchemeObject {
326
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect";
327
+ description?: string;
328
+ name?: string;
329
+ in?: "query" | "header" | "cookie";
330
+ scheme?: string;
331
+ bearerFormat?: string;
332
+ flows?: OAuthFlowsObject;
333
+ openIdConnectUrl?: string;
334
+ }
335
+
336
+ interface ComponentsObject {
337
+ schemas?: Record<string, SchemaObject>;
338
+ responses?: Record<string, ResponseObject | ReferenceObject>;
339
+ parameters?: Record<string, ParameterObject | ReferenceObject>;
340
+ examples?: Record<string, ExampleObject | ReferenceObject>;
341
+ requestBodies?: Record<string, RequestBodyObject | ReferenceObject>;
342
+ headers?: Record<string, HeaderObject | ReferenceObject>;
343
+ securitySchemes?: Record<string, SecuritySchemeObject | ReferenceObject>;
344
+ links?: Record<string, LinkObject | ReferenceObject>;
345
+ callbacks?: Record<string, CallbackObject | ReferenceObject>;
346
+ pathItems?: Record<string, PathItemObject | ReferenceObject>;
347
+ }
348
+
349
+ interface ContactObject {
350
+ name?: string;
351
+ url?: string;
352
+ email?: string;
353
+ }
354
+
355
+ interface LicenseObject {
356
+ name: string;
357
+ identifier?: string;
358
+ url?: string;
359
+ }
360
+
361
+ interface InfoObject {
362
+ title: string;
363
+ summary?: string;
364
+ description?: string;
365
+ termsOfService?: string;
366
+ contact?: ContactObject;
367
+ license?: LicenseObject;
368
+ version: string;
369
+ }
370
+
371
+ type PathsObject = Record<string, PathItemObject>;
372
+
373
+ interface TagObject {
374
+ name: string;
375
+ description?: string;
376
+ externalDocs?: ExternalDocumentationObject;
377
+ }
378
+
379
+ interface OpenAPIObject {
380
+ openapi: string;
381
+ info: InfoObject;
382
+ jsonSchemaDialect?: string;
383
+ servers?: Array<ServerObject>;
384
+ paths?: PathsObject;
385
+ webhooks?: Record<string, PathItemObject>;
386
+ components?: ComponentsObject;
387
+ security?: Array<SecurityRequirementObject>;
388
+ tags?: Array<TagObject>;
389
+ externalDocs?: ExternalDocumentationObject;
390
+ }
391
+
148
392
  type ParseFunction = (_$: typeof Validation) => TypeObject<ValidationBase>;
149
393
 
150
394
  declare class Application extends EventEmitter {
@@ -226,6 +470,27 @@ declare const Query: (key?: string) => ParameterDecorator;
226
470
 
227
471
  declare const Session: (key?: string) => ParameterDecorator;
228
472
 
473
+ declare class ResponseError extends Error {
474
+ readonly status: number;
475
+ constructor(message: string, status?: number);
476
+ }
477
+
478
+ declare class InternalServerError extends ResponseError {
479
+ constructor(message?: string);
480
+ }
481
+
482
+ declare class NotFoundError extends ResponseError {
483
+ constructor(message?: string);
484
+ }
485
+
486
+ declare class UnauthorizedError extends ResponseError {
487
+ constructor(message?: string);
488
+ }
489
+
490
+ declare class ValidationError extends ResponseError {
491
+ constructor(message: string);
492
+ }
493
+
229
494
  declare class Metadata {
230
495
  static readonly EXTENDS: unique symbol;
231
496
  static readonly MIDDLEWARE: unique symbol;
@@ -305,5 +570,5 @@ declare class Status {
305
570
  static readonly NETWORK_CONNECTION_TIMEOUT_ERROR = 599;
306
571
  }
307
572
 
308
- export { All, App, Application, Argument, Body, Cache, Context, Controller, Cookies, Ctx, Delete, Extends, Files, Get, Head, Headers, Metadata, Methods, Middleware, Options, Params, Parse, Patch, Post, Put, Query, Session, Status, Upload, Use, methodFactory, parameterFactory };
309
- export type { IArgs, ICache, ICookie, IFile, IHandler, IMiddlewares, IOptions, IParameter, IRouter, IStore, IUpload, IUse, ParseFunction };
573
+ export { All, App, Application, Argument, Body, Cache, Context, Controller, Cookies, Ctx, Delete, Extends, Files, Get, Head, Headers, InternalServerError, Metadata, Methods, Middleware, NotFoundError, Options, Params, Parse, Patch, Post, Put, Query, ResponseError, Session, Status, UnauthorizedError, Upload, Use, ValidationError, methodFactory, parameterFactory };
574
+ export type { CallbackObject, ComponentsObject, ContactObject, EncodingObject, ExampleObject, ExternalDocumentationObject, HeaderObject, IArgs, ICache, ICookie, IFile, IHandler, IMiddlewares, IOptions, IParameter, IRouter, IStore, IUpload, IUse, InfoObject, LicenseObject, LinkObject, MediaTypeObject, OAuthFlowObject, OAuthFlowsObject, OpenAPIObject, OperationObject, ParameterObject, ParseFunction, PathItemObject, PathsObject, ReferenceObject, RequestBodyObject, ResponseObject, ResponsesObject, SchemaObject, SecurityRequirementObject, SecuritySchemeObject, ServerObject, ServerVariableObject, TagObject };
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v1.2.9
3
- * Decorators for express
2
+ * @andrewcaires/express v2.0.1
3
+ * Decorators for express
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- import{Log as e}from"@andrewcaires/node";import{isNumber as t,forEachKey as s,EventEmitter as r,isConstructor as o,merge as i,isObject as n,isFunction as a,noop as h,isArray as l,isUndefined as p,uuidv7 as E,isString as u,Validation as d}from"@andrewcaires/utils.js";import _ from"compression";import c from"cookie-parser";import T from"cors";import O,{Router as m,json as v,urlencoded as R}from"express";import N from"express-session";import{existsSync as A}from"fs";import*as I from"http";import*as D from"https";import{Server as S}from"net";import{resolve as f,join as g}from"path";import{getClientIp as L}from"request-ip";import{metadata as y}from"@andrewcaires/decorator";import x,{diskStorage as U}from"multer";function C(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{h(r.next(e))}catch(e){i(e)}}function a(e){try{h(r.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}h((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class P{}P.CONTINUE=100,P.SWITCHING_PROTOCOLS=101,P.PROCESSING=102,P.OK=200,P.CREATED=201,P.ACCEPTED=202,P.NON_AUTHORITATIVE_INFORMATION=203,P.NO_CONTENT=204,P.RESET_CONTENT=205,P.PARTIAL_CONTENT=206,P.MULTI_STATUS=207,P.ALREADY_REPORTED=208,P.IM_USED=226,P.MULTIPLE_CHOICES=300,P.MOVED_PERMANENTLY=301,P.FOUND=302,P.SEE_OTHER=303,P.NOT_MODIFIED=304,P.USE_PROXY=305,P.TEMPORARY_REDIRECT=307,P.PERMANENT_REDIRECT=308,P.BAD_REQUEST=400,P.UNAUTHORIZED=401,P.PAYMENT_REQUIRED=402,P.FORBIDDEN=403,P.NOT_FOUND=404,P.METHOD_NOT_ALLOWED=405,P.NOT_ACCEPTABLE=406,P.PROXY_AUTHENTICATION_REQUIRED=407,P.REQUEST_TIMEOUT=408,P.CONFLICT=409,P.GONE=410,P.LENGTH_REQUIRED=411,P.PRECONDITION_FAILED=412,P.PAYLOAD_TOO_LARGE=413,P.REQUEST_URI_TOO_LONG=414,P.UNSUPPORTED_MEDIA_TYPE=415,P.REQUESTED_RANGE_NOT_SATISFIABLE=416,P.EXPECTATION_FAILED=417,P.IM_A_TEAPOT=418,P.MISDIRECTED_REQUEST=421,P.UNPROCESSABLE_ENTITY=422,P.LOCKED=423,P.FAILED_DEPENDENCY=424,P.UPGRADE_REQUIRED=426,P.PRECONDITION_REQUIRED=428,P.TOO_MANY_REQUESTS=429,P.REQUEST_HEADER_FIELDS_TOO_LARGE=431,P.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,P.UNAVAILABLE_FOR_LEGAL_REASONS=451,P.CLIENT_CLOSED_REQUEST=499,P.INTERNAL_SERVER_ERROR=500,P.NOT_IMPLEMENTED=501,P.BAD_GATEWAY=502,P.SERVICE_UNAVAILABLE=503,P.GATEWAY_TIMEOUT=504,P.HTTP_VERSION_NOT_SUPPORTED=505,P.VARIANT_ALSO_NEGOCIATES=506,P.INSUFFICIENT_STORAGE=507,P.LOOP_DETECTED=508,P.NOT_EXTENDED=510,P.NETWORK_AUTHENTICATION_REQUIRED=511,P.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class F{constructor(e,t,s,r,o){this.req=e,this.res=t,this.next=s,this.app=r,this.controller=o}cache(e){const r=[];e.private?r.push("private"):e.public&&r.push("public"),e.noStore&&(e.noCache=!0,r.push("no-store")),e.noCache&&(e.maxAge=0,delete e.sMaxAge,r.push("no-cache")),e.noTransform&&r.push("no-transform"),e.proxyRevalidate&&r.push("proxy-revalidate"),e.mustRevalidate?r.push("must-revalidate"):e.noCache||(t(e.staleIfError)&&r.push(`stale-if-error=${e.staleIfError}`),t(e.staleWhileRevalidate)&&r.push(`stale-while-revalidate=${e.staleWhileRevalidate}`)),t(e.maxAge)&&r.push(`max-age=${e.maxAge}`),t(e.sMaxAge)&&r.push(`s-maxage=${e.sMaxAge}`),r.length&&(this.res.setHeader("Cache-Control",r.join(",")),e.noCache&&s({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}close(e){this.res.headersSent||this.res.json(e||this.storage)}destroy(e){var t;e&&this.error(e.message),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){this.send(P.INTERNAL_SERVER_ERROR,{message:e})}file(e){this.res.headersSent||(this.status(P.OK),this.res.sendFile(f(e)))}getIp(){return L(this.req)||"0.0.0.0"}json(e){this.send(P.OK,e)}notFound(e){this.send(P.NOT_FOUND,{message:e})}prepare(e,t){this.res.headersSent||(this.status(e),this.storage=t)}send(e,t){this.res.headersSent||(this.status(e),this.res.json(t))}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.send(P.OK,{message:e})}unauthorized(e){this.send(P.UNAUTHORIZED,{message:e})}validation(e){this.send(P.BAD_REQUEST,{message:e})}}class M{static extends(e){return y(M.EXTENDS,e,[])}static middleware(e){return y(M.MIDDLEWARE,e,[])}static parameters(e){return y(M.PARAMETERS,e,[])}static path(e,t){return y(M.PATH,e,t)}static routers(e){return y(M.ROUTERS,e,[])}}M.EXTENDS=Symbol("EXTENDS"),M.MIDDLEWARE=Symbol("MIDDLEWARE"),M.PARAMETERS=Symbol("PARAMETERS"),M.PATH=Symbol("PATH"),M.ROUTERS=Symbol("ROUTERS");class b extends r{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(e,t){var s,r;super(),this._app=O(),this._options={},this._base=m(),this._router=m(),this._controllers=[],this._controllers.push(...e.map(e=>o(e)?new e:e)),this._options=i({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=t?t:{}),this._app.use(v(this._options.json)),this._app.disable("x-powered-by"),this._app.use(R({extended:!0})),this._options.cross&&this._app.use(T(n(this._options.cross)?this._options.cross:{})),this._app.use(_(this._options.compression)),this._app.use(c(null===(s=this._options.cookie)||void 0===s?void 0:s.secret,this._options.cookie)),this._app.use(N(this._options.session)),this.init(),this._app.use(this._router);const h=(null===(r=this._options.path)||void 0===r?void 0:r.length)?this._options.path:"/";if(this._app.use(h,this._base),this._app.all(h+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(P.NOT_FOUND),t.json({message:"INVALID API"}))}),this._options.public){const e=f(this._options.public);A(e)&&this._app.use(O.static(e)),this._app.get("*path",(t,s)=>{A(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(P.NOT_FOUND),s.json({message:'FILE "index.html" NOT FOUND'}))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(P.NOT_FOUND),t.json({message:"INVALID API"}))});this._controllers.forEach(e=>{const t=m(),s=this._middlewares(e),r=M.parameters(e);this._extends(e).forEach(e=>{s.push(...this._middlewares(e)),r.push(...M.parameters(e))}),M.routers(e).forEach(o=>{const i=o.propertyKey.toString();if(a(e[i])){if(!a(t[o.method]))return this._notFound(o.method);const h=this._handles(e,i,s,r);return t[o.method](o.path,...h,(t,s,o)=>C(this,void 0,void 0,function*(){const a=new F(t,s,o,this,e),h=this._args(a,this._indexes(i,r)),p=yield e[i](...h);a.close(l(p)||n(p)?p:void 0)}))}this._notFound(`${e.name}.${i}`)}),this._extends(e).forEach(o=>{M.routers(o).forEach(o=>{const i=o.propertyKey.toString();if(a(e[i])){if(!a(t[o.method]))return this._notFound(o.method);const h=this._handles(e,i,s,r);return t[o.method](o.path,...h,(t,s,o)=>C(this,void 0,void 0,function*(){const a=new F(t,s,o,this,e),h=this._args(a,this._indexes(i,r)),p=yield e[i](...h);a.close(l(p)||n(p)?p:void 0)}))}this._notFound(`${e.constructor.name}.${i}`)})}),this._base.use(M.path(e,"/"),t)})}init(){}error(t,s){e.error(t)}log(t,s){e.info(t)}_args(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_handles(e,t,s,r){return s.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=h){const s=this._indexes(t.method,r);return(r,o,i)=>C(this,void 0,void 0,function*(){const h=new F(r,o,i,this,e),p=a(t.argument)?t.argument(h):t.argument,E=yield t.callback.call(e,...this._args(h,s,p));(l(E)||n(E))&&h.close(E)})}this._notFound(t.method)}).filter(a)}_extends(e){return M.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...M.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return C(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=I.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=I.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(P.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()}),t=D.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new S(s=>{s.once("data",r=>{s.pause(),s.unshift(r),(22===r[0]?t:e).emit("connection",s),process.nextTick(()=>s.resume())})}).listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t}this._server||(443==this._options.port&&e.listen(80,()=>this.log(this._port(80),"express")),t.listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t)}})}}const k=e=>t=>{M.path(t,(null==e?void 0:e.length)?e:"/")},w=e=>t=>{M.extends(t).push(e)};var H;!function(e){e.ALL="all",e.GET="get",e.POST="post",e.PUT="put",e.HEAD="head",e.DELETE="delete",e.OPTIONS="options",e.PATCH="patch"}(H||(H={}));const G=e=>t=>(s,r)=>{M.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},$=G(H.ALL),j=G(H.DELETE),K=G(H.GET),Q=G(H.HEAD),Y=G(H.OPTIONS),q=G(H.PATCH),W=G(H.POST),V=G(H.PUT),X=e=>t=>(s,r,o)=>{M.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},B=X(({app:e})=>e),z=X(({argument:e})=>e),Z=(e,t)=>p(t)?e:e[t],J=X(({ctx:e,key:t})=>{var s,r;return Z(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{},t)}),ee=X(({ctx:e,key:t})=>{var s,r;return Z(null!==(r=null===(s=e.req)||void 0===s?void 0:s.cookies)&&void 0!==r?r:{},t)}),te=X(({ctx:e})=>e),se=X(({ctx:e})=>{var t,s;return null!==(s=null===(t=e.req)||void 0===t?void 0:t.files)&&void 0!==s?s:{}}),re=X(({ctx:e,key:t})=>{var s,r;return Z(null!==(r=null===(s=e.req)||void 0===s?void 0:s.headers)&&void 0!==r?r:{},t)}),oe=X(({ctx:e,key:t})=>{var s,r;return Z(null!==(r=null===(s=e.req)||void 0===s?void 0:s.params)&&void 0!==r?r:{},t)}),ie=X(({ctx:e,key:t})=>{var s,r,o;return String(null!==(o=Z(null!==(r=null===(s=e.req)||void 0===s?void 0:s.query)&&void 0!==r?r:{},t))&&void 0!==o?o:"")}),ne=X(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),ae=(e,t)=>(s,r)=>{const o=E();te()(s,o,0),M.middleware(s).push({method:o,argument:t,propertyKey:r,callback:e})},he=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},le=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},pe=(e,t)=>{const s=E()+"."+t;return A(g(e,s))?pe(e,t):s},Ee=e=>{const t=i({},e),s=U({destination(e,s,r){var o;const i=le(t,s.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,s,r){var o;const i=le(t,s.fieldname);r(null,pe(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",he(s.originalname)))}}),r=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),o=x({storage:s,fileFilter(e,s,r){var o;const i=le(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(he(e.originalname))||t.includes(e.mimetype.toLowerCase()))(s,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${s.fieldname}"`)):r(new Error(`UPLOAD FIELD "${s.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*r*1024}}).fields(Object.keys(t).map(e=>{var s,r;return{name:e,maxCount:null!==(r=null===(s=t[e])||void 0===s?void 0:s.count)&&void 0!==r?r:1}}));return(e,t,s)=>{ae(e=>{o(e.req,e.res,t=>{if(t)return"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t);e.next()})})(e,t,s)}},ue=e=>(t,s,r)=>{ae(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},de=(e,t)=>(s,r)=>{let o=h;if(u(r)){const t=s;a(t[e])&&(o=t[e])}M.middleware(s).push({method:e,argument:t,propertyKey:r,callback:o})},_e=e=>{const t=d.object(a(e)?e(d):e).parse();return(e,s,r)=>{ae(e=>C(void 0,void 0,void 0,function*(){const{error:s,message:r,value:o}=yield t.validateAsync(e.req.body);if(s)return e.validation(null!=r?r:s);e.req.body=o,e.next()}))(e,s,r)}};export{$ as All,B as App,b as Application,z as Argument,J as Body,ue as Cache,F as Context,k as Controller,ee as Cookies,te as Ctx,j as Delete,w as Extends,se as Files,K as Get,Q as Head,re as Headers,M as Metadata,H as Methods,de as Middleware,Y as Options,oe as Params,_e as Parse,q as Patch,W as Post,V as Put,ie as Query,ne as Session,P as Status,Ee as Upload,ae as Use,G as methodFactory,X as parameterFactory};
7
+ import{metadata as e,getInjectionArgs as t}from"@andrewcaires/decorator";import{Log as s}from"@andrewcaires/node";import{isNumber as r,forEachKey as o,isUndefined as i,EventEmitter as n,isConstructor as a,merge as h,isObject as l,isFunction as E,noop as p,isArray as u,uuidv7 as d,isString as c,Validation as _}from"@andrewcaires/utils.js";import T from"compression";import O from"cookie-parser";import R from"cors";import m,{Router as v,json as N,urlencoded as A}from"express";import I from"express-session";import{existsSync as S}from"fs";import*as f from"http";import*as D from"https";import{Server as L}from"net";import{resolve as g,join as x}from"path";import{getClientIp as U}from"request-ip";import y,{diskStorage as C}from"multer";function P(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{h(r.next(e))}catch(e){i(e)}}function a(e){try{h(r.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}h((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class F{}F.CONTINUE=100,F.SWITCHING_PROTOCOLS=101,F.PROCESSING=102,F.OK=200,F.CREATED=201,F.ACCEPTED=202,F.NON_AUTHORITATIVE_INFORMATION=203,F.NO_CONTENT=204,F.RESET_CONTENT=205,F.PARTIAL_CONTENT=206,F.MULTI_STATUS=207,F.ALREADY_REPORTED=208,F.IM_USED=226,F.MULTIPLE_CHOICES=300,F.MOVED_PERMANENTLY=301,F.FOUND=302,F.SEE_OTHER=303,F.NOT_MODIFIED=304,F.USE_PROXY=305,F.TEMPORARY_REDIRECT=307,F.PERMANENT_REDIRECT=308,F.BAD_REQUEST=400,F.UNAUTHORIZED=401,F.PAYMENT_REQUIRED=402,F.FORBIDDEN=403,F.NOT_FOUND=404,F.METHOD_NOT_ALLOWED=405,F.NOT_ACCEPTABLE=406,F.PROXY_AUTHENTICATION_REQUIRED=407,F.REQUEST_TIMEOUT=408,F.CONFLICT=409,F.GONE=410,F.LENGTH_REQUIRED=411,F.PRECONDITION_FAILED=412,F.PAYLOAD_TOO_LARGE=413,F.REQUEST_URI_TOO_LONG=414,F.UNSUPPORTED_MEDIA_TYPE=415,F.REQUESTED_RANGE_NOT_SATISFIABLE=416,F.EXPECTATION_FAILED=417,F.IM_A_TEAPOT=418,F.MISDIRECTED_REQUEST=421,F.UNPROCESSABLE_ENTITY=422,F.LOCKED=423,F.FAILED_DEPENDENCY=424,F.UPGRADE_REQUIRED=426,F.PRECONDITION_REQUIRED=428,F.TOO_MANY_REQUESTS=429,F.REQUEST_HEADER_FIELDS_TOO_LARGE=431,F.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,F.UNAVAILABLE_FOR_LEGAL_REASONS=451,F.CLIENT_CLOSED_REQUEST=499,F.INTERNAL_SERVER_ERROR=500,F.NOT_IMPLEMENTED=501,F.BAD_GATEWAY=502,F.SERVICE_UNAVAILABLE=503,F.GATEWAY_TIMEOUT=504,F.HTTP_VERSION_NOT_SUPPORTED=505,F.VARIANT_ALSO_NEGOCIATES=506,F.INSUFFICIENT_STORAGE=507,F.LOOP_DETECTED=508,F.NOT_EXTENDED=510,F.NETWORK_AUTHENTICATION_REQUIRED=511,F.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class M extends Error{constructor(e,t=F.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class b extends M{constructor(e="Internal server error"){super(e,F.INTERNAL_SERVER_ERROR)}}class k extends M{constructor(e="Record not found"){super(e,F.NOT_FOUND)}}class w extends M{constructor(e="Unauthorized"){super(e,F.UNAUTHORIZED)}}class H extends M{constructor(e){super(e,F.UNPROCESSABLE_ENTITY)}}class ${constructor(e,t,s,r,o){this.req=e,this.res=t,this.next=s,this.app=r,this.controller=o}cache(e){const t=[];e.private?t.push("private"):e.public&&t.push("public"),e.noStore&&(e.noCache=!0,t.push("no-store")),e.noCache&&(e.maxAge=0,delete e.sMaxAge,t.push("no-cache")),e.noTransform&&t.push("no-transform"),e.proxyRevalidate&&t.push("proxy-revalidate"),e.mustRevalidate?t.push("must-revalidate"):e.noCache||(r(e.staleIfError)&&t.push(`stale-if-error=${e.staleIfError}`),r(e.staleWhileRevalidate)&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`)),r(e.maxAge)&&t.push(`max-age=${e.maxAge}`),r(e.sMaxAge)&&t.push(`s-maxage=${e.sMaxAge}`),t.length&&(this.res.setHeader("Cache-Control",t.join(",")),e.noCache&&o({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}close(e){this.res.headersSent||this.res.json(e||this.storage)}cookie(e,t,s){i(t)?this.res.clearCookie(e):this.res.cookie(e,t,null!=s?s:{})}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){var t;let s=null!==(t=e.toString())&&void 0!==t?t:"",r=F.INTERNAL_SERVER_ERROR;e instanceof Error&&(s=e.message,e instanceof M&&(r=e.status)),this.send(r,{error:s})}file(e){this.res.headersSent||(this.status(F.OK),this.res.sendFile(g(e)))}getIp(){return U(this.req)||"0.0.0.0"}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}json(e){this.send(F.OK,e)}prepare(e,t){this.res.headersSent||(this.status(e),this.storage=t)}send(e,t){this.res.headersSent||(this.status(e),this.res.json(t))}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.send(F.OK,{message:e})}}class q{static extends(t){return e(q.EXTENDS,t,[])}static middleware(t){return e(q.MIDDLEWARE,t,[])}static parameters(t){return e(q.PARAMETERS,t,[])}static path(t,s){return e(q.PATH,t,s)}static routers(t){return e(q.ROUTERS,t,[])}}q.EXTENDS=Symbol("EXTENDS"),q.MIDDLEWARE=Symbol("MIDDLEWARE"),q.PARAMETERS=Symbol("PARAMETERS"),q.PATH=Symbol("PATH"),q.ROUTERS=Symbol("ROUTERS");class G extends n{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(e,s){var r,o;super(),this._app=m(),this._options={},this._base=v(),this._router=v(),this._controllers=[],this._controllers.push(...e.map(e=>a(e)?new e(...t(e)):e)),this._options=h({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=s?s:{}),this._app.use(N(this._options.json)),this._app.disable("x-powered-by"),this._app.use(A({extended:!0})),this._options.cross&&this._app.use(R(l(this._options.cross)?this._options.cross:{})),this._app.use(T(this._options.compression)),this._app.use(O(null===(r=this._options.cookie)||void 0===r?void 0:r.secret,this._options.cookie)),this._app.use(I(this._options.session)),this.init(),this._app.use(this._router);const i=(null===(o=this._options.path)||void 0===o?void 0:o.length)?this._options.path:"/";if(this._app.use(i,this._base),this._app.all(i+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(F.NOT_FOUND),t.json({message:"INVALID API"}))}),this._options.public){const e=g(this._options.public);S(e)&&this._app.use(m.static(e)),this._app.get("*path",(t,s)=>{S(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(F.NOT_FOUND),s.json({message:'FILE "index.html" NOT FOUND'}))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(F.NOT_FOUND),t.json({message:"INVALID API"}))});this._controllers.forEach(e=>{const t=v(),s=this._middlewares(e),r=q.parameters(e);this._extends(e).forEach(e=>{s.push(...this._middlewares(e)),r.push(...q.parameters(e))}),q.routers(e).forEach(o=>{const i=o.propertyKey.toString();if(E(e[i])){if(!E(t[o.method]))return this._notFound(o.method);const n=this._handles(e,i,s,r);return t[o.method](o.path,...n,(t,s,o)=>P(this,void 0,void 0,function*(){const n=new $(t,s,o,this,e),a=this._args(n,this._indexes(i,r)),h=yield e[i](...a);n.close(u(h)||l(h)?h:void 0)}))}this._notFound(`${e.name}.${i}`)}),this._extends(e).forEach(o=>{q.routers(o).forEach(o=>{const i=o.propertyKey.toString();if(E(e[i])){if(!E(t[o.method]))return this._notFound(o.method);const n=this._handles(e,i,s,r);return t[o.method](o.path,...n,(t,s,o)=>P(this,void 0,void 0,function*(){const n=new $(t,s,o,this,e),a=this._args(n,this._indexes(i,r)),h=yield e[i](...a);n.close(u(h)||l(h)?h:void 0)}))}this._notFound(`${e.constructor.name}.${i}`)})}),this._base.use(q.path(e,"/"),t)})}init(){}error(e,t){s.error(e)}log(e,t){s.info(e)}_args(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_handles(e,t,s,r){return s.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=p){const s=this._indexes(t.method,r);return(r,o,i)=>P(this,void 0,void 0,function*(){const n=new $(r,o,i,this,e),a=E(t.argument)?t.argument(n):t.argument,h=yield t.callback.call(e,...this._args(n,s,a));(u(h)||l(h))&&n.close(h)})}this._notFound(t.method)}).filter(E)}_extends(e){return q.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...q.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return P(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=f.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=f.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(F.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()}),t=D.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new L(s=>{s.once("data",r=>{s.pause(),s.unshift(r),(22===r[0]?t:e).emit("connection",s),process.nextTick(()=>s.resume())})}).listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t}this._server||(443==this._options.port&&e.listen(80,()=>this.log(this._port(80),"express")),t.listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t)}})}}const Y=e=>t=>{q.path(t,(null==e?void 0:e.length)?e:"/")},j=e=>t=>{q.extends(t).push(e)};var K;!function(e){e.ALL="all",e.GET="get",e.POST="post",e.PUT="put",e.HEAD="head",e.DELETE="delete",e.OPTIONS="options",e.PATCH="patch"}(K||(K={}));const Q=e=>t=>(s,r)=>{q.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},V=Q(K.ALL),W=Q(K.DELETE),X=Q(K.GET),B=Q(K.HEAD),z=Q(K.OPTIONS),Z=Q(K.PATCH),J=Q(K.POST),ee=Q(K.PUT),te=e=>t=>(s,r,o)=>{q.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},se=te(({app:e})=>e),re=te(({argument:e})=>e),oe=(e,t)=>i(t)?e:e[t],ie=te(({ctx:e,key:t})=>{var s,r;return oe(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{},t)}),ne=te(({ctx:e,key:t})=>{var s,r;return oe(null!==(r=null===(s=e.req)||void 0===s?void 0:s.cookies)&&void 0!==r?r:{},t)}),ae=te(({ctx:e})=>e),he=te(({ctx:e})=>{var t,s;return null!==(s=null===(t=e.req)||void 0===t?void 0:t.files)&&void 0!==s?s:{}}),le=te(({ctx:e,key:t})=>{var s,r;return oe(null!==(r=null===(s=e.req)||void 0===s?void 0:s.headers)&&void 0!==r?r:{},t)}),Ee=te(({ctx:e,key:t})=>{var s,r;return oe(null!==(r=null===(s=e.req)||void 0===s?void 0:s.params)&&void 0!==r?r:{},t)}),pe=te(({ctx:e,key:t})=>{var s,r,o;return String(null!==(o=oe(null!==(r=null===(s=e.req)||void 0===s?void 0:s.query)&&void 0!==r?r:{},t))&&void 0!==o?o:"")}),ue=te(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),de=(e,t)=>(s,r)=>{const o=d();ae()(s,o,0),q.middleware(s).push({method:o,argument:t,propertyKey:r,callback:e})},ce=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},_e=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},Te=(e,t)=>{const s=d()+"."+t;return S(x(e,s))?Te(e,t):s},Oe=e=>{const t=h({},e),s=C({destination(e,s,r){var o;const i=_e(t,s.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,s,r){var o;const i=_e(t,s.fieldname);r(null,Te(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",ce(s.originalname)))}}),r=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),o=y({storage:s,fileFilter(e,s,r){var o;const i=_e(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(ce(e.originalname))||t.includes(e.mimetype.toLowerCase()))(s,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${s.fieldname}"`)):r(new Error(`UPLOAD FIELD "${s.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*r*1024}}).fields(Object.keys(t).map(e=>{var s,r;return{name:e,maxCount:null!==(r=null===(s=t[e])||void 0===s?void 0:s.count)&&void 0!==r?r:1}}));return(e,t,s)=>{de(e=>{o(e.req,e.res,t=>{if(t)return"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t);e.next()})})(e,t,s)}},Re=e=>(t,s,r)=>{de(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},me=(e,t)=>(s,r)=>{let o=p;if(c(r)){const t=s;E(t[e])&&(o=t[e])}q.middleware(s).push({method:e,argument:t,propertyKey:r,callback:o})},ve=e=>{const t=_.object(E(e)?e(_):e).parse();return(e,s,r)=>{de(e=>P(void 0,void 0,void 0,function*(){var s,r;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{});if(o)return e.error(new H(null!=i?i:o));e.req.body=n,e.next()}))(e,s,r)}};export{V as All,se as App,G as Application,re as Argument,ie as Body,Re as Cache,$ as Context,Y as Controller,ne as Cookies,ae as Ctx,W as Delete,j as Extends,he as Files,X as Get,B as Head,le as Headers,b as InternalServerError,q as Metadata,K as Methods,me as Middleware,k as NotFoundError,z as Options,Ee as Params,ve as Parse,Z as Patch,J as Post,ee as Put,pe as Query,M as ResponseError,ue as Session,F as Status,w as UnauthorizedError,Oe as Upload,de as Use,H as ValidationError,Q as methodFactory,te as parameterFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrewcaires/express",
3
- "version": "1.2.9",
3
+ "version": "2.0.1",
4
4
  "description": "Decorators for express",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs.js",
@@ -36,9 +36,9 @@
36
36
  },
37
37
  "homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
38
38
  "dependencies": {
39
- "@andrewcaires/decorator": "^1.0.4",
40
- "@andrewcaires/node": "^1.2.9",
41
- "@andrewcaires/utils.js": "^0.4.23",
39
+ "@andrewcaires/decorator": "^1.1.1",
40
+ "@andrewcaires/node": "^1.2.10",
41
+ "@andrewcaires/utils.js": "^0.4.26",
42
42
  "compression": "^1.8.1",
43
43
  "cookie-parser": "^1.4.7",
44
44
  "cors": "^2.8.5",
@@ -51,7 +51,7 @@
51
51
  "@rollup/plugin-commonjs": "^29.0.0",
52
52
  "@rollup/plugin-terser": "^0.4.4",
53
53
  "@rollup/plugin-typescript": "^12.3.0",
54
- "@rollup/rollup-darwin-arm64": "^4.55.1",
54
+ "@rollup/rollup-darwin-arm64": "^4.55.3",
55
55
  "@types/compression": "^1.8.1",
56
56
  "@types/cookie-parser": "^1.4.10",
57
57
  "@types/cors": "^2.8.19",
@@ -65,6 +65,6 @@
65
65
  "rollup-plugin-dts": "^6.3.0",
66
66
  "swagger-ui-express": "^5.0.1",
67
67
  "tslib": "^2.8.1",
68
- "typescript-eslint": "^8.53.0"
68
+ "typescript-eslint": "^8.53.1"
69
69
  }
70
70
  }