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.
13 lines (12 loc) • 15.2 kB
JavaScript
import{$ as e,A as t,G as n,H as r,K as i,M as a,N as o,O as s,Y as c,Z as l,g as u,h as d,n as f,o as p,t as m}from"./routing-walker-DjzH37jF.js";import{t as h}from"./peer-helpers-CuO0_h1y.js";import{t as g}from"./security-ts3gqWG9.js";import{globalRegistry as _,z as v}from"zod";import*as y from"ramda";import b from"typescript";const x={Path:`Path`,Implementation:`Implementation`,DefaultContext:`DefaultContext`,key:`key`,path:`path`,params:`params`,ctx:`ctx`,method:`method`,request:`request`,event:`event`,data:`data`,handler:`handler`,msg:`msg`,parseRequest:`parseRequest`,substitute:`substitute`,provide:`provide`,on:`on`,implementation:`implementation`,hasBody:`hasBody`,undefined:`undefined`,response:`response`,rest:`rest`,searchParams:`searchParams`,defaultImplementation:`defaultImplementation`,hasFiles:`hasFiles`,value:`value`,File:`File`,FormData:`FormData`,headers:`headers`,body:`body`,client:`client`,contentType:`contentType`,isBlob:`isBlob`,source:`source`,Method:`Method`,SomeOf:`SomeOf`,Request:`Request`,Pagination:`Pagination`,override:`override`},S={input:`Input`,positive:`PositiveResponse`,negative:`NegativeResponse`,encoded:`EncodedResponse`,response:`Response`},C=e=>Array.from(e,e=>`"${e}"`),w=e=>e;var T=class{serverUrl;paths=new Set;tags=new Map;registry=new Map;constructor(e){this.serverUrl=e}makeMethodType=()=>{let e=C(l).join(` | `);return`export type ${x.Method} = ${e};`};makeOmit=(e,t,n=``)=>`Omit<${e}, ${n&&`\n/** ${n} */\n`}${C(t).join(` | `)}>`;makeSomeOfType=()=>`type ${x.SomeOf}<T> = T[keyof T];`;makeRequestType=()=>`export type ${x.Request} = keyof ${S.input};`;someOf=e=>`${x.SomeOf}<${e}>`;makePathType=()=>{let e=C(this.paths).join(` | `);return`export type ${x.Path} = ${e};`};makePublicInterfaces=()=>Object.keys(S).map(e=>{let t=Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>` ${r?`/** @deprecated */
`:``}"${t}": ${n[e]};`).join(`
`);return`export interface ${S[e]} {\n${t}\n}`});makeEndpointTags=()=>`export const endpointTags = {\n${Array.from(this.tags).map(([e,t])=>` "${e}": [${C(t).join(`, `)}]`).join(`,
`)}\n}`;makeImplementationType=()=>{let e=[`${x.method}: ${x.Method}`,`${x.path}: string`,`${x.params}: Record<string, any>`,`${x.ctx}?: T`].join(`,`);return`export type ${x.Implementation}<T extends Record<string, unknown>> = (${e}) => Promise<any>;`};makeDefaultContextType=()=>`export type ${x.DefaultContext} = { ${x.override}?: (init: RequestInit) => RequestInit };`;makeParseRequestFn=()=>{let e=`${x.request}: string`,t=`[${x.Method}, ${x.Path}]`,n=`${x.request}.${w(`split`)}(/ (.+)/, 2) as ${t}`;return`const ${x.parseRequest} = (${e}) => ${n};`};makeSubstituteFn=()=>{let e=`${x.path}: string, ${x.params}: Record<string, any>`,t=`\`:\${${x.key}}\``,n=`: [typeof ${x.path}, typeof ${x.params}]`;return[`const ${x.substitute} = (${e})${n} => {`,` if (${x.params} instanceof Blob) return [${x.path}, ${x.params}] as const;`,` const ${x.rest} = { ...${x.params} };`,` for (const ${x.key} in ${x.params}) {`,` ${x.path} = ${x.path}.${w(`replace`)}(${t}, () => {`,` delete ${x.rest}[${x.key}];`,` return ${x.params}[${x.key}];`,` });`,` }`,` return [${x.path}, ${x.rest}] as const;`,`}`].join(`
`)};makePaginationType=()=>{let e=w(`nextCursor`),t=w(`total`),n=w(`limit`),r=w(`offset`),i=`{ ${e}: string | null }`,a=`{ ${t}: number; ${n}: number; ${r}: number }`;return`type ${x.Pagination} = ${i} | ${a}`};makeClientClass=e=>{let t=w(`nextCursor`),n=w(`offset`),r=w(`limit`),i=w(`total`),a=`${x.method}, ...${x.substitute}(${x.path}, ${x.params}), ${x.ctx}`;return[`export class ${e}<T extends Record<string, unknown> = ${x.DefaultContext}> {`,` public constructor(`,` protected readonly ${x.implementation}: ${x.Implementation}<T> = ${x.defaultImplementation},`,` ) {}`,` public ${x.provide}<K extends ${x.Request}>(`,` ${x.request}: K,`,` ${x.params}: ${S.input}[K],`,` ${x.ctx}?: T,`,` ): Promise<${S.response}[K]> {`,` const [${x.method}, ${x.path}] = ${x.parseRequest}(${x.request});`,` return this.${x.implementation}(${a});`,` }`,` public static hasMore(${x.response}: ${x.Pagination}): boolean {`,` if ("${t}" in ${x.response}) return ${x.response}.${t} !== null;`,` return ${x.response}.${n} + ${x.response}.${r} < ${x.response}.${i};`,` }`,`}`].join(`
`)};makeDefaultImplementation=t=>{let n=`${x.method}, ${x.path}, ${x.params}, ${x.ctx}`,r=C([`get`,`head`,`delete`]).join(`, `),i=`!${x.hasBody} || ${x.hasFiles} ? ${x.undefined} : { "Content-Type": ${x.isBlob} ? "${e.raw}" : "${e.json}" };`,a=`${x.response}.${w(`headers`)}.${w(`get`)}("content-type")`,o=`\`?\${new ${URLSearchParams.name}(${x.params})}\``;return[`const ${x.defaultImplementation}: ${x.Implementation}<${x.DefaultContext}> = async (${n}) => {`,` const ${x.isBlob} = ${x.params} instanceof Blob;`,` const ${x.hasFiles} = !${x.isBlob} && Object.${w(`values`)}(${x.params}).${w(`some`)}((one) => one instanceof Blob || one instanceof ${x.File});`,` const ${x.hasBody} = ![${r}].includes(${x.method});`,` const ${x.searchParams} = ${x.isBlob} || ${x.hasBody} ? "" : ${o};`,` const ${x.headers} = ${i}`,` let ${x.body}: RequestInit["${x.body}"] = ${x.undefined};`,` if (${x.hasBody}) {`,` if (${x.isBlob}) {`,` ${x.body} = ${x.params};`,` } else if (${x.hasFiles}) {`,` ${x.body} = new ${FormData.name}();`,` for (const [${x.key}, ${x.value}] of Object.${w(`entries`)}(${x.params}))`,` if (${x.value} !== undefined) ${x.body}.${w(`append`)}(${x.key}, ${x.value});`,` } else {`,` ${x.body} = JSON.${w(`stringify`)}(${x.params});`,` }`,` }`,` let init: RequestInit = {`,` ${w(`method`)}: ${x.method}.${w(`toUpperCase`)}(),`,` ${w(`credentials`)}: ${t?`"include"`:x.undefined},`,` ${x.headers},`,` ${x.body},`,` };`,` if (${x.ctx}?.${x.override}) init = ${x.ctx}.${x.override}(init);`,` const ${x.response} = await ${fetch.name}(`,` new ${URL.name}(\`\${${x.path}}\${${x.searchParams}}\`, "${this.serverUrl}"),`,` init,`,` );`,` const ${x.contentType} = ${a};`,` if (!${x.contentType}) return;`,` if (${x.contentType}.${w(`startsWith`)}("${e.json}")) return ${x.response}.${w(`json`)}();`,` if (${x.contentType}.${w(`startsWith`)}("text/")) return ${x.response}.${w(`text`)}();`,` return ${x.response}.${w(`blob`)}();`,`};`].join(`
`)};makeSubscriptionClass=(e,t)=>{let n=`${x.substitute}(${x.parseRequest}(${x.request})[1], ${x.params})`,r=`Extract<R, { ${w(`event`)}: E }>["${w(`data`)}"]`,i=`(${x.msg} as ${MessageEvent.name}).${w(`data`)}`;return[`export class ${e}<`,` K extends Extract<${x.Request}, \`get \${string}\`>,`,` R extends Extract<${S.positive}[K], { ${w(`event`)}: string }>,`,`> {`,` public ${x.source}: EventSource;`,` public constructor(${x.request}: K, ${x.params}: ${S.input}[K]) {`,` const [${x.path}, ${x.rest}] = ${n};`,` const ${x.searchParams} = \`?\${new ${URLSearchParams.name}(${x.rest})}\`;`,` this.${x.source} = new EventSource(`,` new URL(\`\${${x.path}}\${${x.searchParams}}\`, "${this.serverUrl}"),`,` { ${w(`withCredentials`)}: ${t?`true`:x.undefined} }`,` );`,` }`,` public ${x.on}<E extends R["${w(`event`)}"]>(`,` ${w(`event`)}: E,`,` ${x.handler}: (${x.data}: ${r}) => void | Promise<void>,`,` ) {`,` this.${x.source}.${w(`addEventListener`)}(${x.event}, (${x.msg}) =>`,` ${x.handler}(JSON.${w(`parse`)}(${i})),`,` );`,` return this;`,` }`,`}`].join(`
`)};makeUsageStatements=(e,t)=>[`const ${x.client} = new ${e}();`,`${x.client}.${x.provide}("get /v1/user/retrieve", { id: "10" });`,`new ${t}("get /v1/events/stream", {}).${x.on}("time", (time) => {});`].join(`
`)};const E=b.factory,D=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ee=[b.SyntaxKind.AnyKeyword,b.SyntaxKind.BigIntKeyword,b.SyntaxKind.BooleanKeyword,b.SyntaxKind.NeverKeyword,b.SyntaxKind.NumberKeyword,b.SyntaxKind.ObjectKeyword,b.SyntaxKind.StringKeyword,b.SyntaxKind.SymbolKeyword,b.SyntaxKind.UndefinedKeyword,b.SyntaxKind.UnknownKeyword,b.SyntaxKind.VoidKeyword],O=e=>typeof e==`number`?E.createNumericLiteral(e):typeof e==`bigint`?E.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?E.createTrue():E.createFalse():e===null?E.createNull():E.createStringLiteral(e),k=e=>E.createIdentifier(e),A=e=>typeof e==`string`&&D.test(e)?k(e):O(e),j=(e,t)=>typeof e==`number`?E.createKeywordTypeNode(e):typeof e==`string`||b.isIdentifier(e)?E.createTypeReferenceNode(e,t&&y.map(j,t)):e,M=e=>{let t=new Map;for(let n of e)t.set(N(n)?n.kind:n,n);return E.createUnionTypeNode(Array.from(t.values()))},N=e=>ee.includes(e.kind),te=(e,t)=>b.addSyntheticLeadingComment(e,b.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),P=(e,t)=>{let n=b.createSourceFile(`print.ts`,``,b.ScriptTarget.Latest,!1,b.ScriptKind.TS);return b.createPrinter(t).printNode(b.EmitHint.Unspecified,e,n)},F=(e,t,{isOptional:n,hasUndefined:r=n,isDeprecated:i,comment:a}={})=>{let o=j(t),s=E.createPropertySignature(void 0,A(e),n?E.createToken(b.SyntaxKind.QuestionToken):void 0,r?M([o,j(b.SyntaxKind.UndefinedKeyword)]):o),c=y.reject(y.isNil,[i?`@deprecated`:void 0,a]);return c.length?te(s,c.join(` `)):s},I=e=>E.createLiteralTypeNode(O(e)),L=(e,{rules:t,onMissing:n,ctx:r={}})=>{let i=o(e),a=i&&i in t?t[i]:t[e._zod.def.type],s=e=>L(e,{ctx:r,rules:t,onMissing:n});return a?a(e,{...r,next:s}):n(e,r)},R={name:y.path([`name`,`text`]),type:y.path([`type`]),optional:y.path([`questionToken`])},z=({_zod:{def:e}})=>{let t=e.values.map(e=>e===void 0?j(b.SyntaxKind.UndefinedKeyword):I(e));return t.length===1?t[0]:M(t)},B=({_zod:{def:e}},{next:t})=>{let{parts:r}=e,i=0,a=()=>{let e=``;for(;i<r.length;){let t=r[i];if(n(t))break;i++,e+=t??``}return e},o=E.createTemplateHead(a()),s=[];for(;i<r.length;){let e=t(r[i++]),n=a(),o=i<r.length?E.createTemplateMiddle:E.createTemplateTail;s.push(E.createTemplateLiteralTypeSpan(e,o(n)))}return s.length?E.createTemplateLiteralType(o,s):I(o.text)},V=(e,{isResponse:t,next:n,makeAlias:r})=>{let i=()=>{let r=Object.entries(e._zod.def.shape).map(([e,r])=>{let{description:i,deprecated:a}=_.get(r)||{},o=(t?r._zod.optout:r._zod.optin)===`optional`,s=o&&!(r instanceof v.core.$ZodExactOptional);return F(e,n(r),{comment:i,isDeprecated:a,isOptional:o,hasUndefined:s})});return E.createTypeLiteralNode(r)};return d(e,{io:t?`output`:`input`})?r(e,i):i()},H=({_zod:{def:e}},{next:t})=>E.createArrayTypeNode(t(e.element)),U=({_zod:{def:e}})=>M(y.map(I,Object.values(e.entries))),W=({_zod:{def:e}},{next:t})=>M(e.options.map(t)),G=({_zod:{def:e}},{next:t})=>M([t(e.innerType),I(null)]),K=({_zod:{def:e}},{next:t})=>E.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:E.createRestTypeNode(t(e.rest)))),q=({_zod:{def:e}},{next:t})=>{let[n,r]=[e.keyType,e.valueType].map(t),i=j(`Record`,[n,r]);return e.mode===`loose`?E.createIntersectionTypeNode([i,j(`Record`,[`PropertyKey`,r])]):i},J=y.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw Error(`Not objects`);let t=y.chain(y.prop(`members`),e),n=y.uniqWith((...e)=>{if(!y.eqBy(R.name,...e))return!1;if(y.both(y.eqBy(R.type),y.eqBy(R.optional))(...e))return!0;throw Error(`Has conflicting prop`)},t);return E.createTypeLiteralNode(n)},(e,t)=>E.createIntersectionTypeNode(t)),Y=({_zod:{def:e}},{next:t})=>J([e.left,e.right].map(t)),X=e=>()=>j(e),Z=({_zod:{def:e}},{next:t})=>t(e.innerType),Q=e=>j(e?b.SyntaxKind.UnknownKeyword:b.SyntaxKind.AnyKeyword),ne=({_zod:{def:e}},{next:t,isResponse:i})=>{let a=e[i?`out`:`in`],o=e[i?`in`:`out`];if(!n(a,`transform`))return t(a);let s=t(o),c={[b.SyntaxKind.AnyKeyword]:``,[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:``,[b.SyntaxKind.UndefinedKeyword]:void 0}[s.kind],l=r(a,c),u={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return j(l&&u[l]||Q(i))},re=()=>I(null),ie=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ae=()=>j(`Blob`),oe=(e,{next:t})=>t(e._zod.def.shape.raw),se={string:X(b.SyntaxKind.StringKeyword),number:X(b.SyntaxKind.NumberKeyword),bigint:X(b.SyntaxKind.BigIntKeyword),boolean:X(b.SyntaxKind.BooleanKeyword),any:X(b.SyntaxKind.AnyKeyword),undefined:X(b.SyntaxKind.UndefinedKeyword),[t]:X(b.SyntaxKind.StringKeyword),[s]:X(b.SyntaxKind.StringKeyword),never:X(b.SyntaxKind.NeverKeyword),void:X(b.SyntaxKind.UndefinedKeyword),unknown:X(b.SyntaxKind.UnknownKeyword),null:re,array:H,tuple:K,record:q,object:V,literal:z,template_literal:B,intersection:Y,union:W,default:Z,enum:U,optional:Z,nonoptional:Z,nullable:G,catch:Z,pipe:ne,lazy:ie,readonly:Z,[a]:ae,[u]:oe},$=(e,{brandHandling:t,ctx:n})=>L(e,{rules:{...t,...se},onMissing:({},{isResponse:e})=>Q(e),ctx:n});var ce=class extends T{#e=[];#t=new Map;#n;#r(e,t){let n=this.#t.get(e);if(!n){n=`Type${this.#t.size+1}`,this.#t.set(e,n);let r=t();this.#e.push(e=>`type ${n} = ${P(r,e)};`)}return j(n)}constructor({routing:e,config:t,brandHandling:n,variant:r=`client`,clientClassName:a=`Client`,subscriptionClassName:o=`Subscription`,serverUrl:s=`https://example.com`,noBodySchema:l=v.undefined(),hasHeadMethod:u=!0,hasCredentials:d=!1}){super(s);let h={makeAlias:this.#r.bind(this)},_={brandHandling:n,ctx:{...h,isResponse:!1}},y={brandHandling:n,ctx:{...h,isResponse:!0}},b=!1,x=(e,t,n)=>{let r=i.bind(null,e,t),{isDeprecated:a,inputSchema:o,tags:s}=n,u=`${e} ${t}`,d=r(`input`),f=g(n.security,`cookie`);f.size&&(b=!0);let m=$(o,_);this.#e.push(e=>{let t=P(m,e);return[`/** ${u} */`,`type ${d} = ${f.size?this.makeOmit(t,f,`security cookies`):t};`].join(`
`)});let h=p.reduce((t,i)=>{let a=n.getResponses(i),o=[];for(let[t,{schema:n,mimeTypes:s,statusCodes:d}]of a.entries()){let a=c(e,s),f=r(i,`variant`,`${t+1}`),p=$(a?n:l,y);this.#e.push(e=>`/** ${u} */\ntype ${f} = ${P(p,e)};`);for(let e of d)o.push(` ${e}: ${f};`)}let s=r(i,`response`,`variants`);return this.#e.push(`/** ${u} */\ninterface ${s} {\n${o.join(`
`)}\n}`),Object.assign(t,{[i]:s})},{});this.paths.add(t);let v={input:d,positive:this.someOf(h.positive),negative:this.someOf(h.negative),response:`${S.positive}["${u}"] | ${S.negative}["${u}"]`,encoded:`${h.positive} & ${h.negative}`};this.registry.set(u,{isDeprecated:a,store:v}),this.tags.set(u,s)};m({routing:e,config:t,onEndpoint:u?f(x):x}),this.#e.push(this.makeSomeOfType(),this.makePathType(),this.makeMethodType(),...this.makePublicInterfaces(),this.makeRequestType()),r!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makePaginationType(),this.makeDefaultContextType(),this.makeDefaultImplementation(d&&b),this.makeClientClass(a),this.makeSubscriptionClass(o,d&&b)),this.#n=this.makeUsageStatements(a,o))}print(e){let t=this.#e.map(t=>typeof t==`function`?t(e):t);return this.#n&&t.push(`// Usage example:\n/*\n${this.#n}*/`),t.join(`
`)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=h(`prettier`).format;n=t=>e(t,{filepath:`client.ts`})}catch{}this.#n&&n&&(this.#n=await n(this.#n));let r=this.print(e);return n?n(r):r}};export{ce as Integration};