@x82-softworks/aws-api
Version:
An OpenAPI compatible api system intended for use with AWS Lambda and API Gateway
2 lines • 10.9 kB
JavaScript
(()=>{"use strict";var e,t={n:e=>{var r=e&&e.__esModule?()=>e.default:()=>e;return t.d(r,{a:r}),r},d:(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},r={};t.r(r),t.d(r,{APIKEY:()=>v,ARRAY:()=>m,BINARY:()=>f,BOOLEAN:()=>n,BYTE:()=>p,DATE:()=>l,DATETIME:()=>y,DEFAULT_CORS:()=>K,DOUBLE:()=>h,EMAIL:()=>g,FLOAT:()=>c,FORM_ENCODED:()=>X,GENERIC_ERROR:()=>O,HEADER:()=>b,INT32:()=>a,INT64:()=>i,INTEGER:()=>s,NUMBER:()=>o,OBJECT:()=>u,PASSWORD:()=>w,STRING:()=>d,create:()=>ue,default:()=>he,jsonResponseContent:()=>fe,requiredJsonRequest:()=>pe}),function(e){e.GET="get",e.POST="post",e.PUT="put",e.DELETE="delete",e.PATCH="patch",e.OPTIONS="options"}(e||(e={}));const o="number",n="boolean",s="integer",a="int32",i="int64",d="string",c="float",h="double",u="object",p="byte",f="binary",l="date",y="dateTime",m="array",b="header",w="password",v="apikey",g="email",E=/({[^}]*})/g;class C{constructor(e){const t=[];let r;for(;r=E.exec(e);)r=r[0].slice(1,-1),t.push(r);this.keys=t,e=e.replace(/({[^}]*})/g,"([a-zA-Z0-9-\\._~ %]+)"),this.regex=new RegExp(e)}match(e){let t,r=null;if(t=this.regex.exec(e)){r={};for(let e=0;e<this.keys.length;e++)r[this.keys[e]]=t[e+1]}return r}}var D=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function a(e){try{d(o.next(e))}catch(e){s(e)}}function i(e){try{d(o.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,i)}d((o=o.apply(e,t||[])).next())}))};const O="GenericError",R=e=>(e.body&&"string"!=typeof e.body&&(e.body=JSON.stringify(e.body)),e),P=e=>"object"==typeof e&&"string"==typeof(null==e?void 0:e.$ref),q=(e,t)=>{switch(e.type){case u:"string"==typeof t&&(t=JSON.parse(t));break;case s:case o:t=Number(t);break;case n:t=Boolean(t)}return t},x=function(e){return D(this,void 0,void 0,(function*(){return R(Object.assign(Object.assign({},e),{statusCode:404}))}))},T=e=>new C(e),k=require("serialize-error"),A=require("@x82-softworks/clone-merge");var S=t.n(A);const j=require("cookie");var N=t.n(j);const B=require("ajv");var M=t.n(B);const I=require("is-integer");var H=t.n(I);const L=2147483647,_=new(M())({useDefaults:!0,coerceTypes:!0});_.addFormat(a,{validate:function(e){return H()(e)&&e<=L&&e>=-2147483647},type:o}),_.addFormat(i,{validate:function(e){return H()(e)},type:o});const G=(e,t)=>{let r,o=_.compile(e);if(!o(t))throw r=new Error("Validation error"),r.additional=o.errors,r};var U=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function a(e){try{d(o.next(e))}catch(e){s(e)}}function i(e){try{d(o.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,i)}d((o=o.apply(e,t||[])).next())}))};const z=require("@x82-softworks/aws-api-multipart"),V=require("query-string");var F=t.n(V),J=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function a(e){try{d(o.next(e))}catch(e){s(e)}}function i(e){try{d(o.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,i)}d((o=o.apply(e,t||[])).next())}))};function $(e,t,r){return J(this,void 0,void 0,(function*(){let o,n,s,a=null===e.body||void 0===e.body;if(t){if(P(t)&&(t=r.getRef(t)),t.required&&a)throw new Error("Request body must be supplied");if(!a&&(s=e.headers["content-type"],s)){if(s=s.split(";")[0],!(o=t.content[s]))throw new Error(`Content Type "${s}" is not supported`);switch(n=o.schema,s){case"application/json":try{e.body=JSON.parse(e.body)}catch(e){throw new Error("Cannot parse request body")}break;case"application/x-www-form-urlencoded":e.body=F().parse(e.body);break;case"multipart/form-data":const t=yield(0,z.parse)(e),{val:r,multiparts:o}=t.files.reduce(((e,t)=>(e.val[t.fieldName]=t.data.toString("utf-8"),e.multiparts[t.fieldName]=t,e)),{val:{},multiparts:{}});e.body=r,e.multiparts=o}!function(e,t,r){if(!t)return;P(t)&&(t=r.getRef(t));const o=e.body=q(t,e.body);G(t,o)}(e,n,r)}}}))}var Y=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function a(e){try{d(o.next(e))}catch(e){s(e)}}function i(e){try{d(o.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,i)}d((o=o.apply(e,t||[])).next())}))};const X="application/x-www-form-urlencoded",K={"Access-Control-Allow-Methods":"GET,OPTIONS,HEAD","Access-Control-Allow-headers":"Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"},W="requestBodies",Z="schemas",Q="callbacks",ee="headers",te="securitySchemes",re="parameters",oe="responses",ne="examples",se="links",ae="content-type",ie=/\{([^}]*)\}/;function de(e,t){return{$ref:"#/components/"+e+"/"+t}}class ce{constructor(e,t){this.devMode=!!t,this.rootDef=S()({openapi:"3.0.0",info:{version:"0.0.0",description:"Default API",termsOfService:"http://swagger.io/terms/",title:"",contact:{email:"no-reply@example.com"},license:{name:"Proprietary"}},host:"localhost",basePath:"/",paths:{}},e),this.corsConfig=function(e,t){const r=e.headers.Origin?e.headers.Origin:"*";t.headers=S()(t.headers,{"Access-Control-Allow-Origin":r},K)},this.paths=[],this.defSchema("genericError",{type:"object",properties:{code:{description:"Error code",type:d},message:{description:"Human readable message",type:d}},required:["code","message"]}),this.defResponse("genericError",{description:"An unexpected error occurred",content:{"application/json":{schema:this.refSchema("genericError")}}}),this._suppressValidationErrors=!1}suppressValidationErrors(e){this._suppressValidationErrors=e}getRoot(){return S()(!0,this.rootDef)}defRoot(e){this.rootDef=S()(!0,this.rootDef,e)}cors(e){this.corsConfig=e}defComponent(e,t,r){if(this.rootDef.components||(this.rootDef.components={}),this.rootDef.components[e]||(this.rootDef.components[e]={}),this.rootDef.components[e][t])throw new Error('Component of type : "'+e+'" and name : "'+t+'" is already defined');return this.rootDef.components[e][t]=r,this}defSecurity(e,t){return this.defComponent(te,e,t)}defResponse(e,t){return this.defComponent(oe,e,t)}ref(e,t){return de(e,t)}defSchema(e,t){return t.title||(t.title=e),this.defComponent(Z,e,t)}getHost(){return this.rootDef.host}getRef(e){if(!P(e))throw new Error("Not a valid reference object");return e.$ref.split("/").slice(1).reduce((function(e,t){return e[t]}),this.rootDef)}refResponse(e){return de(oe,e)}refSchema(e){return de(Z,e)}refRequestBody(e){return de(W,e)}refSecurity(e){return de(te,e)}refExample(e){return de(ne,e)}refParameter(e){return de(re,e)}refHeader(e){return de(ee,e)}refCallback(e){return de(Q,e)}refLink(e){return de(se,e)}path(e,t,r,o){o||(o=r,r=null),(r=S()(!0,{summary:"",description:"",tags:[],parameters:[],requestBody:null,responses:{200:{description:"Success"},default:this.refResponse("genericError")}},r)).requestBody||delete r.requestBody;const n=t.toLowerCase();if(r.handler=o,this.rootDef.paths||(this.rootDef.paths={}),this.rootDef.paths[e]||(this.rootDef.paths[e]={}),this.rootDef.paths[e][n])throw new Error("Redefinition of path : "+e+" method : "+n);return this.rootDef.paths[e][n]=r,ie.test(e)&&this.paths.push({regex:T(e),original:e}),this}get(t,r,o){return this.path(t,e.GET,r,o)}post(t,r,o){return this.path(t,e.POST,r,o)}put(t,r,o){return this.path(t,e.PUT,r,o)}patch(t,r,o){return this.path(t,e.PATCH,r,o)}delete(t,r,o){return this.path(t,e.DELETE,r,o)}defParameter(e,t){return this.defComponent(re,e,t)}defExample(e,t){return this.defComponent(ne,e,t)}defRequestBody(e,t){return this.defComponent(W,e,t)}defHeader(e,t){return this.defComponent(ee,e,t)}defLink(e,t){return this.defComponent(se,e,t)}defCallback(e,t){return this.defComponent(Q,e,t)}lambda(){const e=this;return function(t){return Y(this,void 0,void 0,(function*(){if(t.headers&&t.headers.Host){let r="";t.requestContext&&0===t.requestContext.path.indexOf("/"+t.requestContext.stage)&&(r="/"+t.requestContext.stage),e.defRoot({host:"https://"+t.headers.Host+r})}return yield e.dispatch(t)}))}}dispatch(t){var r;return Y(this,void 0,void 0,(function*(){const o=Object.assign({path:"/",rawPath:"/",httpMethod:e.GET,headers:{},rawHeaders:{},queryStringParameters:{},params:{},stageVariables:{},requestContext:{},pathParams:{},body:null,isBase64Encoded:!1,rawBody:null},t),n=this;if(o.rawPath=o.path,o.httpMethod=o.httpMethod.toLowerCase(),o.headers=Object.keys(o.headers||{}).reduce(((e,t)=>(e[t.toLowerCase()]=o.headers[t],e)),{}),o.rawBody=o.body,o.rawHeaders=o.headers,(null===(r=o.headers)||void 0===r?void 0:r.cookie)&&(o.headers.cookie=N().parse(o.headers.cookie)),"/"!==o.path[0]&&(o.path="/"+o.path),!o.httpMethod||!o.path)throw new Error("Event is not wellformed");const s={body:void 0,headers:{},statusCode:200};if(0!==o.path.indexOf(n.rootDef.basePath))return x(s);n.corsConfig(o,s),o.path=o.path.slice(n.rootDef.basePath.length),"/"!==o.path[0]&&(o.path="/"+o.path);let a,i=n.rootDef.paths[o.path],d=null;if(!i)for(let e=0,t=n.paths.length;e<t;e++)if(d=n.paths[e].regex.match(o.path)){i=n.rootDef.paths[n.paths[e].original];break}return o.pathParams=d,i&&(a=i[o.httpMethod])?$(o,a.requestBody,n).catch((e=>{throw s.statusCode=400,e})).then((()=>Y(this,void 0,void 0,(function*(){return yield((e,t,r)=>U(void 0,void 0,void 0,(function*(){(t.parameters||[]).forEach((t=>{let o;switch(t.in){case"query":o=(e.queryStringParameters||{})[t.name];break;case"header":o=e.headers[t.name];break;case"path":o=decodeURIComponent(e.pathParams[t.name]);break;case"cookie":o=e.headers.cookie[t.name];break;default:throw new Error("Unknown param type : "+t.in)}if(void 0===o){if(t.required)throw new Error(`Required parameter "${t.name}" not found`)}else if(t.schema){let e=t.schema;P(e)&&(e=r.getRef(e)),o=q(e,o),G(e,o)}e.params[t.name]=o}))})))(o,a,n),new Promise(((e,t)=>{try{e(a.handler(o,s))}catch(e){t(e)}})).catch((e=>{s.body||(n.devMode?s.body=e:(console.error(e),s.body=new Error("An internal server error has occurred")),s.statusCode=s.body.statusCode?s.body.statusCode:500)}))})))).catch((e=>{s.body=e})).then((()=>{var e,t;return s.body instanceof Error&&(n.devMode?s.body=(0,k.serializeError)(s.body):s.body={code:(null===(e=s.body)||void 0===e?void 0:e.code)||O,message:s.body.message,additional:n._suppressValidationErrors?null:null===(t=s.body)||void 0===t?void 0:t.additional},s.statusCode||(s.statusCode=s.body.statusCode||500)),"object"!=typeof s.body||s.headers[ae]||(s.headers[ae]="application/json"),R(s)})):"options"===o.httpMethod?s:x(s)}))}}const he=ce,ue=function(e,t){return new ce(e,t)},pe=e=>({required:!0,content:{"application/json":{schema:e}}}),fe=e=>({"application/json":{schema:e}});module.exports=r})();
//# sourceMappingURL=commonjs.min.cjs.map