@andrewcaires/express 1.1.4 → 1.1.5

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,85 +16,85 @@ The module is now available on npm! `npm i @andrewcaires/express`
16
16
  ```js
17
17
  // index.ts
18
18
 
19
- import {
20
-
21
- Application,
22
- Argument,
23
- Body,
24
- Controller,
25
- Delete,
26
- Get,
27
- Middleware,
28
- Next,
29
- Params,
30
- Post,
31
- Put,
32
- Res,
33
- Responses
34
-
35
- } from "@andrewcaires/express";
36
- import { NextFunction, Response } from "express";
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 ".";
37
22
 
38
23
  @Controller("/test")
39
24
  class TestController {
40
25
 
41
26
  public middleware(
42
27
  @Argument() arg: string,
43
- @Next() next: NextFunction
44
- ) {
28
+ @Next() next: TypeCallbackFunction
29
+ ): void {
45
30
 
46
31
  console.log("middleware", arg);
47
32
 
48
- return next();
33
+ next();
49
34
  }
50
35
 
51
36
  @Post()
52
37
  @Middleware("middleware", "add")
53
38
  public add(
54
- @Res() res: Response,
39
+ @Ctx() ctx: Context,
55
40
  @Body() body: any
56
- ) {
41
+ ): void {
57
42
 
58
- return Responses.data(res, body);
43
+ ctx.data(body);
59
44
  }
60
45
 
61
46
  @Get()
62
47
  @Middleware("middleware", "all")
63
48
  public all(
64
- @Res() res: Response
65
- ) {
49
+ @Ctx() ctx: Context
50
+ ): void {
66
51
 
67
- return Responses.list(res, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
52
+ ctx.list([1, 2, 3, 4, 5, 6, 7, 8, 9]);
68
53
  }
69
54
 
70
55
  @Delete("/:id")
71
56
  @Middleware("middleware", "del")
72
57
  public del(
73
- @Res() res: Response,
58
+ @Ctx() ctx: Context,
74
59
  @Params("id") id: string
75
- ) {
60
+ ): void {
76
61
 
77
- return Responses.success(res, id);
62
+ ctx.success(id);
78
63
  }
79
64
 
80
65
  @Get("/:id")
81
66
  @Middleware("middleware", "get")
82
67
  public get(
83
- @Res() res: Response,
68
+ @Ctx() ctx: Context,
84
69
  @Params("id") id: string
85
- ) {
70
+ ): void {
86
71
 
87
- return Responses.data(res, { id, name: "test" });
72
+ ctx.data({ id, name: "TestController" });
88
73
  }
89
74
 
90
75
  @Put("/:id")
91
76
  @Middleware("middleware", "set")
92
77
  public set(
93
- @Res() res: Response,
78
+ @Ctx() ctx: Context,
79
+ @Params("id") id: string
80
+ ): void {
81
+
82
+ ctx.success(id);
83
+ }
84
+ }
85
+
86
+ @Controller("/test2")
87
+ @Extends(TestController)
88
+ class Test2Controller extends TestController {
89
+
90
+ @Get("/:id")
91
+ @Middleware("middleware", "get")
92
+ public get(
93
+ @Ctx() ctx: Context,
94
94
  @Params("id") id: string
95
- ) {
95
+ ): void {
96
96
 
97
- return Responses.success(res, id);
97
+ ctx.data({ id, name: "Test2Controller" });
98
98
  }
99
99
  }
100
100
 
@@ -103,10 +103,12 @@ const main = async () => {
103
103
  const app = new Application([
104
104
 
105
105
  new TestController,
106
+ new Test2Controller,
106
107
 
107
108
  ], {
108
109
 
109
110
  path: "/api",
111
+ port: 8081,
110
112
 
111
113
  });
112
114
 
package/dist/index.cjs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v1.1.4
2
+ * @andrewcaires/express v1.1.5
3
3
  * Decorators for express
4
4
  * (c) 2024 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- "use strict";var e=require("@andrewcaires/utils.js"),t=require("cookie-parser"),s=require("cors"),r=require("express"),o=require("express-session"),i=require("fs"),n=require("http"),a=require("https"),p=require("net"),E=require("path");function h(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 _=h(n),u=h(a);function d(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 c{}c.CONTINUE=100,c.SWITCHING_PROTOCOLS=101,c.PROCESSING=102,c.OK=200,c.CREATED=201,c.ACCEPTED=202,c.NON_AUTHORITATIVE_INFORMATION=203,c.NO_CONTENT=204,c.RESET_CONTENT=205,c.PARTIAL_CONTENT=206,c.MULTI_STATUS=207,c.ALREADY_REPORTED=208,c.IM_USED=226,c.MULTIPLE_CHOICES=300,c.MOVED_PERMANENTLY=301,c.FOUND=302,c.SEE_OTHER=303,c.NOT_MODIFIED=304,c.USE_PROXY=305,c.TEMPORARY_REDIRECT=307,c.PERMANENT_REDIRECT=308,c.BAD_REQUEST=400,c.UNAUTHORIZED=401,c.PAYMENT_REQUIRED=402,c.FORBIDDEN=403,c.NOT_FOUND=404,c.METHOD_NOT_ALLOWED=405,c.NOT_ACCEPTABLE=406,c.PROXY_AUTHENTICATION_REQUIRED=407,c.REQUEST_TIMEOUT=408,c.CONFLICT=409,c.GONE=410,c.LENGTH_REQUIRED=411,c.PRECONDITION_FAILED=412,c.PAYLOAD_TOO_LARGE=413,c.REQUEST_URI_TOO_LONG=414,c.UNSUPPORTED_MEDIA_TYPE=415,c.REQUESTED_RANGE_NOT_SATISFIABLE=416,c.EXPECTATION_FAILED=417,c.IM_A_TEAPOT=418,c.MISDIRECTED_REQUEST=421,c.UNPROCESSABLE_ENTITY=422,c.LOCKED=423,c.FAILED_DEPENDENCY=424,c.UPGRADE_REQUIRED=426,c.PRECONDITION_REQUIRED=428,c.TOO_MANY_REQUESTS=429,c.REQUEST_HEADER_FIELDS_TOO_LARGE=431,c.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,c.UNAVAILABLE_FOR_LEGAL_REASONS=451,c.CLIENT_CLOSED_REQUEST=499,c.INTERNAL_SERVER_ERROR=500,c.NOT_IMPLEMENTED=501,c.BAD_GATEWAY=502,c.SERVICE_UNAVAILABLE=503,c.GATEWAY_TIMEOUT=504,c.HTTP_VERSION_NOT_SUPPORTED=505,c.VARIANT_ALSO_NEGOCIATES=506,c.INSUFFICIENT_STORAGE=507,c.LOOP_DETECTED=508,c.NOT_EXTENDED=510,c.NETWORK_AUTHENTICATION_REQUIRED=511,c.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class T{constructor(e,t,s){this.req=e,this.res=t,this.next=s}data(e){this.res.headersSent||this.res.status(c.OK).json(Object.assign({},e))}error(e){this.res.headersSent||this.res.status(c.INTERNAL_SERVER_ERROR).json({message:e})}file(e){this.res.headersSent||this.res.status(c.OK).sendFile(E.resolve(e))}list(e){this.res.headersSent||this.res.status(c.OK).json([...e])}notFound(e){this.res.headersSent||this.res.status(c.NOT_FOUND).json({message:e})}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.res.headersSent||this.res.status(c.OK).json({message:e})}unauthorized(e){this.res.headersSent||this.res.status(c.UNAUTHORIZED).json({message:e})}validation(e){this.res.headersSent||this.res.status(c.BAD_REQUEST).json({message:e})}}const O=e.cache(),R=(t,s,r)=>{e.isObject(s)&&(s=s.constructor);const o=O(s);return o[t]||(o[t]=r),o[t]};class l{static success(e,t){return e.status(c.OK).json({message:t})}static data(e,t){return e.status(c.OK).json(Object.assign({},t))}static error(e,t){return e.status(c.INTERNAL_SERVER_ERROR).json({message:t})}static list(e,t){return e.status(c.OK).json([...t])}static notfound(e,t){return e.status(c.NOT_FOUND).json({message:t})}static validation(e,t){return e.status(c.BAD_REQUEST).json({message:t})}static unauthorized(e,t){return e.status(c.UNAUTHORIZED).json({message:t})}}var x,N;exports.MetadataKeys=void 0,(x=exports.MetadataKeys||(exports.MetadataKeys={})).EXTENDS="__extends__",x.MIDDLEWARE="__middleware__",x.PARAMETERS="__parameters__",x.PATH="__path__",x.ROUTERS="__routers__",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";class A extends e.EventEmitter{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(n,a){var p;super(),this._app=r(),this._options={},this._default={cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},this._router=r.Router(),this._controllers=r.Router(),this._options=e.merge(Object.assign({},this._default),Object.assign({},a)),this._app.use(r.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(r.urlencoded({extended:!0})),this._options.cross&&this._app.use(s(e.isObject(this._options.cross)?this._options.cross:{}));const h=this._options.cookie;this._app.use(t(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 _=(null===(p=this._options.path)||void 0===p?void 0:p.length)?this._options.path:"/";if(this._app.use(_,this._controllers),this._app.all(_+"/*",((e,t)=>{this._options.redirect?t.redirect(this._options.redirect):l.notfound(t,"Invalid API")})),this._options.public){const e=E.resolve(this._options.public);i.existsSync(e)&&this._app.use(r.static(e)),this._app.get("*",((t,s)=>{i.existsSync(e)?s.sendFile(e+"/index.html"):this._options.redirect?s.redirect(this._options.redirect):l.notfound(s,'File "index.html" not found')}))}n.forEach((t=>{const s=r.Router(),o=this._middlewares(t),i=this._parameters(t);this._extends(t).forEach((e=>{o.push(...this._middlewares(e)),i.push(...this._parameters(e))})),this._routers(t).forEach((r=>{const n=r.propertyKey.toString();if(e.isFunction(t[n])){if(!e.isFunction(s[r.method]))return this.error(new Error('Method "'+r.method+'" Not Found'),"express");const a=this._handles(t,n,o,i);return s[r.method](r.path,...a,((s,r,o)=>d(this,void 0,void 0,(function*(){const a=new T(s,r,o),p=this._args(a,s,r,o,this._indexes(n,i)),E=yield t[n](...p);return E&&!r.headersSent&&(e.isArray(E)||e.isObject(E))&&r.send(E),E}))))}return this.error(new Error('Router "'+t.name+"."+n+'" Not Found'),"express")})),this._extends(t).forEach((r=>{this._routers(r).forEach((r=>{const n=r.propertyKey.toString();if(e.isFunction(t[n])){if(!e.isFunction(s[r.method]))return this.error(new Error('Method "'+r.method+'" Not Found'),"express");const a=this._handles(t,n,o,i);return s[r.method](r.path,...a,((s,r,o)=>d(this,void 0,void 0,(function*(){const a=new T(s,r,o),p=this._args(a,s,r,o,this._indexes(n,i)),E=yield t[n](...p);return E&&!r.headersSent&&(e.isArray(E)||e.isObject(E))&&r.send(E),E}))))}return this.error(new Error('Router "'+t.constructor.name+"."+n+'" Not Found'),"express")}))})),this._controllers.use(this._path(t),s)}))}init(){}error(t,s){e.isUndefined(s)?console.error(t):console.error(s+":",t)}log(t,s){e.isUndefined(s)?console.log(t):console.log(s+":",t)}_args(e,t,s,r,o,i){const n=[],a={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({},a),{key:e.key}))})),n}_handles(t,s,r,o){return r.filter((e=>e.propertyKey==s)).map((s=>{if(e.isFunction(t[s.method])){const e=this._indexes(s.method,o);return(r,o,i)=>{const n=new T(r,o,i);return t[s.method](...this._args(n,r,o,i,e,s.argument))}}this.error(new Error('Middleware "'+s.method+'" Not Found'),"express")})).filter(e.isFunction)}_extends(e){return R(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[...R(exports.MetadataKeys.MIDDLEWARE,e,[])].reverse()}_parameters(e){return R(exports.MetadataKeys.PARAMETERS,e,[])}_path(e){return R(exports.MetadataKeys.PATH,e,"/")}_routers(e){return R(exports.MetadataKeys.ROUTERS,e,[])}listen(){return d(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("Server started on port "+this._options.port,"express")))),!this._server){const e=_.createServer(((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(301,{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 p.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 S=e=>t=>(s,r)=>{R(exports.MetadataKeys.ROUTERS,s,[]).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},I=S(exports.Methods.ALL),D=S(exports.Methods.GET),y=S(exports.Methods.POST),U=S(exports.Methods.PUT),M=S(exports.Methods.DELETE),m=S(exports.Methods.PATCH),f=S(exports.Methods.HEAD),P=S(exports.Methods.OPTIONS),v=e=>t=>(s,r,o)=>{R(exports.MetadataKeys.PARAMETERS,s,[]).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},L=(t,s)=>e.isUndefined(s)?t:t[s],g=v((({app:e})=>e)),C=v((({argument:e})=>e)),F=v((({req:e,key:t})=>L(e.body,t))),j=v((({req:e,key:t})=>L(e.cookies,t))),K=v((({ctx:e})=>e)),b=v((({req:e,key:t})=>L(e.headers,t))),H=v((({next:e})=>e)),k=v((({req:e,key:t})=>L(e.params,t))),w=v((({req:e,key:t})=>L(e.query,t))),q=v((({req:e,key:t})=>L(e,t))),G=v((({res:e})=>e)),Q=v((({req:e})=>e.session));exports.All=I,exports.App=g,exports.Application=A,exports.Argument=C,exports.Body=F,exports.Context=T,exports.Controller=e=>t=>{R(exports.MetadataKeys.PATH,t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=j,exports.Ctx=K,exports.Delete=M,exports.Extends=e=>t=>{R(exports.MetadataKeys.EXTENDS,t,[]).push(e)},exports.Get=D,exports.Head=f,exports.Headers=b,exports.Metadata=R,exports.Middleware=(e,t)=>(s,r)=>{R(exports.MetadataKeys.MIDDLEWARE,s,[]).push({method:e,argument:t,propertyKey:r})},exports.Next=H,exports.Options=P,exports.Params=k,exports.Patch=m,exports.Post=y,exports.Put=U,exports.Query=w,exports.Req=q,exports.Res=G,exports.Responses=l,exports.Session=Q,exports.Status=c,exports.methodFactory=S,exports.parameterFactory=v;
7
+ "use strict";var e=require("@andrewcaires/utils.js"),t=require("cookie-parser"),s=require("cors"),r=require("express"),o=require("express-session"),i=require("fs"),n=require("http"),p=require("https"),a=require("net"),E=require("path");function h(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 _=h(n),d=h(p);function u(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 c{}c.CONTINUE=100,c.SWITCHING_PROTOCOLS=101,c.PROCESSING=102,c.OK=200,c.CREATED=201,c.ACCEPTED=202,c.NON_AUTHORITATIVE_INFORMATION=203,c.NO_CONTENT=204,c.RESET_CONTENT=205,c.PARTIAL_CONTENT=206,c.MULTI_STATUS=207,c.ALREADY_REPORTED=208,c.IM_USED=226,c.MULTIPLE_CHOICES=300,c.MOVED_PERMANENTLY=301,c.FOUND=302,c.SEE_OTHER=303,c.NOT_MODIFIED=304,c.USE_PROXY=305,c.TEMPORARY_REDIRECT=307,c.PERMANENT_REDIRECT=308,c.BAD_REQUEST=400,c.UNAUTHORIZED=401,c.PAYMENT_REQUIRED=402,c.FORBIDDEN=403,c.NOT_FOUND=404,c.METHOD_NOT_ALLOWED=405,c.NOT_ACCEPTABLE=406,c.PROXY_AUTHENTICATION_REQUIRED=407,c.REQUEST_TIMEOUT=408,c.CONFLICT=409,c.GONE=410,c.LENGTH_REQUIRED=411,c.PRECONDITION_FAILED=412,c.PAYLOAD_TOO_LARGE=413,c.REQUEST_URI_TOO_LONG=414,c.UNSUPPORTED_MEDIA_TYPE=415,c.REQUESTED_RANGE_NOT_SATISFIABLE=416,c.EXPECTATION_FAILED=417,c.IM_A_TEAPOT=418,c.MISDIRECTED_REQUEST=421,c.UNPROCESSABLE_ENTITY=422,c.LOCKED=423,c.FAILED_DEPENDENCY=424,c.UPGRADE_REQUIRED=426,c.PRECONDITION_REQUIRED=428,c.TOO_MANY_REQUESTS=429,c.REQUEST_HEADER_FIELDS_TOO_LARGE=431,c.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,c.UNAVAILABLE_FOR_LEGAL_REASONS=451,c.CLIENT_CLOSED_REQUEST=499,c.INTERNAL_SERVER_ERROR=500,c.NOT_IMPLEMENTED=501,c.BAD_GATEWAY=502,c.SERVICE_UNAVAILABLE=503,c.GATEWAY_TIMEOUT=504,c.HTTP_VERSION_NOT_SUPPORTED=505,c.VARIANT_ALSO_NEGOCIATES=506,c.INSUFFICIENT_STORAGE=507,c.LOOP_DETECTED=508,c.NOT_EXTENDED=510,c.NETWORK_AUTHENTICATION_REQUIRED=511,c.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class T{constructor(e,t,s,r){this.req=e,this.res=t,this.next=s,this.controller=r}can(){return!this.res.headersSent}data(e){this.prepare(c.OK,Object.assign({},e))}destroy(e){this.can()&&this.res.json(e||(this.dispatch||{}))}error(e){this.prepare(c.INTERNAL_SERVER_ERROR,{message:e})}file(e){this.can()&&(this.status(c.OK),this.res.sendFile(E.resolve(e)))}list(e){this.prepare(c.OK,[...e])}notFound(e){this.prepare(c.NOT_FOUND,{message:e})}prepare(e,t){this.can()&&(this.status(e),this.dispatch=t)}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.prepare(c.OK,{message:e})}unauthorized(e){this.prepare(c.UNAUTHORIZED,{message:e})}validation(e){this.prepare(c.BAD_REQUEST,{message:e})}}const O=e.cache(),R=(t,s,r)=>{e.isObject(s)&&(s=s.constructor);const o=O(s);return o[t]||(o[t]=r),o[t]};var l,N;exports.MetadataKeys=void 0,(l=exports.MetadataKeys||(exports.MetadataKeys={})).EXTENDS="__extends__",l.MIDDLEWARE="__middleware__",l.PARAMETERS="__parameters__",l.PATH="__path__",l.ROUTERS="__routers__",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";class x extends e.EventEmitter{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(n,p){var a;super(),this._app=r(),this._options={},this._default={cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},this._router=r.Router(),this._controllers=r.Router(),this._options=e.merge(Object.assign({},this._default),Object.assign({},p)),this._app.use(r.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(r.urlencoded({extended:!0})),this._options.cross&&this._app.use(s(e.isObject(this._options.cross)?this._options.cross:{}));const h=this._options.cookie;this._app.use(t(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 _=(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(c.NOT_FOUND),t.json({message:"Invalid API"}))})),this._options.public){const e=E.resolve(this._options.public);i.existsSync(e)&&this._app.use(r.static(e)),this._app.get("*",((t,s)=>{i.existsSync(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(c.NOT_FOUND),s.json({message:'File "index.html" not found'}))}))}n.forEach((t=>{const s=r.Router(),o=this._middlewares(t),i=this._parameters(t);this._extends(t).forEach((e=>{o.push(...this._middlewares(e)),i.push(...this._parameters(e))})),this._routers(t).forEach((r=>{const n=r.propertyKey.toString();if(e.isFunction(t[n])){if(!e.isFunction(s[r.method]))return this.error(new Error('Method "'+r.method+'" Not Found'),"express");const p=this._handles(t,n,o,i);return s[r.method](r.path,...p,((s,r,o)=>u(this,void 0,void 0,(function*(){const p=new T(s,r,o,t),a=this._args(p,s,r,o,this._indexes(n,i)),E=yield t[n](...a);return p.destroy(e.isArray(E)||e.isObject(E)?E:void 0),E}))))}return this.error(new Error('Router "'+t.name+"."+n+'" Not Found'),"express")})),this._extends(t).forEach((r=>{this._routers(r).forEach((r=>{const n=r.propertyKey.toString();if(e.isFunction(t[n])){if(!e.isFunction(s[r.method]))return this.error(new Error('Method "'+r.method+'" Not Found'),"express");const p=this._handles(t,n,o,i);return s[r.method](r.path,...p,((s,r,o)=>u(this,void 0,void 0,(function*(){const p=new T(s,r,o,t),a=this._args(p,s,r,o,this._indexes(n,i)),E=yield t[n](...a);return p.destroy(e.isArray(E)||e.isObject(E)?E:void 0),E}))))}return this.error(new Error('Router "'+t.constructor.name+"."+n+'" Not Found'),"express")}))})),this._controllers.use(this._path(t),s)}))}init(){}error(t,s){e.isUndefined(s)?console.error(t):console.error(s+":",t)}log(t,s){e.isUndefined(s)?console.log(t):console.log(s+":",t)}_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(t,s,r,o){return r.filter((e=>e.propertyKey==s)).map((s=>{if(e.isFunction(t[s.method])){const r=this._indexes(s.method,o);return(o,i,n)=>{const p=new T(o,i,n,t),a=e.isFunction(s.argument)?s.argument(p):s.argument;return t[s.method](...this._args(p,o,i,n,r,a))}}this.error(new Error('Middleware "'+s.method+'" Not Found'),"express")})).filter(e.isFunction)}_extends(e){return R(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[...R(exports.MetadataKeys.MIDDLEWARE,e,[])].reverse()}_parameters(e){return R(exports.MetadataKeys.PARAMETERS,e,[])}_path(e){return R(exports.MetadataKeys.PATH,e,"/")}_routers(e){return R(exports.MetadataKeys.ROUTERS,e,[])}listen(){return u(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("Server started on port "+this._options.port,"express")))),!this._server){const e=_.createServer(((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(c.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 a.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 A=e=>t=>(s,r)=>{R(exports.MetadataKeys.ROUTERS,s,[]).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},I=A(exports.Methods.ALL),S=A(exports.Methods.GET),D=A(exports.Methods.POST),y=A(exports.Methods.PUT),M=A(exports.Methods.DELETE),U=A(exports.Methods.PATCH),P=A(exports.Methods.HEAD),m=A(exports.Methods.OPTIONS),f=e=>t=>(s,r,o)=>{R(exports.MetadataKeys.PARAMETERS,s,[]).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},v=(t,s)=>e.isUndefined(s)?t:t[s],L=f((({app:e})=>e)),g=f((({argument:e})=>e)),C=f((({req:e,key:t})=>v(e.body,t))),F=f((({req:e,key:t})=>v(e.cookies,t))),K=f((({ctx:e})=>e)),b=f((({req:e,key:t})=>v(e.headers,t))),H=f((({next:e})=>e)),w=f((({req:e,key:t})=>v(e.params,t))),k=f((({req:e,key:t})=>v(e.query,t))),j=f((({req:e})=>e.session));exports.All=I,exports.App=L,exports.Application=x,exports.Argument=g,exports.Body=C,exports.Context=T,exports.Controller=e=>t=>{R(exports.MetadataKeys.PATH,t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=F,exports.Ctx=K,exports.Delete=M,exports.Extends=e=>t=>{R(exports.MetadataKeys.EXTENDS,t,[]).push(e)},exports.Get=S,exports.Head=P,exports.Headers=b,exports.Metadata=R,exports.Middleware=(e,t)=>(s,r)=>{R(exports.MetadataKeys.MIDDLEWARE,s,[]).push({method:e,argument:t,propertyKey:r})},exports.Next=H,exports.Options=m,exports.Params=w,exports.Patch=U,exports.Post=D,exports.Put=y,exports.Query=k,exports.Session=j,exports.Status=c,exports.methodFactory=A,exports.parameterFactory=f;
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  /*!
2
- * @andrewcaires/express v1.1.4
2
+ * @andrewcaires/express v1.1.5
3
3
  * Decorators for express
4
4
  * (c) 2024 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- import { TypeCallbackFunction, TypeObjectAny, EventEmitter } from '@andrewcaires/utils.js';
8
- import { NextFunction, Request, Response, Express, Router } from 'express';
7
+ import { TypeObjectAny, TypeCallbackFunction, EventEmitter } from '@andrewcaires/utils.js';
8
+ import { Request, Response, NextFunction, 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';
@@ -13,21 +13,21 @@ import { CorsOptions } from 'cors';
13
13
  import { SessionOptions } from 'express-session';
14
14
  import { CookieParseOptions } from 'cookie-parser';
15
15
 
16
- type INextFunction = NextFunction;
17
- type IRequest = Request;
18
- type IResponse = Response;
19
- type ResponseJson = Response<any, Record<string, any>>;
20
-
21
- declare class Context {
16
+ declare class Context<T = any> {
22
17
  readonly req: Request;
23
18
  readonly res: Response;
24
19
  readonly next: NextFunction;
25
- constructor(req: Request, res: Response, next: NextFunction);
20
+ readonly controller: T;
21
+ private dispatch?;
22
+ constructor(req: Request, res: Response, next: NextFunction, controller: T);
23
+ can(): boolean;
26
24
  data(obj: object): void;
25
+ destroy(value?: TypeObjectAny): void;
27
26
  error(message: string): void;
28
27
  file(path: string): void;
29
28
  list(arr: Array<any>): void;
30
29
  notFound(message: string): void;
30
+ private prepare;
31
31
  status(value?: number): number;
32
32
  success(message: string): void;
33
33
  unauthorized(message: string): void;
@@ -62,6 +62,7 @@ interface IOptions {
62
62
  hybrid?: boolean;
63
63
  json?: OptionsJson;
64
64
  key?: Buffer;
65
+ notfound?: string;
65
66
  path?: string;
66
67
  port?: number;
67
68
  public?: string;
@@ -162,22 +163,10 @@ declare const Headers: (key?: string) => ParameterDecorator;
162
163
  declare const Next: (key?: string) => ParameterDecorator;
163
164
  declare const Params: (key?: string) => ParameterDecorator;
164
165
  declare const Query: (key?: string) => ParameterDecorator;
165
- declare const Req: (key?: string) => ParameterDecorator;
166
- declare const Res: (key?: string) => ParameterDecorator;
167
166
  declare const Session: (key?: string) => ParameterDecorator;
168
167
 
169
168
  declare const Metadata: <T = any>(metadataKey: MetadataKeys, target: any, metadataValue: T) => T;
170
169
 
171
- declare class Responses {
172
- static success(res: Response, message: string): ResponseJson;
173
- static data(res: Response, obj: object): ResponseJson;
174
- static error(res: Response, message: string): ResponseJson;
175
- static list(res: Response, arr: Array<any>): ResponseJson;
176
- static notfound(res: Response, message: string): ResponseJson;
177
- static validation(res: Response, message: string): ResponseJson;
178
- static unauthorized(res: Response, message: string): ResponseJson;
179
- }
180
-
181
170
  declare class Status {
182
171
  static readonly CONTINUE = 100;
183
172
  static readonly SWITCHING_PROTOCOLS = 101;
@@ -244,4 +233,4 @@ declare class Status {
244
233
  static readonly NETWORK_CONNECTION_TIMEOUT_ERROR = 599;
245
234
  }
246
235
 
247
- export { All, App, Application, Argument, Body, Context, Controller, Cookies, Ctx, Delete, Extends, Get, Head, Headers, type IArgs, type IMiddlewares, type INextFunction, type IOptions, type IParameter, type IRequest, type IResponse, type IRouter, type IStore, Metadata, MetadataKeys, Methods, Middleware, Next, Options, Params, Patch, Post, Put, Query, Req, Res, type ResponseJson, Responses, Session, Status, methodFactory, parameterFactory };
236
+ 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, Next, Options, Params, Patch, Post, Put, Query, Session, Status, methodFactory, parameterFactory };
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v1.1.4
2
+ * @andrewcaires/express v1.1.5
3
3
  * Decorators for express
4
4
  * (c) 2024 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- import{cache as t,isObject as s,EventEmitter as e,merge as r,isFunction as o,isUndefined as i,isArray as n}from"@andrewcaires/utils.js";import E from"cookie-parser";import _ from"cors";import h,{Router as a,json as p,urlencoded as u}from"express";import T from"express-session";import{existsSync as c}from"fs";import*as d from"http";import*as O from"https";import{Server as R}from"net";import{resolve as N}from"path";function A(t,s,e,r){return new(e||(e=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 s;t.done?o(t.value):(s=t.value,s instanceof e?s:new e((function(t){t(s)}))).then(n,E)}_((r=r.apply(t,s||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class l{}l.CONTINUE=100,l.SWITCHING_PROTOCOLS=101,l.PROCESSING=102,l.OK=200,l.CREATED=201,l.ACCEPTED=202,l.NON_AUTHORITATIVE_INFORMATION=203,l.NO_CONTENT=204,l.RESET_CONTENT=205,l.PARTIAL_CONTENT=206,l.MULTI_STATUS=207,l.ALREADY_REPORTED=208,l.IM_USED=226,l.MULTIPLE_CHOICES=300,l.MOVED_PERMANENTLY=301,l.FOUND=302,l.SEE_OTHER=303,l.NOT_MODIFIED=304,l.USE_PROXY=305,l.TEMPORARY_REDIRECT=307,l.PERMANENT_REDIRECT=308,l.BAD_REQUEST=400,l.UNAUTHORIZED=401,l.PAYMENT_REQUIRED=402,l.FORBIDDEN=403,l.NOT_FOUND=404,l.METHOD_NOT_ALLOWED=405,l.NOT_ACCEPTABLE=406,l.PROXY_AUTHENTICATION_REQUIRED=407,l.REQUEST_TIMEOUT=408,l.CONFLICT=409,l.GONE=410,l.LENGTH_REQUIRED=411,l.PRECONDITION_FAILED=412,l.PAYLOAD_TOO_LARGE=413,l.REQUEST_URI_TOO_LONG=414,l.UNSUPPORTED_MEDIA_TYPE=415,l.REQUESTED_RANGE_NOT_SATISFIABLE=416,l.EXPECTATION_FAILED=417,l.IM_A_TEAPOT=418,l.MISDIRECTED_REQUEST=421,l.UNPROCESSABLE_ENTITY=422,l.LOCKED=423,l.FAILED_DEPENDENCY=424,l.UPGRADE_REQUIRED=426,l.PRECONDITION_REQUIRED=428,l.TOO_MANY_REQUESTS=429,l.REQUEST_HEADER_FIELDS_TOO_LARGE=431,l.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,l.UNAVAILABLE_FOR_LEGAL_REASONS=451,l.CLIENT_CLOSED_REQUEST=499,l.INTERNAL_SERVER_ERROR=500,l.NOT_IMPLEMENTED=501,l.BAD_GATEWAY=502,l.SERVICE_UNAVAILABLE=503,l.GATEWAY_TIMEOUT=504,l.HTTP_VERSION_NOT_SUPPORTED=505,l.VARIANT_ALSO_NEGOCIATES=506,l.INSUFFICIENT_STORAGE=507,l.LOOP_DETECTED=508,l.NOT_EXTENDED=510,l.NETWORK_AUTHENTICATION_REQUIRED=511,l.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class S{constructor(t,s,e){this.req=t,this.res=s,this.next=e}data(t){this.res.headersSent||this.res.status(l.OK).json(Object.assign({},t))}error(t){this.res.headersSent||this.res.status(l.INTERNAL_SERVER_ERROR).json({message:t})}file(t){this.res.headersSent||this.res.status(l.OK).sendFile(N(t))}list(t){this.res.headersSent||this.res.status(l.OK).json([...t])}notFound(t){this.res.headersSent||this.res.status(l.NOT_FOUND).json({message:t})}status(t){return t&&this.res.status(t),this.res.statusCode}success(t){this.res.headersSent||this.res.status(l.OK).json({message:t})}unauthorized(t){this.res.headersSent||this.res.status(l.UNAUTHORIZED).json({message:t})}validation(t){this.res.headersSent||this.res.status(l.BAD_REQUEST).json({message:t})}}const I=t(),D=(t,e,r)=>{s(e)&&(e=e.constructor);const o=I(e);return o[t]||(o[t]=r),o[t]};class m{static success(t,s){return t.status(l.OK).json({message:s})}static data(t,s){return t.status(l.OK).json(Object.assign({},s))}static error(t,s){return t.status(l.INTERNAL_SERVER_ERROR).json({message:s})}static list(t,s){return t.status(l.OK).json([...s])}static notfound(t,s){return t.status(l.NOT_FOUND).json({message:s})}static validation(t,s){return t.status(l.BAD_REQUEST).json({message:s})}static unauthorized(t,s){return t.status(l.UNAUTHORIZED).json({message:s})}}var U,f;!function(t){t.EXTENDS="__extends__",t.MIDDLEWARE="__middleware__",t.PARAMETERS="__parameters__",t.PATH="__path__",t.ROUTERS="__routers__"}(U||(U={})),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"}(f||(f={}));class L extends e{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(t,e){var i;super(),this._app=h(),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=r(Object.assign({},this._default),Object.assign({},e)),this._app.use(p(this._options.json)),this._app.disable("x-powered-by"),this._app.use(u({extended:!0})),this._options.cross&&this._app.use(_(s(this._options.cross)?this._options.cross:{}));const d=this._options.cookie;this._app.use(E(null==d?void 0:d.secret,null==d?void 0:d.options)),this._app.use(T(this._options.session)),this.init(),this._app.use(this._router);const O=(null===(i=this._options.path)||void 0===i?void 0:i.length)?this._options.path:"/";if(this._app.use(O,this._controllers),this._app.all(O+"/*",((t,s)=>{this._options.redirect?s.redirect(this._options.redirect):m.notfound(s,"Invalid API")})),this._options.public){const t=N(this._options.public);c(t)&&this._app.use(h.static(t)),this._app.get("*",((s,e)=>{c(t)?e.sendFile(t+"/index.html"):this._options.redirect?e.redirect(this._options.redirect):m.notfound(e,'File "index.html" not found')}))}t.forEach((t=>{const e=a(),r=this._middlewares(t),i=this._parameters(t);this._extends(t).forEach((t=>{r.push(...this._middlewares(t)),i.push(...this._parameters(t))})),this._routers(t).forEach((E=>{const _=E.propertyKey.toString();if(o(t[_])){if(!o(e[E.method]))return this.error(new Error('Method "'+E.method+'" Not Found'),"express");const h=this._handles(t,_,r,i);return e[E.method](E.path,...h,((e,r,o)=>A(this,void 0,void 0,(function*(){const E=new S(e,r,o),h=this._args(E,e,r,o,this._indexes(_,i)),a=yield t[_](...h);return a&&!r.headersSent&&(n(a)||s(a))&&r.send(a),a}))))}return this.error(new Error('Router "'+t.name+"."+_+'" Not Found'),"express")})),this._extends(t).forEach((E=>{this._routers(E).forEach((E=>{const _=E.propertyKey.toString();if(o(t[_])){if(!o(e[E.method]))return this.error(new Error('Method "'+E.method+'" Not Found'),"express");const h=this._handles(t,_,r,i);return e[E.method](E.path,...h,((e,r,o)=>A(this,void 0,void 0,(function*(){const E=new S(e,r,o),h=this._args(E,e,r,o,this._indexes(_,i)),a=yield t[_](...h);return a&&!r.headersSent&&(n(a)||s(a))&&r.send(a),a}))))}return this.error(new Error('Router "'+t.constructor.name+"."+_+'" Not Found'),"express")}))})),this._controllers.use(this._path(t),e)}))}init(){}error(t,s){i(s)?console.error(t):console.error(s+":",t)}log(t,s){i(s)?console.log(t):console.log(s+":",t)}_args(t,s,e,r,o,i){const n=[],E={ctx:t,req:s,res:e,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,s,e,r){return e.filter((t=>t.propertyKey==s)).map((s=>{if(o(t[s.method])){const e=this._indexes(s.method,r);return(r,o,i)=>{const n=new S(r,o,i);return t[s.method](...this._args(n,r,o,i,e,s.argument))}}this.error(new Error('Middleware "'+s.method+'" Not Found'),"express")})).filter(o)}_extends(t){return D(U.EXTENDS,t,[]).reduce(((t,s)=>(t.push(s,...this._extends(s)),t)),[]).filter(((t,s,e)=>e.indexOf(t)===s))}_indexes(t,s){return s.filter((s=>s.propertyKey==t))}_middlewares(t){return[...D(U.MIDDLEWARE,t,[])].reverse()}_parameters(t){return D(U.PARAMETERS,t,[])}_path(t){return D(U.PATH,t,"/")}_routers(t){return D(U.ROUTERS,t,[])}listen(){return A(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 t=d.createServer(((t,s)=>{const e=80==this._options.port?":80":"";s.writeHead(301,{Location:"https://"+t.headers.host+e+t.url}),s.end()})),s=O.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new R((e=>{e.once("data",(r=>{e.pause(),e.unshift(r),(22===r[0]?s:t).emit("connection",e),process.nextTick((()=>e.resume()))}))})).listen(this._options.port,(()=>this.log("Server started on port "+this._options.port,"express"))),this._server=s}this._server||(443==this._options.port&&t.listen(80,(()=>this.log("Server started on port 80","express"))),s.listen(this._options.port,(()=>this.log("Server started on port "+this._options.port,"express"))),this._server=s)}}))}}const P=t=>s=>{D(U.PATH,s,(null==t?void 0:t.length)?t:"/")},g=t=>s=>{D(U.EXTENDS,s,[]).push(t)},C=t=>s=>(e,r)=>{D(U.ROUTERS,e,[]).push({method:t,path:(null==s?void 0:s.length)?s:"/",propertyKey:r})},y=C(f.ALL),v=C(f.GET),x=C(f.POST),M=C(f.PUT),F=C(f.DELETE),j=C(f.PATCH),H=C(f.HEAD),k=C(f.OPTIONS),w=(t,s)=>(e,r)=>{D(U.MIDDLEWARE,e,[]).push({method:t,argument:s,propertyKey:r})},K=t=>s=>(e,r,o)=>{D(U.PARAMETERS,e,[]).push({callback:t,key:s,propertyKey:r,parameterIndex:o})},G=(t,s)=>i(s)?t:t[s],Q=K((({app:t})=>t)),b=K((({argument:t})=>t)),Y=K((({req:t,key:s})=>G(t.body,s))),q=K((({req:t,key:s})=>G(t.cookies,s))),B=K((({ctx:t})=>t)),V=K((({req:t,key:s})=>G(t.headers,s))),W=K((({next:t})=>t)),X=K((({req:t,key:s})=>G(t.params,s))),z=K((({req:t,key:s})=>G(t.query,s))),Z=K((({req:t,key:s})=>G(t,s))),J=K((({res:t})=>t)),$=K((({req:t})=>t.session));export{y as All,Q as App,L as Application,b as Argument,Y as Body,S as Context,P as Controller,q as Cookies,B as Ctx,F as Delete,g as Extends,v as Get,H as Head,V as Headers,D as Metadata,U as MetadataKeys,f as Methods,w as Middleware,W as Next,k as Options,X as Params,j as Patch,x as Post,M as Put,z as Query,Z as Req,J as Res,m as Responses,$ as Session,l as Status,C as methodFactory,K as parameterFactory};
7
+ import{cache as t,isObject as e,EventEmitter as s,merge as r,isFunction as o,isUndefined as i,isArray as n}from"@andrewcaires/utils.js";import E from"cookie-parser";import _ from"cors";import h,{Router as p,json as a,urlencoded as T}from"express";import u from"express-session";import{existsSync as c}from"fs";import*as O from"http";import*as d from"https";import{Server as R}from"net";import{resolve as N}from"path";function A(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 l{}l.CONTINUE=100,l.SWITCHING_PROTOCOLS=101,l.PROCESSING=102,l.OK=200,l.CREATED=201,l.ACCEPTED=202,l.NON_AUTHORITATIVE_INFORMATION=203,l.NO_CONTENT=204,l.RESET_CONTENT=205,l.PARTIAL_CONTENT=206,l.MULTI_STATUS=207,l.ALREADY_REPORTED=208,l.IM_USED=226,l.MULTIPLE_CHOICES=300,l.MOVED_PERMANENTLY=301,l.FOUND=302,l.SEE_OTHER=303,l.NOT_MODIFIED=304,l.USE_PROXY=305,l.TEMPORARY_REDIRECT=307,l.PERMANENT_REDIRECT=308,l.BAD_REQUEST=400,l.UNAUTHORIZED=401,l.PAYMENT_REQUIRED=402,l.FORBIDDEN=403,l.NOT_FOUND=404,l.METHOD_NOT_ALLOWED=405,l.NOT_ACCEPTABLE=406,l.PROXY_AUTHENTICATION_REQUIRED=407,l.REQUEST_TIMEOUT=408,l.CONFLICT=409,l.GONE=410,l.LENGTH_REQUIRED=411,l.PRECONDITION_FAILED=412,l.PAYLOAD_TOO_LARGE=413,l.REQUEST_URI_TOO_LONG=414,l.UNSUPPORTED_MEDIA_TYPE=415,l.REQUESTED_RANGE_NOT_SATISFIABLE=416,l.EXPECTATION_FAILED=417,l.IM_A_TEAPOT=418,l.MISDIRECTED_REQUEST=421,l.UNPROCESSABLE_ENTITY=422,l.LOCKED=423,l.FAILED_DEPENDENCY=424,l.UPGRADE_REQUIRED=426,l.PRECONDITION_REQUIRED=428,l.TOO_MANY_REQUESTS=429,l.REQUEST_HEADER_FIELDS_TOO_LARGE=431,l.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,l.UNAVAILABLE_FOR_LEGAL_REASONS=451,l.CLIENT_CLOSED_REQUEST=499,l.INTERNAL_SERVER_ERROR=500,l.NOT_IMPLEMENTED=501,l.BAD_GATEWAY=502,l.SERVICE_UNAVAILABLE=503,l.GATEWAY_TIMEOUT=504,l.HTTP_VERSION_NOT_SUPPORTED=505,l.VARIANT_ALSO_NEGOCIATES=506,l.INSUFFICIENT_STORAGE=507,l.LOOP_DETECTED=508,l.NOT_EXTENDED=510,l.NETWORK_AUTHENTICATION_REQUIRED=511,l.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class I{constructor(t,e,s,r){this.req=t,this.res=e,this.next=s,this.controller=r}can(){return!this.res.headersSent}data(t){this.prepare(l.OK,Object.assign({},t))}destroy(t){this.can()&&this.res.json(t||(this.dispatch||{}))}error(t){this.prepare(l.INTERNAL_SERVER_ERROR,{message:t})}file(t){this.can()&&(this.status(l.OK),this.res.sendFile(N(t)))}list(t){this.prepare(l.OK,[...t])}notFound(t){this.prepare(l.NOT_FOUND,{message:t})}prepare(t,e){this.can()&&(this.status(t),this.dispatch=e)}status(t){return t&&this.res.status(t),this.res.statusCode}success(t){this.prepare(l.OK,{message:t})}unauthorized(t){this.prepare(l.UNAUTHORIZED,{message:t})}validation(t){this.prepare(l.BAD_REQUEST,{message:t})}}const D=t(),S=(t,s,r)=>{e(s)&&(s=s.constructor);const o=D(s);return o[t]||(o[t]=r),o[t]};var m,U;!function(t){t.EXTENDS="__extends__",t.MIDDLEWARE="__middleware__",t.PARAMETERS="__parameters__",t.PATH="__path__",t.ROUTERS="__routers__"}(m||(m={})),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 f extends s{get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(t,s){var i;super(),this._app=h(),this._options={},this._default={cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},this._router=p(),this._controllers=p(),this._options=r(Object.assign({},this._default),Object.assign({},s)),this._app.use(a(this._options.json)),this._app.disable("x-powered-by"),this._app.use(T({extended:!0})),this._options.cross&&this._app.use(_(e(this._options.cross)?this._options.cross:{}));const O=this._options.cookie;this._app.use(E(null==O?void 0:O.secret,null==O?void 0:O.options)),this._app.use(u(this._options.session)),this.init(),this._app.use(this._router);const d=(null===(i=this._options.path)||void 0===i?void 0:i.length)?this._options.path:"/";if(this._app.use(d,this._controllers),this._app.all(d+"/*",((t,e)=>{this._options.redirect?e.redirect(this._options.redirect):(e.status(l.NOT_FOUND),e.json({message:"Invalid API"}))})),this._options.public){const t=N(this._options.public);c(t)&&this._app.use(h.static(t)),this._app.get("*",((e,s)=>{c(t)?s.sendFile(t+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(l.NOT_FOUND),s.json({message:'File "index.html" not found'}))}))}t.forEach((t=>{const s=p(),r=this._middlewares(t),i=this._parameters(t);this._extends(t).forEach((t=>{r.push(...this._middlewares(t)),i.push(...this._parameters(t))})),this._routers(t).forEach((E=>{const _=E.propertyKey.toString();if(o(t[_])){if(!o(s[E.method]))return this.error(new Error('Method "'+E.method+'" Not Found'),"express");const h=this._handles(t,_,r,i);return s[E.method](E.path,...h,((s,r,o)=>A(this,void 0,void 0,(function*(){const E=new I(s,r,o,t),h=this._args(E,s,r,o,this._indexes(_,i)),p=yield t[_](...h);return E.destroy(n(p)||e(p)?p:void 0),p}))))}return this.error(new Error('Router "'+t.name+"."+_+'" Not Found'),"express")})),this._extends(t).forEach((E=>{this._routers(E).forEach((E=>{const _=E.propertyKey.toString();if(o(t[_])){if(!o(s[E.method]))return this.error(new Error('Method "'+E.method+'" Not Found'),"express");const h=this._handles(t,_,r,i);return s[E.method](E.path,...h,((s,r,o)=>A(this,void 0,void 0,(function*(){const E=new I(s,r,o,t),h=this._args(E,s,r,o,this._indexes(_,i)),p=yield t[_](...h);return E.destroy(n(p)||e(p)?p:void 0),p}))))}return this.error(new Error('Router "'+t.constructor.name+"."+_+'" Not Found'),"express")}))})),this._controllers.use(this._path(t),s)}))}init(){}error(t,e){i(e)?console.error(t):console.error(e+":",t)}log(t,e){i(e)?console.log(t):console.log(e+":",t)}_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(o(t[e.method])){const s=this._indexes(e.method,r);return(r,i,n)=>{const E=new I(r,i,n,t),_=o(e.argument)?e.argument(E):e.argument;return t[e.method](...this._args(E,r,i,n,s,_))}}this.error(new Error('Middleware "'+e.method+'" Not Found'),"express")})).filter(o)}_extends(t){return S(m.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[...S(m.MIDDLEWARE,t,[])].reverse()}_parameters(t){return S(m.PARAMETERS,t,[])}_path(t){return S(m.PATH,t,"/")}_routers(t){return S(m.ROUTERS,t,[])}listen(){return A(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(l.MOVED_PERMANENTLY,{Location:"https://"+t.headers.host+s+t.url}),e.end()})),e=d.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new R((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 L=t=>e=>{S(m.PATH,e,(null==t?void 0:t.length)?t:"/")},P=t=>e=>{S(m.EXTENDS,e,[]).push(t)},y=t=>e=>(s,r)=>{S(m.ROUTERS,s,[]).push({method:t,path:(null==e?void 0:e.length)?e:"/",propertyKey:r})},C=y(U.ALL),g=y(U.GET),v=y(U.POST),x=y(U.PUT),M=y(U.DELETE),F=y(U.PATCH),H=y(U.HEAD),w=y(U.OPTIONS),k=(t,e)=>(s,r)=>{S(m.MIDDLEWARE,s,[]).push({method:t,argument:e,propertyKey:r})},G=t=>e=>(s,r,o)=>{S(m.PARAMETERS,s,[]).push({callback:t,key:e,propertyKey:r,parameterIndex:o})},K=(t,e)=>i(e)?t:t[e],Q=G((({app:t})=>t)),b=G((({argument:t})=>t)),Y=G((({req:t,key:e})=>K(t.body,e))),j=G((({req:t,key:e})=>K(t.cookies,e))),V=G((({ctx:t})=>t)),W=G((({req:t,key:e})=>K(t.headers,e))),q=G((({next:t})=>t)),B=G((({req:t,key:e})=>K(t.params,e))),X=G((({req:t,key:e})=>K(t.query,e))),z=G((({req:t})=>t.session));export{C as All,Q as App,f as Application,b as Argument,Y as Body,I as Context,L as Controller,j as Cookies,V as Ctx,M as Delete,P as Extends,g as Get,H as Head,W as Headers,S as Metadata,m as MetadataKeys,U as Methods,k as Middleware,q as Next,w as Options,B as Params,F as Patch,v as Post,x as Put,X as Query,z as Session,l as Status,y as methodFactory,G as parameterFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrewcaires/express",
3
- "version": "1.1.4",
3
+ "version": "1.1.5",
4
4
  "description": "Decorators for express",
5
5
  "main": "./dist/index.cjs.js",
6
6
  "types": "./dist/index.d.ts",
@@ -35,7 +35,7 @@
35
35
  },
36
36
  "homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
37
37
  "dependencies": {
38
- "@andrewcaires/utils.js": "^0.2.27",
38
+ "@andrewcaires/utils.js": "^0.2.30",
39
39
  "cookie-parser": "^1.4.6",
40
40
  "cors": "^2.8.5",
41
41
  "express": "^4.19.2",
@@ -43,7 +43,7 @@
43
43
  "multer": "^1.4.5-lts.1"
44
44
  },
45
45
  "devDependencies": {
46
- "@rollup/plugin-commonjs": "^25.0.7",
46
+ "@rollup/plugin-commonjs": "^26.0.1",
47
47
  "@rollup/plugin-terser": "^0.4.4",
48
48
  "@rollup/plugin-typescript": "^11.1.6",
49
49
  "@types/cookie-parser": "^1.4.7",
@@ -51,12 +51,12 @@
51
51
  "@types/express": "^4.17.21",
52
52
  "@types/express-session": "^1.18.0",
53
53
  "@types/multer": "^1.4.11",
54
- "@types/node": "^20.12.12",
55
- "@typescript-eslint/eslint-plugin": "^7.10.0",
56
- "@typescript-eslint/parser": "^7.10.0",
54
+ "@types/node": "^20.14.2",
55
+ "@typescript-eslint/eslint-plugin": "^7.13.0",
56
+ "@typescript-eslint/parser": "^7.13.0",
57
57
  "eslint": "^8.57.0",
58
58
  "rollup-plugin-dts": "^6.1.1",
59
59
  "ts-node-dev": "^2.0.0",
60
- "tslib": "^2.6.2"
60
+ "tslib": "^2.6.3"
61
61
  }
62
62
  }