@jwn-js/common 2.2.9 → 2.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/docs/assets/navigation.js +1 -1
  2. package/docs/assets/search.js +1 -1
  3. package/docs/classes/ApiError.html +2 -2
  4. package/docs/classes/AsyncJwt.html +2 -2
  5. package/docs/classes/Controller.html +2 -2
  6. package/docs/classes/Jwt.html +2 -2
  7. package/docs/classes/Memcached.html +2 -2
  8. package/docs/classes/Model.html +2 -2
  9. package/docs/classes/Server.html +2 -2
  10. package/docs/classes/Ssr.html +2 -2
  11. package/docs/classes/Web.html +2 -2
  12. package/docs/functions/action.html +1 -2
  13. package/docs/functions/allow.html +1 -0
  14. package/docs/functions/body.html +1 -2
  15. package/docs/functions/codeToStatus.html +1 -1
  16. package/docs/functions/config-1.html +1 -2
  17. package/docs/functions/connection.html +1 -2
  18. package/docs/functions/context.html +1 -2
  19. package/docs/functions/controller-1.html +1 -2
  20. package/docs/functions/cookies.html +1 -2
  21. package/docs/functions/db.html +1 -2
  22. package/docs/functions/headers.html +1 -2
  23. package/docs/functions/home.html +1 -2
  24. package/docs/functions/hostname.html +1 -2
  25. package/docs/functions/http.html +1 -4
  26. package/docs/functions/init.html +1 -2
  27. package/docs/functions/json.html +1 -3
  28. package/docs/functions/logerror.html +1 -3
  29. package/docs/functions/method.html +1 -2
  30. package/docs/functions/mixin.html +1 -5
  31. package/docs/functions/mount.html +2 -2
  32. package/docs/functions/pool.html +1 -2
  33. package/docs/functions/protocol.html +1 -2
  34. package/docs/functions/request.html +1 -2
  35. package/docs/functions/selectControllersSchema.html +1 -1
  36. package/docs/functions/stream.html +1 -2
  37. package/docs/functions/subaction.html +1 -2
  38. package/docs/functions/url.html +1 -2
  39. package/docs/functions/xml.html +1 -3
  40. package/docs/index.html +2 -2
  41. package/docs/interfaces/ApiErrorMessage.html +2 -2
  42. package/docs/interfaces/Config.html +2 -2
  43. package/docs/interfaces/ContextSsr.html +2 -2
  44. package/docs/interfaces/ContextWeb.html +2 -2
  45. package/docs/interfaces/OptionsSsr.html +2 -2
  46. package/docs/interfaces/OptionsWeb.html +2 -2
  47. package/docs/interfaces/ResponseOptions.html +2 -2
  48. package/docs/interfaces/Route.html +2 -2
  49. package/docs/interfaces/Schema.html +2 -2
  50. package/docs/interfaces/ServerHandler.html +2 -2
  51. package/docs/interfaces/ServerOptions.html +2 -2
  52. package/docs/interfaces/ServerWebsocket.html +2 -2
  53. package/docs/modules.html +3 -2
  54. package/docs/types/ServerRoutes.html +1 -1
  55. package/docs/variables/helpers.html +2 -2
  56. package/index.d.ts +3 -87
  57. package/index.js +4 -4
  58. package/index.mjs +4 -4
  59. package/package.json +1 -1
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var u=require("./ApiError.js"),_=require("./Server.js"),g=require("./Jwt-CDdbxwvH.js"),q=require("crypto"),Q=require("util"),v=require("./Memcached.js"),E=require("./jsonBody.js"),$=require("stream"),H=require("./urlencodedBody.js"),R=require("./multipartBody.js"),U=require("./readConfig.js"),V=require("./readConfigSync.js"),P=require("./cookieParse.js"),B=require("./cookieString.js"),y=require("./staticBody.js"),X=require("fs"),W=require("path"),S=require("easy-ash"),z=require("querystring"),C=require("xml-js"),G=require("os");require("reflect-metadata"),require("dns"),require("uWebSockets.js"),require("formidable");function O(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 M=O(X),Y=O(W),Z=O(G);const{subtle:N}=q.webcrypto;class ee{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=g.toBase64url({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=g.toBase64url(t),i=await this.signString(`${e}.${s}`);return`${e}.${s}.${i}`}decode(t){const e=(t||"").split("."),s=g.fromBase64url(e[0]),i=g.fromBase64url(e[1]);return{head:s,body:i}}async signString(t){const e=new Q.TextEncoder,s=await N.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return g.urlEncode(Buffer.from(await N.sign("HMAC",s,e.encode(t))).toString("base64"))}}const te=o=>{const t=(o||"").split("."),e=g.fromBase64url(t[0]),s=g.fromBase64url(t[1]);return{head:e,body:s}},j=o=>new Promise((t,e)=>{se(o,s=>t(s),()=>{e(new u.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function se(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 A=(o,t,e=!0)=>{o.onAborted(()=>new u.ApiError({message:"Connection aborted",code:1,statusCode:404}));const s=new $.PassThrough;return s.headers={},t.forEach((i,n)=>s.headers[i]=n),o.onData((i,n)=>{s.write(Buffer.from(Buffer.from(i))),e&&s.resume(),n&&s.end()}),s},oe=(o,t={})=>{for(const e of o){const s=Y.resolve(e);Object.assign(t,JSON.parse(M.readFileSync(s).toString()))}return t};class ie{constructor(t,e,s,i){this.res=t,this.req=e,this.context=s,this.entry=i}async request(t={}){this.res.onAborted(()=>{console.log("Abort is SSR handler")});const e=this.req.getQuery(),s=this.req.getUrl()+(e?`?${e}`:""),i=y.getExt(s);if(y.extensions.includes(i)){await y.staticBody(this.res,this.req,"./dist/client");return}const n={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:P.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,m)=>n.headers[c]=m);const a=`${n.protocol}://${n.hostname}${n.url}`;let r,d=null;this.context.memcached&&(d=await this.context.memcached.getPage(a)),d?(r=d.data.toString(),n.headers=d.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:n}),n.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,n.headers,r,n.memcache)),this.res.cork(()=>{this.res.writeStatus(_.codeToStatus(n.statusCode)),Object.keys(n.headers).map(c=>this.res.writeHeader(c,n.headers[c])),this.res.end(r)})}}const ne=async(o,t,e)=>(await o.poolQuery({sql:`
1
+ "use strict";var h=require("./ApiError.js"),y=require("./Server.js"),g=require("./Jwt-CDdbxwvH.js"),E=require("crypto"),V=require("util"),v=require("./Memcached.js"),H=require("./jsonBody.js"),S=require("stream"),R=require("./urlencodedBody.js"),P=require("./multipartBody.js"),X=require("./readConfig.js"),z=require("./readConfigSync.js"),B=require("./cookieParse.js"),W=require("./cookieString.js"),w=require("./staticBody.js"),G=require("fs"),M=require("path"),A=require("easy-ash"),Y=require("querystring"),O=require("xml-js"),Z=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 N=j(G),ee=j(M),te=j(Z);const{subtle:D}=E.webcrypto;class se{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=g.toBase64url({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=g.toBase64url(t),i=await this.signString(`${e}.${s}`);return`${e}.${s}.${i}`}decode(t){const e=(t||"").split("."),s=g.fromBase64url(e[0]),i=g.fromBase64url(e[1]);return{head:s,body:i}}async signString(t){const e=new V.TextEncoder,s=await D.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return g.urlEncode(Buffer.from(await D.sign("HMAC",s,e.encode(t))).toString("base64"))}}const oe=o=>{const t=(o||"").split("."),e=g.fromBase64url(t[0]),s=g.fromBase64url(t[1]);return{head:e,body:s}},k=o=>new Promise((t,e)=>{ie(o,s=>t(s),()=>{e(new h.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function ie(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)=>{o.onAborted(()=>new h.ApiError({message:"Connection aborted",code:1,statusCode:404}));const s=new S.PassThrough;return s.headers={},t.forEach((i,n)=>s.headers[i]=n),o.onData((i,n)=>{s.write(Buffer.from(Buffer.from(i))),e&&s.resume(),n&&s.end()}),s},ne=(o,t={})=>{for(const e of o){const s=ee.resolve(e);Object.assign(t,JSON.parse(N.readFileSync(s).toString()))}return t};class re{constructor(t,e,s,i){this.res=t,this.req=e,this.context=s,this.entry=i}async request(t={}){this.res.onAborted(()=>{console.log("Abort is SSR handler")});const e=this.req.getQuery(),s=this.req.getUrl()+(e?`?${e}`:""),i=w.getExt(s);if(w.extensions.includes(i)){await w.staticBody(this.res,this.req,"./dist/client");return}const n={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:B.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,m)=>n.headers[c]=m);const a=`${n.protocol}://${n.hostname}${n.url}`;let r,u=null;this.context.memcached&&(u=await this.context.memcached.getPage(a)),u?(r=u.data.toString(),n.headers=u.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:n}),n.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,n.headers,r,n.memcache)),this.res.cork(()=>{this.res.writeStatus(y.codeToStatus(n.statusCode)),Object.keys(n.headers).map(c=>this.res.writeHeader(c,n.headers[c])),this.res.end(r)})}}const ae=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,
@@ -17,7 +17,7 @@
17
17
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
18
18
  LEFT JOIN app_actions a ON a.id = s.app_actions_id
19
19
  WHERE c.name = :name AND s.name = :subaction
20
- `,namedPlaceholders:!0},{name:t,subaction:e}))?.[0],re=async o=>(await o.poolQuery(`
20
+ `,namedPlaceholders:!0},{name:t,subaction:e}))?.[0],ce=async o=>(await o.poolQuery(`
21
21
  SELECT c.id AS controller_id,
22
22
  c.name AS controller_name,
23
23
  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),{}),ae=async(o,t,e,s,i="",n=3600)=>{const a=`${i}::routes::controllers`,r=`${t}::${e}`,d=await s.getValue(a);if(d){const c=JSON.parse(d.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await re(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),n),(c||{}).hasOwnProperty(r)?c[r]:void 0}},D=async(o,t,e,s,i,n="",a=3600)=>{let r;if(i&&i.isClient()&&i.isConnectedServers()?r=await ae(o,e,s,i,n,a):r=await ne(o,e,s),!r)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const d=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new u.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!d.includes(t))throw new u.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}}},ce=async o=>{const t={},e={};return(await o.poolQuery(`
38
+ `)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),he=async(o,t,e,s,i="",n=3600)=>{const a=`${i}::routes::controllers`,r=`${t}::${e}`,u=await s.getValue(a);if(u){const c=JSON.parse(u.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await ce(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),n),(c||{}).hasOwnProperty(r)?c[r]:void 0}},J=async(o,t,e,s,i,n="",a=3600)=>{let r;if(i&&i.isClient()&&i.isConnectedServers()?r=await he(o,e,s,i,n,a):r=await ae(o,e,s),!r)throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const u=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new h.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new h.ApiError({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new h.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new h.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!u.includes(t))throw new h.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}}},ue=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)}},J=(o,t,e,s)=>{let i=o.controllers.find(d=>d.name===e);if(!i)throw new u.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 u.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(d=>d.name===s);if(!n)throw new u.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 u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(d=>d.name===n.action);if(!a)throw new u.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 u.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(d=>d.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new u.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 he{constructor(t,e,s){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.res.onAborted(()=>new u.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s}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,z.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},getRequest:()=>i},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,m)=>this.contextWeb.headers[c]=m);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:A(this.res,this.req,!1)});const c=this.importControllerSync(i.controller),m=new c;if(this.injectContext(m),i.subaction in m)e=await m[i.subaction]();else throw new u.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 m=await c.getPage(this.memcachedKey);if(m){const{data:b,headers:x}=m;this.success({body:b.toString(),headers:x,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)Object.assign(i,await E.jsonBody(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await R.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 H.urlencodedBody(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await j(this.res)).toString(),m=C.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,m||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:A(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const m=A(this.res,this.req),b=Z.tmpdir(),x="./body_"+q.randomBytes(32).toString("hex"),h=W.resolve(b,x),p=M.createWriteStream(h);m.pipe(p),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:h}}}),m.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await j(this.res)});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 D(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});const a=await this.importController(i.controller),r=new a;this.injectContext(r);const d=await this.initComponent(r);if(typeof d>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new u.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=d;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importController(t){let e=this.route.component.default||this.route.component;if(S.isClass(e)||(e=(await this.route.component()).default),typeof e!="function")throw new u.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}importControllerSync(t){const e=this.route.component.default||this.route.component;if(typeof e!="function")throw new u.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}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.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 $.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=_.codeToStatus(i),a=!s&&!e&&S.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 u.ApiError&&t.getData()instanceof $.Stream;let s=_.codeToStatus(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof u.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=_.codeToStatus(t.getStatusCode()),i=t.getHeaders()||this.defaultResponse.headers,e?n=t.getData():n=S.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 ue=async(o,t,e={})=>{const s=async a=>{let r;return"init"in a&&(r=await a.init()),r},i=(a,r)=>{"$inject"in a&&a.$inject(r)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home?await D(t.db.home,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:t.config?.server?.development?.host,protocol:"http",headers:{}},t);const n=new o;if(i(n,t),await s(n))throw new u.ApiError({statusCode:404,code:13,message:"init method response value"});return n},T={compact:!0,ignoreComment:!0,spaces:4};class de{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return B.cookieString(t,e,s)}success(t={},e){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,data: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:C.js2xml(Object.assign(s,{body:{...i.body}}),T),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:C.js2xml(Object.assign(s,{body:{...i.body}}),T),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({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,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader});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 $.PassThrough().end()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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 le{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({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,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"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()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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)}}const f=Symbol("arguments"),I=Symbol("connections"),k=Symbol("response"),L=Symbol("init"),F=Symbol("logger"),me=o=>o.charAt(0).toUpperCase()+o.slice(1);function fe(o,t={}){const e=Reflect.ownKeys(o),s=Reflect.ownKeys(t),i=Symbol("isa");function n(a){for(const r of e)Object.defineProperty(a.prototype,r,{value:o[r]});return Object.defineProperty(a.prototype,i,{value:!0}),a}for(const a of s)Object.defineProperty(n,a,{value:t[a],enumerable:t.propertyIsEnumerable(a)});return Object.defineProperty(n,Symbol.hasInstance,{value:a=>!!a[i]}),n}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 pe(){return function(o,t,e){l(f,o,t,e,"request")}}function be(){return function(o,t,e){l(f,o,t,e,"context")}}function ge(){return function(o,t,e){l(f,o,t,e,"config")}}function _e(){return function(o,t,e){l(f,o,t,e,"method")}}function ye(){return function(o,t,e){l(f,o,t,e,"cookies")}}function xe(){return function(o,t,e){l(f,o,t,e,"hostname")}}function we(){return function(o,t,e){l(f,o,t,e,"url")}}function $e(){return function(o,t,e){l(f,o,t,e,"protocol")}}function Se(){return function(o,t,e){l(f,o,t,e,"db")}}function Ae(){return function(o,t,e){l(f,o,t,e,"headers")}}function ve(){return function(o,t,e){l(f,o,t,e,"controller")}}function Ce(){return function(o,t,e){l(f,o,t,e,"action")}}function Oe(){return function(o,t,e){l(f,o,t,e,"subaction")}}function je(){return function(o,t,e){l(f,o,t,e,"body")}}function ke(){return function(o,t,e){l(f,o,t,e,"stream")}}function qe(){return function(o,t,e){l(f,o,t,e,"home")}}function Ee(o="home"){return function(t,e,s){l(f,t,e,s,"pool",o)}}function He(o="home"){return function(t,e,s){l(I,t,e,s,"connection",o)}}function Re(o={}){return function(t,e,s){l(k,t,e,0,"json",o)}}function Pe(o={}){return function(t,e,s){l(k,t,e,0,"xml",o)}}function Be(o){return function(t,e,s){l(F,t,e,o,"logger",o)}}function We(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=[],d=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(I,t,e)||{},m=Reflect.getOwnMetadata(F,t,e)||{},b=Reflect.getOwnMetadata(k,t,e)?.[0]||{type:"json",params:{}},x=Reflect.getOwnMetadata(L,t,e)?.[0]||{type:"",params:{}};for(const h in d){if(!d.hasOwnProperty(h))continue;const p=`get${me(d[h].type)}`;a[+h]=this[p](d[h].params)}for(const h in c)c.hasOwnProperty(h)&&(c[h].type,a[+h]=await this.getDb()[c[h].params].getConnection(),r.push(a[+h]));try{let h=await n.apply(this,a),p;if(Array.isArray(h)&&([h,p]=h),x.type!=="init")return i.format==="xml"||b.type==="xml"?this.successXml(h,Object.assign(b.params,p||{})):i.format==="buffer"?this.successBuffer(h,Object.assign(b.params,p||{})):this.success(h,Object.assign(b.params,p||{}))}catch(h){await Promise.all([...r.map(w=>w.rollback())]);let p;i.format==="xml"||b.type==="xml"?p=this.errorXml(h):p=this.error(h);for(const w in m){if(!m.hasOwnProperty(w))continue;const K=m[w].params;await this[K].error(h,{response:S.omit(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(h=>h.release())])}}}}function Me(){return function(o,t,e){l(L,o,t,0,"init"),e.value,"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}const Ne={cookieParse:P.cookieParse,cookieString:B.cookieString,jsonBody:E.jsonBody,rawBody:j,streamBody:A,urlencodedBody:H.urlencodedBody,multipartBody:R.multipartBody,readConfig:U.readConfig,readConfigSync:V.readConfigSync,staticBody:y.staticBody,extensions:y.extensions,getExt:y.getExt,jwtDecode:te,readJsonConfigsSync:oe};exports.ApiError=u.ApiError,exports.Server=_.Server,exports.codeToStatus=_.codeToStatus,exports.Jwt=g.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=ee,exports.Controller=de,exports.Model=le,exports.Ssr=ie,exports.Web=he,exports.action=Ce,exports.body=je,exports.config=ge,exports.connection=He,exports.context=be,exports.controller=ve,exports.cookies=ye,exports.db=Se,exports.headers=Ae,exports.helpers=Ne,exports.home=qe,exports.hostname=xe,exports.http=We,exports.init=Me,exports.json=Re,exports.logerror=Be,exports.method=_e,exports.mixin=fe,exports.mount=ue,exports.pool=Ee,exports.protocol=$e,exports.request=pe,exports.selectControllersSchema=ce,exports.stream=ke,exports.subaction=Oe,exports.url=we,exports.xml=Pe;
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)}},T=(o,t,e,s)=>{let i=o.controllers.find(u=>u.name===e);if(!i)throw new h.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 h.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(u=>u.name===s);if(!n)throw new h.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 h.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(u=>u.name===n.action);if(!a)throw new h.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 h.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(u=>u.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new h.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 de{constructor(t,e,s){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.res.onAborted(()=>new h.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s}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,Y.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},getRequest:()=>i},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,m)=>this.contextWeb.headers[c]=m);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,T(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(i.controller),m=new c;if(this.injectContext(m),i.subaction in m)e=await m[i.subaction]();else throw new h.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 m=await c.getPage(this.memcachedKey);if(m){const{data:b,headers:x}=m;this.success({body:b.toString(),headers:x,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)Object.assign(i,await H.jsonBody(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await P.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 R.urlencodedBody(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),m=O.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,m||{})}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 m=C(this.res,this.req),b=te.tmpdir(),x="./body_"+E.randomBytes(32).toString("hex"),_=M.resolve(b,x),d=N.createWriteStream(_);m.pipe(d),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:_}}}),m.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?T(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await J(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});const a=await this.importController(i.controller),r=new a;this.injectContext(r);const u=await this.initComponent(r);if(typeof u>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new h.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=u;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importController(t){let e=this.route.component.default||this.route.component;if(A.isClass(e)||(e=(await this.route.component()).default),typeof e!="function")throw new h.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}importControllerSync(t){const e=this.route.component.default||this.route.component;if(typeof e!="function")throw new h.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}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 h.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 S.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=y.codeToStatus(i),a=!s&&!e&&A.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 h.ApiError&&t.getData()instanceof S.Stream;let s=y.codeToStatus(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof h.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=y.codeToStatus(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=A.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 le=async(o,t,e={})=>{const s=async a=>{let r;return"init"in a&&(r=await a.init()),r},i=(a,r)=>{"$inject"in a&&a.$inject(r)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home?await J(t.db.home,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:t.config?.server?.development?.host,protocol:"http",headers:{}},t);const n=new o;if(i(n,t),await s(n))throw new h.ApiError({statusCode:404,code:13,message:"init method response value"});return n},I={compact:!0,ignoreComment:!0,spaces:4};class me{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return W.cookieString(t,e,s)}success(t={},e){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,data: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}}),I),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}}),I),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({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,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader});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 S.PassThrough().end()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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 fe{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({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,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"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()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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)}}const f=Symbol("arguments"),L=Symbol("connections"),q=Symbol("response"),F=Symbol("init"),K=Symbol("logger"),Q=Symbol("filters"),pe=o=>o.charAt(0).toUpperCase()+o.slice(1);function be(o,t={}){const e=Reflect.ownKeys(o),s=Reflect.ownKeys(t),i=Symbol("isa");function n(a){for(const r of e)Object.defineProperty(a.prototype,r,{value:o[r]});return Object.defineProperty(a.prototype,i,{value:!0}),a}for(const a of s)Object.defineProperty(n,a,{value:t[a],enumerable:t.propertyIsEnumerable(a)});return Object.defineProperty(n,Symbol.hasInstance,{value:a=>!!a[i]}),n}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 ge(){return function(o,t,e){l(f,o,t,e,"request")}}function _e(){return function(o,t,e){l(f,o,t,e,"context")}}function ye(){return function(o,t,e){l(f,o,t,e,"config")}}function we(){return function(o,t,e){l(f,o,t,e,"method")}}function xe(){return function(o,t,e){l(f,o,t,e,"cookies")}}function $e(){return function(o,t,e){l(f,o,t,e,"hostname")}}function Se(){return function(o,t,e){l(f,o,t,e,"url")}}function Ae(){return function(o,t,e){l(f,o,t,e,"protocol")}}function Ce(){return function(o,t,e){l(f,o,t,e,"db")}}function ve(){return function(o,t,e){l(f,o,t,e,"headers")}}function Oe(){return function(o,t,e){l(f,o,t,e,"controller")}}function je(){return function(o,t,e){l(f,o,t,e,"action")}}function ke(){return function(o,t,e){l(f,o,t,e,"subaction")}}function qe(){return function(o,t,e){l(f,o,t,e,"body")}}function Ee(){return function(o,t,e){l(f,o,t,e,"stream")}}function He(){return function(o,t,e){l(f,o,t,e,"home")}}function Re(o="home"){return function(t,e,s){l(f,t,e,s,"pool",o)}}function Pe(o="home"){return function(t,e,s){l(L,t,e,s,"connection",o)}}function Be(o={}){return function(t,e,s){l(q,t,e,0,"json",o)}}function We(o={}){return function(t,e,s){l(q,t,e,0,"xml",o)}}function Me(o){return function(t,e,s){l(K,t,e,o,"logger",o)}}function Ne(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=[],u=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(L,t,e)||{},m=Reflect.getOwnMetadata(K,t,e)||{},b=Reflect.getOwnMetadata(q,t,e)?.[0]||{type:"json",params:{}},x=Reflect.getOwnMetadata(F,t,e)?.[0]||{type:"",params:{}},_=(Reflect.getOwnMetadata(Q,t,e)?.[0]||{type:"allow",params:[]}).params;if(_.length&&!_.includes(this.getMethod())&&this.getMethod()!=="any")throw new h.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${_.join(",")} methods`});for(const d in u){if(!u.hasOwnProperty(d))continue;const p=`get${pe(u[d].type)}`;a[+d]=this[p](u[d].params)}for(const d in c)c.hasOwnProperty(d)&&(c[d].type,a[+d]=await this.getDb()[c[d].params].getConnection(),r.push(a[+d]));try{let d=await n.apply(this,a),p;if(Array.isArray(d)&&([d,p]=d),x.type!=="init")return i.format==="xml"||b.type==="xml"?this.successXml(d,Object.assign(b.params,p||{})):i.format==="buffer"?this.successBuffer(d,Object.assign(b.params,p||{})):this.success(d,Object.assign(b.params,p||{}))}catch(d){await Promise.all([...r.map($=>$.rollback())]);let p;i.format==="xml"||b.type==="xml"?p=this.errorXml(d):p=this.error(d);for(const $ in m){if(!m.hasOwnProperty($))continue;const U=m[$].params;await this[U].error(d,{response:A.omit(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(d=>d.release())])}}}}function De(){return function(o,t,e){l(F,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Je(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){l(Q,t,e,0,"allow",o)}}const Te={cookieParse:B.cookieParse,cookieString:W.cookieString,jsonBody:H.jsonBody,rawBody:k,streamBody:C,urlencodedBody:R.urlencodedBody,multipartBody:P.multipartBody,readConfig:X.readConfig,readConfigSync:z.readConfigSync,staticBody:w.staticBody,extensions:w.extensions,getExt:w.getExt,jwtDecode:oe,readJsonConfigsSync:ne};exports.ApiError=h.ApiError,exports.Server=y.Server,exports.codeToStatus=y.codeToStatus,exports.Jwt=g.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=se,exports.Controller=me,exports.Model=fe,exports.Ssr=re,exports.Web=de,exports.action=je,exports.allow=Je,exports.body=qe,exports.config=ye,exports.connection=Pe,exports.context=_e,exports.controller=Oe,exports.cookies=xe,exports.db=Ce,exports.headers=ve,exports.helpers=Te,exports.home=He,exports.hostname=$e,exports.http=Ne,exports.init=De,exports.json=Be,exports.logerror=Me,exports.method=we,exports.mixin=be,exports.mount=le,exports.pool=Re,exports.protocol=Ae,exports.request=ge,exports.selectControllersSchema=ue,exports.stream=Ee,exports.subaction=ke,exports.url=Se,exports.xml=We;
package/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as _}from"./Server.mjs";import{Server as pe}from"./Server.mjs";import{t as O,f as x,u as U}from"./Jwt-7tQL-rwa.js";import{J as ge}from"./Jwt-7tQL-rwa.js";import V,{webcrypto as X}from"crypto";import{TextEncoder as z}from"util";import{Memcached as $}from"./Memcached.mjs";import{jsonBody as v}from"./jsonBody.mjs";import{PassThrough as j,Stream as k}from"stream";import{urlencodedBody as H}from"./urlencodedBody.mjs";import{multipartBody as R}from"./multipartBody.mjs";import{readConfig as G}from"./readConfig.mjs";import{readConfigSync as Y}from"./readConfigSync.mjs";import{cookieParse as q}from"./cookieParse.mjs";import{cookieString as P}from"./cookieString.mjs";import{getExt as W,extensions as E,staticBody as N}from"./staticBody.mjs";import*as B from"fs";import*as Z from"path";import tt from"path";import{isClass as et,isObject as M,omit as st}from"easy-ash";import ot from"querystring";import S from"xml-js";import*as nt from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:D}=X;class it{constructor(e,t){this.algorithm="SHA-256",this.secret=e,this.algorithm=t?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(e){if(!e)return!1;const t=e.split(".");return await this.signString(`${t[0]}.${t[1]}`)===t[2]}async sign(e){const t=O({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=O(e),n=await this.signString(`${t}.${s}`);return`${t}.${s}.${n}`}decode(e){const t=(e||"").split("."),s=x(t[0]),n=x(t[1]);return{head:s,body:n}}async signString(e){const t=new z,s=await D.importKey("raw",t.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return U(Buffer.from(await D.sign("HMAC",s,t.encode(e))).toString("base64"))}}const rt=o=>{const e=(o||"").split("."),t=x(e[0]),s=x(e[1]);return{head:t,body:s}},C=o=>new Promise((e,t)=>{at(o,s=>e(s),()=>{t(new d({message:"Can`t parse request",code:1,statusCode:404}))})});function at(o,e,t){let s=Buffer.from([]);o.onData((n,i)=>{s=Buffer.concat([s,Buffer.from(n)]),i&&e(s)}),o.onAborted(t)}const w=(o,e,t=!0)=>{o.onAborted(()=>new d({message:"Connection aborted",code:1,statusCode:404}));const s=new j;return s.headers={},e.forEach((n,i)=>s.headers[n]=i),o.onData((n,i)=>{s.write(Buffer.from(Buffer.from(n))),t&&s.resume(),i&&s.end()}),s},ct=(o,e={})=>{for(const t of o){const s=Z.resolve(t);Object.assign(e,JSON.parse(B.readFileSync(s).toString()))}return e};class ht{constructor(e,t,s,n){this.res=e,this.req=t,this.context=s,this.entry=n}async request(e={}){this.res.onAborted(()=>{console.log("Abort is SSR handler")});const t=this.req.getQuery(),s=this.req.getUrl()+(t?`?${t}`:""),n=W(s);if(E.includes(n)){await N(this.res,this.req,"./dist/client");return}const i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:q(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,l)=>i.headers[c]=l);const a=`${i.protocol}://${i.hostname}${i.url}`;let r,u=null;this.context.memcached&&(u=await this.context.memcached.getPage(a)),u?(r=u.data.toString(),i.headers=u.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,i.headers,r,i.memcache)),this.res.cork(()=>{this.res.writeStatus(_(i.statusCode)),Object.keys(i.headers).map(c=>this.res.writeHeader(c,i.headers[c])),this.res.end(r)})}}const dt=async(o,e,t)=>(await o.poolQuery({sql:`
1
+ import{ApiError as h}from"./ApiError.mjs";import{codeToStatus as y}from"./Server.mjs";import{Server as _e}from"./Server.mjs";import{t as v,f as x,u as X}from"./Jwt-7tQL-rwa.js";import{J as we}from"./Jwt-7tQL-rwa.js";import z,{webcrypto as G}from"crypto";import{TextEncoder as Y}from"util";import{Memcached as S}from"./Memcached.mjs";import{jsonBody as j}from"./jsonBody.mjs";import{PassThrough as k,Stream as H}from"stream";import{urlencodedBody as R}from"./urlencodedBody.mjs";import{multipartBody as q}from"./multipartBody.mjs";import{readConfig as Z}from"./readConfig.mjs";import{readConfigSync as tt}from"./readConfigSync.mjs";import{cookieParse as P}from"./cookieParse.mjs";import{cookieString as W}from"./cookieString.mjs";import{getExt as E,extensions as M,staticBody as N}from"./staticBody.mjs";import*as B from"fs";import*as et from"path";import st from"path";import{isClass as ot,isObject as D,omit as nt}from"easy-ash";import it from"querystring";import C from"xml-js";import*as rt from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:J}=G;class at{constructor(e,t){this.algorithm="SHA-256",this.secret=e,this.algorithm=t?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(e){if(!e)return!1;const t=e.split(".");return await this.signString(`${t[0]}.${t[1]}`)===t[2]}async sign(e){const t=v({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=v(e),n=await this.signString(`${t}.${s}`);return`${t}.${s}.${n}`}decode(e){const t=(e||"").split("."),s=x(t[0]),n=x(t[1]);return{head:s,body:n}}async signString(e){const t=new Y,s=await J.importKey("raw",t.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return X(Buffer.from(await J.sign("HMAC",s,t.encode(e))).toString("base64"))}}const ct=o=>{const e=(o||"").split("."),t=x(e[0]),s=x(e[1]);return{head:t,body:s}},A=o=>new Promise((e,t)=>{ht(o,s=>e(s),()=>{t(new h({message:"Can`t parse request",code:1,statusCode:404}))})});function ht(o,e,t){let s=Buffer.from([]);o.onData((n,i)=>{s=Buffer.concat([s,Buffer.from(n)]),i&&e(s)}),o.onAborted(t)}const $=(o,e,t=!0)=>{o.onAborted(()=>new h({message:"Connection aborted",code:1,statusCode:404}));const s=new k;return s.headers={},e.forEach((n,i)=>s.headers[n]=i),o.onData((n,i)=>{s.write(Buffer.from(Buffer.from(n))),t&&s.resume(),i&&s.end()}),s},dt=(o,e={})=>{for(const t of o){const s=et.resolve(t);Object.assign(e,JSON.parse(B.readFileSync(s).toString()))}return e};class ut{constructor(e,t,s,n){this.res=e,this.req=t,this.context=s,this.entry=n}async request(e={}){this.res.onAborted(()=>{console.log("Abort is SSR handler")});const t=this.req.getQuery(),s=this.req.getUrl()+(t?`?${t}`:""),n=E(s);if(M.includes(n)){await N(this.res,this.req,"./dist/client");return}const i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:P(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,l)=>i.headers[c]=l);const a=`${i.protocol}://${i.hostname}${i.url}`;let r,d=null;this.context.memcached&&(d=await this.context.memcached.getPage(a)),d?(r=d.data.toString(),i.headers=d.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,i.headers,r,i.memcache)),this.res.cork(()=>{this.res.writeStatus(y(i.statusCode)),Object.keys(i.headers).map(c=>this.res.writeHeader(c,i.headers[c])),this.res.end(r)})}}const mt=async(o,e,t)=>(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,
@@ -17,7 +17,7 @@ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as _}from"./Server
17
17
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
18
18
  LEFT JOIN app_actions a ON a.id = s.app_actions_id
19
19
  WHERE c.name = :name AND s.name = :subaction
20
- `,namedPlaceholders:!0},{name:e,subaction:t}))?.[0],ut=async o=>(await o.poolQuery(`
20
+ `,namedPlaceholders:!0},{name:e,subaction:t}))?.[0],lt=async o=>(await o.poolQuery(`
21
21
  SELECT c.id AS controller_id,
22
22
  c.name AS controller_name,
23
23
  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((e,t)=>(e[`${t.controller_name}::${t.subaction_name}`]=t,e),{}),mt=async(o,e,t,s,n="",i=3600)=>{const a=`${n}::routes::controllers`,r=`${e}::${t}`,u=await s.getValue(a);if(u){const c=JSON.parse(u.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await ut(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),i),(c||{}).hasOwnProperty(r)?c[r]:void 0}},J=async(o,e,t,s,n,i="",a=3600)=>{let r;if(n&&n.isClient()&&n.isConnectedServers()?r=await mt(o,t,s,n,i,a):r=await dt(o,t,s),!r)throw new d({statusCode:404,code:11,message:`Controller ${t} not found in site schema`});const u=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new d({statusCode:404,code:11,message:`Controller ${t} not active in site schema`});if(!r.action_id)throw new d({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new d({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!u.includes(e))throw new d({statusCode:404,code:11,message:`Controller ${t} 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}}},lt=async o=>{const e={},t={};return(await o.poolQuery(`
38
+ `)).reduce((e,t)=>(e[`${t.controller_name}::${t.subaction_name}`]=t,e),{}),ft=async(o,e,t,s,n="",i=3600)=>{const a=`${n}::routes::controllers`,r=`${e}::${t}`,d=await s.getValue(a);if(d){const c=JSON.parse(d.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await lt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),i),(c||{}).hasOwnProperty(r)?c[r]:void 0}},I=async(o,e,t,s,n,i="",a=3600)=>{let r;if(n&&n.isClient()&&n.isConnectedServers()?r=await ft(o,t,s,n,i,a):r=await mt(o,t,s),!r)throw new h({statusCode:404,code:11,message:`Controller ${t} not found in site schema`});const d=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new h({statusCode:404,code:11,message:`Controller ${t} not active in site schema`});if(!r.action_id)throw new h({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new h({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new h({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new h({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!d.includes(e))throw new h({statusCode:404,code:11,message:`Controller ${t} 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 e={},t={};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=>{e[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},t[s.controller_name]=t[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},t[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(t),actions:Object.values(e)}},I=(o,e,t,s)=>{let n=o.controllers.find(u=>u.name===t);if(!n)throw new d({statusCode:404,code:11,message:`Controller ${t} 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 ${t} not active is site schema`});let i=n.subactions.find(u=>u.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(u=>u.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(u=>u.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(e))throw new d({statusCode:404,code:11,message:`Controller ${t} 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 ft{constructor(e,t,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=e,this.req=t,this.res.onAborted(()=>new d({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(e){return Object.assign(this.defaultRequest,e),this}async request(e={}){let t={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,e,ot.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},getRequest:()=>n},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,l)=>this.contextWeb.headers[c]=l);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,I(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(n.controller),l=new c;if(this.injectContext(l),n.subaction in l)t=await l[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});t=Object.assign({},this.defaultResponse,t),this.success(t);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof $){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const l=await c.getPage(this.memcachedKey);if(l){const{data:b,headers:g}=l;this.success({body:b.toString(),headers:g,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)Object.assign(n,await v(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await R(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 H(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const c=(await C(this.res)).toString(),l=S.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,l||{})}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 l=w(this.res,this.req),b=nt.tmpdir(),g="./body_"+V.randomBytes(32).toString("hex"),h=tt.resolve(b,g),p=B.createWriteStream(h);l.pipe(p),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:h}}}),l.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await C(this.res)});this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?I(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await J(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});const a=await this.importController(n.controller),r=new a;this.injectContext(r);const u=await this.initComponent(r);if(typeof u>"u")if(n.subaction in r)t=await r[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else t=u;t=Object.assign({},this.defaultResponse,t),this.success(t)}catch(s){this.error(s)}}async importController(e){let t=this.route.component.default||this.route.component;if(et(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}importControllerSync(e){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 ${e} route`});return t}findRoute(e){const t=this.context.routes.filter(s=>s.name===e&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!t)throw new d({statusCode:404,code:11,message:`Route ${e} not found`});return t}injectContext(e){"$inject"in e&&e.$inject(this.contextWeb)}async initComponent(e){const t=[...new Set(["init",...e.$inits||[]])];for(const s of t)if(e[s]){const n=await e[s]();if(n)return n}}success(e){const t=e.body instanceof k,s=e.body instanceof Uint8Array,n=e.statusCode||200,i=_(n),a=!s&&!t&&M(e.body)?JSON.stringify(e.body):e.body;!s&&!t&&["get","head"].includes(this.contextWeb.method)&&n===200&&e.memcache&&this.contextWeb?.stack?.memcached instanceof $&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,e.headers,a,e.memcache).then(),t?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),this.res.end(a)})}error(e){const t=e instanceof d&&e.getData()instanceof k;let s=_(404),n=this.defaultResponse.headers,i=e.message;if(e instanceof d){const a={isError:!0,code:e.getCode(),error:e.getMessage()};s=_(e.getStatusCode()),n=e.getHeaders()||this.defaultResponse.headers,t?i=e.getData():i=M(e.getData())&&Object.keys(e.getData()).length>0?JSON.stringify(e.getData()):JSON.stringify(a)}t?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(e){Object.entries(e).forEach(([t,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(t,n)):this.res.writeHeader(t,s)})}}const pt=async(o,e,t={})=>{const s=async a=>{let r;return"init"in a&&(r=await a.init()),r},n=(a,r)=>{"$inject"in a&&a.$inject(r)};e=Object.assign({config:{},getRequest:()=>t,method:"get",...t.controller&&t.subaction&&e.db?.home?await J(e.db.home,e.method||"get",t.controller,t.subaction):{},cookies:{},hostname:e.config?.server?.development?.host,protocol:"http",headers:{}},e);const i=new o;if(n(i,e),await s(i))throw new d({statusCode:404,code:13,message:"init method response value"});return i},L={compact:!0,ignoreComment:!0,spaces:4};class bt{constructor(){this.responseHeaders={}}setCookieHeader(e,t,s={}){return P(e,t,s)}success(e={},t){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,t?.headers||{}),body:{isError:!1,data:e},memcache:t?.memcache||null,statusCode:t?.statusCode||200}}successBuffer(e,t){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,t?.headers||{}),body:e,memcache:t?.memcache||null,statusCode:t?.statusCode||200}}error(e){const t=e,s=t.code?t.code:0,n=t.message?t.message:"Api request error",i=t.statusCode?t.statusCode:404,a=t.data?t.data:{},r=t.response?{status:t.response.status,headers:t.response.headers,config:{url:t.response.url,method:t.response.method,params:t.response.params,headers:t.response.headers},data:t.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},t.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?t.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(e={},t){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(e,t);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,t?.headers||{}),body:S.js2xml(Object.assign(s,{body:{...n.body}}),L),memcache:n.memcache}}errorXml(e){const t=e,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(t);return{headers:Object.assign({"content-type":"application/xml"},t.headers),body:S.js2xml(Object.assign(s,{body:{...n.body}}),L),statusCode:n.statusCode}}async $create(e,...t){const s=new e(...t);"$inject"in s&&s.$inject({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,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}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 j().end()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){this.responseHeaders.hasOwnProperty(e)?(this.responseHeaders[e]=Array.isArray(this.responseHeaders[e])?this.responseHeaders[e]:[this.responseHeaders[e]],this.responseHeaders[e].push(t)):this.responseHeaders[e]=t}}class gt{async $create(e,...t){const s=new e(...t);return"$inject"in s&&s.$inject({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,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){return this.$context.setResponseHeader(e,t)}setCookieHeader(e,t,s={}){return this.$context.setCookieHeader(e,t,s)}}const f=Symbol("arguments"),T=Symbol("connections"),A=Symbol("response"),F=Symbol("init"),K=Symbol("logger"),_t=o=>o.charAt(0).toUpperCase()+o.slice(1);function yt(o,e={}){const t=Reflect.ownKeys(o),s=Reflect.ownKeys(e),n=Symbol("isa");function i(a){for(const r of t)Object.defineProperty(a.prototype,r,{value:o[r]});return Object.defineProperty(a.prototype,n,{value:!0}),a}for(const a of s)Object.defineProperty(i,a,{value:e[a],enumerable:e.propertyIsEnumerable(a)});return Object.defineProperty(i,Symbol.hasInstance,{value:a=>!!a[n]}),i}const m=(o,e,t,s,n,i)=>{const a=Reflect.getOwnMetadata(o,e,t)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,e,t)};function xt(){return function(o,e,t){m(f,o,e,t,"request")}}function wt(){return function(o,e,t){m(f,o,e,t,"context")}}function $t(){return function(o,e,t){m(f,o,e,t,"config")}}function St(){return function(o,e,t){m(f,o,e,t,"method")}}function Ct(){return function(o,e,t){m(f,o,e,t,"cookies")}}function At(){return function(o,e,t){m(f,o,e,t,"hostname")}}function Ot(){return function(o,e,t){m(f,o,e,t,"url")}}function vt(){return function(o,e,t){m(f,o,e,t,"protocol")}}function jt(){return function(o,e,t){m(f,o,e,t,"db")}}function kt(){return function(o,e,t){m(f,o,e,t,"headers")}}function Ht(){return function(o,e,t){m(f,o,e,t,"controller")}}function Rt(){return function(o,e,t){m(f,o,e,t,"action")}}function qt(){return function(o,e,t){m(f,o,e,t,"subaction")}}function Pt(){return function(o,e,t){m(f,o,e,t,"body")}}function Wt(){return function(o,e,t){m(f,o,e,t,"stream")}}function Et(){return function(o,e,t){m(f,o,e,t,"home")}}function Nt(o="home"){return function(e,t,s){m(f,e,t,s,"pool",o)}}function Bt(o="home"){return function(e,t,s){m(T,e,t,s,"connection",o)}}function Mt(o={}){return function(e,t,s){m(A,e,t,0,"json",o)}}function Dt(o={}){return function(e,t,s){m(A,e,t,0,"xml",o)}}function Jt(o){return function(e,t,s){m(K,e,t,o,"logger",o)}}function It(o){return function(e,t,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],u=Reflect.getOwnMetadata(f,e,t)||{},c=Reflect.getOwnMetadata(T,e,t)||{},l=Reflect.getOwnMetadata(K,e,t)||{},b=Reflect.getOwnMetadata(A,e,t)?.[0]||{type:"json",params:{}},g=Reflect.getOwnMetadata(F,e,t)?.[0]||{type:"",params:{}};for(const h in u){if(!u.hasOwnProperty(h))continue;const p=`get${_t(u[h].type)}`;a[+h]=this[p](u[h].params)}for(const h in c)c.hasOwnProperty(h)&&(c[h].type,a[+h]=await this.getDb()[c[h].params].getConnection(),r.push(a[+h]));try{let h=await i.apply(this,a),p;if(Array.isArray(h)&&([h,p]=h),g.type!=="init")return n.format==="xml"||b.type==="xml"?this.successXml(h,Object.assign(b.params,p||{})):n.format==="buffer"?this.successBuffer(h,Object.assign(b.params,p||{})):this.success(h,Object.assign(b.params,p||{}))}catch(h){await Promise.all([...r.map(y=>y.rollback())]);let p;n.format==="xml"||b.type==="xml"?p=this.errorXml(h):p=this.error(h);for(const y in l){if(!l.hasOwnProperty(y))continue;const Q=l[y].params;await this[Q].error(h,{response:st(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(h=>h.release())])}}}}function Lt(){return function(o,e,t){m(F,o,e,0,"init"),t.value,"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(e)}}const Tt={cookieParse:q,cookieString:P,jsonBody:v,rawBody:C,streamBody:w,urlencodedBody:H,multipartBody:R,readConfig:G,readConfigSync:Y,staticBody:N,extensions:E,getExt:W,jwtDecode:rt,readJsonConfigsSync:ct};export{d as ApiError,it as AsyncJwt,bt as Controller,ge as Jwt,$ as Memcached,gt as Model,pe as Server,ht as Ssr,ft as Web,Rt as action,Pt as body,_ as codeToStatus,$t as config,Bt as connection,wt as context,Ht as controller,Ct as cookies,jt as db,kt as headers,Tt as helpers,Et as home,At as hostname,It as http,Lt as init,Mt as json,Jt as logerror,St as method,yt as mixin,pt as mount,Nt as pool,vt as protocol,xt as request,lt as selectControllersSchema,Wt as stream,qt as subaction,Ot as url,Dt as xml};
57
+ `)).forEach(s=>{e[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},t[s.controller_name]=t[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},t[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(t),actions:Object.values(e)}},L=(o,e,t,s)=>{let n=o.controllers.find(d=>d.name===t);if(!n)throw new h({statusCode:404,code:11,message:`Controller ${t} not found is site schema`});if(n=Object.assign({isActive:!0,isSitemap:!1},n),!n.isActive)throw new h({statusCode:404,code:11,message:`Controller ${t} not active is site schema`});let i=n.subactions.find(d=>d.name===s);if(!i)throw new h({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 h({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(d=>d.name===i.action);if(!a)throw new h({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new h({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(d=>d.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(e))throw new h({statusCode:404,code:11,message:`Controller ${t} 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 bt{constructor(e,t,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=e,this.req=t,this.res.onAborted(()=>new h({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(e){return Object.assign(this.defaultRequest,e),this}async request(e={}){let t={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,e,it.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},getRequest:()=>n},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,l)=>this.contextWeb.headers[c]=l);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,L(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:$(this.res,this.req,!1)});const c=this.importControllerSync(n.controller),l=new c;if(this.injectContext(l),n.subaction in l)t=await l[n.subaction]();else throw new h({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});t=Object.assign({},this.defaultResponse,t),this.success(t);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const l=await c.getPage(this.memcachedKey);if(l){const{data:b,headers:_}=l;this.success({body:b.toString(),headers:_,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)Object.assign(n,await j(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await q(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 R(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const c=(await A(this.res)).toString(),l=C.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,l||{})}else i.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:$(this.res,this.req,!1)}):i.indexOf("binary")!==-1?await new Promise(c=>{const l=$(this.res,this.req),b=rt.tmpdir(),_="./body_"+z.randomBytes(32).toString("hex"),g=st.resolve(b,_),u=B.createWriteStream(g);l.pipe(u),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:g}}}),l.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await A(this.res)});this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?L(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await I(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});const a=await this.importController(n.controller),r=new a;this.injectContext(r);const d=await this.initComponent(r);if(typeof d>"u")if(n.subaction in r)t=await r[n.subaction]();else throw new h({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else t=d;t=Object.assign({},this.defaultResponse,t),this.success(t)}catch(s){this.error(s)}}async importController(e){let t=this.route.component.default||this.route.component;if(ot(t)||(t=(await this.route.component()).default),typeof t!="function")throw new h({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}importControllerSync(e){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new h({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}findRoute(e){const t=this.context.routes.filter(s=>s.name===e&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!t)throw new h({statusCode:404,code:11,message:`Route ${e} not found`});return t}injectContext(e){"$inject"in e&&e.$inject(this.contextWeb)}async initComponent(e){const t=[...new Set(["init",...e.$inits||[]])];for(const s of t)if(e[s]){const n=await e[s]();if(n)return n}}success(e){const t=e.body instanceof H,s=e.body instanceof Uint8Array,n=e.statusCode||200,i=y(n),a=!s&&!t&&D(e.body)?JSON.stringify(e.body):e.body;!s&&!t&&["get","head"].includes(this.contextWeb.method)&&n===200&&e.memcache&&this.contextWeb?.stack?.memcached instanceof S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,e.headers,a,e.memcache).then(),t?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),this.res.end(a)})}error(e){const t=e instanceof h&&e.getData()instanceof H;let s=y(404),n=this.defaultResponse.headers,i=e.message;if(e instanceof h){const a={isError:!0,code:e.getCode(),error:e.getMessage()};s=y(e.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,e.getHeaders()||{}),t?i=e.getData():i=D(e.getData())&&Object.keys(e.getData()).length>0?JSON.stringify(e.getData()):JSON.stringify(a)}t?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(e){Object.entries(e).forEach(([t,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(t,n)):this.res.writeHeader(t,s)})}}const gt=async(o,e,t={})=>{const s=async a=>{let r;return"init"in a&&(r=await a.init()),r},n=(a,r)=>{"$inject"in a&&a.$inject(r)};e=Object.assign({config:{},getRequest:()=>t,method:"get",...t.controller&&t.subaction&&e.db?.home?await I(e.db.home,e.method||"get",t.controller,t.subaction):{},cookies:{},hostname:e.config?.server?.development?.host,protocol:"http",headers:{}},e);const i=new o;if(n(i,e),await s(i))throw new h({statusCode:404,code:13,message:"init method response value"});return i},T={compact:!0,ignoreComment:!0,spaces:4};class _t{constructor(){this.responseHeaders={}}setCookieHeader(e,t,s={}){return W(e,t,s)}success(e={},t){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,t?.headers||{}),body:{isError:!1,data:e},memcache:t?.memcache||null,statusCode:t?.statusCode||200}}successBuffer(e,t){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,t?.headers||{}),body:e,memcache:t?.memcache||null,statusCode:t?.statusCode||200}}error(e){const t=e,s=t.code?t.code:0,n=t.message?t.message:"Api request error",i=t.statusCode?t.statusCode:404,a=t.data?t.data:{},r=t.response?{status:t.response.status,headers:t.response.headers,config:{url:t.response.url,method:t.response.method,params:t.response.params,headers:t.response.headers},data:t.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},t.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?t.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(e={},t){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(e,t);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,t?.headers||{}),body:C.js2xml(Object.assign(s,{body:{...n.body}}),T),memcache:n.memcache}}errorXml(e){const t=e,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(t);return{headers:Object.assign({"content-type":"application/xml"},t.headers),body:C.js2xml(Object.assign(s,{body:{...n.body}}),T),statusCode:n.statusCode}}async $create(e,...t){const s=new e(...t);"$inject"in s&&s.$inject({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,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}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 k().end()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){this.responseHeaders.hasOwnProperty(e)?(this.responseHeaders[e]=Array.isArray(this.responseHeaders[e])?this.responseHeaders[e]:[this.responseHeaders[e]],this.responseHeaders[e].push(t)):this.responseHeaders[e]=t}}class yt{async $create(e,...t){const s=new e(...t);return"$inject"in s&&s.$inject({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,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}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(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){return this.$context.setResponseHeader(e,t)}setCookieHeader(e,t,s={}){return this.$context.setCookieHeader(e,t,s)}}const f=Symbol("arguments"),F=Symbol("connections"),O=Symbol("response"),K=Symbol("init"),Q=Symbol("logger"),U=Symbol("filters"),wt=o=>o.charAt(0).toUpperCase()+o.slice(1);function xt(o,e={}){const t=Reflect.ownKeys(o),s=Reflect.ownKeys(e),n=Symbol("isa");function i(a){for(const r of t)Object.defineProperty(a.prototype,r,{value:o[r]});return Object.defineProperty(a.prototype,n,{value:!0}),a}for(const a of s)Object.defineProperty(i,a,{value:e[a],enumerable:e.propertyIsEnumerable(a)});return Object.defineProperty(i,Symbol.hasInstance,{value:a=>!!a[n]}),i}const m=(o,e,t,s,n,i)=>{const a=Reflect.getOwnMetadata(o,e,t)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,e,t)};function $t(){return function(o,e,t){m(f,o,e,t,"request")}}function St(){return function(o,e,t){m(f,o,e,t,"context")}}function Ct(){return function(o,e,t){m(f,o,e,t,"config")}}function At(){return function(o,e,t){m(f,o,e,t,"method")}}function Ot(){return function(o,e,t){m(f,o,e,t,"cookies")}}function vt(){return function(o,e,t){m(f,o,e,t,"hostname")}}function jt(){return function(o,e,t){m(f,o,e,t,"url")}}function kt(){return function(o,e,t){m(f,o,e,t,"protocol")}}function Ht(){return function(o,e,t){m(f,o,e,t,"db")}}function Rt(){return function(o,e,t){m(f,o,e,t,"headers")}}function qt(){return function(o,e,t){m(f,o,e,t,"controller")}}function Pt(){return function(o,e,t){m(f,o,e,t,"action")}}function Wt(){return function(o,e,t){m(f,o,e,t,"subaction")}}function Et(){return function(o,e,t){m(f,o,e,t,"body")}}function Mt(){return function(o,e,t){m(f,o,e,t,"stream")}}function Nt(){return function(o,e,t){m(f,o,e,t,"home")}}function Bt(o="home"){return function(e,t,s){m(f,e,t,s,"pool",o)}}function Dt(o="home"){return function(e,t,s){m(F,e,t,s,"connection",o)}}function Jt(o={}){return function(e,t,s){m(O,e,t,0,"json",o)}}function It(o={}){return function(e,t,s){m(O,e,t,0,"xml",o)}}function Lt(o){return function(e,t,s){m(Q,e,t,o,"logger",o)}}function Tt(o){return function(e,t,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],d=Reflect.getOwnMetadata(f,e,t)||{},c=Reflect.getOwnMetadata(F,e,t)||{},l=Reflect.getOwnMetadata(Q,e,t)||{},b=Reflect.getOwnMetadata(O,e,t)?.[0]||{type:"json",params:{}},_=Reflect.getOwnMetadata(K,e,t)?.[0]||{type:"",params:{}},g=(Reflect.getOwnMetadata(U,e,t)?.[0]||{type:"allow",params:[]}).params;if(g.length&&!g.includes(this.getMethod())&&this.getMethod()!=="any")throw new h({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${g.join(",")} methods`});for(const u in d){if(!d.hasOwnProperty(u))continue;const p=`get${wt(d[u].type)}`;a[+u]=this[p](d[u].params)}for(const u in c)c.hasOwnProperty(u)&&(c[u].type,a[+u]=await this.getDb()[c[u].params].getConnection(),r.push(a[+u]));try{let u=await i.apply(this,a),p;if(Array.isArray(u)&&([u,p]=u),_.type!=="init")return n.format==="xml"||b.type==="xml"?this.successXml(u,Object.assign(b.params,p||{})):n.format==="buffer"?this.successBuffer(u,Object.assign(b.params,p||{})):this.success(u,Object.assign(b.params,p||{}))}catch(u){await Promise.all([...r.map(w=>w.rollback())]);let p;n.format==="xml"||b.type==="xml"?p=this.errorXml(u):p=this.error(u);for(const w in l){if(!l.hasOwnProperty(w))continue;const V=l[w].params;await this[V].error(u,{response:nt(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(u=>u.release())])}}}}function Ft(){return function(o,e,t){m(K,o,e,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(e)}}function Kt(o){return o=(Array.isArray(o)?o:[o]).map(e=>e.toLowerCase()),function(e,t,s){m(U,e,t,0,"allow",o)}}const Qt={cookieParse:P,cookieString:W,jsonBody:j,rawBody:A,streamBody:$,urlencodedBody:R,multipartBody:q,readConfig:Z,readConfigSync:tt,staticBody:N,extensions:M,getExt:E,jwtDecode:ct,readJsonConfigsSync:dt};export{h as ApiError,at as AsyncJwt,_t as Controller,we as Jwt,S as Memcached,yt as Model,_e as Server,ut as Ssr,bt as Web,Pt as action,Kt as allow,Et as body,y as codeToStatus,Ct as config,Dt as connection,St as context,qt as controller,Ot as cookies,Ht as db,Rt as headers,Qt as helpers,Nt as home,vt as hostname,Tt as http,Ft as init,Jt as json,Lt as logerror,At as method,xt as mixin,gt as mount,Bt as pool,kt as protocol,$t as request,pt as selectControllersSchema,Mt as stream,Wt as subaction,jt as url,It as xml};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jwn-js/common",
3
3
  "private": false,
4
- "version": "2.2.9",
4
+ "version": "2.2.11",
5
5
  "description": "@jwn-js/common package",
6
6
  "main": "./index.js",
7
7
  "types": "./index.d.ts",