@jwn-js/common 2.6.4 → 2.6.6

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 (61) hide show
  1. package/docs/assets/search.js +1 -1
  2. package/docs/classes/ApiError.html +2 -2
  3. package/docs/classes/AsyncJwt.html +2 -2
  4. package/docs/classes/Binding.html +2 -3
  5. package/docs/classes/Controller.html +3 -2
  6. package/docs/classes/Jwt.html +2 -2
  7. package/docs/classes/Memcached.html +2 -2
  8. package/docs/classes/Model.html +3 -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 -1
  13. package/docs/functions/allow.html +1 -1
  14. package/docs/functions/body.html +1 -1
  15. package/docs/functions/codeToStatus.html +1 -1
  16. package/docs/functions/config-1.html +1 -1
  17. package/docs/functions/connection.html +1 -1
  18. package/docs/functions/context.html +1 -1
  19. package/docs/functions/controller-1.html +1 -1
  20. package/docs/functions/cookies.html +1 -1
  21. package/docs/functions/db.html +1 -1
  22. package/docs/functions/headers.html +1 -1
  23. package/docs/functions/home.html +1 -1
  24. package/docs/functions/hostname.html +1 -1
  25. package/docs/functions/http.html +1 -1
  26. package/docs/functions/init.html +1 -1
  27. package/docs/functions/inject.html +1 -1
  28. package/docs/functions/json.html +1 -1
  29. package/docs/functions/logerror.html +1 -1
  30. package/docs/functions/method.html +1 -1
  31. package/docs/functions/mixin.html +1 -1
  32. package/docs/functions/mount.html +1 -1
  33. package/docs/functions/pool.html +1 -1
  34. package/docs/functions/protocol.html +1 -1
  35. package/docs/functions/remote.html +1 -1
  36. package/docs/functions/request.html +1 -1
  37. package/docs/functions/selectControllersSchema.html +1 -1
  38. package/docs/functions/stream.html +1 -1
  39. package/docs/functions/subaction.html +1 -1
  40. package/docs/functions/url.html +1 -1
  41. package/docs/functions/xml.html +1 -1
  42. package/docs/index.html +2 -2
  43. package/docs/interfaces/ApiErrorMessage.html +2 -2
  44. package/docs/interfaces/Config.html +2 -2
  45. package/docs/interfaces/ContextSsr.html +2 -2
  46. package/docs/interfaces/ContextWeb.html +2 -2
  47. package/docs/interfaces/OptionsSsr.html +2 -2
  48. package/docs/interfaces/OptionsWeb.html +2 -2
  49. package/docs/interfaces/ResponseOptions.html +2 -2
  50. package/docs/interfaces/Route.html +2 -2
  51. package/docs/interfaces/Schema.html +2 -2
  52. package/docs/interfaces/ServerHandler.html +2 -2
  53. package/docs/interfaces/ServerOptions.html +2 -2
  54. package/docs/interfaces/ServerWebsocket.html +2 -2
  55. package/docs/modules.html +2 -2
  56. package/docs/types/ServerRoutes.html +1 -1
  57. package/docs/variables/helpers.html +2 -2
  58. package/index.d.ts +45 -44
  59. package/index.js +1 -1
  60. package/index.mjs +1 -1
  61. package/package.json +1 -1
package/index.js CHANGED
@@ -54,4 +54,4 @@
54
54
  FROM app_controllers c
55
55
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
56
56
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
57
- `)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},q=(o,t,e,s)=>{let i=o.controllers.find(h=>h.name===e);if(!i)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(h=>h.name===s);if(!n)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===n.action);if(!a)throw new d.ApiError({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class bt{constructor(t,e,s,i={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.isAborted=!1,this.res=t,this.req=e,this.opts=i,this.res.onAborted(()=>this.isAborted=!0),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,st.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$bindings:{},$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,u)=>this.contextWeb.headers[c]=u);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)});const c=this.importControllerSync(),u=new c;if(this.injectContext(u),i.subaction in u)e=await u[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof O.Memcached){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const u=await c.getPage(this.memcachedKey);if(u){const{data:g,headers:m}=u;this.success({body:g.toString(),headers:m,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)if(this.opts.raw){const c=await K(this.res);let u={};try{u=JSON.parse(c)}catch{}Object.assign(i,u),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await B.jsonBody(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await P.urlencodedBody(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),u=v.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,u||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const u=C(this.res,this.req),g=nt.tmpdir(),m="./body_"+R.randomBytes(32).toString("hex"),p=D.resolve(g,m),l=J.createWriteStream(p);u.pipe(l),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:p}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await L(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const u of c){const g=await this.importBinding(u),m=new g;this.injectContext(m),Object.assign(this.contextWeb.$di,await this.initComponent(m)),m.getBindingKey()&&(this.contextWeb.$bindings[m.getBindingKey()]?(this.contextWeb.$bindings[m.getBindingKey()]=[this.contextWeb.$bindings[m.getBindingKey()]],this.contextWeb.$bindings[m.getBindingKey()].push(m)):this.contextWeb.$bindings[m.getBindingKey()]=m)}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){s instanceof d.ApiError&&s.getCode()==="abort"||this.isAborted||this.error(s)}}async importBinding(t){let e=t.default||t;if(w.isClass(e)||(e=(await t()).default),typeof e!="function")throw new d.ApiError({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(w.isClass(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new d.ApiError({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof A.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=x.codeToStatus(i),a=!s&&!e&&w.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof O.Memcached&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d.ApiError&&t.getData()instanceof A.Stream;let s=x.codeToStatus(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof d.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x.codeToStatus(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=w.isObject(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const I={compact:!0,ignoreComment:!0,spaces:4};class E{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return N.cookieString(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:v.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:v.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({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new A.PassThrough().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class U{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class F{getBindingKey(){return this.$key}assignDi(t={}){Object.assign(this.$context.$di,t)}async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const pt=async(o,t,e={},s)=>{const i=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const u=await r[c]();if(u)return u}},n=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await L(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?q(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof E)return n(a,t),t.$initResponse=await i(a),a;if(a instanceof U||a instanceof F){const r=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return n(r,t),t.$initResponse=await i(r),r.getModel()}else throw new d.ApiError({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},b=Symbol("arguments"),Q=Symbol("connections"),H=Symbol("response"),V=Symbol("init"),X=Symbol("logger"),z=Symbol("filters"),$t=o=>o.charAt(0).toUpperCase()+o.slice(1);function xt(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const n=Object.getPrototypeOf(i);n&&t(s,n)};function e(s){return t(s,o),s}return e}const f=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function yt(){return function(o,t,e){f(b,o,t,e,"request")}}function _t(){return function(o,t,e){f(b,o,t,e,"context")}}function wt(){return function(o,t,e){f(b,o,t,e,"config")}}function St(){return function(o,t,e){f(b,o,t,e,"method")}}function At(){return function(o,t,e){f(b,o,t,e,"remote")}}function Ct(){return function(o,t,e){f(b,o,t,e,"cookies")}}function Ot(){return function(o,t,e){f(b,o,t,e,"hostname")}}function vt(){return function(o,t,e){f(b,o,t,e,"url")}}function jt(){return function(o,t,e){f(b,o,t,e,"protocol")}}function kt(){return function(o,t,e){f(b,o,t,e,"db")}}function qt(){return function(o,t,e){f(b,o,t,e,"headers")}}function Et(){return function(o,t,e){f(b,o,t,e,"controller")}}function Ht(){return function(o,t,e){f(b,o,t,e,"action")}}function Rt(){return function(o,t,e){f(b,o,t,e,"subaction")}}function Bt(){return function(o,t,e){f(b,o,t,e,"body")}}function Pt(){return function(o,t,e){f(b,o,t,e,"stream")}}function Mt(){return function(o,t,e){f(b,o,t,e,"home")}}function Wt(o="home"){return function(t,e,s){f(b,t,e,s,"pool",o)}}function Nt(o="home"){return function(t,e,s){f(Q,t,e,s,"connection",o)}}function Dt(o={}){return function(t,e,s){f(H,t,e,0,"json",o)}}function Jt(o={}){return function(t,e,s){f(H,t,e,0,"xml",o)}}function Tt(o){return function(t,e,s){f(X,t,e,o,"logger",o)}}function Kt(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(b,t,e)||{},c=Reflect.getOwnMetadata(Q,t,e)||{},u=Reflect.getOwnMetadata(X,t,e)||{},g=Reflect.getOwnMetadata(H,t,e)?.[0]||{type:"json",params:{}},m=Reflect.getOwnMetadata(V,t,e)?.[0]||{type:"",params:{}},p=(Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"allow",params:[]}).params;if(p.length&&!p.includes(this.getMethod())&&this.getMethod()!=="any")throw new d.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${p.join(",")} methods`});for(const l in h){if(!h.hasOwnProperty(l))continue;const $=`get${$t(h[l].type)}`;a[+l]=this[$](h[l].params)}for(const l in c)c.hasOwnProperty(l)&&(c[l].type,a[+l]=await this.getDb()[c[l].params].getConnection(),r.push(a[+l]));try{let l=await n.apply(this,a),$;if(Array.isArray(l)&&([l,$]=l),m.type!=="init")return i.format==="xml"||g.type==="xml"?this.successXml(l,Object.assign(g.params,$||{})):i.format==="buffer"?this.successBuffer(l,Object.assign(g.params,$||{})):this.success(l,Object.assign(g.params,$||{}))}catch(l){await Promise.all([...r.map(S=>S.rollback())]);let $;i.format==="xml"||g.type==="xml"?$=this.errorXml(l):$=this.error(l);for(const S in u){if(!u.hasOwnProperty(S))continue;const G=u[S].params;await this[G].error(l,{response:w.omit($?.body||{},["stack"])})}return $}finally{await Promise.all([...r.map(l=>l.release())])}}}}function Lt(){return function(o,t,e){f(V,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function It(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){f(z,t,e,0,"allow",o)}}function Ut(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Ft={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:B.jsonBody,jsonBodyRaw:K,rawBody:k,streamBody:C,urlencodedBody:P.urlencodedBody,multipartBody:M.multipartBody,readConfig:Z.readConfig,readConfigSync:tt.readConfigSync,staticBody:_.staticBody,extensions:_.extensions,getExt:_.getExt,jwtDecode:at,readJsonConfigsSync:ut};exports.ApiError=d.ApiError,exports.Server=x.Server,exports.codeToStatus=x.codeToStatus,exports.Jwt=y.Jwt,exports.Memcached=O.Memcached,exports.AsyncJwt=rt,exports.Binding=F,exports.Controller=E,exports.Model=U,exports.Ssr=dt,exports.Web=bt,exports.action=Ht,exports.allow=It,exports.body=Bt,exports.config=wt,exports.connection=Nt,exports.context=_t,exports.controller=Et,exports.cookies=Ct,exports.db=kt,exports.headers=qt,exports.helpers=Ft,exports.home=Mt,exports.hostname=Ot,exports.http=Kt,exports.init=Lt,exports.inject=Ut,exports.json=Dt,exports.logerror=Tt,exports.method=St,exports.mixin=xt,exports.mount=pt,exports.pool=Wt,exports.protocol=jt,exports.remote=At,exports.request=yt,exports.selectControllersSchema=gt,exports.stream=Pt,exports.subaction=Rt,exports.url=vt,exports.xml=Jt;
57
+ `)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},q=(o,t,e,s)=>{let i=o.controllers.find(h=>h.name===e);if(!i)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(h=>h.name===s);if(!n)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===n.action);if(!a)throw new d.ApiError({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class bt{constructor(t,e,s,i={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.isAborted=!1,this.res=t,this.req=e,this.opts=i,this.res.onAborted(()=>this.isAborted=!0),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,st.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$bindings:{},$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,u)=>this.contextWeb.headers[c]=u);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)});const c=this.importControllerSync(),u=new c;if(this.injectContext(u),i.subaction in u)e=await u[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof O.Memcached){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const u=await c.getPage(this.memcachedKey);if(u){const{data:g,headers:m}=u;this.success({body:g.toString(),headers:m,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)if(this.opts.raw){const c=await K(this.res);let u={};try{u=JSON.parse(c)}catch{}Object.assign(i,u),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await B.jsonBody(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await P.urlencodedBody(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),u=v.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,u||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const u=C(this.res,this.req),g=nt.tmpdir(),m="./body_"+R.randomBytes(32).toString("hex"),p=D.resolve(g,m),l=J.createWriteStream(p);u.pipe(l),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:p}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await L(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const u of c){const g=await this.importBinding(u),m=new g;this.injectContext(m),Object.assign(this.contextWeb.$di,await this.initComponent(m)),m.getBindingKey()&&(this.contextWeb.$bindings[m.getBindingKey()]?(this.contextWeb.$bindings[m.getBindingKey()]=[this.contextWeb.$bindings[m.getBindingKey()]],this.contextWeb.$bindings[m.getBindingKey()].push(m)):this.contextWeb.$bindings[m.getBindingKey()]=m)}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){s instanceof d.ApiError&&s.getCode()==="abort"||this.isAborted||this.error(s)}}async importBinding(t){let e=t.default||t;if(w.isClass(e)||(e=(await t()).default),typeof e!="function")throw new d.ApiError({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(w.isClass(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new d.ApiError({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof A.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=x.codeToStatus(i),a=!s&&!e&&w.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof O.Memcached&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d.ApiError&&t.getData()instanceof A.Stream;let s=x.codeToStatus(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof d.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x.codeToStatus(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=w.isObject(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const I={compact:!0,ignoreComment:!0,spaces:4};class E{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return N.cookieString(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:v.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:v.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({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new A.PassThrough().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}getBinding(t){return this.$context.$bindings[t]}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 U{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}getBinding(t){return this.$context.$bindings[t]}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class F{getBindingKey(){return this.constructor.name}assignDi(t={}){Object.assign(this.$context.$di,t)}async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const pt=async(o,t,e={},s)=>{const i=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const u=await r[c]();if(u)return u}},n=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await L(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?q(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof E)return n(a,t),t.$initResponse=await i(a),a;if(a instanceof U||a instanceof F){const r=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return n(r,t),t.$initResponse=await i(r),r.getModel()}else throw new d.ApiError({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},b=Symbol("arguments"),Q=Symbol("connections"),H=Symbol("response"),V=Symbol("init"),X=Symbol("logger"),z=Symbol("filters"),$t=o=>o.charAt(0).toUpperCase()+o.slice(1);function xt(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const n=Object.getPrototypeOf(i);n&&t(s,n)};function e(s){return t(s,o),s}return e}const f=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function yt(){return function(o,t,e){f(b,o,t,e,"request")}}function _t(){return function(o,t,e){f(b,o,t,e,"context")}}function wt(){return function(o,t,e){f(b,o,t,e,"config")}}function St(){return function(o,t,e){f(b,o,t,e,"method")}}function At(){return function(o,t,e){f(b,o,t,e,"remote")}}function Ct(){return function(o,t,e){f(b,o,t,e,"cookies")}}function Ot(){return function(o,t,e){f(b,o,t,e,"hostname")}}function vt(){return function(o,t,e){f(b,o,t,e,"url")}}function jt(){return function(o,t,e){f(b,o,t,e,"protocol")}}function kt(){return function(o,t,e){f(b,o,t,e,"db")}}function qt(){return function(o,t,e){f(b,o,t,e,"headers")}}function Et(){return function(o,t,e){f(b,o,t,e,"controller")}}function Ht(){return function(o,t,e){f(b,o,t,e,"action")}}function Rt(){return function(o,t,e){f(b,o,t,e,"subaction")}}function Bt(){return function(o,t,e){f(b,o,t,e,"body")}}function Pt(){return function(o,t,e){f(b,o,t,e,"stream")}}function Mt(){return function(o,t,e){f(b,o,t,e,"home")}}function Wt(o="home"){return function(t,e,s){f(b,t,e,s,"pool",o)}}function Nt(o="home"){return function(t,e,s){f(Q,t,e,s,"connection",o)}}function Dt(o={}){return function(t,e,s){f(H,t,e,0,"json",o)}}function Jt(o={}){return function(t,e,s){f(H,t,e,0,"xml",o)}}function Tt(o){return function(t,e,s){f(X,t,e,o,"logger",o)}}function Kt(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(b,t,e)||{},c=Reflect.getOwnMetadata(Q,t,e)||{},u=Reflect.getOwnMetadata(X,t,e)||{},g=Reflect.getOwnMetadata(H,t,e)?.[0]||{type:"json",params:{}},m=Reflect.getOwnMetadata(V,t,e)?.[0]||{type:"",params:{}},p=(Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"allow",params:[]}).params;if(p.length&&!p.includes(this.getMethod())&&this.getMethod()!=="any")throw new d.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${p.join(",")} methods`});for(const l in h){if(!h.hasOwnProperty(l))continue;const $=`get${$t(h[l].type)}`;a[+l]=this[$](h[l].params)}for(const l in c)c.hasOwnProperty(l)&&(c[l].type,a[+l]=await this.getDb()[c[l].params].getConnection(),r.push(a[+l]));try{let l=await n.apply(this,a),$;if(Array.isArray(l)&&([l,$]=l),m.type!=="init")return i.format==="xml"||g.type==="xml"?this.successXml(l,Object.assign(g.params,$||{})):i.format==="buffer"?this.successBuffer(l,Object.assign(g.params,$||{})):this.success(l,Object.assign(g.params,$||{}))}catch(l){await Promise.all([...r.map(S=>S.rollback())]);let $;i.format==="xml"||g.type==="xml"?$=this.errorXml(l):$=this.error(l);for(const S in u){if(!u.hasOwnProperty(S))continue;const G=u[S].params;await this[G].error(l,{response:w.omit($?.body||{},["stack"])})}return $}finally{await Promise.all([...r.map(l=>l.release())])}}}}function Lt(){return function(o,t,e){f(V,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function It(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){f(z,t,e,0,"allow",o)}}function Ut(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Ft={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:B.jsonBody,jsonBodyRaw:K,rawBody:k,streamBody:C,urlencodedBody:P.urlencodedBody,multipartBody:M.multipartBody,readConfig:Z.readConfig,readConfigSync:tt.readConfigSync,staticBody:_.staticBody,extensions:_.extensions,getExt:_.getExt,jwtDecode:at,readJsonConfigsSync:ut};exports.ApiError=d.ApiError,exports.Server=x.Server,exports.codeToStatus=x.codeToStatus,exports.Jwt=y.Jwt,exports.Memcached=O.Memcached,exports.AsyncJwt=rt,exports.Binding=F,exports.Controller=E,exports.Model=U,exports.Ssr=dt,exports.Web=bt,exports.action=Ht,exports.allow=It,exports.body=Bt,exports.config=wt,exports.connection=Nt,exports.context=_t,exports.controller=Et,exports.cookies=Ct,exports.db=kt,exports.headers=qt,exports.helpers=Ft,exports.home=Mt,exports.hostname=Ot,exports.http=Kt,exports.init=Lt,exports.inject=Ut,exports.json=Dt,exports.logerror=Tt,exports.method=St,exports.mixin=xt,exports.mount=pt,exports.pool=Wt,exports.protocol=jt,exports.remote=At,exports.request=yt,exports.selectControllersSchema=gt,exports.stream=Pt,exports.subaction=Rt,exports.url=vt,exports.xml=Jt;
package/index.mjs CHANGED
@@ -54,4 +54,4 @@ import{ApiError as u}from"./ApiError.mjs";import{codeToStatus as x}from"./Server
54
54
  FROM app_controllers c
55
55
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
56
56
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
57
- `)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},j=(o,t,e,s)=>{let i=o.controllers.find(h=>h.name===e);if(!i)throw new u({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new u({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(h=>h.name===s);if(!n)throw new u({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new u({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===n.action);if(!a)throw new u({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new u({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new u({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class _t{constructor(t,e,s,i={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.isAborted=!1,this.res=t,this.req=e,this.opts=i,this.res.onAborted(()=>this.isAborted=!0),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,ht.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$bindings:{},$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,d)=>this.contextWeb.headers[c]=d);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,j(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)});const c=this.importControllerSync(),d=new c;if(this.injectContext(d),i.subaction in d)e=await d[i.subaction]();else throw new u({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const d=await c.getPage(this.memcachedKey);if(d){const{data:g,headers:l}=d;this.success({body:g.toString(),headers:l,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)if(this.opts.raw){const c=await I(this.res);let d={};try{d=JSON.parse(c)}catch{}Object.assign(i,d),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await R(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await W(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await B(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await O(this.res)).toString(),d=A.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,d||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const d=w(this.res,this.req),g=dt.tmpdir(),l="./body_"+et.randomBytes(32).toString("hex"),p=at.resolve(g,l),m=K.createWriteStream(p);d.pipe(m),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:p}}}),d.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await O(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?j(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await U(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const d of c){const g=await this.importBinding(d),l=new g;this.injectContext(l),Object.assign(this.contextWeb.$di,await this.initComponent(l)),l.getBindingKey()&&(this.contextWeb.$bindings[l.getBindingKey()]?(this.contextWeb.$bindings[l.getBindingKey()]=[this.contextWeb.$bindings[l.getBindingKey()]],this.contextWeb.$bindings[l.getBindingKey()].push(l)):this.contextWeb.$bindings[l.getBindingKey()]=l)}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new u({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){s instanceof u&&s.getCode()==="abort"||this.isAborted||this.error(s)}}async importBinding(t){let e=t.default||t;if(L(e)||(e=(await t()).default),typeof e!="function")throw new u({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(L(t)||(t=(await this.route.component()).default),typeof t!="function")throw new u({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new u({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new u({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof P,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=x(i),a=!s&&!e&&C(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof u&&t.getData()instanceof P;let s=x(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof u){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=C(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const F={compact:!0,ignoreComment:!0,spaces:4};class k{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return E(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:A.js2xml(Object.assign(s,{body:{...i.body}}),F),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:A.js2xml(Object.assign(s,{body:{...i.body}}),F),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new q().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class Q{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class V{getBindingKey(){return this.$key}assignDi(t={}){Object.assign(this.$context.$di,t)}async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const wt=async(o,t,e={},s)=>{const i=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const d=await r[c]();if(d)return d}},n=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await U(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?j(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof k)return n(a,t),t.$initResponse=await i(a),a;if(a instanceof Q||a instanceof V){const r=new class extends k{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return n(r,t),t.$initResponse=await i(r),r.getModel()}else throw new u({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},b=Symbol("arguments"),X=Symbol("connections"),v=Symbol("response"),z=Symbol("init"),G=Symbol("logger"),Y=Symbol("filters"),St=o=>o.charAt(0).toUpperCase()+o.slice(1);function Ct(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const n=Object.getPrototypeOf(i);n&&t(s,n)};function e(s){return t(s,o),s}return e}const f=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function At(){return function(o,t,e){f(b,o,t,e,"request")}}function Ot(){return function(o,t,e){f(b,o,t,e,"context")}}function jt(){return function(o,t,e){f(b,o,t,e,"config")}}function kt(){return function(o,t,e){f(b,o,t,e,"method")}}function vt(){return function(o,t,e){f(b,o,t,e,"remote")}}function Ht(){return function(o,t,e){f(b,o,t,e,"cookies")}}function Rt(){return function(o,t,e){f(b,o,t,e,"hostname")}}function qt(){return function(o,t,e){f(b,o,t,e,"url")}}function Pt(){return function(o,t,e){f(b,o,t,e,"protocol")}}function Bt(){return function(o,t,e){f(b,o,t,e,"db")}}function Wt(){return function(o,t,e){f(b,o,t,e,"headers")}}function Mt(){return function(o,t,e){f(b,o,t,e,"controller")}}function Et(){return function(o,t,e){f(b,o,t,e,"action")}}function Nt(){return function(o,t,e){f(b,o,t,e,"subaction")}}function Dt(){return function(o,t,e){f(b,o,t,e,"body")}}function Jt(){return function(o,t,e){f(b,o,t,e,"stream")}}function Kt(){return function(o,t,e){f(b,o,t,e,"home")}}function Lt(o="home"){return function(t,e,s){f(b,t,e,s,"pool",o)}}function Tt(o="home"){return function(t,e,s){f(X,t,e,s,"connection",o)}}function It(o={}){return function(t,e,s){f(v,t,e,0,"json",o)}}function Ut(o={}){return function(t,e,s){f(v,t,e,0,"xml",o)}}function Ft(o){return function(t,e,s){f(G,t,e,o,"logger",o)}}function Qt(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(b,t,e)||{},c=Reflect.getOwnMetadata(X,t,e)||{},d=Reflect.getOwnMetadata(G,t,e)||{},g=Reflect.getOwnMetadata(v,t,e)?.[0]||{type:"json",params:{}},l=Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"",params:{}},p=(Reflect.getOwnMetadata(Y,t,e)?.[0]||{type:"allow",params:[]}).params;if(p.length&&!p.includes(this.getMethod())&&this.getMethod()!=="any")throw new u({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${p.join(",")} methods`});for(const m in h){if(!h.hasOwnProperty(m))continue;const $=`get${St(h[m].type)}`;a[+m]=this[$](h[m].params)}for(const m in c)c.hasOwnProperty(m)&&(c[m].type,a[+m]=await this.getDb()[c[m].params].getConnection(),r.push(a[+m]));try{let m=await n.apply(this,a),$;if(Array.isArray(m)&&([m,$]=m),l.type!=="init")return i.format==="xml"||g.type==="xml"?this.successXml(m,Object.assign(g.params,$||{})):i.format==="buffer"?this.successBuffer(m,Object.assign(g.params,$||{})):this.success(m,Object.assign(g.params,$||{}))}catch(m){await Promise.all([...r.map(y=>y.rollback())]);let $;i.format==="xml"||g.type==="xml"?$=this.errorXml(m):$=this.error(m);for(const y in d){if(!d.hasOwnProperty(y))continue;const Z=d[y].params;await this[Z].error(m,{response:ct($?.body||{},["stack"])})}return $}finally{await Promise.all([...r.map(m=>m.release())])}}}}function Vt(){return function(o,t,e){f(z,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Xt(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){f(Y,t,e,0,"allow",o)}}function zt(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Gt={cookieParse:M,cookieString:E,jsonBody:R,jsonBodyRaw:I,rawBody:O,streamBody:w,urlencodedBody:B,multipartBody:W,readConfig:it,readConfigSync:nt,staticBody:J,extensions:N,getExt:D,jwtDecode:mt,readJsonConfigsSync:gt};export{u as ApiError,ut as AsyncJwt,V as Binding,k as Controller,Ae as Jwt,S as Memcached,Q as Model,Se as Server,bt as Ssr,_t as Web,Et as action,Xt as allow,Dt as body,x as codeToStatus,jt as config,Tt as connection,Ot as context,Mt as controller,Ht as cookies,Bt as db,Wt as headers,Gt as helpers,Kt as home,Rt as hostname,Qt as http,Vt as init,zt as inject,It as json,Ft as logerror,kt as method,Ct as mixin,wt as mount,Lt as pool,Pt as protocol,vt as remote,At as request,yt as selectControllersSchema,Jt as stream,Nt as subaction,qt as url,Ut as xml};
57
+ `)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},j=(o,t,e,s)=>{let i=o.controllers.find(h=>h.name===e);if(!i)throw new u({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new u({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(h=>h.name===s);if(!n)throw new u({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new u({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===n.action);if(!a)throw new u({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new u({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new u({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class _t{constructor(t,e,s,i={}){this.opts={},this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.isAborted=!1,this.res=t,this.req=e,this.opts=i,this.res.onAborted(()=>this.isAborted=!0),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,ht.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,$bindings:{},$di:{},hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,d)=>this.contextWeb.headers[c]=d);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,j(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)});const c=this.importControllerSync(),d=new c;if(this.injectContext(d),i.subaction in d)e=await d[i.subaction]();else throw new u({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const d=await c.getPage(this.memcachedKey);if(d){const{data:g,headers:l}=d;this.success({body:g.toString(),headers:l,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)if(this.opts.raw){const c=await I(this.res);let d={};try{d=JSON.parse(c)}catch{}Object.assign(i,d),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await R(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await W(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await B(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await O(this.res)).toString(),d=A.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,d||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const d=w(this.res,this.req),g=dt.tmpdir(),l="./body_"+et.randomBytes(32).toString("hex"),p=at.resolve(g,l),m=K.createWriteStream(p);d.pipe(m),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:p}}}),d.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await O(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?j(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await U(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const d of c){const g=await this.importBinding(d),l=new g;this.injectContext(l),Object.assign(this.contextWeb.$di,await this.initComponent(l)),l.getBindingKey()&&(this.contextWeb.$bindings[l.getBindingKey()]?(this.contextWeb.$bindings[l.getBindingKey()]=[this.contextWeb.$bindings[l.getBindingKey()]],this.contextWeb.$bindings[l.getBindingKey()].push(l)):this.contextWeb.$bindings[l.getBindingKey()]=l)}}const a=await this.importController(),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new u({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){s instanceof u&&s.getCode()==="abort"||this.isAborted||this.error(s)}}async importBinding(t){let e=t.default||t;if(L(e)||(e=(await t()).default),typeof e!="function")throw new u({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(L(t)||(t=(await this.route.component()).default),typeof t!="function")throw new u({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new u({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new u({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof P,s=t.body instanceof Uint8Array,i=t.statusCode||200,n=x(i),a=!s&&!e&&C(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof u&&t.getData()instanceof P;let s=x(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof u){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?n=t.getData():n=C(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const F={compact:!0,ignoreComment:!0,spaces:4};class k{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return E(t,e,s)}success(t={},e){const s=e?.field??"data";return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,...s?{[s]:t}:{...t||{}}},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:A.js2xml(Object.assign(s,{body:{...i.body}}),F),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:A.js2xml(Object.assign(s,{body:{...i.body}}),F),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new q().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}getBinding(t){return this.$context.$bindings[t]}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class Q{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}getBinding(t){return this.$context.$bindings[t]}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}class V{getBindingKey(){return this.constructor.name}assignDi(t={}){Object.assign(this.$context.$di,t)}async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader,$di:this.$context.$di,$bindings:this.$context.$bindings}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const wt=async(o,t,e={},s)=>{const i=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const d=await r[c]();if(d)return d}},n=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await U(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?j(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof k)return n(a,t),t.$initResponse=await i(a),a;if(a instanceof Q||a instanceof V){const r=new class extends k{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return n(r,t),t.$initResponse=await i(r),r.getModel()}else throw new u({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},b=Symbol("arguments"),X=Symbol("connections"),v=Symbol("response"),z=Symbol("init"),G=Symbol("logger"),Y=Symbol("filters"),St=o=>o.charAt(0).toUpperCase()+o.slice(1);function Ct(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const n=Object.getPrototypeOf(i);n&&t(s,n)};function e(s){return t(s,o),s}return e}const f=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function At(){return function(o,t,e){f(b,o,t,e,"request")}}function Ot(){return function(o,t,e){f(b,o,t,e,"context")}}function jt(){return function(o,t,e){f(b,o,t,e,"config")}}function kt(){return function(o,t,e){f(b,o,t,e,"method")}}function vt(){return function(o,t,e){f(b,o,t,e,"remote")}}function Ht(){return function(o,t,e){f(b,o,t,e,"cookies")}}function Rt(){return function(o,t,e){f(b,o,t,e,"hostname")}}function qt(){return function(o,t,e){f(b,o,t,e,"url")}}function Pt(){return function(o,t,e){f(b,o,t,e,"protocol")}}function Bt(){return function(o,t,e){f(b,o,t,e,"db")}}function Wt(){return function(o,t,e){f(b,o,t,e,"headers")}}function Mt(){return function(o,t,e){f(b,o,t,e,"controller")}}function Et(){return function(o,t,e){f(b,o,t,e,"action")}}function Nt(){return function(o,t,e){f(b,o,t,e,"subaction")}}function Dt(){return function(o,t,e){f(b,o,t,e,"body")}}function Jt(){return function(o,t,e){f(b,o,t,e,"stream")}}function Kt(){return function(o,t,e){f(b,o,t,e,"home")}}function Lt(o="home"){return function(t,e,s){f(b,t,e,s,"pool",o)}}function Tt(o="home"){return function(t,e,s){f(X,t,e,s,"connection",o)}}function It(o={}){return function(t,e,s){f(v,t,e,0,"json",o)}}function Ut(o={}){return function(t,e,s){f(v,t,e,0,"xml",o)}}function Ft(o){return function(t,e,s){f(G,t,e,o,"logger",o)}}function Qt(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(b,t,e)||{},c=Reflect.getOwnMetadata(X,t,e)||{},d=Reflect.getOwnMetadata(G,t,e)||{},g=Reflect.getOwnMetadata(v,t,e)?.[0]||{type:"json",params:{}},l=Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"",params:{}},p=(Reflect.getOwnMetadata(Y,t,e)?.[0]||{type:"allow",params:[]}).params;if(p.length&&!p.includes(this.getMethod())&&this.getMethod()!=="any")throw new u({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${p.join(",")} methods`});for(const m in h){if(!h.hasOwnProperty(m))continue;const $=`get${St(h[m].type)}`;a[+m]=this[$](h[m].params)}for(const m in c)c.hasOwnProperty(m)&&(c[m].type,a[+m]=await this.getDb()[c[m].params].getConnection(),r.push(a[+m]));try{let m=await n.apply(this,a),$;if(Array.isArray(m)&&([m,$]=m),l.type!=="init")return i.format==="xml"||g.type==="xml"?this.successXml(m,Object.assign(g.params,$||{})):i.format==="buffer"?this.successBuffer(m,Object.assign(g.params,$||{})):this.success(m,Object.assign(g.params,$||{}))}catch(m){await Promise.all([...r.map(y=>y.rollback())]);let $;i.format==="xml"||g.type==="xml"?$=this.errorXml(m):$=this.error(m);for(const y in d){if(!d.hasOwnProperty(y))continue;const Z=d[y].params;await this[Z].error(m,{response:ct($?.body||{},["stack"])})}return $}finally{await Promise.all([...r.map(m=>m.release())])}}}}function Vt(){return function(o,t,e){f(z,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Xt(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){f(Y,t,e,0,"allow",o)}}function zt(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Gt={cookieParse:M,cookieString:E,jsonBody:R,jsonBodyRaw:I,rawBody:O,streamBody:w,urlencodedBody:B,multipartBody:W,readConfig:it,readConfigSync:nt,staticBody:J,extensions:N,getExt:D,jwtDecode:mt,readJsonConfigsSync:gt};export{u as ApiError,ut as AsyncJwt,V as Binding,k as Controller,Ae as Jwt,S as Memcached,Q as Model,Se as Server,bt as Ssr,_t as Web,Et as action,Xt as allow,Dt as body,x as codeToStatus,jt as config,Tt as connection,Ot as context,Mt as controller,Ht as cookies,Bt as db,Wt as headers,Gt as helpers,Kt as home,Rt as hostname,Qt as http,Vt as init,zt as inject,It as json,Ft as logerror,kt as method,Ct as mixin,wt as mount,Lt as pool,Pt as protocol,vt as remote,At as request,yt as selectControllersSchema,Jt as stream,Nt as subaction,qt as url,Ut 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.6.4",
4
+ "version": "2.6.6",
5
5
  "description": "@jwn-js/common package",
6
6
  "module": "./index.mjs",
7
7
  "main": "./index.js",