UNPKG

express-zod-api

Version:

A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.

1 lines 10.3 kB
import{globalRegistry as e,z as t}from"zod";import*as n from"ramda";import{isPromise as r}from"node:util/types";import i,{isHttpError as a}from"http-errors";import o from"express";const s={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},c=[`get`,`post`,`put`,`delete`,`patch`,`query`],l=[...c,`head`],u=e=>c.includes(e),d=t.object({}),f=/:([A-Za-z0-9_]+)/g,ee=e=>e.match(f)?.map(e=>e.slice(1))||[],p=(e,t=1)=>e.replace(f,()=>`:${t++}`),te=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(s.upload);return`files`in e&&t},ne={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`],query:[`query`,`body`,`params`]},m=[`body`,`query`,`params`],h=e=>e.method.toLowerCase(),g=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:u(e)?e:void 0;return(n?t[n]||ne[n]:void 0)||m},_=(e,t={})=>{let n=h(e);return g(n,t).filter(t=>t!==`files`||te(e)).reduce((t,n)=>Object.assign(t,e[n]),{})},v=e=>e instanceof Error?e:e instanceof t.ZodError?new t.ZodRealError(e.issues):Error(String(e)),y=e=>e instanceof t.ZodError?e.issues.map(({path:e,message:n})=>`${e.length?`${t.core.toDotPath(e)}: `:``}${n}`).join(`; `):e.message,b=(e,t)=>w(e)&&`_zod`in e&&(!t||n.path([`_zod`,`def`,`type`],e)===t),x=(e,t,r)=>e.length&&t.length?n.xprod(e,t).map(r):e.concat(t),S=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),C=(...e)=>{let t=n.chain(e=>e.split(/[^A-Z0-9]/gi),e);return n.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),t).map(S).join(``)},re=n.tryCatch((e,n)=>typeof t.parse(e,n),n.always(void 0)),w=e=>typeof e==`object`&&!!e,T=n.memoizeWith(()=>`static`,()=>process.env.NODE_ENV===`production`),ie=(e,t)=>!!t&&e!==`head`,E=`x-brand`,D=t=>{let{[E]:n}=e.get(t)||{};if(typeof n==`symbol`||typeof n==`string`||typeof n==`number`)return n},O=t=>{let{examples:n}=e.get(t)||{};return Array.isArray(n)?n:[]},k=Symbol(`Buffer`),A=()=>t.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).meta({[E]:k}),j=Symbol(`DateIn`),ae=({examples:e,...n}={})=>t.union([t.iso.date(),t.iso.datetime({local:!0,offset:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(t.date()).meta({...n,[E]:j}),M=Symbol(`DateOut`),oe=(e={})=>t.date().transform(e=>e.toISOString()).pipe(t.iso.datetime()).meta({...e,[E]:M});var N=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},P=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},F=class extends Error{name=`IOSchemaError`},se=class extends F{cause;name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},I=class extends F{cause;name=`OutputValidationError`;constructor(e){let n=new t.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(y(n),{cause:e}),this.cause=e}},L=class extends F{cause;name=`InputValidationError`;constructor(e){super(y(e),{cause:e}),this.cause=e}},R=class extends Error{cause;handled;name=`ResultHandlerError`;constructor(e,t){super(y(e),{cause:e}),this.cause=e,this.handled=t}},ce=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const z=Symbol(`Form`),le=e=>(e instanceof t.ZodObject?e:t.object(e)).meta({[E]:z}),B=Symbol(`Upload`),V=e=>w(e)&&`name`in e&&`encoding`in e&&`mimetype`in e&&`data`in e&&`tempFilePath`in e&&`truncated`in e&&`size`in e&&`md5`in e&&`mv`in e,H=()=>t.custom(e=>V(e)&&typeof e.name==`string`&&typeof e.encoding==`string`&&typeof e.mimetype==`string`&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath==`string`&&typeof e.truncated==`boolean`&&typeof e.size==`number`&&typeof e.md5==`string`&&typeof e.mv==`function`,{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).meta({[E]:B}),U=Symbol(`Raw`),W=t.object({raw:A()}),ue=e=>W.extend(e).meta({[E]:U});function G(e){return e?ue(e):W.meta({[E]:U})}const K=(e,{io:r,condition:i})=>n.tryCatch(()=>void t.toJSONSchema(e,{io:r,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new se(e)}}),e=>e.cause)(),de=(e,{io:r})=>{let i=[t.toJSONSchema(e,{io:r,unrepresentable:`any`})];for(let e=0;e<i.length;e++){let t=i[e];if(n.is(Object,t)){if(t.$ref===`#`)return!0;i.push(...n.values(t))}n.is(Array,t)&&i.push(...n.values(t))}return!1},fe=e=>K(e,{condition:e=>{let t=D(e);return typeof t==`symbol`&&[B,U,z].includes(t)},io:`input`}),pe=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`],me=(e,t)=>K(e,{io:t,condition:e=>{let n=D(e),{type:r}=e._zod.def;return!!(pe.includes(r)||n===k||t===`input`&&(r===`date`||n===M)||t===`output`&&(n===j||n===U||n===B))}});var he=class{},q=class extends he{#e;#t;#n;constructor({input:e,security:t,handler:n}){super(),this.#e=e,this.#t=t,this.#n=n}get security(){return this.#t}get schema(){return this.#e}async execute({input:e,...n}){try{let t=await(this.#e||d).parseAsync(e);return this.#n({...n,input:t})}catch(e){throw e instanceof t.ZodError?new L(e):e}}},J=class extends q{constructor(e,{provider:t=()=>({}),transformer:n=e=>e}={}){super({handler:async({request:i,response:a})=>{let{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=e=>{if(e&&e instanceof Error)return c(n(e));s(t(i,a))},u=e(i,a,l);return r(u)&&u.catch(l),o}})}};const ge=(e,{variant:n,args:r,...i})=>{if(typeof e==`function`&&(e=e(...r)),e instanceof t.ZodType)return[{schema:e,...i}];if(Array.isArray(e)&&!e.length)throw new R(Error(`At least one ${n} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||i.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?i.mimeTypes:n}))},_e=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),ve=e=>a(e)?e:i(e instanceof L?400:500,y(e),{cause:e.cause||e}),ye=e=>T()&&!e.expose?i(e.statusCode).message:e.message,be=e=>Object.entries(e._zod.def.shape).reduce((e,[t,r])=>x(e,O(r).map(n.objOf(t)),([e,t])=>({...e,...t})),[]);var Y=class{nest(e){return{...e,"":this}}},xe=class r extends Y{#e;#t;#n=n.once(()=>{if(O(this.#e.outputSchema).length||!b(this.#e.outputSchema,`object`))return;let t=be(this.#e.outputSchema);if(!t.length)return;let n=this.#e.outputSchema.meta();e.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...n,examples:t})});constructor(e){super(),this.#e=e}#r(e){return new r({...this.#e,...e})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get summary(){return this.#e.summary}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}getProbableRequestType(e){return e===`query`?`form`:this.#t??=(()=>{let e=fe(this.#e.inputSchema);if(e){let t=D(e);if(t===B)return`upload`;if(t===U)return`raw`;if(t===z)return`form`}return`json`})()}getResponses(e){return e===`positive`&&this.#n(),Object.freeze(e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let e=n.pluck(`security`,this.#e.middlewares||[]);return n.reject(n.isNil,e)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(e){return this.#e.getOperationId?.(e)}async#i(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new I(e):e}}async#a({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof J))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#o({input:e,...n}){let r;try{r=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new L(e):e}return this.#e.handler({...n,input:r})}async#s(e){await this.#e.resultHandler.execute(e)}async execute({request:e,response:t,logger:n,config:r}){let i=h(e),a={},o,s=_(e,r.inputSources);try{if(await this.#a({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();let r=await this.#o({input:s,logger:n,ctx:a});if(t.writableEnded)return;o={output:await this.#i(r),error:null}}catch(e){o={output:null,error:v(e)}}await this.#s({...o,input:s,request:e,response:t,logger:n,ctx:a})}};const X={positive:200,negative:400},Se=Object.keys(X);function Ce(e){return e instanceof t.ZodType?{schema:e}:e}var Z=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,o.static(...this.#e))}};const we=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},Te=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&u(t)?[n,t]:[e]},Ee=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Q=({recognizeMethodDependentRoutes:e=!0},t,n)=>Object.entries(t).map(([t,r])=>{let[i,a]=e&&u(t)&&r instanceof Y?[`/`,t]:Te(t);return[[n||``].concat(Ee(i)||[]).join(`/`)||`/`,r,a]}),De=(e,t)=>{throw new N(`Route with explicit method can only be assigned with Endpoint`,e,t)},Oe=(e,t,n)=>{if(!(!n||n.includes(e)))throw new N(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},$=(e,t,n)=>{let r=t.includes(`:`)?p(t):t,i=`${e} ${r}`;if(n.has(i))throw new N(`Route has a duplicate: the normalized path "${r}" is already registered`,e,t);n.add(i)},ke=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=Q(t,e),a=new Set;for(let e=0;e<i.length;e++){let[o,s,c]=i[e];if(s instanceof Y)if(c)$(c,o,a),Oe(c,o,s.methods),n(c,o,s);else{let{methods:e=[`get`]}=s;for(let t of e)$(t,o,a),n(t,o,s)}else c&&De(c,o),s instanceof Z?r&&s.apply(o,r):i.splice(e+1,0,...Q(t,s,o))}};export{s as $,j as A,y as B,ce as C,oe as D,N as E,x as F,b as G,re as H,d as I,f as J,C as K,v as L,k as M,D as N,M as O,O as P,u as Q,_ as R,L as S,R as T,w as U,ee as V,T as W,S as X,ie as Y,l as Z,G as _,X as a,le as b,ve as c,ge as d,J as f,U as g,de as h,Ce as i,A as j,ae as k,ye as l,me as m,we as n,Se as o,q as p,p as q,Z as r,xe as s,ke as t,_e as u,B as v,I as w,P as x,H as y,g as z};