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 • 12 kB
JavaScript
import{$ as e,F as t,G as n,I as r,J as i,K as a,N as o,Q as s,R as c,W as l,X as u,j as d,nt as f,q as p,r as m,w as h,x as g,y as _}from"./routing-walker-BXNIeg98.js";import{z as v}from"zod";import*as y from"ramda";import{isReferenceObject as b,isSchemaObject as x}from"openapi3-ts/oas32";const S=e=>e.type===`object`,C=y.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return y.concat(e,t);if(e===t)return t;throw Error(`Can not flatten properties`,{cause:{a:e,b:t}})}),w=new Set([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),T=e=>{for(let t of Object.keys(e))if(!w.has(t))return!1;return!0},E=y.pair(!0),ee=(e,t,n)=>!(`allOf`in e)||!e.allOf?[]:e.allOf.map(e=>{if(t===`throw`&&!(e.type===`object`&&T(e)))throw Error(`Can not merge`);return y.pair(n,e)}),te=e=>{let t=[];return e.anyOf&&t.push(...y.map(E,e.anyOf)),e.oneOf&&t.push(...y.map(E,e.oneOf)),t},ne=(e,t,n,r)=>{if(!a(e.propertyNames))return;let i=[];typeof e.propertyNames.const==`string`&&i.push(e.propertyNames.const),e.propertyNames.enum&&i.push(...e.propertyNames.enum.filter(e=>typeof e==`string`));let o={...Object(e.additionalProperties)};for(let e of i)t.properties[e]??=o;r||n.push(...i)},re=(e,t,n)=>{t.examples?.length&&(e.examples=n?y.concat(e.examples||[],t.examples):c(e.examples?.filter(a)||[],t.examples.filter(a),([e,t])=>y.mergeDeepRight(e,t)))},D=(e,t=`coerce`)=>{let n=[y.pair(!1,e)],r={type:`object`,properties:{}},i=[];for(let[e,a]of n)a.description&&(r.description??=a.description),n.push(...ee(a,t,e)),n.push(...te(a)),re(r,a,e),S(a)&&(n.push([e,{examples:O(a)}]),a.properties&&(r.properties=(t===`throw`?C:y.mergeDeepRight)(r.properties,a.properties),!e&&a.required&&i.push(...a.required)),ne(a,r,i,e));return i.length&&(r.required=[...new Set(i)]),r},O=e=>Object.entries(e.properties||{}).reduce((e,[t,n])=>{let{examples:r=[]}=a(n)?n:{};return c(e,r.map(y.objOf(t)),([e,t])=>({...e,...t}))},[]),k=`x-coerce`,A=(e,t)=>{if(e[`x-coerce`]===!0)return!0;if(e.anyOf)return e.anyOf.some(e=>A(e,t));if(e.oneOf)return e.oneOf.some(e=>A(e,t));if(e.allOf)return e.allOf.every(e=>A(e,t));if(e.type===void 0||e.type===`string`)return!0;if(t===`query`&&[`array`,`object`].includes(e.type)){let n=[e.items,e.prefixItems,e.additionalItems,Object.values(e.properties??{}),e.additionalProperties,e.propertyNames];for(let e of n){if(!a(e))continue;let n=Array.isArray(e)?e:[e];for(let e of n)if(a(e)&&!A(e,t))return!1}return!0}return!1};let j;const M=()=>j??=new Set(`a-im.accept.accept-additions.accept-charset.accept-datetime.accept-encoding.accept-features.accept-language.accept-signature.access-control.access-control-request-headers.access-control-request-method.alpn.alt-used.amp-cache-transform.apply-to-redirect-ref.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cdn-loop.cert-not-after.cert-not-before.client-cert.client-cert-chain.close.cmcd-object.cmcd-request.cmcd-session.cmcd-status.cmsd-dynamic.cmsd-static.concealed-auth-export.configuration-context.connection.content-digest.content-disposition.content-encoding.content-id.content-language.content-length.content-location.content-md5.content-range.content-script-type.content-type.cookie.cookie2.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.dictionary-id.differential-id.digest.dpop.early-data.ediint-features.expect.expect-ct.ext.forwarded.from.getprofile.hobareg.host.http2-settings.if.if-match.if-modified-since.if-none-match.if-range.if-schedule-tag-match.if-unmodified-since.im.include-referred-token-binding-id.incremental.isolation.keep-alive.label.last-event-id.link.link-template.lock-token.man.max-forwards.memento-datetime.meter.method-check.method-check-expires.mime-version.negotiate.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.pep.pep-info.permissions-policy.pics-label.ping-from.ping-to.position.pragma.prefer.preference-applied.priority.profileobject.protocol.protocol-info.protocol-query.protocol-request.proxy-authorization.proxy-features.proxy-instruction.range.redirect-ref.referer.referer-root.referrer-policy.repeatability-client-id.repeatability-first-sent.repeatability-request-id.repeatability-result.replay-nonce.reporting-endpoints.repr-digest.safe.schedule-reply.schedule-tag.sec-fetch-storage-access.sec-gpc.sec-purpose.sec-token-binding.sec-websocket-extensions.sec-websocket-key.sec-websocket-protocol.sec-websocket-version.security-scheme.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.want-unencoded-digest.warning.x-content-type-options.x-frame-options`.split(`.`)),N={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},P=e=>e.replace(u,e=>`{${e.slice(1)}}`),F=({},e)=>{if(e.isResponse)throw new h(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},I=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),L=({zodSchema:e,jsonSchema:t})=>{if(!p(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},R=y.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return D(e,`throw`)},(e,{jsonSchema:t})=>t),z=({jsonSchema:e})=>{if(!e.anyOf||!e.anyOf.length)return e;let t=e.anyOf[0];return Object.assign(t,{type:K(t.type)})},B=e=>e,V=({jsonSchema:e},t)=>{if(t.isResponse)throw new h(`Please use ez.dateOut() for output.`,t);return e},H=({jsonSchema:e},t)=>{if(!t.isResponse)throw new h(`Please use ez.dateIn() for input.`,t);return e},U=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),W=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,G=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return N?.[t]},K=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],ie=new Set([`number`,`string`,`boolean`]),q=({zodSchema:e,jsonSchema:t},r)=>{let i=e._zod.def[r.isResponse?`out`:`in`],a=e._zod.def[r.isResponse?`in`:`out`];if(!p(i,`transform`))return t;let o=B(Z(a,{ctx:r}));if(x(o))if(r.isResponse){let e=n(i,G(o));if(e&&ie.has(e))return{...t,type:e}}else{let{type:e,...t}=o;return{...t,format:`${t.format||e} (preprocessed)`}}return t},J=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!a(t.properties.raw)?e:t.properties.raw},Y=e=>e.length?y.fromPairs(y.zip(y.times(e=>`example${e+1}`,e.length),y.map(y.objOf(`dataValue`),e))):void 0,ae=(e,t)=>t?.has(e)||e.startsWith(`x-`)||M().has(e),oe=({method:e,path:t,security:n,inputSources:r,isHeader:i})=>{let a=new Set(l(t)),o=r.includes(`query`),s=r.includes(`params`),c=r.includes(`headers`),u=r.includes(`cookies`)||r.includes(`signedCookies`),d;c&&n&&(d=m(n,`header`));let f;return u&&n&&(f=m(n,`cookie`)),{pathParams:a,getLocation:n=>{if(s&&a.has(n)&&a.delete(n))return`path`;if(u&&f?.has(n))return`cookie`;if(c&&(i?.(n,e,t)??ae(n,d)))return`header`;if(o&&e!==`query`)return`query`},isQueryEnabled:o}},se=({path:e,method:t,flatRequest:n,makeRef:r,composition:o,getLocation:s,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let l=[];for(let[e,t]of Object.entries(n.properties)){if(!a(t))continue;let u=s(e);if(!u)continue;let d=B(t),f=o===`components`?r(t.id||JSON.stringify(t),d,t.id||i(c,e)):d;l.push({name:e,in:u,deprecated:t.deprecated,required:n.required?.includes(e)||u===`path`,description:d.description||c,schema:f,examples:Y(x(d)&&d.examples?.length?d.examples:y.pluck(e,n.examples?.filter(y.both(a,y.has(e)))||[]))})}return l},X={nullable:z,union:L,bigint:U,intersection:R,tuple:W,pipe:q,[o]:V,[d]:H,[g]:F,[_]:J,[t]:I},ce=(e,t,n)=>{let r=[e,t],i=e=>/schema\d+$/.test(e)?void 0:e;for(let e=0;e<r.length;e++){let a=r[e];if(y.is(Object,a)){if(b(a)&&!a.$ref.startsWith(`#/components`)){let e=a.$ref.split(`/`).pop(),r=t[e];if(r){let t=r.id||i(e);a.$ref=n.makeRef(t||r,B(r),t).$ref}continue}r.push(...y.values(a))}y.is(Array,a)&&r.push(...y.values(a))}return e},Z=(e,{ctx:t,rules:n=X})=>{let{$defs:i={},properties:o={}}=v.toJSONSchema(v.object({subject:e}),{unrepresentable:`any`,io:t.isResponse?`output`:`input`,override:e=>{let i=v.globalRegistry.get(e.zodSchema)?.id;if(i){let n=t.seenIds.get(i);if(n&&n!==e.zodSchema)throw new h(`The meta id "${i}" is used by two different schemas. Please make the ids unique or reuse the same schema instance.`,t);t.seenIds.set(i,e.zodSchema)}let a=r(e.zodSchema),o=n[a&&a in n?a:e.zodSchema._zod.def.type];if(o){let n={...o(e,t)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,n)}}});return ce(a(o.subject)?o.subject:{},i,t)},Q=(e,t)=>{if(b(e))return[e,!1];let n=!1,r=y.map(e=>{let[r,i]=Q(e,t);return n||=i,r}),i=y.omit(t),a={properties:i,examples:y.map(i),required:y.without(t),allOf:r,oneOf:r,anyOf:r},o=y.evolve(a,e);return[o,n||!!o.required?.length]},le=({method:t,path:n,schema:r,mimeTypes:a,variant:o,makeRef:c,composition:l,hasMultipleStatusCodes:u,statusCode:d,brandHandling:p,seenIds:m,description:h=`${t.toUpperCase()} ${n} ${e(o)} response ${u?d:``}`.trim()})=>{if(!s(t,a))return{description:h};let g=B(Z(r,{rules:{...p,...X},ctx:{isResponse:!0,makeRef:c,path:n,method:t,seenIds:m}})),_=[];x(g)&&g.examples&&(_.push(...g.examples),delete g.examples);let v=l===`components`?c(r,g,i(h)):g;return{description:h,content:y.fromPairs(a.map(e=>[e,{[e===f.sse?`itemSchema`:`schema`]:v,examples:Y(_)}]))}},ue=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},de=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},fe=({name:e})=>({type:`apiKey`,in:`header`,name:e}),pe=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),$=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),me=({flows:e={},oauth2MetadataUrl:t})=>({type:`oauth2`,flows:y.map(e=>({...e,scopes:e.scopes||{}}),y.reject(y.isNil,e)),oauth2MetadataUrl:t}),he=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?ue(e):e.type===`input`?de(e,t):e.type===`header`?fe(e):e.type===`cookie`?pe(e):e.type===`openid`?$(e):me(e);return e.map(e=>e.map(({deprecated:e,...t})=>({...n(t),deprecated:e})))},ge=Set.prototype.has.bind(new Set([`oauth2`,`openIdConnect`])),_e=(e,t,n)=>{let r=Array.from(t);return e.map(e=>{let t={};for(let i of e){let e=n(i);t[e]=ge(i.type)?r:[]}return t})},ve=({schema:e,brandHandling:t,makeRef:n,path:r,method:i,seenIds:a})=>Z(e,{rules:{...t,...X},ctx:{isResponse:!1,makeRef:n,path:r,method:i,seenIds:a}}),ye=({method:e,path:t,bodyJsonSchema:n,hasRequiredBodyProps:r,flatRequest:o,mimeType:s,makeRef:c,composition:l,paramNames:u,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=B(n),m=[];x(p)&&p.examples&&(m.push(...p.examples),delete p.examples);let h={schema:l===`components`?c(JSON.stringify(p),p,i(d)):p,examples:Y(m.length?m:o.examples?.filter(e=>a(e)&&!Array.isArray(e)).map(y.omit(u))||[])},g={description:d,content:{[s]:h}};return(r||s===f.raw)&&(g.required=!0),g},be=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;if(typeof n==`string`)return e.concat({name:t,description:n});let{url:r,...i}=n,a={...i,name:t};return r&&(a.externalDocs={...a.externalDocs,url:r}),e.concat(a)},[]),xe=(e,t=50)=>!e||e.length<=t?e:e.slice(0,Math.max(1,t||0)-1)+`…`,Se=e=>{let t=Array.from(e);return t.length?t:void 0};export{he as a,Q as c,P as d,xe as f,A as h,le as i,oe as l,D as m,ve as n,_e as o,k as p,se as r,be as s,ye as t,Se as u};