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