@jwn-js/common 2.5.1 → 2.5.3
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/cookieString.d.ts +0 -9
- package/cookieString.js +1 -1
- package/cookieString.mjs +1 -1
- package/docs/assets/search.js +1 -1
- package/docs/classes/ApiError.html +2 -2
- package/docs/classes/AsyncJwt.html +2 -2
- package/docs/classes/Binding.html +2 -2
- package/docs/classes/Controller.html +2 -2
- package/docs/classes/Jwt.html +2 -2
- package/docs/classes/Memcached.html +2 -2
- package/docs/classes/Model.html +2 -2
- package/docs/classes/Server.html +2 -2
- package/docs/classes/Ssr.html +2 -6
- package/docs/classes/Web.html +2 -2
- package/docs/functions/action.html +1 -1
- package/docs/functions/allow.html +1 -1
- package/docs/functions/body.html +1 -1
- package/docs/functions/codeToStatus.html +1 -1
- package/docs/functions/config-1.html +1 -1
- package/docs/functions/connection.html +1 -1
- package/docs/functions/context.html +1 -1
- package/docs/functions/controller-1.html +1 -1
- package/docs/functions/cookies.html +1 -1
- package/docs/functions/db.html +1 -1
- package/docs/functions/headers.html +1 -1
- package/docs/functions/home.html +1 -1
- package/docs/functions/hostname.html +1 -1
- package/docs/functions/http.html +1 -1
- package/docs/functions/init.html +1 -1
- package/docs/functions/inject.html +1 -1
- package/docs/functions/json.html +1 -1
- package/docs/functions/logerror.html +1 -1
- package/docs/functions/method.html +1 -1
- package/docs/functions/mixin.html +1 -1
- package/docs/functions/mount.html +1 -1
- package/docs/functions/pool.html +1 -1
- package/docs/functions/protocol.html +1 -1
- package/docs/functions/remote.html +1 -1
- package/docs/functions/request.html +1 -1
- package/docs/functions/selectControllersSchema.html +1 -1
- package/docs/functions/stream.html +1 -1
- package/docs/functions/subaction.html +1 -1
- package/docs/functions/url.html +1 -1
- package/docs/functions/xml.html +1 -1
- package/docs/index.html +2 -2
- package/docs/interfaces/ApiErrorMessage.html +2 -2
- package/docs/interfaces/Config.html +2 -2
- package/docs/interfaces/ContextSsr.html +2 -2
- package/docs/interfaces/ContextWeb.html +2 -2
- package/docs/interfaces/OptionsSsr.html +3 -2
- package/docs/interfaces/OptionsWeb.html +2 -2
- package/docs/interfaces/ResponseOptions.html +2 -2
- package/docs/interfaces/Route.html +2 -2
- package/docs/interfaces/Schema.html +2 -2
- package/docs/interfaces/ServerHandler.html +2 -2
- package/docs/interfaces/ServerOptions.html +2 -2
- package/docs/interfaces/ServerWebsocket.html +2 -2
- package/docs/modules.html +2 -2
- package/docs/types/ServerRoutes.html +1 -1
- package/docs/variables/helpers.html +2 -11
- package/index.d.ts +16 -10
- package/index.js +3 -3
- package/index.mjs +3 -3
- package/jsonBody.js +1 -1
- package/jsonBody.mjs +1 -1
- package/multipartBody.js +1 -1
- package/multipartBody.mjs +1 -1
- package/package.json +1 -1
- package/readConfig.d.ts +0 -4
- package/readConfigSync.d.ts +0 -4
- package/staticBody.d.ts +0 -9
- package/staticBody.js +1 -1
- package/staticBody.mjs +1 -1
- package/urlencodedBody.d.ts +0 -4
- package/urlencodedBody.js +1 -1
- package/urlencodedBody.mjs +1 -1
package/index.d.ts
CHANGED
|
@@ -4,8 +4,9 @@ import { Stream, PassThrough } from 'stream';
|
|
|
4
4
|
import * as uWebSockets_js from 'uWebSockets.js';
|
|
5
5
|
import { RecognizedString, WebSocketBehavior, AppOptions, TemplatedApp, HttpResponse, HttpRequest } from 'uWebSockets.js';
|
|
6
6
|
import { Client } from 'memjs';
|
|
7
|
-
import {
|
|
7
|
+
import { Context as Context$2 } from 'vite-ssr-vue';
|
|
8
8
|
export { Context as ContextSsr } from 'vite-ssr-vue';
|
|
9
|
+
import { Query } from 'buildmsql';
|
|
9
10
|
|
|
10
11
|
interface ApiErrorMessage {
|
|
11
12
|
message?: string;
|
|
@@ -159,26 +160,30 @@ declare class Memcached {
|
|
|
159
160
|
private objectKeysToLower;
|
|
160
161
|
}
|
|
161
162
|
|
|
162
|
-
/**
|
|
163
|
-
* Reed static files
|
|
164
|
-
*/
|
|
165
163
|
declare function staticBody(res: HttpResponse, req: HttpRequest, base: string): Promise<void>;
|
|
166
164
|
|
|
167
165
|
interface OptionsSsr {
|
|
168
166
|
readonly manifest: Record<string, any>;
|
|
169
167
|
readonly ssrManifest?: Record<string, any>;
|
|
170
168
|
readonly memcached?: Memcached;
|
|
169
|
+
onError?: (e: any, context: Context$2, options: {
|
|
170
|
+
isManifest: boolean;
|
|
171
|
+
isSsrManifest: boolean;
|
|
172
|
+
isMemcached: boolean;
|
|
173
|
+
isUsedMemcached: boolean;
|
|
174
|
+
}) => void;
|
|
171
175
|
readonly [key: string]: any;
|
|
172
176
|
}
|
|
173
177
|
type EntryFunction = (url: string, opt: Record<string, any>) => Promise<any>;
|
|
174
178
|
|
|
175
179
|
declare class Ssr {
|
|
176
|
-
res
|
|
177
|
-
req
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
180
|
+
private readonly res;
|
|
181
|
+
private readonly req;
|
|
182
|
+
private readonly options;
|
|
183
|
+
private readonly entry;
|
|
184
|
+
private isAborted;
|
|
185
|
+
constructor(res: HttpResponse, req: HttpRequest, options: OptionsSsr, entry: EntryFunction | any);
|
|
186
|
+
request(): Promise<void>;
|
|
182
187
|
}
|
|
183
188
|
|
|
184
189
|
/**
|
|
@@ -339,6 +344,7 @@ declare class Web {
|
|
|
339
344
|
contextWeb: ContextWebController & {
|
|
340
345
|
[key: string]: any;
|
|
341
346
|
};
|
|
347
|
+
private isAborted;
|
|
342
348
|
constructor(res: HttpResponse, req: HttpRequest, context: OptionsWeb, opts?: {
|
|
343
349
|
raw?: boolean;
|
|
344
350
|
});
|
package/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var d=require("./ApiError.js"),$=require("./Server.js"),y=require("./Jwt-CDdbxwvH.js"),
|
|
1
|
+
"use strict";var d=require("./ApiError.js"),$=require("./Server.js"),y=require("./Jwt-CDdbxwvH.js"),R=require("crypto"),Y=require("util"),v=require("./Memcached.js"),P=require("./jsonBody.js"),A=require("stream"),B=require("./urlencodedBody.js"),M=require("./multipartBody.js"),Z=require("./readConfig.js"),tt=require("./readConfigSync.js"),W=require("./cookieParse.js"),N=require("./cookieString.js"),_=require("./staticBody.js"),et=require("fs"),D=require("path"),w=require("easy-ash"),st=require("querystring"),O=require("xml-js"),ot=require("os");require("reflect-metadata"),require("dns"),require("uWebSockets.js"),require("formidable");function j(o){var t=Object.create(null);return o&&Object.keys(o).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return o[e]}})}}),t.default=o,Object.freeze(t)}var J=j(et),it=j(D),nt=j(ot);const{subtle:T}=R.webcrypto;class rt{constructor(t,e){this.algorithm="SHA-256",this.secret=t,this.algorithm=e?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(t){if(!t)return!1;const e=t.split(".");return await this.signString(`${e[0]}.${e[1]}`)===e[2]}async sign(t){const e=y.toBase64url({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=y.toBase64url(t),i=await this.signString(`${e}.${s}`);return`${e}.${s}.${i}`}decode(t){const e=(t||"").split("."),s=y.fromBase64url(e[0]),i=y.fromBase64url(e[1]);return{head:s,body:i}}async signString(t){const e=new Y.TextEncoder,s=await T.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return y.urlEncode(Buffer.from(await T.sign("HMAC",s,e.encode(t))).toString("base64"))}}const at=o=>{const t=(o||"").split("."),e=y.fromBase64url(t[0]),s=y.fromBase64url(t[1]);return{head:e,body:s}},L=o=>new Promise((t,e)=>{ct(o,s=>t(s),()=>{e(new d.ApiError({message:"Client abort connection",code:"abort",statusCode:404}))})});function ct(o,t,e){let s=Buffer.from([]);o.onData((i,n)=>{s=Buffer.concat([s,Buffer.from(i)]),n&&t(s.toString())}),o.onAborted(e)}const k=o=>new Promise((t,e)=>{ht(o,s=>t(s),()=>{e(new d.ApiError({message:"Client abort connection",code:"abort",statusCode:404}))})});function ht(o,t,e){let s=Buffer.from([]);o.onData((i,n)=>{s=Buffer.concat([s,Buffer.from(i)]),n&&t(s)}),o.onAborted(e)}const C=(o,t,e=!0)=>{let s=!1;const i=new A.PassThrough;return i.headers={},t.forEach((n,a)=>i.headers[n]=a),o.onAborted(()=>{s=!0,i.destroy()}),o.onData((n,a)=>{s||(i.write(Buffer.from(Buffer.from(n))),e&&i.resume(),a&&i.end())}),i},ut=(o,t={})=>{const e=Object.assign({},t);for(const s of o){const i=it.resolve(s),n=J.readFileSync(i,"utf-8"),a=JSON.parse(n);Object.assign(e,a)}return e};class dt{constructor(t,e,s,i){this.isAborted=!1,this.res=t,this.req=e,this.options=s,this.entry=i}async request(){this.res.onAborted(()=>this.isAborted=!0);const t=this.req.getQuery(),e=this.options.ssrManifest||this.options.manifest,s=this.options.manifest,i=this.req.getHeader("host"),n=this.req.getHeader("x-forwarded-proto")||"http",a=`${n}://${i}`+this.req.getUrl()+(t?`?${t}`:"");let r=!1;if(_.extensions.includes(_.getExt(a))){await _.staticBody(this.res,this.req,"./dist/client");return}const h={hostname:i,protocol:n,url:a,cookies:W.cookieParse(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((c,u)=>h.headers[c]=u);try{const c=`${h.protocol}://${h.hostname}${h.url}`;let u,f=null;if(this.options.memcached&&(f=await this.options.memcached.getPage(c)),f?(u=f.data.toString(),h.responseHeaders=f.headers,r=!0):({html:u}=await this.entry(a,{manifest:s,ssrManifest:e,res:this.res,req:this.req,context:h}),h.statusCode===200&&this.options.memcached&&await this.options.memcached.setPage(c,h.headers,u,h.memcache)),this.isAborted)return;this.res.cork(()=>{this.res.writeStatus($.codeToStatus(h.statusCode)),Object.keys(h.responseHeaders).forEach(g=>this.res.writeHeader(g,h.responseHeaders[g])),this.res.end(u)})}catch(c){if(this.isAborted)return;let u=$.codeToStatus(500),f=Object.assign({},h.responseHeaders||{}),g=c.message;c instanceof d.ApiError&&(u=$.codeToStatus(c.getStatusCode()),f=Object.assign(f,c.getHeaders()||{}),g=w.isObject(c.getData())&&Object.keys(c.getData()).length>0?JSON.stringify(c.getData()):g),this.options.onError&&this.options.onError(c,h,{isManifest:!!s,isSsrManifest:!!e,isMemcached:!!this.options.memcached,isUsedMemcached:r}),this.res.cork(()=>{this.res.writeStatus(u),Object.keys(f).forEach(x=>this.res.writeHeader(x,f[x])),this.res.end(g)})}}}const lt=async(o,t,e)=>(await o.poolQuery({sql:`
|
|
2
2
|
SELECT c.id AS controller_id,
|
|
3
3
|
c.name AS controller_name,
|
|
4
4
|
c.is_active AS controller_is_active,
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
FROM app_controllers c
|
|
36
36
|
INNER JOIN app_subactions s ON s.app_controllers_id = c.id
|
|
37
37
|
LEFT JOIN app_actions a ON a.id = s.app_actions_id;
|
|
38
|
-
`)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),ft=async(o,t,e,s,i="",n=3600)=>{const a=`${i}::routes::controllers`,r=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await mt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),n),(c||{}).hasOwnProperty(r)?c[r]:void 0}},I=async(o,t,e,s,i,n="",a=3600)=>{let r;if(i&&i.isClient()&&i.isConnectedServers()?r=await ft(o,e,s,i,n,a):r=await lt(o,e,s),!r)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new d.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!h.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},
|
|
38
|
+
`)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),ft=async(o,t,e,s,i="",n=3600)=>{const a=`${i}::routes::controllers`,r=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await mt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),n),(c||{}).hasOwnProperty(r)?c[r]:void 0}},I=async(o,t,e,s,i,n="",a=3600)=>{let r;if(i&&i.isClient()&&i.isConnectedServers()?r=await ft(o,e,s,i,n,a):r=await lt(o,e,s),!r)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new d.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!h.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},pt=async o=>{const t={},e={};return(await o.poolQuery(`
|
|
39
39
|
SELECT c.id AS controller_id,
|
|
40
40
|
c.name AS controller_name,
|
|
41
41
|
c.is_active AS controller_is_active,
|
|
@@ -54,4 +54,4 @@
|
|
|
54
54
|
FROM app_controllers c
|
|
55
55
|
INNER JOIN app_subactions s ON s.app_controllers_id = c.id
|
|
56
56
|
LEFT JOIN app_actions a ON a.id = s.app_actions_id;
|
|
57
|
-
`)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},q=(o,t,e,s)=>{let i=o.controllers.find(h=>h.name===e);if(!i)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(h=>h.name===s);if(!n)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===n.action);if(!a)throw new d.ApiError({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class pt{constructor(t,e,s,i={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=t,this.req=e,this.opts=i,this.res.onAborted(()=>new d.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,st.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,u)=>this.contextWeb.headers[c]=u);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)});const c=this.importControllerSync(),u=new c;if(this.injectContext(u),i.subaction in u)e=await u[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof v.Memcached){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const u=await c.getPage(this.memcachedKey);if(u){const{data:f,headers:p}=u;this.success({body:f.toString(),headers:p,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)if(this.opts.raw){const c=await L(this.res);let u={};try{u=JSON.parse(c)}catch{}Object.assign(i,u),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await P.jsonBody(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await B.urlencodedBody(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),u=O.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,u||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const u=C(this.res,this.req),f=nt.tmpdir(),p="./body_"+H.randomBytes(32).toString("hex"),x=D.resolve(f,p),l=J.createWriteStream(x);u.pipe(l),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:x}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await I(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const u of c){const f=await this.importBinding(u),p=new f;this.injectContext(p),Object.assign(this.contextWeb.$di,await this.initComponent(p))}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importBinding(t){let e=t.default||t;if(w.isClass(e)||(e=(await t()).default),typeof e!="function")throw new d.ApiError({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(w.isClass(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new d.ApiError({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof A.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=$.codeToStatus(i),a=!s&&!e&&w.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof v.Memcached&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d.ApiError&&t.getData()instanceof A.Stream;let s=$.codeToStatus(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof d.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=$.codeToStatus(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=w.isObject(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const U={compact:!0,ignoreComment:!0,spaces:4};class E{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return N.cookieString(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:O.js2xml(Object.assign(s,{body:{...i.body}}),U),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:O.js2xml(Object.assign(s,{body:{...i.body}}),U),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new A.PassThrough().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class F{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class K{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const bt=async(o,t,e={},s)=>{const i=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const u=await r[c]();if(u)return u}},n=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await I(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?q(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof E)return n(a,t),t.$initResponse=await i(a),a;if(a instanceof F||a instanceof K){const r=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return n(r,t),t.$initResponse=await i(r),r.getModel()}else throw new d.ApiError({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},g=Symbol("arguments"),Q=Symbol("connections"),R=Symbol("response"),V=Symbol("init"),X=Symbol("logger"),z=Symbol("filters"),xt=o=>o.charAt(0).toUpperCase()+o.slice(1);function $t(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const n=Object.getPrototypeOf(i);n&&t(s,n)};function e(s){return t(s,o),s}return e}const m=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function yt(){return function(o,t,e){m(g,o,t,e,"request")}}function _t(){return function(o,t,e){m(g,o,t,e,"context")}}function wt(){return function(o,t,e){m(g,o,t,e,"config")}}function St(){return function(o,t,e){m(g,o,t,e,"method")}}function At(){return function(o,t,e){m(g,o,t,e,"remote")}}function Ct(){return function(o,t,e){m(g,o,t,e,"cookies")}}function vt(){return function(o,t,e){m(g,o,t,e,"hostname")}}function Ot(){return function(o,t,e){m(g,o,t,e,"url")}}function jt(){return function(o,t,e){m(g,o,t,e,"protocol")}}function kt(){return function(o,t,e){m(g,o,t,e,"db")}}function qt(){return function(o,t,e){m(g,o,t,e,"headers")}}function Et(){return function(o,t,e){m(g,o,t,e,"controller")}}function Rt(){return function(o,t,e){m(g,o,t,e,"action")}}function Ht(){return function(o,t,e){m(g,o,t,e,"subaction")}}function Pt(){return function(o,t,e){m(g,o,t,e,"body")}}function Bt(){return function(o,t,e){m(g,o,t,e,"stream")}}function Mt(){return function(o,t,e){m(g,o,t,e,"home")}}function Wt(o="home"){return function(t,e,s){m(g,t,e,s,"pool",o)}}function Nt(o="home"){return function(t,e,s){m(Q,t,e,s,"connection",o)}}function Dt(o={}){return function(t,e,s){m(R,t,e,0,"json",o)}}function Jt(o={}){return function(t,e,s){m(R,t,e,0,"xml",o)}}function Tt(o){return function(t,e,s){m(X,t,e,o,"logger",o)}}function Lt(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(g,t,e)||{},c=Reflect.getOwnMetadata(Q,t,e)||{},u=Reflect.getOwnMetadata(X,t,e)||{},f=Reflect.getOwnMetadata(R,t,e)?.[0]||{type:"json",params:{}},p=Reflect.getOwnMetadata(V,t,e)?.[0]||{type:"",params:{}},x=(Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"allow",params:[]}).params;if(x.length&&!x.includes(this.getMethod())&&this.getMethod()!=="any")throw new d.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${x.join(",")} methods`});for(const l in h){if(!h.hasOwnProperty(l))continue;const b=`get${xt(h[l].type)}`;a[+l]=this[b](h[l].params)}for(const l in c)c.hasOwnProperty(l)&&(c[l].type,a[+l]=await this.getDb()[c[l].params].getConnection(),r.push(a[+l]));try{let l=await n.apply(this,a),b;if(Array.isArray(l)&&([l,b]=l),p.type!=="init")return i.format==="xml"||f.type==="xml"?this.successXml(l,Object.assign(f.params,b||{})):i.format==="buffer"?this.successBuffer(l,Object.assign(f.params,b||{})):this.success(l,Object.assign(f.params,b||{}))}catch(l){await Promise.all([...r.map(S=>S.rollback())]);let b;i.format==="xml"||f.type==="xml"?b=this.errorXml(l):b=this.error(l);for(const S in u){if(!u.hasOwnProperty(S))continue;const G=u[S].params;await this[G].error(l,{response:w.omit(b?.body||{},["stack"])})}return b}finally{await Promise.all([...r.map(l=>l.release())])}}}}function It(){return function(o,t,e){m(V,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Ut(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){m(z,t,e,0,"allow",o)}}function Ft(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Kt={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:P.jsonBody,jsonBodyRaw:L,rawBody:k,streamBody:C,urlencodedBody:B.urlencodedBody,multipartBody:M.multipartBody,readConfig:Z.readConfig,readConfigSync:tt.readConfigSync,staticBody:_.staticBody,extensions:_.extensions,getExt:_.getExt,jwtDecode:at,readJsonConfigsSync:ut};exports.ApiError=d.ApiError,exports.Server=$.Server,exports.codeToStatus=$.codeToStatus,exports.Jwt=y.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=rt,exports.Binding=K,exports.Controller=E,exports.Model=F,exports.Ssr=dt,exports.Web=pt,exports.action=Rt,exports.allow=Ut,exports.body=Pt,exports.config=wt,exports.connection=Nt,exports.context=_t,exports.controller=Et,exports.cookies=Ct,exports.db=kt,exports.headers=qt,exports.helpers=Kt,exports.home=Mt,exports.hostname=vt,exports.http=Lt,exports.init=It,exports.inject=Ft,exports.json=Dt,exports.logerror=Tt,exports.method=St,exports.mixin=$t,exports.mount=bt,exports.pool=Wt,exports.protocol=jt,exports.remote=At,exports.request=yt,exports.selectControllersSchema=gt,exports.stream=Bt,exports.subaction=Ht,exports.url=Ot,exports.xml=Jt;
|
|
57
|
+
`)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},q=(o,t,e,s)=>{let i=o.controllers.find(h=>h.name===e);if(!i)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(h=>h.name===s);if(!n)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===n.action);if(!a)throw new d.ApiError({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class gt{constructor(t,e,s,i={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.isAborted=!1,this.res=t,this.req=e,this.opts=i,this.res.onAborted(()=>this.isAborted=!0),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,st.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,u)=>this.contextWeb.headers[c]=u);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)});const c=this.importControllerSync(),u=new c;if(this.injectContext(u),i.subaction in u)e=await u[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof v.Memcached){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const u=await c.getPage(this.memcachedKey);if(u){const{data:f,headers:g}=u;this.success({body:f.toString(),headers:g,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)if(this.opts.raw){const c=await L(this.res);let u={};try{u=JSON.parse(c)}catch{}Object.assign(i,u),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await P.jsonBody(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await B.urlencodedBody(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),u=O.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,u||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const u=C(this.res,this.req),f=nt.tmpdir(),g="./body_"+R.randomBytes(32).toString("hex"),x=D.resolve(f,g),l=J.createWriteStream(x);u.pipe(l),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:x}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await I(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const u of c){const f=await this.importBinding(u),g=new f;this.injectContext(g),Object.assign(this.contextWeb.$di,await this.initComponent(g))}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){s instanceof d.ApiError&&s.getCode()==="abort"||this.isAborted||this.error(s)}}async importBinding(t){let e=t.default||t;if(w.isClass(e)||(e=(await t()).default),typeof e!="function")throw new d.ApiError({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(w.isClass(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new d.ApiError({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof A.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=$.codeToStatus(i),a=!s&&!e&&w.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof v.Memcached&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d.ApiError&&t.getData()instanceof A.Stream;let s=$.codeToStatus(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof d.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=$.codeToStatus(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=w.isObject(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const U={compact:!0,ignoreComment:!0,spaces:4};class E{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return N.cookieString(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:O.js2xml(Object.assign(s,{body:{...i.body}}),U),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:O.js2xml(Object.assign(s,{body:{...i.body}}),U),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new A.PassThrough().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class F{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class K{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const bt=async(o,t,e={},s)=>{const i=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const u=await r[c]();if(u)return u}},n=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await I(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?q(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof E)return n(a,t),t.$initResponse=await i(a),a;if(a instanceof F||a instanceof K){const r=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return n(r,t),t.$initResponse=await i(r),r.getModel()}else throw new d.ApiError({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},p=Symbol("arguments"),Q=Symbol("connections"),H=Symbol("response"),V=Symbol("init"),X=Symbol("logger"),z=Symbol("filters"),xt=o=>o.charAt(0).toUpperCase()+o.slice(1);function $t(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const n=Object.getPrototypeOf(i);n&&t(s,n)};function e(s){return t(s,o),s}return e}const m=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function yt(){return function(o,t,e){m(p,o,t,e,"request")}}function _t(){return function(o,t,e){m(p,o,t,e,"context")}}function wt(){return function(o,t,e){m(p,o,t,e,"config")}}function St(){return function(o,t,e){m(p,o,t,e,"method")}}function At(){return function(o,t,e){m(p,o,t,e,"remote")}}function Ct(){return function(o,t,e){m(p,o,t,e,"cookies")}}function vt(){return function(o,t,e){m(p,o,t,e,"hostname")}}function Ot(){return function(o,t,e){m(p,o,t,e,"url")}}function jt(){return function(o,t,e){m(p,o,t,e,"protocol")}}function kt(){return function(o,t,e){m(p,o,t,e,"db")}}function qt(){return function(o,t,e){m(p,o,t,e,"headers")}}function Et(){return function(o,t,e){m(p,o,t,e,"controller")}}function Ht(){return function(o,t,e){m(p,o,t,e,"action")}}function Rt(){return function(o,t,e){m(p,o,t,e,"subaction")}}function Pt(){return function(o,t,e){m(p,o,t,e,"body")}}function Bt(){return function(o,t,e){m(p,o,t,e,"stream")}}function Mt(){return function(o,t,e){m(p,o,t,e,"home")}}function Wt(o="home"){return function(t,e,s){m(p,t,e,s,"pool",o)}}function Nt(o="home"){return function(t,e,s){m(Q,t,e,s,"connection",o)}}function Dt(o={}){return function(t,e,s){m(H,t,e,0,"json",o)}}function Jt(o={}){return function(t,e,s){m(H,t,e,0,"xml",o)}}function Tt(o){return function(t,e,s){m(X,t,e,o,"logger",o)}}function Lt(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(p,t,e)||{},c=Reflect.getOwnMetadata(Q,t,e)||{},u=Reflect.getOwnMetadata(X,t,e)||{},f=Reflect.getOwnMetadata(H,t,e)?.[0]||{type:"json",params:{}},g=Reflect.getOwnMetadata(V,t,e)?.[0]||{type:"",params:{}},x=(Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"allow",params:[]}).params;if(x.length&&!x.includes(this.getMethod())&&this.getMethod()!=="any")throw new d.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${x.join(",")} methods`});for(const l in h){if(!h.hasOwnProperty(l))continue;const b=`get${xt(h[l].type)}`;a[+l]=this[b](h[l].params)}for(const l in c)c.hasOwnProperty(l)&&(c[l].type,a[+l]=await this.getDb()[c[l].params].getConnection(),r.push(a[+l]));try{let l=await n.apply(this,a),b;if(Array.isArray(l)&&([l,b]=l),g.type!=="init")return i.format==="xml"||f.type==="xml"?this.successXml(l,Object.assign(f.params,b||{})):i.format==="buffer"?this.successBuffer(l,Object.assign(f.params,b||{})):this.success(l,Object.assign(f.params,b||{}))}catch(l){await Promise.all([...r.map(S=>S.rollback())]);let b;i.format==="xml"||f.type==="xml"?b=this.errorXml(l):b=this.error(l);for(const S in u){if(!u.hasOwnProperty(S))continue;const G=u[S].params;await this[G].error(l,{response:w.omit(b?.body||{},["stack"])})}return b}finally{await Promise.all([...r.map(l=>l.release())])}}}}function It(){return function(o,t,e){m(V,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Ut(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){m(z,t,e,0,"allow",o)}}function Ft(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Kt={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:P.jsonBody,jsonBodyRaw:L,rawBody:k,streamBody:C,urlencodedBody:B.urlencodedBody,multipartBody:M.multipartBody,readConfig:Z.readConfig,readConfigSync:tt.readConfigSync,staticBody:_.staticBody,extensions:_.extensions,getExt:_.getExt,jwtDecode:at,readJsonConfigsSync:ut};exports.ApiError=d.ApiError,exports.Server=$.Server,exports.codeToStatus=$.codeToStatus,exports.Jwt=y.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=rt,exports.Binding=K,exports.Controller=E,exports.Model=F,exports.Ssr=dt,exports.Web=gt,exports.action=Ht,exports.allow=Ut,exports.body=Pt,exports.config=wt,exports.connection=Nt,exports.context=_t,exports.controller=Et,exports.cookies=Ct,exports.db=kt,exports.headers=qt,exports.helpers=Kt,exports.home=Mt,exports.hostname=vt,exports.http=Lt,exports.init=It,exports.inject=Ft,exports.json=Dt,exports.logerror=Tt,exports.method=St,exports.mixin=$t,exports.mount=bt,exports.pool=Wt,exports.protocol=jt,exports.remote=At,exports.request=yt,exports.selectControllersSchema=pt,exports.stream=Bt,exports.subaction=Rt,exports.url=Ot,exports.xml=Jt;
|
package/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ApiError as
|
|
1
|
+
import{ApiError as u}from"./ApiError.mjs";import{codeToStatus as $}from"./Server.mjs";import{Server as Se}from"./Server.mjs";import{t as H,f as y,u as tt}from"./Jwt-7tQL-rwa.js";import{J as Ae}from"./Jwt-7tQL-rwa.js";import et,{webcrypto as st}from"crypto";import{TextEncoder as ot}from"util";import{Memcached as S}from"./Memcached.mjs";import{jsonBody as R}from"./jsonBody.mjs";import{PassThrough as q,Stream as P}from"stream";import{urlencodedBody as M}from"./urlencodedBody.mjs";import{multipartBody as B}from"./multipartBody.mjs";import{readConfig as it}from"./readConfig.mjs";import{readConfigSync as nt}from"./readConfigSync.mjs";import{cookieParse as E}from"./cookieParse.mjs";import{cookieString as W}from"./cookieString.mjs";import{extensions as N,getExt as D,staticBody as J}from"./staticBody.mjs";import*as L from"fs";import*as rt from"path";import at from"path";import{isObject as C,isClass as T,omit as ct}from"easy-ash";import ht from"querystring";import A from"xml-js";import*as dt from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:I}=st;class ut{constructor(t,e){this.algorithm="SHA-256",this.secret=t,this.algorithm=e?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(t){if(!t)return!1;const e=t.split(".");return await this.signString(`${e[0]}.${e[1]}`)===e[2]}async sign(t){const e=H({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=H(t),i=await this.signString(`${e}.${s}`);return`${e}.${s}.${i}`}decode(t){const e=(t||"").split("."),s=y(e[0]),i=y(e[1]);return{head:s,body:i}}async signString(t){const e=new ot,s=await I.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return tt(Buffer.from(await I.sign("HMAC",s,e.encode(t))).toString("base64"))}}const mt=o=>{const t=(o||"").split("."),e=y(t[0]),s=y(t[1]);return{head:e,body:s}},U=o=>new Promise((t,e)=>{lt(o,s=>t(s),()=>{e(new u({message:"Client abort connection",code:"abort",statusCode:404}))})});function lt(o,t,e){let s=Buffer.from([]);o.onData((i,n)=>{s=Buffer.concat([s,Buffer.from(i)]),n&&t(s.toString())}),o.onAborted(e)}const O=o=>new Promise((t,e)=>{ft(o,s=>t(s),()=>{e(new u({message:"Client abort connection",code:"abort",statusCode:404}))})});function ft(o,t,e){let s=Buffer.from([]);o.onData((i,n)=>{s=Buffer.concat([s,Buffer.from(i)]),n&&t(s)}),o.onAborted(e)}const w=(o,t,e=!0)=>{let s=!1;const i=new q;return i.headers={},t.forEach((n,a)=>i.headers[n]=a),o.onAborted(()=>{s=!0,i.destroy()}),o.onData((n,a)=>{s||(i.write(Buffer.from(Buffer.from(n))),e&&i.resume(),a&&i.end())}),i},pt=(o,t={})=>{const e=Object.assign({},t);for(const s of o){const i=rt.resolve(s),n=L.readFileSync(i,"utf-8"),a=JSON.parse(n);Object.assign(e,a)}return e};class gt{constructor(t,e,s,i){this.isAborted=!1,this.res=t,this.req=e,this.options=s,this.entry=i}async request(){this.res.onAborted(()=>this.isAborted=!0);const t=this.req.getQuery(),e=this.options.ssrManifest||this.options.manifest,s=this.options.manifest,i=this.req.getHeader("host"),n=this.req.getHeader("x-forwarded-proto")||"http",a=`${n}://${i}`+this.req.getUrl()+(t?`?${t}`:"");let r=!1;if(N.includes(D(a))){await J(this.res,this.req,"./dist/client");return}const h={hostname:i,protocol:n,url:a,cookies:E(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((c,d)=>h.headers[c]=d);try{const c=`${h.protocol}://${h.hostname}${h.url}`;let d,f=null;if(this.options.memcached&&(f=await this.options.memcached.getPage(c)),f?(d=f.data.toString(),h.responseHeaders=f.headers,r=!0):({html:d}=await this.entry(a,{manifest:s,ssrManifest:e,res:this.res,req:this.req,context:h}),h.statusCode===200&&this.options.memcached&&await this.options.memcached.setPage(c,h.headers,d,h.memcache)),this.isAborted)return;this.res.cork(()=>{this.res.writeStatus($(h.statusCode)),Object.keys(h.responseHeaders).forEach(g=>this.res.writeHeader(g,h.responseHeaders[g])),this.res.end(d)})}catch(c){if(this.isAborted)return;let d=$(500),f=Object.assign({},h.responseHeaders||{}),g=c.message;c instanceof u&&(d=$(c.getStatusCode()),f=Object.assign(f,c.getHeaders()||{}),g=C(c.getData())&&Object.keys(c.getData()).length>0?JSON.stringify(c.getData()):g),this.options.onError&&this.options.onError(c,h,{isManifest:!!s,isSsrManifest:!!e,isMemcached:!!this.options.memcached,isUsedMemcached:r}),this.res.cork(()=>{this.res.writeStatus(d),Object.keys(f).forEach(x=>this.res.writeHeader(x,f[x])),this.res.end(g)})}}}const bt=async(o,t,e)=>(await o.poolQuery({sql:`
|
|
2
2
|
SELECT c.id AS controller_id,
|
|
3
3
|
c.name AS controller_name,
|
|
4
4
|
c.is_active AS controller_is_active,
|
|
@@ -35,7 +35,7 @@ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as $}from"./Server
|
|
|
35
35
|
FROM app_controllers c
|
|
36
36
|
INNER JOIN app_subactions s ON s.app_controllers_id = c.id
|
|
37
37
|
LEFT JOIN app_actions a ON a.id = s.app_actions_id;
|
|
38
|
-
`)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),$t=async(o,t,e,s,
|
|
38
|
+
`)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),$t=async(o,t,e,s,i="",n=3600)=>{const a=`${i}::routes::controllers`,r=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await xt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),n),(c||{}).hasOwnProperty(r)?c[r]:void 0}},F=async(o,t,e,s,i,n="",a=3600)=>{let r;if(i&&i.isClient()&&i.isConnectedServers()?r=await $t(o,e,s,i,n,a):r=await bt(o,e,s),!r)throw new u({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new u({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new u({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new u({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new u({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new u({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!h.includes(t))throw new u({statusCode:404,code:11,message:`Controller ${e} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},_t=async o=>{const t={},e={};return(await o.poolQuery(`
|
|
39
39
|
SELECT c.id AS controller_id,
|
|
40
40
|
c.name AS controller_name,
|
|
41
41
|
c.is_active AS controller_is_active,
|
|
@@ -54,4 +54,4 @@ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as $}from"./Server
|
|
|
54
54
|
FROM app_controllers c
|
|
55
55
|
INNER JOIN app_subactions s ON s.app_controllers_id = c.id
|
|
56
56
|
LEFT JOIN app_actions a ON a.id = s.app_actions_id;
|
|
57
|
-
`)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},j=(o,t,e,s)=>{let n=o.controllers.find(h=>h.name===e);if(!n)throw new d({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(n=Object.assign({isActive:!0,isSitemap:!1},n),!n.isActive)throw new d({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let i=n.subactions.find(h=>h.name===s);if(!i)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(i=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},i),!i.isActive)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===i.action);if(!a)throw new d({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new d({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new d({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:n.id,name:n.name,isActive:n.isActive,isSitemap:n.isSitemap},subaction:{id:i.id,name:i.name,isPermission:i.isPermission,isCheckMethod:i.isCheckMethod,isLog:i.isLog,isActive:i.isActive,isSync:!!i.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class yt{constructor(t,e,s,n={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=t,this.req=e,this.opts=n,this.res.onAborted(()=>new d({message:"The connection was close",code:1,statusCode:404})),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(i=>({name:i.name,method:i.method,component:i.component,binding:i.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,t,ht.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>n,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,u)=>this.contextWeb.headers[c]=u);const i=this.contextWeb.headers["content-type"]||"application/json";if(n.controller&&n.subaction&&this.context.schema&&(this.route=this.findRoute(n.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,j(this.context.schema,this.contextWeb.method,this.route.name,n.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)});const c=this.importControllerSync(),u=new c;if(this.injectContext(u),n.subaction in u)e=await u[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const u=await c.getPage(this.memcachedKey);if(u){const{data:f,headers:p}=u;this.success({body:f.toString(),headers:p,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(i.indexOf("application/json")!==-1||i.indexOf("text/json")!==-1)if(this.opts.raw){const c=await U(this.res);let u={};try{u=JSON.parse(c)}catch{}Object.assign(n,u),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(n,await H(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await W(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:n.files});else if(i.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await B(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const c=(await O(this.res)).toString(),u=A.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,u||{})}else i.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)}):i.indexOf("binary")!==-1?await new Promise(c=>{const u=w(this.res,this.req),f=ut.tmpdir(),p="./body_"+et.randomBytes(32).toString("hex"),x=at.resolve(f,p),m=T.createWriteStream(x);u.pipe(m),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:x}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await O(this.res)});if(this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?j(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await F(this.contextWeb.db.home,this.contextWeb.method,this.route.name,n.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const u of c){const f=await this.importBinding(u),p=new f;this.injectContext(p),Object.assign(this.contextWeb.$di,await this.initComponent(p))}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(n.subaction in r)e=await r[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importBinding(t){let e=t.default||t;if(L(e)||(e=(await t()).default),typeof e!="function")throw new d({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(L(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new d({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const n=await t[s]();if(n)return n}}success(t){const e=t.body instanceof P,s=t.body instanceof Uint8Array,n=t.statusCode||200,i=$(n),a=!s&&!e&&C(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&n===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d&&t.getData()instanceof P;let s=$(404),n=this.defaultResponse.headers,i=t.message;if(t instanceof d){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=$(t.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?i=t.getData():i=C(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),i.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),this.res.end(i)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(e,n)):this.res.writeHeader(e,s)})}}const K={compact:!0,ignoreComment:!0,spaces:4};class k{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return E(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,n=e.message?e.message:"Api request error",i=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:A.js2xml(Object.assign(s,{body:{...n.body}}),K),memcache:n.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:A.js2xml(Object.assign(s,{body:{...n.body}}),K),statusCode:n.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new q().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class Q{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class V{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const wt=async(o,t,e={},s)=>{const n=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const u=await r[c]();if(u)return u}},i=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await F(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?j(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof k)return i(a,t),t.$initResponse=await n(a),a;if(a instanceof Q||a instanceof V){const r=new class extends k{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return i(r,t),t.$initResponse=await n(r),r.getModel()}else throw new d({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},g=Symbol("arguments"),X=Symbol("connections"),v=Symbol("response"),z=Symbol("init"),G=Symbol("logger"),Y=Symbol("filters"),St=o=>o.charAt(0).toUpperCase()+o.slice(1);function Ct(o){const t=(s,n)=>{for(const a of Reflect.ownKeys(n))Object.defineProperty(s.prototype,a,{value:n[a]});const i=Object.getPrototypeOf(n);i&&t(s,i)};function e(s){return t(s,o),s}return e}const l=(o,t,e,s,n,i)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,t,e)};function At(){return function(o,t,e){l(g,o,t,e,"request")}}function Ot(){return function(o,t,e){l(g,o,t,e,"context")}}function jt(){return function(o,t,e){l(g,o,t,e,"config")}}function kt(){return function(o,t,e){l(g,o,t,e,"method")}}function vt(){return function(o,t,e){l(g,o,t,e,"remote")}}function Rt(){return function(o,t,e){l(g,o,t,e,"cookies")}}function Ht(){return function(o,t,e){l(g,o,t,e,"hostname")}}function qt(){return function(o,t,e){l(g,o,t,e,"url")}}function Pt(){return function(o,t,e){l(g,o,t,e,"protocol")}}function Bt(){return function(o,t,e){l(g,o,t,e,"db")}}function Wt(){return function(o,t,e){l(g,o,t,e,"headers")}}function Mt(){return function(o,t,e){l(g,o,t,e,"controller")}}function Et(){return function(o,t,e){l(g,o,t,e,"action")}}function Nt(){return function(o,t,e){l(g,o,t,e,"subaction")}}function Dt(){return function(o,t,e){l(g,o,t,e,"body")}}function Jt(){return function(o,t,e){l(g,o,t,e,"stream")}}function Tt(){return function(o,t,e){l(g,o,t,e,"home")}}function Lt(o="home"){return function(t,e,s){l(g,t,e,s,"pool",o)}}function It(o="home"){return function(t,e,s){l(X,t,e,s,"connection",o)}}function Ut(o={}){return function(t,e,s){l(v,t,e,0,"json",o)}}function Ft(o={}){return function(t,e,s){l(v,t,e,0,"xml",o)}}function Kt(o){return function(t,e,s){l(G,t,e,o,"logger",o)}}function Qt(o){return function(t,e,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(g,t,e)||{},c=Reflect.getOwnMetadata(X,t,e)||{},u=Reflect.getOwnMetadata(G,t,e)||{},f=Reflect.getOwnMetadata(v,t,e)?.[0]||{type:"json",params:{}},p=Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"",params:{}},x=(Reflect.getOwnMetadata(Y,t,e)?.[0]||{type:"allow",params:[]}).params;if(x.length&&!x.includes(this.getMethod())&&this.getMethod()!=="any")throw new d({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${x.join(",")} methods`});for(const m in h){if(!h.hasOwnProperty(m))continue;const b=`get${St(h[m].type)}`;a[+m]=this[b](h[m].params)}for(const m in c)c.hasOwnProperty(m)&&(c[m].type,a[+m]=await this.getDb()[c[m].params].getConnection(),r.push(a[+m]));try{let m=await i.apply(this,a),b;if(Array.isArray(m)&&([m,b]=m),p.type!=="init")return n.format==="xml"||f.type==="xml"?this.successXml(m,Object.assign(f.params,b||{})):n.format==="buffer"?this.successBuffer(m,Object.assign(f.params,b||{})):this.success(m,Object.assign(f.params,b||{}))}catch(m){await Promise.all([...r.map(_=>_.rollback())]);let b;n.format==="xml"||f.type==="xml"?b=this.errorXml(m):b=this.error(m);for(const _ in u){if(!u.hasOwnProperty(_))continue;const Z=u[_].params;await this[Z].error(m,{response:ct(b?.body||{},["stack"])})}return b}finally{await Promise.all([...r.map(m=>m.release())])}}}}function Vt(){return function(o,t,e){l(z,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Xt(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){l(Y,t,e,0,"allow",o)}}function zt(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Gt={cookieParse:M,cookieString:E,jsonBody:H,jsonBodyRaw:U,rawBody:O,streamBody:w,urlencodedBody:B,multipartBody:W,readConfig:nt,readConfigSync:it,staticBody:J,extensions:N,getExt:D,jwtDecode:mt,readJsonConfigsSync:gt};export{d as ApiError,dt as AsyncJwt,V as Binding,k as Controller,Ae as Jwt,S as Memcached,Q as Model,Se as Server,pt as Ssr,yt as Web,Et as action,Xt as allow,Dt as body,$ as codeToStatus,jt as config,It as connection,Ot as context,Mt as controller,Rt as cookies,Bt as db,Wt as headers,Gt as helpers,Tt as home,Ht as hostname,Qt as http,Vt as init,zt as inject,Ut as json,Kt as logerror,kt as method,Ct as mixin,wt as mount,Lt as pool,Pt as protocol,vt as remote,At as request,_t as selectControllersSchema,Jt as stream,Nt as subaction,qt as url,Ft as xml};
|
|
57
|
+
`)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},j=(o,t,e,s)=>{let i=o.controllers.find(h=>h.name===e);if(!i)throw new u({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new u({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(h=>h.name===s);if(!n)throw new u({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new u({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===n.action);if(!a)throw new u({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new u({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new u({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class yt{constructor(t,e,s,i={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.isAborted=!1,this.res=t,this.req=e,this.opts=i,this.res.onAborted(()=>this.isAborted=!0),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,ht.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,d)=>this.contextWeb.headers[c]=d);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,j(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)});const c=this.importControllerSync(),d=new c;if(this.injectContext(d),i.subaction in d)e=await d[i.subaction]();else throw new u({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const d=await c.getPage(this.memcachedKey);if(d){const{data:f,headers:g}=d;this.success({body:f.toString(),headers:g,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)if(this.opts.raw){const c=await U(this.res);let d={};try{d=JSON.parse(c)}catch{}Object.assign(i,d),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await R(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await B(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await M(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await O(this.res)).toString(),d=A.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,d||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const d=w(this.res,this.req),f=dt.tmpdir(),g="./body_"+et.randomBytes(32).toString("hex"),x=at.resolve(f,g),m=L.createWriteStream(x);d.pipe(m),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:x}}}),d.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await O(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?j(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await F(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const d of c){const f=await this.importBinding(d),g=new f;this.injectContext(g),Object.assign(this.contextWeb.$di,await this.initComponent(g))}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new u({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){s instanceof u&&s.getCode()==="abort"||this.isAborted||this.error(s)}}async importBinding(t){let e=t.default||t;if(T(e)||(e=(await t()).default),typeof e!="function")throw new u({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(T(t)||(t=(await this.route.component()).default),typeof t!="function")throw new u({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new u({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new u({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof P,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=$(i),a=!s&&!e&&C(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof u&&t.getData()instanceof P;let s=$(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof u){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=$(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=C(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const K={compact:!0,ignoreComment:!0,spaces:4};class k{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return W(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:A.js2xml(Object.assign(s,{body:{...i.body}}),K),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:A.js2xml(Object.assign(s,{body:{...i.body}}),K),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new q().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class Q{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class V{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const wt=async(o,t,e={},s)=>{const i=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const d=await r[c]();if(d)return d}},n=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await F(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?j(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof k)return n(a,t),t.$initResponse=await i(a),a;if(a instanceof Q||a instanceof V){const r=new class extends k{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return n(r,t),t.$initResponse=await i(r),r.getModel()}else throw new u({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},p=Symbol("arguments"),X=Symbol("connections"),v=Symbol("response"),z=Symbol("init"),G=Symbol("logger"),Y=Symbol("filters"),St=o=>o.charAt(0).toUpperCase()+o.slice(1);function Ct(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const n=Object.getPrototypeOf(i);n&&t(s,n)};function e(s){return t(s,o),s}return e}const l=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function At(){return function(o,t,e){l(p,o,t,e,"request")}}function Ot(){return function(o,t,e){l(p,o,t,e,"context")}}function jt(){return function(o,t,e){l(p,o,t,e,"config")}}function kt(){return function(o,t,e){l(p,o,t,e,"method")}}function vt(){return function(o,t,e){l(p,o,t,e,"remote")}}function Ht(){return function(o,t,e){l(p,o,t,e,"cookies")}}function Rt(){return function(o,t,e){l(p,o,t,e,"hostname")}}function qt(){return function(o,t,e){l(p,o,t,e,"url")}}function Pt(){return function(o,t,e){l(p,o,t,e,"protocol")}}function Mt(){return function(o,t,e){l(p,o,t,e,"db")}}function Bt(){return function(o,t,e){l(p,o,t,e,"headers")}}function Et(){return function(o,t,e){l(p,o,t,e,"controller")}}function Wt(){return function(o,t,e){l(p,o,t,e,"action")}}function Nt(){return function(o,t,e){l(p,o,t,e,"subaction")}}function Dt(){return function(o,t,e){l(p,o,t,e,"body")}}function Jt(){return function(o,t,e){l(p,o,t,e,"stream")}}function Lt(){return function(o,t,e){l(p,o,t,e,"home")}}function Tt(o="home"){return function(t,e,s){l(p,t,e,s,"pool",o)}}function It(o="home"){return function(t,e,s){l(X,t,e,s,"connection",o)}}function Ut(o={}){return function(t,e,s){l(v,t,e,0,"json",o)}}function Ft(o={}){return function(t,e,s){l(v,t,e,0,"xml",o)}}function Kt(o){return function(t,e,s){l(G,t,e,o,"logger",o)}}function Qt(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(p,t,e)||{},c=Reflect.getOwnMetadata(X,t,e)||{},d=Reflect.getOwnMetadata(G,t,e)||{},f=Reflect.getOwnMetadata(v,t,e)?.[0]||{type:"json",params:{}},g=Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"",params:{}},x=(Reflect.getOwnMetadata(Y,t,e)?.[0]||{type:"allow",params:[]}).params;if(x.length&&!x.includes(this.getMethod())&&this.getMethod()!=="any")throw new u({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${x.join(",")} methods`});for(const m in h){if(!h.hasOwnProperty(m))continue;const b=`get${St(h[m].type)}`;a[+m]=this[b](h[m].params)}for(const m in c)c.hasOwnProperty(m)&&(c[m].type,a[+m]=await this.getDb()[c[m].params].getConnection(),r.push(a[+m]));try{let m=await n.apply(this,a),b;if(Array.isArray(m)&&([m,b]=m),g.type!=="init")return i.format==="xml"||f.type==="xml"?this.successXml(m,Object.assign(f.params,b||{})):i.format==="buffer"?this.successBuffer(m,Object.assign(f.params,b||{})):this.success(m,Object.assign(f.params,b||{}))}catch(m){await Promise.all([...r.map(_=>_.rollback())]);let b;i.format==="xml"||f.type==="xml"?b=this.errorXml(m):b=this.error(m);for(const _ in d){if(!d.hasOwnProperty(_))continue;const Z=d[_].params;await this[Z].error(m,{response:ct(b?.body||{},["stack"])})}return b}finally{await Promise.all([...r.map(m=>m.release())])}}}}function Vt(){return function(o,t,e){l(z,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Xt(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){l(Y,t,e,0,"allow",o)}}function zt(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Gt={cookieParse:E,cookieString:W,jsonBody:R,jsonBodyRaw:U,rawBody:O,streamBody:w,urlencodedBody:M,multipartBody:B,readConfig:it,readConfigSync:nt,staticBody:J,extensions:N,getExt:D,jwtDecode:mt,readJsonConfigsSync:pt};export{u as ApiError,ut as AsyncJwt,V as Binding,k as Controller,Ae as Jwt,S as Memcached,Q as Model,Se as Server,gt as Ssr,yt as Web,Wt as action,Xt as allow,Dt as body,$ as codeToStatus,jt as config,It as connection,Ot as context,Et as controller,Ht as cookies,Mt as db,Bt as headers,Gt as helpers,Lt as home,Rt as hostname,Qt as http,Vt as init,zt as inject,Ut as json,Kt as logerror,kt as method,Ct as mixin,wt as mount,Tt as pool,Pt as protocol,vt as remote,At as request,_t as selectControllersSchema,Jt as stream,Nt as subaction,qt as url,Ft as xml};
|
package/jsonBody.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var s=require("./ApiError.js");const a=r=>new Promise((e,t)=>{c(r,o=>e(o),()=>{t(new s.ApiError({message:"Client abort connection",code:"abort",statusCode:404}))})});function c(r,e,t){let o=Buffer.from([]);r.onData((n,f)=>{if(o=Buffer.concat([o,Buffer.from(n)]),f)try{e(JSON.parse(o.toString()))}catch{e({})}}),r.onAborted(t)}exports.jsonBody=a;
|
package/jsonBody.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ApiError as
|
|
1
|
+
import{ApiError as a}from"./ApiError.mjs";const c=r=>new Promise((t,e)=>{i(r,o=>t(o),()=>{e(new a({message:"Client abort connection",code:"abort",statusCode:404}))})});function i(r,t,e){let o=Buffer.from([]);r.onData((n,f)=>{if(o=Buffer.concat([o,Buffer.from(n)]),f)try{t(JSON.parse(o.toString()))}catch{t({})}}),r.onAborted(e)}export{c as jsonBody};
|
package/multipartBody.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var b=require("stream"),p=require("./ApiError.js"),A=require("formidable");const g=(i,u,l={multiples:!0})=>new Promise(async(d,o)=>{const f=new p.ApiError({message:"Can`t parse body",code:1,statusCode:404}),y=new p.ApiError({message:"Client abort connection",code:"abort",statusCode:404});let n=!1;i.onAborted(()=>{n=!0,o(y)});try{const r=new b.PassThrough;r.headers={},u.forEach((e,t)=>r.headers[e]=t),i.onData((e,t)=>{r.write(Buffer.from(Buffer.from(e))),r.resume(),t&&r.end()});const h=A(l),m=e=>({size:e.size,path:e.filepath,name:e.originalFilename,type:e.mimetype,mtime:e.mtime,newFilename:e.newFilename});h.parse(r,(e,t,a)=>{if(e){o(e);return}const c={};Object.keys(a).map(s=>{c[s]=Array.isArray(a[s])?a[s].map(w=>m(w)):m(a[s])}),t.files=c,!n&&d(t)})}catch{o(f)}});exports.multipartBody=g;
|
package/multipartBody.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PassThrough as
|
|
1
|
+
import{PassThrough as b}from"stream";import{ApiError as c}from"./ApiError.mjs";import g from"formidable";const A=(s,f,l={multiples:!0})=>new Promise(async(d,m)=>{const y=new c({message:"Can`t parse body",code:1,statusCode:404}),u=new c({message:"Client abort connection",code:"abort",statusCode:404});let n=!1;s.onAborted(()=>{n=!0,m(u)});try{const t=new b;t.headers={},f.forEach((e,o)=>t.headers[e]=o),s.onData((e,o)=>{t.write(Buffer.from(Buffer.from(e))),t.resume(),o&&t.end()});const h=g(l),i=e=>({size:e.size,path:e.filepath,name:e.originalFilename,type:e.mimetype,mtime:e.mtime,newFilename:e.newFilename});h.parse(t,(e,o,r)=>{if(e){m(e);return}const p={};Object.keys(r).map(a=>{p[a]=Array.isArray(r[a])?r[a].map(w=>i(w)):i(r[a])}),o.files=p,!n&&d(o)})}catch{m(y)}});export{A as multipartBody};
|
package/package.json
CHANGED
package/readConfig.d.ts
CHANGED
package/readConfigSync.d.ts
CHANGED
package/staticBody.d.ts
CHANGED
|
@@ -1,17 +1,8 @@
|
|
|
1
1
|
import { HttpResponse, HttpRequest } from 'uWebSockets.js';
|
|
2
2
|
|
|
3
3
|
declare const exts: Record<string, string>;
|
|
4
|
-
/**
|
|
5
|
-
* approved extensions
|
|
6
|
-
*/
|
|
7
4
|
declare const extensions: Array<string>;
|
|
8
|
-
/**
|
|
9
|
-
* Get extension from path
|
|
10
|
-
*/
|
|
11
5
|
declare const getExt: (path: string) => string;
|
|
12
|
-
/**
|
|
13
|
-
* Reed static files
|
|
14
|
-
*/
|
|
15
6
|
declare function staticBody(res: HttpResponse, req: HttpRequest, base: string): Promise<void>;
|
|
16
7
|
|
|
17
8
|
export { extensions, exts, getExt, staticBody };
|
package/staticBody.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var l=require("path"),n=require("fs");const p={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2",webmanifest:"application/manifest+json"},s=Object.keys(p),e=t=>t.split(".").pop(),r=t=>p[t.toLowerCase()]||"application/octet-stream";async function d(t,o,c){let i=!1;try{t.onAborted(()=>i=!0);let a=o.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const x=l.resolve(c,a),m=await n.promises.readFile(x);if(i)return;t.cork(()=>{t.writeStatus("200 OK").writeHeader("content-type",r(e(a))).end(m)})}catch(a){if(i)return;t.cork(()=>{t.writeStatus("404 Not Found").end(a.message)})}}exports.extensions=s,exports.exts=p,exports.getExt=e,exports.staticBody=d;
|
package/staticBody.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import l from"path";import{promises as n}from"fs";const p={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2",webmanifest:"application/manifest+json"},s=Object.keys(p),e=t=>t.split(".").pop(),r=t=>p[t.toLowerCase()]||"application/octet-stream";async function d(t,o,c){let i=!1;try{t.onAborted(()=>i=!0);let a=o.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const m=l.resolve(c,a),x=await n.readFile(m);if(i)return;t.cork(()=>{t.writeStatus("200 OK").writeHeader("content-type",r(e(a))).end(x)})}catch(a){if(i)return;t.cork(()=>{t.writeStatus("404 Not Found").end(a.message)})}}export{s as extensions,p as exts,e as getExt,d as staticBody};
|
package/urlencodedBody.d.ts
CHANGED
package/urlencodedBody.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var i=require("./ApiError.js"),a=require("querystring");const f=e=>new Promise((o,t)=>{s(e,r=>o(r),()=>{t(new i.ApiError({message:"Client abort connection",code:"abort",statusCode:404}))})});function s(e,o,t){let r=Buffer.from([]);e.onData((n,c)=>{if(r=Buffer.concat([r,Buffer.from(n)]),c)try{o(a.parse(r.toString()))}catch{o({})}}),e.onAborted(t)}exports.urlencodedBody=f;
|
package/urlencodedBody.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ApiError as
|
|
1
|
+
import{ApiError as c}from"./ApiError.mjs";import i from"querystring";const a=r=>new Promise((t,e)=>{m(r,o=>t(o),()=>{e(new c({message:"Client abort connection",code:"abort",statusCode:404}))})});function m(r,t,e){let o=Buffer.from([]);r.onData((n,f)=>{if(o=Buffer.concat([o,Buffer.from(n)]),f)try{t(i.parse(o.toString()))}catch{t({})}}),r.onAborted(e)}export{a as urlencodedBody};
|