@andrewcaires/express 1.1.9 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,9 +16,7 @@ The module is now available on npm! `npm i @andrewcaires/express`
16
16
  ```js
17
17
  // index.ts
18
18
 
19
- import { TypeCallbackFunction } from "@andrewcaires/utils.js";
20
-
21
- import { Application, Argument, Body, Context, Controller, Ctx, Delete, Extends, Get, Middleware, Next, Params, Post, Put } from ".";
19
+ import { Application, Argument, Body, Context, Controller, Ctx, Delete, Extends, Get, Middleware, Params, Post, Put } from ".";
22
20
 
23
21
  @Controller("/test")
24
22
  class TestController {
package/dist/index.cjs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v1.1.9
2
+ * @andrewcaires/express v1.1.11
3
3
  * Decorators for express
4
4
  * (c) 2024 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- "use strict";var e=require("@andrewcaires/node"),t=require("@andrewcaires/utils.js"),s=require("cookie-parser"),r=require("cors"),o=require("express"),i=require("express-session"),n=require("fs"),p=require("http"),a=require("https"),E=require("net"),h=require("path");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 d=_(p),u=_(a);function c(e,t,s,r){return new(s||(s=Promise))((function(o,i){function n(e){try{a(r.next(e))}catch(e){i(e)}}function p(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(n,p)}a((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class T{}T.CONTINUE=100,T.SWITCHING_PROTOCOLS=101,T.PROCESSING=102,T.OK=200,T.CREATED=201,T.ACCEPTED=202,T.NON_AUTHORITATIVE_INFORMATION=203,T.NO_CONTENT=204,T.RESET_CONTENT=205,T.PARTIAL_CONTENT=206,T.MULTI_STATUS=207,T.ALREADY_REPORTED=208,T.IM_USED=226,T.MULTIPLE_CHOICES=300,T.MOVED_PERMANENTLY=301,T.FOUND=302,T.SEE_OTHER=303,T.NOT_MODIFIED=304,T.USE_PROXY=305,T.TEMPORARY_REDIRECT=307,T.PERMANENT_REDIRECT=308,T.BAD_REQUEST=400,T.UNAUTHORIZED=401,T.PAYMENT_REQUIRED=402,T.FORBIDDEN=403,T.NOT_FOUND=404,T.METHOD_NOT_ALLOWED=405,T.NOT_ACCEPTABLE=406,T.PROXY_AUTHENTICATION_REQUIRED=407,T.REQUEST_TIMEOUT=408,T.CONFLICT=409,T.GONE=410,T.LENGTH_REQUIRED=411,T.PRECONDITION_FAILED=412,T.PAYLOAD_TOO_LARGE=413,T.REQUEST_URI_TOO_LONG=414,T.UNSUPPORTED_MEDIA_TYPE=415,T.REQUESTED_RANGE_NOT_SATISFIABLE=416,T.EXPECTATION_FAILED=417,T.IM_A_TEAPOT=418,T.MISDIRECTED_REQUEST=421,T.UNPROCESSABLE_ENTITY=422,T.LOCKED=423,T.FAILED_DEPENDENCY=424,T.UPGRADE_REQUIRED=426,T.PRECONDITION_REQUIRED=428,T.TOO_MANY_REQUESTS=429,T.REQUEST_HEADER_FIELDS_TOO_LARGE=431,T.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,T.UNAVAILABLE_FOR_LEGAL_REASONS=451,T.CLIENT_CLOSED_REQUEST=499,T.INTERNAL_SERVER_ERROR=500,T.NOT_IMPLEMENTED=501,T.BAD_GATEWAY=502,T.SERVICE_UNAVAILABLE=503,T.GATEWAY_TIMEOUT=504,T.HTTP_VERSION_NOT_SUPPORTED=505,T.VARIANT_ALSO_NEGOCIATES=506,T.INSUFFICIENT_STORAGE=507,T.LOOP_DETECTED=508,T.NOT_EXTENDED=510,T.NETWORK_AUTHENTICATION_REQUIRED=511,T.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class O{constructor(e,t,s,r){this.req=e,this.res=t,this.next=s,this.controller=r}close(e){this.res.headersSent||this.res.json(e||(this.dispatch||{}))}destroy(e){var t;e&&this.error(e.message),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){this.prepare(T.INTERNAL_SERVER_ERROR,{message:e})}file(e){this.res.headersSent||(this.status(T.OK),this.res.sendFile(h.resolve(e)))}json(e){this.prepare(T.OK,e)}notFound(e){this.prepare(T.NOT_FOUND,{message:e})}prepare(e,t){this.res.headersSent||(this.status(e),this.dispatch=t)}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.prepare(T.OK,{message:e})}unauthorized(e){this.prepare(T.UNAUTHORIZED,{message:e})}validation(e){this.prepare(T.BAD_REQUEST,{message:e})}}const R=t.cache(),l=(e,s,r)=>{t.isObject(s)&&(s=s.constructor);const o=R(s);return o[e]||(o[e]=r),o[e]};var N,x;exports.MetadataKeys=void 0,(N=exports.MetadataKeys||(exports.MetadataKeys={})).EXTENDS="__extends__",N.MIDDLEWARE="__middleware__",N.PARAMETERS="__parameters__",N.PATH="__path__",N.ROUTERS="__routers__",exports.Methods=void 0,(x=exports.Methods||(exports.Methods={})).ALL="all",x.GET="get",x.POST="post",x.PUT="put",x.HEAD="head",x.DELETE="delete",x.OPTIONS="options",x.PATCH="patch";class A extends t.EventEmitter{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(e,p){var a;super(),this._app=o(),this._options={},this._default={cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},this._router=o.Router(),this._controllers=o.Router(),this._options=t.merge(Object.assign({},this._default),Object.assign({},p)),this._app.use(o.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(o.urlencoded({extended:!0})),this._options.cross&&this._app.use(r(t.isObject(this._options.cross)?this._options.cross:{}));const E=this._options.cookie;this._app.use(s(null==E?void 0:E.secret,null==E?void 0:E.options)),this._app.use(i(this._options.session)),this.init(),this._app.use(this._router);const _=(null===(a=this._options.path)||void 0===a?void 0:a.length)?this._options.path:"/";if(this._app.use(_,this._controllers),this._app.all(_+"/*",((e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(T.NOT_FOUND),t.json({message:"Invalid API"}))})),this._options.public){const e=h.resolve(this._options.public);n.existsSync(e)&&this._app.use(o.static(e)),this._app.get("*",((t,s)=>{n.existsSync(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(T.NOT_FOUND),s.json({message:'File "index.html" not found'}))}))}e.forEach((e=>{const s=o.Router(),r=this._middlewares(e),i=this._parameters(e);this._extends(e).forEach((e=>{r.push(...this._middlewares(e)),i.push(...this._parameters(e))})),this._routers(e).forEach((o=>{const n=o.propertyKey.toString();if(t.isFunction(e[n])){if(!t.isFunction(s[o.method]))return this.error(new Error('Method "'+o.method+'" Not Found'),"express");const p=this._handles(e,n,r,i);return s[o.method](o.path,...p,((s,r,o)=>c(this,void 0,void 0,(function*(){const p=new O(s,r,o,e),a=this._args(p,s,r,o,this._indexes(n,i)),E=yield e[n](...a);return p.close(t.isArray(E)||t.isObject(E)?E:void 0),E}))))}return this.error(new Error('Router "'+e.name+"."+n+'" Not Found'),"express")})),this._extends(e).forEach((o=>{this._routers(o).forEach((o=>{const n=o.propertyKey.toString();if(t.isFunction(e[n])){if(!t.isFunction(s[o.method]))return this.error(new Error('Method "'+o.method+'" Not Found'),"express");const p=this._handles(e,n,r,i);return s[o.method](o.path,...p,((s,r,o)=>c(this,void 0,void 0,(function*(){const p=new O(s,r,o,e),a=this._args(p,s,r,o,this._indexes(n,i)),E=yield e[n](...a);return p.close(t.isArray(E)||t.isObject(E)?E:void 0),E}))))}return this.error(new Error('Router "'+e.constructor.name+"."+n+'" Not Found'),"express")}))})),this._controllers.use(this._path(e),s)}))}init(){}error(s,r){e.Log.error(t.isUndefined(r)?s:r+":",s)}log(s,r){e.Log.info(t.isUndefined(r)?s:r+":",s)}_args(e,t,s,r,o,i){const n=[],p={ctx:e,req:t,res:s,next:r,key:"",app:this,argument:i};return o.forEach((e=>{n[e.parameterIndex]=e.callback(Object.assign(Object.assign({},p),{key:e.key}))})),n}_handles(e,s,r,o){return r.filter((e=>e.propertyKey==s)).map((s=>{if(t.isFunction(e[s.method])){const r=this._indexes(s.method,o);return(o,i,n)=>{const p=new O(o,i,n,e),a=t.isFunction(s.argument)?s.argument(p):s.argument;return e[s.method](...this._args(p,o,i,n,r,a))}}this.error(new Error('Middleware "'+s.method+'" Not Found'),"express")})).filter(t.isFunction)}_extends(e){return l(exports.MetadataKeys.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[...l(exports.MetadataKeys.MIDDLEWARE,e,[])].reverse()}_parameters(e){return l(exports.MetadataKeys.PARAMETERS,e,[])}_path(e){return l(exports.MetadataKeys.PATH,e,"/")}_routers(e){return l(exports.MetadataKeys.ROUTERS,e,[])}listen(){return c(this,void 0,void 0,(function*(){if(this._options.cert&&this._options.key||(this._server=d.createServer(this._app),this._server.listen(this._options.port,(()=>this.log("Server started on port "+this._options.port,"express")))),!this._server){const e=d.createServer(((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(T.MOVED_PERMANENTLY,{Location:"https://"+e.headers.host+s+e.url}),t.end()})),t=u.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new E.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("Server started on port "+this._options.port,"express"))),this._server=t}this._server||(443==this._options.port&&e.listen(80,(()=>this.log("Server started on port 80","express"))),t.listen(this._options.port,(()=>this.log("Server started on port "+this._options.port,"express"))),this._server=t)}}))}}const I=e=>t=>(s,r)=>{l(exports.MetadataKeys.ROUTERS,s,[]).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},S=I(exports.Methods.ALL),D=I(exports.Methods.GET),y=I(exports.Methods.POST),M=I(exports.Methods.PUT),U=I(exports.Methods.DELETE),m=I(exports.Methods.PATCH),P=I(exports.Methods.HEAD),f=I(exports.Methods.OPTIONS),v=e=>t=>(s,r,o)=>{l(exports.MetadataKeys.PARAMETERS,s,[]).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},L=(e,s)=>t.isUndefined(s)?e:e[s],g=v((({app:e})=>e)),C=v((({argument:e})=>e)),F=v((({req:e,key:t})=>L(e.body,t))),K=v((({req:e,key:t})=>L(e.cookies,t))),b=v((({ctx:e})=>e)),w=v((({req:e,key:t})=>L(e.headers,t))),H=v((({req:e,key:t})=>L(e.params,t))),k=v((({req:e,key:t})=>L(e.query,t))),j=v((({req:e})=>e.session));exports.All=S,exports.App=g,exports.Application=A,exports.Argument=C,exports.Body=F,exports.Context=O,exports.Controller=e=>t=>{l(exports.MetadataKeys.PATH,t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=K,exports.Ctx=b,exports.Delete=U,exports.Extends=e=>t=>{l(exports.MetadataKeys.EXTENDS,t,[]).push(e)},exports.Get=D,exports.Head=P,exports.Headers=w,exports.Metadata=l,exports.Middleware=(e,t)=>(s,r)=>{l(exports.MetadataKeys.MIDDLEWARE,s,[]).push({method:e,argument:t,propertyKey:r})},exports.Options=f,exports.Params=H,exports.Patch=m,exports.Post=y,exports.Put=M,exports.Query=k,exports.Session=j,exports.Status=T,exports.methodFactory=I,exports.parameterFactory=v;
7
+ "use strict";var e=require("@andrewcaires/node"),t=require("@andrewcaires/utils.js"),s=require("cookie-parser"),r=require("cors"),o=require("express"),i=require("express-session"),n=require("fs"),a=require("http"),p=require("https"),h=require("net"),E=require("path"),d=require("multer");function u(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 _=u(a),c=u(p);function l(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 T{}T.CONTINUE=100,T.SWITCHING_PROTOCOLS=101,T.PROCESSING=102,T.OK=200,T.CREATED=201,T.ACCEPTED=202,T.NON_AUTHORITATIVE_INFORMATION=203,T.NO_CONTENT=204,T.RESET_CONTENT=205,T.PARTIAL_CONTENT=206,T.MULTI_STATUS=207,T.ALREADY_REPORTED=208,T.IM_USED=226,T.MULTIPLE_CHOICES=300,T.MOVED_PERMANENTLY=301,T.FOUND=302,T.SEE_OTHER=303,T.NOT_MODIFIED=304,T.USE_PROXY=305,T.TEMPORARY_REDIRECT=307,T.PERMANENT_REDIRECT=308,T.BAD_REQUEST=400,T.UNAUTHORIZED=401,T.PAYMENT_REQUIRED=402,T.FORBIDDEN=403,T.NOT_FOUND=404,T.METHOD_NOT_ALLOWED=405,T.NOT_ACCEPTABLE=406,T.PROXY_AUTHENTICATION_REQUIRED=407,T.REQUEST_TIMEOUT=408,T.CONFLICT=409,T.GONE=410,T.LENGTH_REQUIRED=411,T.PRECONDITION_FAILED=412,T.PAYLOAD_TOO_LARGE=413,T.REQUEST_URI_TOO_LONG=414,T.UNSUPPORTED_MEDIA_TYPE=415,T.REQUESTED_RANGE_NOT_SATISFIABLE=416,T.EXPECTATION_FAILED=417,T.IM_A_TEAPOT=418,T.MISDIRECTED_REQUEST=421,T.UNPROCESSABLE_ENTITY=422,T.LOCKED=423,T.FAILED_DEPENDENCY=424,T.UPGRADE_REQUIRED=426,T.PRECONDITION_REQUIRED=428,T.TOO_MANY_REQUESTS=429,T.REQUEST_HEADER_FIELDS_TOO_LARGE=431,T.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,T.UNAVAILABLE_FOR_LEGAL_REASONS=451,T.CLIENT_CLOSED_REQUEST=499,T.INTERNAL_SERVER_ERROR=500,T.NOT_IMPLEMENTED=501,T.BAD_GATEWAY=502,T.SERVICE_UNAVAILABLE=503,T.GATEWAY_TIMEOUT=504,T.HTTP_VERSION_NOT_SUPPORTED=505,T.VARIANT_ALSO_NEGOCIATES=506,T.INSUFFICIENT_STORAGE=507,T.LOOP_DETECTED=508,T.NOT_EXTENDED=510,T.NETWORK_AUTHENTICATION_REQUIRED=511,T.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class O{constructor(e,t,s,r){this.req=e,this.res=t,this.next=s,this.controller=r}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(T.INTERNAL_SERVER_ERROR,{message:e})}file(e){this.res.headersSent||(this.status(T.OK),this.res.sendFile(E.resolve(e)))}json(e){this.send(T.OK,e)}notFound(e){this.send(T.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(T.OK,{message:e})}unauthorized(e){this.send(T.UNAUTHORIZED,{message:e})}validation(e){this.send(T.BAD_REQUEST,{message:e})}}class R{static extends(t){return e.Metadata(R.EXTENDS,t,[])}static middleware(t){return e.Metadata(R.MIDDLEWARE,t,[])}static parameters(t){return e.Metadata(R.PARAMETERS,t,[])}static path(t,s){return e.Metadata(R.PATH,t,s)}static routers(t){return e.Metadata(R.ROUTERS,t,[])}}R.EXTENDS=Symbol(),R.MIDDLEWARE=Symbol(),R.PARAMETERS=Symbol(),R.PATH=Symbol(),R.ROUTERS=Symbol();class N extends t.EventEmitter{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(e,a){var p;super(),this._app=o(),this._options={},this._default={cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},this._router=o.Router(),this._controllers=o.Router(),this._options=t.merge(Object.assign({},this._default),Object.assign({},a)),this._app.use(o.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(o.urlencoded({extended:!0})),this._options.cross&&this._app.use(r(t.isObject(this._options.cross)?this._options.cross:{}));const h=this._options.cookie;this._app.use(s(null==h?void 0:h.secret,null==h?void 0:h.options)),this._app.use(i(this._options.session)),this.init(),this._app.use(this._router);const d=(null===(p=this._options.path)||void 0===p?void 0:p.length)?this._options.path:"/";if(this._app.use(d,this._controllers),this._app.all(d+"/*",((e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(T.NOT_FOUND),t.json({message:"Invalid API"}))})),this._options.public){const e=E.resolve(this._options.public);n.existsSync(e)&&this._app.use(o.static(e)),this._app.get("*",((t,s)=>{n.existsSync(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(T.NOT_FOUND),s.json({message:'File "index.html" not found'}))}))}e.forEach((e=>{const s=o.Router(),r=this._middlewares(e),i=R.parameters(e);this._extends(e).forEach((e=>{r.push(...this._middlewares(e)),i.push(...R.parameters(e))})),R.routers(e).forEach((o=>{const n=o.propertyKey.toString();if(t.isFunction(e[n])){if(!t.isFunction(s[o.method]))return this._notFound(o.method);const a=this._handles(e,n,r,i);return s[o.method](o.path,...a,((s,r,o)=>l(this,void 0,void 0,(function*(){const a=new O(s,r,o,e),p=this._args(a,this._indexes(n,i)),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((o=>{R.routers(o).forEach((o=>{const n=o.propertyKey.toString();if(t.isFunction(e[n])){if(!t.isFunction(s[o.method]))return this._notFound(o.method);const a=this._handles(e,n,r,i);return s[o.method](o.path,...a,((s,r,o)=>l(this,void 0,void 0,(function*(){const a=new O(s,r,o,e),p=this._args(a,this._indexes(n,i)),h=yield e[n](...p);a.close(t.isArray(h)||t.isObject(h)?h:void 0)}))))}this._notFound(`${e.constructor.name}.${n}`)}))})),this._controllers.use(R.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(t.isFunction(e[s.method])){const r=this._indexes(s.method,o);return(o,i,n)=>l(this,void 0,void 0,(function*(){const a=new O(o,i,n,e),p=t.isFunction(s.argument)?s.argument(a):s.argument,h=yield e[s.method](...this._args(a,r,p));(t.isArray(h)||t.isObject(h))&&a.close(h)}))}this._notFound(s.method)})).filter(t.isFunction)}_extends(e){return R.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[...R.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return l(this,void 0,void 0,(function*(){if(this._options.cert&&this._options.key||(this._server=_.createServer(this._app),this._server.listen(this._options.port,(()=>this.log(this._port(this._options.port),"express")))),!this._server){const e=_.createServer(((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(T.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()})),t=c.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 x;exports.Methods=void 0,(x=exports.Methods||(exports.Methods={})).ALL="all",x.GET="get",x.POST="post",x.PUT="put",x.HEAD="head",x.DELETE="delete",x.OPTIONS="options",x.PATCH="patch";const A=e=>t=>(s,r)=>{R.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},S=A(exports.Methods.ALL),I=A(exports.Methods.DELETE),m=A(exports.Methods.GET),D=A(exports.Methods.HEAD),f=A(exports.Methods.OPTIONS),y=A(exports.Methods.PATCH),v=A(exports.Methods.POST),g=A(exports.Methods.PUT),U=e=>t=>(s,r,o)=>{R.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},P=U((({app:e})=>e)),L=U((({argument:e})=>e)),C=(e,s)=>t.isUndefined(s)?e:e[s],M=U((({ctx:e,key:t})=>C(e.req.body,t))),F=U((({ctx:e,key:t})=>C(e.req.cookies,t))),b=U((({ctx:e})=>e)),k=U((({ctx:e})=>t.toArray(e.req.files))),w=U((({ctx:e,key:t})=>C(e.req.headers,t))),j=U((({ctx:e,key:t})=>C(e.req.params,t))),q=U((({ctx:e,key:t})=>C(e.req.query,t))),H=U((({ctx:e})=>e.req.session));class G{static file(e,s){const r=t.uuidv4()+"."+s;return n.existsSync(E.join(e,r))?G.file(e,s):r}static middleware(e,t){const s=G._cache(t);s.upload||(s.upload=G.multer(t)),s.upload(e.req,e.res,(t=>{if(t)return e.destroy(t);e.next()}))}static multer(e){const t=(null==e?void 0:e.path)||"./",s=d.diskStorage({destination:(e,s,r)=>r(null,t),filename:(e,s,r)=>l(this,void 0,void 0,(function*(){return r(null,G.file(t,s.originalname.split(".").pop()||"bin"))}))}),r=(null==e?void 0:e.types)||[];return d({storage:s,fileFilter(e,t,s){return l(this,void 0,void 0,(function*(){if(r.length){const e=t.originalname.split(".").pop()||"bin";return-1!=r.indexOf(t.mimetype)||-1!=r.indexOf(e)?s(null,!0):s(new Error("File not allowed"))}return s(null,!0)}))},limits:{fileSize:1e6*((null==e?void 0:e.size)||5)}}).array((null==e?void 0:e.field)||"field",(null==e?void 0:e.count)||1)}}G._cache=t.cache(),exports.All=S,exports.App=P,exports.Application=N,exports.Argument=L,exports.Body=M,exports.Context=O,exports.Controller=e=>t=>{R.path(t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=F,exports.Ctx=b,exports.Delete=I,exports.Extends=e=>t=>{R.extends(t).push(e)},exports.Files=k,exports.Get=m,exports.Head=D,exports.Headers=w,exports.Metadata=R,exports.Middleware=(e,t)=>(s,r)=>{R.middleware(s).push({method:e,argument:t,propertyKey:r})},exports.Options=f,exports.Params=j,exports.Patch=y,exports.Post=v,exports.Put=g,exports.Query=q,exports.Session=H,exports.Status=T,exports.Upload=G,exports.methodFactory=A,exports.parameterFactory=U;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @andrewcaires/express v1.1.9
2
+ * @andrewcaires/express v1.1.11
3
3
  * Decorators for express
4
4
  * (c) 2024 Andrew Caires
5
5
  * @license: MIT
@@ -18,15 +18,16 @@ declare class Context<T = any> {
18
18
  readonly res: Response;
19
19
  readonly next: NextFunction;
20
20
  readonly controller: T;
21
- private dispatch?;
21
+ private storage?;
22
22
  constructor(req: Request, res: Response, next: NextFunction, controller: T);
23
23
  close(value?: TypeObjectAny): void;
24
24
  destroy(error?: Error): void;
25
25
  error(message: string): void;
26
26
  file(path: string): void;
27
- json(value: object | Array<any>): void;
27
+ json(value?: TypeObjectAny | Array<TypeObjectAny>): void;
28
28
  notFound(message: string): void;
29
- private prepare;
29
+ prepare(status: number, value: TypeObjectAny | Array<TypeObjectAny>): void;
30
+ send(status: number, value?: TypeObjectAny | Array<TypeObjectAny>): void;
30
31
  status(value?: number): number;
31
32
  success(message: string): void;
32
33
  unauthorized(message: string): void;
@@ -35,25 +36,33 @@ declare class Context<T = any> {
35
36
 
36
37
  interface IArgs {
37
38
  ctx: Context;
38
- req: Request;
39
- res: Response;
40
- next: NextFunction;
41
39
  key: string;
42
40
  app: Application;
43
41
  argument: any;
44
42
  }
45
43
 
44
+ interface ICookie {
45
+ secret?: string | Array<string>;
46
+ options?: CookieParseOptions;
47
+ }
48
+
49
+ interface IFile {
50
+ fieldname: string;
51
+ originalname: string;
52
+ encoding: string;
53
+ mimetype: string;
54
+ destination: string;
55
+ filename: string;
56
+ path: string;
57
+ size: number;
58
+ }
59
+
46
60
  interface IMiddlewares {
47
61
  method: string;
48
62
  argument: any;
49
63
  propertyKey: string | symbol;
50
64
  }
51
65
 
52
- interface ICookie {
53
- secret?: string | Array<string>;
54
- options?: CookieParseOptions;
55
- }
56
-
57
66
  interface IOptions {
58
67
  cert?: Buffer;
59
68
  cookie?: ICookie;
@@ -103,12 +112,12 @@ interface IStore extends TypeObjectAny {
103
112
  touch(): this;
104
113
  }
105
114
 
106
- declare enum MetadataKeys {
107
- EXTENDS = "__extends__",
108
- MIDDLEWARE = "__middleware__",
109
- PARAMETERS = "__parameters__",
110
- PATH = "__path__",
111
- ROUTERS = "__routers__"
115
+ interface IUpload {
116
+ count?: number;
117
+ field?: string;
118
+ path?: string;
119
+ size?: number;
120
+ types?: Array<string>;
112
121
  }
113
122
 
114
123
  declare class Application extends EventEmitter {
@@ -123,16 +132,15 @@ declare class Application extends EventEmitter {
123
132
  get server(): http.Server | https.Server | undefined;
124
133
  constructor(controllers: Array<object>, options?: IOptions);
125
134
  init(): void;
126
- error(error: any, source?: string): void;
135
+ error(message: any, source?: string): void;
127
136
  log(message: string, source?: string): void;
128
137
  private _args;
129
138
  private _handles;
130
139
  private _extends;
131
140
  private _indexes;
132
141
  private _middlewares;
133
- private _parameters;
134
- private _path;
135
- private _routers;
142
+ private _notFound;
143
+ private _port;
136
144
  listen(): Promise<void>;
137
145
  }
138
146
 
@@ -140,30 +148,60 @@ declare const Controller: (path?: string) => ClassDecorator;
140
148
 
141
149
  declare const Extends: (type: any) => ClassDecorator;
142
150
 
143
- declare const methodFactory: (method: Methods) => (path?: string) => MethodDecorator;
144
151
  declare const All: (path?: string) => MethodDecorator;
145
- declare const Get: (path?: string) => MethodDecorator;
146
- declare const Post: (path?: string) => MethodDecorator;
147
- declare const Put: (path?: string) => MethodDecorator;
152
+
148
153
  declare const Delete: (path?: string) => MethodDecorator;
149
- declare const Patch: (path?: string) => MethodDecorator;
154
+
155
+ declare const Get: (path?: string) => MethodDecorator;
156
+
150
157
  declare const Head: (path?: string) => MethodDecorator;
151
- declare const Options: (path?: string) => MethodDecorator;
158
+
159
+ declare const methodFactory: (method: Methods) => (path?: string) => MethodDecorator;
152
160
 
153
161
  declare const Middleware: (method: string, argument?: any) => MethodDecorator;
154
162
 
155
- declare const parameterFactory: (callback: TypeCallbackFunction) => (key?: string) => ParameterDecorator;
163
+ declare const Options: (path?: string) => MethodDecorator;
164
+
165
+ declare const Patch: (path?: string) => MethodDecorator;
166
+
167
+ declare const Post: (path?: string) => MethodDecorator;
168
+
169
+ declare const Put: (path?: string) => MethodDecorator;
170
+
156
171
  declare const App: (key?: string) => ParameterDecorator;
172
+
157
173
  declare const Argument: (key?: string) => ParameterDecorator;
174
+
158
175
  declare const Body: (key?: string) => ParameterDecorator;
176
+
159
177
  declare const Cookies: (key?: string) => ParameterDecorator;
178
+
160
179
  declare const Ctx: (key?: string) => ParameterDecorator;
180
+
181
+ declare const Files: (key?: string) => ParameterDecorator;
182
+
161
183
  declare const Headers: (key?: string) => ParameterDecorator;
184
+
185
+ declare const parameterFactory: (callback: TypeCallbackFunction) => (key?: string) => ParameterDecorator;
186
+
162
187
  declare const Params: (key?: string) => ParameterDecorator;
188
+
163
189
  declare const Query: (key?: string) => ParameterDecorator;
190
+
164
191
  declare const Session: (key?: string) => ParameterDecorator;
165
192
 
166
- declare const Metadata: <T = any>(metadataKey: MetadataKeys, target: any, metadataValue: T) => T;
193
+ declare class Metadata {
194
+ static readonly EXTENDS: unique symbol;
195
+ static readonly MIDDLEWARE: unique symbol;
196
+ static readonly PARAMETERS: unique symbol;
197
+ static readonly PATH: unique symbol;
198
+ static readonly ROUTERS: unique symbol;
199
+ static extends(target: any): Array<object>;
200
+ static middleware(target: any): Array<IMiddlewares>;
201
+ static parameters(target: any): Array<IParameter>;
202
+ static path(target: any, value: string): string;
203
+ static routers(target: any): Array<IRouter>;
204
+ }
167
205
 
168
206
  declare class Status {
169
207
  static readonly CONTINUE = 100;
@@ -231,4 +269,11 @@ declare class Status {
231
269
  static readonly NETWORK_CONNECTION_TIMEOUT_ERROR = 599;
232
270
  }
233
271
 
234
- export { All, App, Application, Argument, Body, Context, Controller, Cookies, Ctx, Delete, Extends, Get, Head, Headers, type IArgs, type IMiddlewares, type IOptions, type IParameter, type IRouter, type IStore, Metadata, MetadataKeys, Methods, Middleware, Options, Params, Patch, Post, Put, Query, Session, Status, methodFactory, parameterFactory };
272
+ declare class Upload {
273
+ private static _cache;
274
+ private static file;
275
+ static middleware(ctx: Context, options: IUpload): void;
276
+ private static multer;
277
+ }
278
+
279
+ export { All, App, Application, Argument, Body, Context, Controller, Cookies, Ctx, Delete, Extends, Files, Get, Head, Headers, type IArgs, type ICookie, type IFile, type IMiddlewares, type IOptions, type IParameter, type IRouter, type IStore, type IUpload, Metadata, Methods, Middleware, Options, Params, Patch, Post, Put, Query, Session, Status, Upload, methodFactory, parameterFactory };
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v1.1.9
2
+ * @andrewcaires/express v1.1.11
3
3
  * Decorators for express
4
4
  * (c) 2024 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- import{Log as t}from"@andrewcaires/node";import{cache as e,isObject as s,EventEmitter as r,merge as o,isFunction as i,isUndefined as n,isArray as E}from"@andrewcaires/utils.js";import _ from"cookie-parser";import h from"cors";import p,{Router as a,json as T,urlencoded as u}from"express";import d from"express-session";import{existsSync as c}from"fs";import*as O from"http";import*as R from"https";import{Server as N}from"net";import{resolve as A}from"path";function l(t,e,s,r){return new(s||(s=Promise))((function(o,i){function n(t){try{_(r.next(t))}catch(t){i(t)}}function E(t){try{_(r.throw(t))}catch(t){i(t)}}function _(t){var e;t.done?o(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(n,E)}_((r=r.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class I{}I.CONTINUE=100,I.SWITCHING_PROTOCOLS=101,I.PROCESSING=102,I.OK=200,I.CREATED=201,I.ACCEPTED=202,I.NON_AUTHORITATIVE_INFORMATION=203,I.NO_CONTENT=204,I.RESET_CONTENT=205,I.PARTIAL_CONTENT=206,I.MULTI_STATUS=207,I.ALREADY_REPORTED=208,I.IM_USED=226,I.MULTIPLE_CHOICES=300,I.MOVED_PERMANENTLY=301,I.FOUND=302,I.SEE_OTHER=303,I.NOT_MODIFIED=304,I.USE_PROXY=305,I.TEMPORARY_REDIRECT=307,I.PERMANENT_REDIRECT=308,I.BAD_REQUEST=400,I.UNAUTHORIZED=401,I.PAYMENT_REQUIRED=402,I.FORBIDDEN=403,I.NOT_FOUND=404,I.METHOD_NOT_ALLOWED=405,I.NOT_ACCEPTABLE=406,I.PROXY_AUTHENTICATION_REQUIRED=407,I.REQUEST_TIMEOUT=408,I.CONFLICT=409,I.GONE=410,I.LENGTH_REQUIRED=411,I.PRECONDITION_FAILED=412,I.PAYLOAD_TOO_LARGE=413,I.REQUEST_URI_TOO_LONG=414,I.UNSUPPORTED_MEDIA_TYPE=415,I.REQUESTED_RANGE_NOT_SATISFIABLE=416,I.EXPECTATION_FAILED=417,I.IM_A_TEAPOT=418,I.MISDIRECTED_REQUEST=421,I.UNPROCESSABLE_ENTITY=422,I.LOCKED=423,I.FAILED_DEPENDENCY=424,I.UPGRADE_REQUIRED=426,I.PRECONDITION_REQUIRED=428,I.TOO_MANY_REQUESTS=429,I.REQUEST_HEADER_FIELDS_TOO_LARGE=431,I.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,I.UNAVAILABLE_FOR_LEGAL_REASONS=451,I.CLIENT_CLOSED_REQUEST=499,I.INTERNAL_SERVER_ERROR=500,I.NOT_IMPLEMENTED=501,I.BAD_GATEWAY=502,I.SERVICE_UNAVAILABLE=503,I.GATEWAY_TIMEOUT=504,I.HTTP_VERSION_NOT_SUPPORTED=505,I.VARIANT_ALSO_NEGOCIATES=506,I.INSUFFICIENT_STORAGE=507,I.LOOP_DETECTED=508,I.NOT_EXTENDED=510,I.NETWORK_AUTHENTICATION_REQUIRED=511,I.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class S{constructor(t,e,s,r){this.req=t,this.res=e,this.next=s,this.controller=r}close(t){this.res.headersSent||this.res.json(t||(this.dispatch||{}))}destroy(t){var e;t&&this.error(t.message),null===(e=this.res.socket)||void 0===e||e.destroy(t)}error(t){this.prepare(I.INTERNAL_SERVER_ERROR,{message:t})}file(t){this.res.headersSent||(this.status(I.OK),this.res.sendFile(A(t)))}json(t){this.prepare(I.OK,t)}notFound(t){this.prepare(I.NOT_FOUND,{message:t})}prepare(t,e){this.res.headersSent||(this.status(t),this.dispatch=e)}status(t){return t&&this.res.status(t),this.res.statusCode}success(t){this.prepare(I.OK,{message:t})}unauthorized(t){this.prepare(I.UNAUTHORIZED,{message:t})}validation(t){this.prepare(I.BAD_REQUEST,{message:t})}}const D=e(),m=(t,e,r)=>{s(e)&&(e=e.constructor);const o=D(e);return o[t]||(o[t]=r),o[t]};var f,U;!function(t){t.EXTENDS="__extends__",t.MIDDLEWARE="__middleware__",t.PARAMETERS="__parameters__",t.PATH="__path__",t.ROUTERS="__routers__"}(f||(f={})),function(t){t.ALL="all",t.GET="get",t.POST="post",t.PUT="put",t.HEAD="head",t.DELETE="delete",t.OPTIONS="options",t.PATCH="patch"}(U||(U={}));class L extends r{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(t,e){var r;super(),this._app=p(),this._options={},this._default={cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},this._router=a(),this._controllers=a(),this._options=o(Object.assign({},this._default),Object.assign({},e)),this._app.use(T(this._options.json)),this._app.disable("x-powered-by"),this._app.use(u({extended:!0})),this._options.cross&&this._app.use(h(s(this._options.cross)?this._options.cross:{}));const n=this._options.cookie;this._app.use(_(null==n?void 0:n.secret,null==n?void 0:n.options)),this._app.use(d(this._options.session)),this.init(),this._app.use(this._router);const O=(null===(r=this._options.path)||void 0===r?void 0:r.length)?this._options.path:"/";if(this._app.use(O,this._controllers),this._app.all(O+"/*",((t,e)=>{this._options.redirect?e.redirect(this._options.redirect):(e.status(I.NOT_FOUND),e.json({message:"Invalid API"}))})),this._options.public){const t=A(this._options.public);c(t)&&this._app.use(p.static(t)),this._app.get("*",((e,s)=>{c(t)?s.sendFile(t+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(I.NOT_FOUND),s.json({message:'File "index.html" not found'}))}))}t.forEach((t=>{const e=a(),r=this._middlewares(t),o=this._parameters(t);this._extends(t).forEach((t=>{r.push(...this._middlewares(t)),o.push(...this._parameters(t))})),this._routers(t).forEach((n=>{const _=n.propertyKey.toString();if(i(t[_])){if(!i(e[n.method]))return this.error(new Error('Method "'+n.method+'" Not Found'),"express");const h=this._handles(t,_,r,o);return e[n.method](n.path,...h,((e,r,i)=>l(this,void 0,void 0,(function*(){const n=new S(e,r,i,t),h=this._args(n,e,r,i,this._indexes(_,o)),p=yield t[_](...h);return n.close(E(p)||s(p)?p:void 0),p}))))}return this.error(new Error('Router "'+t.name+"."+_+'" Not Found'),"express")})),this._extends(t).forEach((n=>{this._routers(n).forEach((n=>{const _=n.propertyKey.toString();if(i(t[_])){if(!i(e[n.method]))return this.error(new Error('Method "'+n.method+'" Not Found'),"express");const h=this._handles(t,_,r,o);return e[n.method](n.path,...h,((e,r,i)=>l(this,void 0,void 0,(function*(){const n=new S(e,r,i,t),h=this._args(n,e,r,i,this._indexes(_,o)),p=yield t[_](...h);return n.close(E(p)||s(p)?p:void 0),p}))))}return this.error(new Error('Router "'+t.constructor.name+"."+_+'" Not Found'),"express")}))})),this._controllers.use(this._path(t),e)}))}init(){}error(e,s){t.error(n(s)?e:s+":",e)}log(e,s){t.info(n(s)?e:s+":",e)}_args(t,e,s,r,o,i){const n=[],E={ctx:t,req:e,res:s,next:r,key:"",app:this,argument:i};return o.forEach((t=>{n[t.parameterIndex]=t.callback(Object.assign(Object.assign({},E),{key:t.key}))})),n}_handles(t,e,s,r){return s.filter((t=>t.propertyKey==e)).map((e=>{if(i(t[e.method])){const s=this._indexes(e.method,r);return(r,o,n)=>{const E=new S(r,o,n,t),_=i(e.argument)?e.argument(E):e.argument;return t[e.method](...this._args(E,r,o,n,s,_))}}this.error(new Error('Middleware "'+e.method+'" Not Found'),"express")})).filter(i)}_extends(t){return m(f.EXTENDS,t,[]).reduce(((t,e)=>(t.push(e,...this._extends(e)),t)),[]).filter(((t,e,s)=>s.indexOf(t)===e))}_indexes(t,e){return e.filter((e=>e.propertyKey==t))}_middlewares(t){return[...m(f.MIDDLEWARE,t,[])].reverse()}_parameters(t){return m(f.PARAMETERS,t,[])}_path(t){return m(f.PATH,t,"/")}_routers(t){return m(f.ROUTERS,t,[])}listen(){return l(this,void 0,void 0,(function*(){if(this._options.cert&&this._options.key||(this._server=O.createServer(this._app),this._server.listen(this._options.port,(()=>this.log("Server started on port "+this._options.port,"express")))),!this._server){const t=O.createServer(((t,e)=>{const s=80==this._options.port?":80":"";e.writeHead(I.MOVED_PERMANENTLY,{Location:"https://"+t.headers.host+s+t.url}),e.end()})),e=R.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new N((s=>{s.once("data",(r=>{s.pause(),s.unshift(r),(22===r[0]?e:t).emit("connection",s),process.nextTick((()=>s.resume()))}))})).listen(this._options.port,(()=>this.log("Server started on port "+this._options.port,"express"))),this._server=e}this._server||(443==this._options.port&&t.listen(80,(()=>this.log("Server started on port 80","express"))),e.listen(this._options.port,(()=>this.log("Server started on port "+this._options.port,"express"))),this._server=e)}}))}}const P=t=>e=>{m(f.PATH,e,(null==t?void 0:t.length)?t:"/")},v=t=>e=>{m(f.EXTENDS,e,[]).push(t)},C=t=>e=>(s,r)=>{m(f.ROUTERS,s,[]).push({method:t,path:(null==e?void 0:e.length)?e:"/",propertyKey:r})},y=C(U.ALL),g=C(U.GET),x=C(U.POST),M=C(U.PUT),F=C(U.DELETE),w=C(U.PATCH),H=C(U.HEAD),k=C(U.OPTIONS),G=(t,e)=>(s,r)=>{m(f.MIDDLEWARE,s,[]).push({method:t,argument:e,propertyKey:r})},Q=t=>e=>(s,r,o)=>{m(f.PARAMETERS,s,[]).push({callback:t,key:e,propertyKey:r,parameterIndex:o})},K=(t,e)=>n(e)?t:t[e],Y=Q((({app:t})=>t)),b=Q((({argument:t})=>t)),j=Q((({req:t,key:e})=>K(t.body,e))),V=Q((({req:t,key:e})=>K(t.cookies,e))),W=Q((({ctx:t})=>t)),q=Q((({req:t,key:e})=>K(t.headers,e))),B=Q((({req:t,key:e})=>K(t.params,e))),X=Q((({req:t,key:e})=>K(t.query,e))),z=Q((({req:t})=>t.session));export{y as All,Y as App,L as Application,b as Argument,j as Body,S as Context,P as Controller,V as Cookies,W as Ctx,F as Delete,v as Extends,g as Get,H as Head,q as Headers,m as Metadata,f as MetadataKeys,U as Methods,G as Middleware,k as Options,B as Params,w as Patch,x as Post,M as Put,X as Query,z as Session,I as Status,C as methodFactory,Q as parameterFactory};
7
+ import{Metadata as t,Log as e}from"@andrewcaires/node";import{EventEmitter as s,merge as r,isObject as i,isFunction as o,isArray as n,isUndefined as h,toArray as E,cache as a,uuidv4 as _}from"@andrewcaires/utils.js";import p from"cookie-parser";import d from"cors";import u,{Router as l,json as c,urlencoded as T}from"express";import O from"express-session";import{existsSync as R}from"fs";import*as N from"http";import*as m from"https";import{Server as A}from"net";import{resolve as I,join as S}from"path";import f from"multer";function D(t,e,s,r){return new(s||(s=Promise))((function(i,o){function n(t){try{E(r.next(t))}catch(t){o(t)}}function h(t){try{E(r.throw(t))}catch(t){o(t)}}function E(t){var e;t.done?i(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(n,h)}E((r=r.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class U{}U.CONTINUE=100,U.SWITCHING_PROTOCOLS=101,U.PROCESSING=102,U.OK=200,U.CREATED=201,U.ACCEPTED=202,U.NON_AUTHORITATIVE_INFORMATION=203,U.NO_CONTENT=204,U.RESET_CONTENT=205,U.PARTIAL_CONTENT=206,U.MULTI_STATUS=207,U.ALREADY_REPORTED=208,U.IM_USED=226,U.MULTIPLE_CHOICES=300,U.MOVED_PERMANENTLY=301,U.FOUND=302,U.SEE_OTHER=303,U.NOT_MODIFIED=304,U.USE_PROXY=305,U.TEMPORARY_REDIRECT=307,U.PERMANENT_REDIRECT=308,U.BAD_REQUEST=400,U.UNAUTHORIZED=401,U.PAYMENT_REQUIRED=402,U.FORBIDDEN=403,U.NOT_FOUND=404,U.METHOD_NOT_ALLOWED=405,U.NOT_ACCEPTABLE=406,U.PROXY_AUTHENTICATION_REQUIRED=407,U.REQUEST_TIMEOUT=408,U.CONFLICT=409,U.GONE=410,U.LENGTH_REQUIRED=411,U.PRECONDITION_FAILED=412,U.PAYLOAD_TOO_LARGE=413,U.REQUEST_URI_TOO_LONG=414,U.UNSUPPORTED_MEDIA_TYPE=415,U.REQUESTED_RANGE_NOT_SATISFIABLE=416,U.EXPECTATION_FAILED=417,U.IM_A_TEAPOT=418,U.MISDIRECTED_REQUEST=421,U.UNPROCESSABLE_ENTITY=422,U.LOCKED=423,U.FAILED_DEPENDENCY=424,U.UPGRADE_REQUIRED=426,U.PRECONDITION_REQUIRED=428,U.TOO_MANY_REQUESTS=429,U.REQUEST_HEADER_FIELDS_TOO_LARGE=431,U.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,U.UNAVAILABLE_FOR_LEGAL_REASONS=451,U.CLIENT_CLOSED_REQUEST=499,U.INTERNAL_SERVER_ERROR=500,U.NOT_IMPLEMENTED=501,U.BAD_GATEWAY=502,U.SERVICE_UNAVAILABLE=503,U.GATEWAY_TIMEOUT=504,U.HTTP_VERSION_NOT_SUPPORTED=505,U.VARIANT_ALSO_NEGOCIATES=506,U.INSUFFICIENT_STORAGE=507,U.LOOP_DETECTED=508,U.NOT_EXTENDED=510,U.NETWORK_AUTHENTICATION_REQUIRED=511,U.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class y{constructor(t,e,s,r){this.req=t,this.res=e,this.next=s,this.controller=r}close(t){this.res.headersSent||this.res.json(t||this.storage)}destroy(t){var e;t&&this.error(t.message),null===(e=this.res.socket)||void 0===e||e.destroy(t)}error(t){this.send(U.INTERNAL_SERVER_ERROR,{message:t})}file(t){this.res.headersSent||(this.status(U.OK),this.res.sendFile(I(t)))}json(t){this.send(U.OK,t)}notFound(t){this.send(U.NOT_FOUND,{message:t})}prepare(t,e){this.res.headersSent||(this.status(t),this.storage=e)}send(t,e){this.res.headersSent||(this.status(t),this.res.json(e))}status(t){return t&&this.res.status(t),this.res.statusCode}success(t){this.send(U.OK,{message:t})}unauthorized(t){this.send(U.UNAUTHORIZED,{message:t})}validation(t){this.send(U.BAD_REQUEST,{message:t})}}class v{static extends(e){return t(v.EXTENDS,e,[])}static middleware(e){return t(v.MIDDLEWARE,e,[])}static parameters(e){return t(v.PARAMETERS,e,[])}static path(e,s){return t(v.PATH,e,s)}static routers(e){return t(v.ROUTERS,e,[])}}v.EXTENDS=Symbol(),v.MIDDLEWARE=Symbol(),v.PARAMETERS=Symbol(),v.PATH=Symbol(),v.ROUTERS=Symbol();class L extends s{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(t,e){var s;super(),this._app=u(),this._options={},this._default={cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},this._router=l(),this._controllers=l(),this._options=r(Object.assign({},this._default),Object.assign({},e)),this._app.use(c(this._options.json)),this._app.disable("x-powered-by"),this._app.use(T({extended:!0})),this._options.cross&&this._app.use(d(i(this._options.cross)?this._options.cross:{}));const h=this._options.cookie;this._app.use(p(null==h?void 0:h.secret,null==h?void 0:h.options)),this._app.use(O(this._options.session)),this.init(),this._app.use(this._router);const E=(null===(s=this._options.path)||void 0===s?void 0:s.length)?this._options.path:"/";if(this._app.use(E,this._controllers),this._app.all(E+"/*",((t,e)=>{this._options.redirect?e.redirect(this._options.redirect):(e.status(U.NOT_FOUND),e.json({message:"Invalid API"}))})),this._options.public){const t=I(this._options.public);R(t)&&this._app.use(u.static(t)),this._app.get("*",((e,s)=>{R(t)?s.sendFile(t+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(U.NOT_FOUND),s.json({message:'File "index.html" not found'}))}))}t.forEach((t=>{const e=l(),s=this._middlewares(t),r=v.parameters(t);this._extends(t).forEach((t=>{s.push(...this._middlewares(t)),r.push(...v.parameters(t))})),v.routers(t).forEach((h=>{const E=h.propertyKey.toString();if(o(t[E])){if(!o(e[h.method]))return this._notFound(h.method);const a=this._handles(t,E,s,r);return e[h.method](h.path,...a,((e,s,o)=>D(this,void 0,void 0,(function*(){const h=new y(e,s,o,t),a=this._args(h,this._indexes(E,r)),_=yield t[E](...a);h.close(n(_)||i(_)?_:void 0)}))))}this._notFound(`${t.name}.${E}`)})),this._extends(t).forEach((h=>{v.routers(h).forEach((h=>{const E=h.propertyKey.toString();if(o(t[E])){if(!o(e[h.method]))return this._notFound(h.method);const a=this._handles(t,E,s,r);return e[h.method](h.path,...a,((e,s,o)=>D(this,void 0,void 0,(function*(){const h=new y(e,s,o,t),a=this._args(h,this._indexes(E,r)),_=yield t[E](...a);h.close(n(_)||i(_)?_:void 0)}))))}this._notFound(`${t.constructor.name}.${E}`)}))})),this._controllers.use(v.path(t,"/"),e)}))}init(){}error(t,s){e.error(t)}log(t,s){e.info(t)}_args(t,e,s){const r=[],i={ctx:t,key:"",app:this,argument:s};return e.forEach((t=>{r[t.parameterIndex]=t.callback(Object.assign(Object.assign({},i),{key:t.key}))})),r}_handles(t,e,s,r){return s.filter((t=>t.propertyKey==e)).map((e=>{if(o(t[e.method])){const s=this._indexes(e.method,r);return(r,h,E)=>D(this,void 0,void 0,(function*(){const a=new y(r,h,E,t),_=o(e.argument)?e.argument(a):e.argument,p=yield t[e.method](...this._args(a,s,_));(n(p)||i(p))&&a.close(p)}))}this._notFound(e.method)})).filter(o)}_extends(t){return v.extends(t).reduce(((t,e)=>(t.push(e,...this._extends(e)),t)),[]).filter(((t,e,s)=>s.indexOf(t)===e))}_indexes(t,e){return e.filter((e=>e.propertyKey==t))}_middlewares(t){return[...v.middleware(t)].reverse()}_notFound(t){this.error(new Error(`Router "${t}" not found`),"express")}_port(t){return`Server listening on port ${t}`}listen(){return D(this,void 0,void 0,(function*(){if(this._options.cert&&this._options.key||(this._server=N.createServer(this._app),this._server.listen(this._options.port,(()=>this.log(this._port(this._options.port),"express")))),!this._server){const t=N.createServer(((t,e)=>{const s=80==this._options.port?":80":"";e.writeHead(U.MOVED_PERMANENTLY,{Location:`https://${t.headers.host}${s}${t.url}`}),e.end()})),e=m.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new A((s=>{s.once("data",(r=>{s.pause(),s.unshift(r),(22===r[0]?e:t).emit("connection",s),process.nextTick((()=>s.resume()))}))})).listen(this._options.port,(()=>this.log(this._port(this._options.port),"express"))),this._server=e}this._server||(443==this._options.port&&t.listen(80,(()=>this.log(this._port(80),"express"))),e.listen(this._options.port,(()=>this.log(this._port(this._options.port),"express"))),this._server=e)}}))}}const g=t=>e=>{v.path(e,(null==t?void 0:t.length)?t:"/")},P=t=>e=>{v.extends(e).push(t)};var x;!function(t){t.ALL="all",t.GET="get",t.POST="post",t.PUT="put",t.HEAD="head",t.DELETE="delete",t.OPTIONS="options",t.PATCH="patch"}(x||(x={}));const C=t=>e=>(s,r)=>{v.routers(s).push({method:t,path:(null==e?void 0:e.length)?e:"/",propertyKey:r})},F=C(x.ALL),M=C(x.DELETE),k=C(x.GET),w=C(x.HEAD),b=(t,e)=>(s,r)=>{v.middleware(s).push({method:t,argument:e,propertyKey:r})},H=C(x.OPTIONS),G=C(x.PATCH),Q=C(x.POST),K=C(x.PUT),Y=t=>e=>(s,r,i)=>{v.parameters(s).push({callback:t,key:e,propertyKey:r,parameterIndex:i})},j=Y((({app:t})=>t)),q=Y((({argument:t})=>t)),V=(t,e)=>h(e)?t:t[e],B=Y((({ctx:t,key:e})=>V(t.req.body,e))),W=Y((({ctx:t,key:e})=>V(t.req.cookies,e))),$=Y((({ctx:t})=>t)),X=Y((({ctx:t})=>E(t.req.files))),z=Y((({ctx:t,key:e})=>V(t.req.headers,e))),Z=Y((({ctx:t,key:e})=>V(t.req.params,e))),J=Y((({ctx:t,key:e})=>V(t.req.query,e))),tt=Y((({ctx:t})=>t.req.session));class et{static file(t,e){const s=_()+"."+e;return R(S(t,s))?et.file(t,e):s}static middleware(t,e){const s=et._cache(e);s.upload||(s.upload=et.multer(e)),s.upload(t.req,t.res,(e=>{if(e)return t.destroy(e);t.next()}))}static multer(t){const e=(null==t?void 0:t.path)||"./",s=f.diskStorage({destination:(t,s,r)=>r(null,e),filename:(t,s,r)=>D(this,void 0,void 0,(function*(){return r(null,et.file(e,s.originalname.split(".").pop()||"bin"))}))}),r=(null==t?void 0:t.types)||[];return f({storage:s,fileFilter(t,e,s){return D(this,void 0,void 0,(function*(){if(r.length){const t=e.originalname.split(".").pop()||"bin";return-1!=r.indexOf(e.mimetype)||-1!=r.indexOf(t)?s(null,!0):s(new Error("File not allowed"))}return s(null,!0)}))},limits:{fileSize:1e6*((null==t?void 0:t.size)||5)}}).array((null==t?void 0:t.field)||"field",(null==t?void 0:t.count)||1)}}et._cache=a();export{F as All,j as App,L as Application,q as Argument,B as Body,y as Context,g as Controller,W as Cookies,$ as Ctx,M as Delete,P as Extends,X as Files,k as Get,w as Head,z as Headers,v as Metadata,x as Methods,b as Middleware,H as Options,Z as Params,G as Patch,Q as Post,K as Put,J as Query,tt as Session,U as Status,et as Upload,C as methodFactory,Y as parameterFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrewcaires/express",
3
- "version": "1.1.9",
3
+ "version": "1.1.11",
4
4
  "description": "Decorators for express",
5
5
  "main": "./dist/index.cjs.js",
6
6
  "types": "./dist/index.d.ts",
@@ -35,27 +35,27 @@
35
35
  },
36
36
  "homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
37
37
  "dependencies": {
38
- "@andrewcaires/node": "^1.1.0",
39
- "@andrewcaires/utils.js": "^0.3.1",
38
+ "@andrewcaires/node": "^1.1.5",
39
+ "@andrewcaires/utils.js": "^0.3.5",
40
40
  "cookie-parser": "^1.4.6",
41
41
  "cors": "^2.8.5",
42
- "express": "^4.19.2",
42
+ "express": "^4.21.0",
43
43
  "express-session": "^1.18.0",
44
44
  "multer": "^1.4.5-lts.1"
45
45
  },
46
46
  "devDependencies": {
47
- "@rollup/plugin-commonjs": "^26.0.1",
47
+ "@rollup/plugin-commonjs": "^28.0.0",
48
48
  "@rollup/plugin-terser": "^0.4.4",
49
- "@rollup/plugin-typescript": "^11.1.6",
49
+ "@rollup/plugin-typescript": "^12.1.0",
50
50
  "@types/cookie-parser": "^1.4.7",
51
51
  "@types/cors": "^2.8.17",
52
52
  "@types/express": "^4.17.21",
53
53
  "@types/express-session": "^1.18.0",
54
- "@types/multer": "^1.4.11",
55
- "@types/node": "^20.14.2",
56
- "eslint": "^9.5.0",
54
+ "@types/multer": "^1.4.12",
55
+ "@types/node": "^22.7.0",
56
+ "eslint": "^9.11.1",
57
57
  "rollup-plugin-dts": "^6.1.1",
58
- "tslib": "^2.6.3",
59
- "typescript-eslint": "^8.0.0-alpha.30"
58
+ "tslib": "^2.7.0",
59
+ "typescript-eslint": "^8.7.0"
60
60
  }
61
61
  }