express-zod-api 18.6.2 → 18.6.3

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  ## Version 18
4
4
 
5
+ ### v18.6.3
6
+
7
+ - Better approach on logger instance recognition:
8
+ - Backported from [v19.1.2](https://github.com/RobinTail/express-zod-api/blob/master/CHANGELOG.md#v1912).
9
+
5
10
  ### v18.6.2
6
11
 
7
12
  - Compatibility improvement for Jest: all dynamic `import()` in CJS build are replaced with `require()`.
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var Io=Object.create;var Ve=Object.defineProperty;var Eo=Object.getOwnPropertyDescriptor;var Zo=Object.getOwnPropertyNames;var zo=Object.getPrototypeOf,wo=Object.prototype.hasOwnProperty;var Mo=(e,t)=>{for(var r in t)Ve(e,r,{get:t[r],enumerable:!0})},or=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Zo(t))!wo.call(e,i)&&i!==r&&Ve(e,i,{get:()=>t[i],enumerable:!(o=Eo(t,i))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?Io(zo(e)):{},or(t||!e||!e.__esModule?Ve(r,"default",{value:e,enumerable:!0}):r,e)),No=e=>or(Ve({},"__esModule",{value:!0}),e);var ci={};Mo(ci,{AbstractEndpoint:()=>ie,DependsOnMethod:()=>Te,Documentation:()=>mt,DocumentationError:()=>C,EndpointsFactory:()=>xe,InputValidationError:()=>H,Integration:()=>ht,MissingPeerError:()=>ee,OutputValidationError:()=>$,RoutingError:()=>W,ServeStatic:()=>Se,arrayEndpointsFactory:()=>Ir,arrayResultHandler:()=>it,attachRouting:()=>Kr,createConfig:()=>nr,createLogger:()=>st,createMiddleware:()=>ot,createResultHandler:()=>nt,createServer:()=>Fr,defaultEndpointsFactory:()=>Cr,defaultResultHandler:()=>he,ez:()=>Po,getExamples:()=>F,getMessageFromError:()=>K,getStatusCodeFromError:()=>Me,testEndpoint:()=>mo,withMeta:()=>lr});module.exports=No(ci);function nr(e){return e}var zt=S(require("assert/strict"),1),tt=require("zod");var ir=require("zod"),me={positive:200,negative:400},Tt=(e,t)=>e instanceof ir.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));var Tr=require("zod");var sr=require("http-errors"),ar=require("crypto"),le=require("ramda"),pr=require("zod");var W=class extends Error{name="RoutingError"},C=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
- Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},V=class extends Error{name="IOSchemaError"},$=class extends V{name="OutputValidationError";originalError;constructor(t){super(K(t)),this.originalError=t}},H=class extends V{name="InputValidationError";originalError;constructor(t){super(K(t)),this.originalError=t}},X=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ee=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var N={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var vo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(N.upload);return"files"in e&&r},bt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Do=["body","query","params"],St=e=>e.method.toLowerCase(),Ot=e=>e.startsWith("x-"),ko=e=>(0,le.pickBy)((0,le.flip)(Ot),e),dr=(e,t={})=>{let r=St(e);return r==="options"?{}:(t[r]||bt[r]||Do).filter(o=>o==="files"?vo(e):!0).map(o=>o==="headers"?ko(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},ue=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),K=e=>e instanceof pr.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof $?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Me=e=>(0,sr.isHttpError)(e)?e.statusCode:e instanceof H?400:500,At=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
1
+ "use strict";var Io=Object.create;var Ve=Object.defineProperty;var Eo=Object.getOwnPropertyDescriptor;var Zo=Object.getOwnPropertyNames;var zo=Object.getPrototypeOf,wo=Object.prototype.hasOwnProperty;var Mo=(e,t)=>{for(var r in t)Ve(e,r,{get:t[r],enumerable:!0})},or=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Zo(t))!wo.call(e,i)&&i!==r&&Ve(e,i,{get:()=>t[i],enumerable:!(o=Eo(t,i))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?Io(zo(e)):{},or(t||!e||!e.__esModule?Ve(r,"default",{value:e,enumerable:!0}):r,e)),No=e=>or(Ve({},"__esModule",{value:!0}),e);var ci={};Mo(ci,{AbstractEndpoint:()=>ie,DependsOnMethod:()=>Te,Documentation:()=>lt,DocumentationError:()=>C,EndpointsFactory:()=>xe,InputValidationError:()=>H,Integration:()=>xt,MissingPeerError:()=>ee,OutputValidationError:()=>$,RoutingError:()=>W,ServeStatic:()=>Se,arrayEndpointsFactory:()=>Ir,arrayResultHandler:()=>it,attachRouting:()=>Kr,createConfig:()=>nr,createLogger:()=>at,createMiddleware:()=>ot,createResultHandler:()=>nt,createServer:()=>Fr,defaultEndpointsFactory:()=>Cr,defaultResultHandler:()=>he,ez:()=>Po,getExamples:()=>F,getMessageFromError:()=>K,getStatusCodeFromError:()=>Me,testEndpoint:()=>mo,withMeta:()=>lr});module.exports=No(ci);function nr(e){return e}var wt=S(require("assert/strict"),1),tt=require("zod");var ir=require("zod"),me={positive:200,negative:400},bt=(e,t)=>e instanceof ir.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));var Tr=require("zod");var sr=require("http-errors"),ar=require("crypto"),le=require("ramda"),pr=require("zod");var W=class extends Error{name="RoutingError"},C=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
+ Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},V=class extends Error{name="IOSchemaError"},$=class extends V{name="OutputValidationError";originalError;constructor(t){super(K(t)),this.originalError=t}},H=class extends V{name="InputValidationError";originalError;constructor(t){super(K(t)),this.originalError=t}},X=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ee=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var N={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var vo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(N.upload);return"files"in e&&r},St={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Do=["body","query","params"],Ot=e=>e.method.toLowerCase(),At=e=>e.startsWith("x-"),ko=e=>(0,le.pickBy)((0,le.flip)(At),e),dr=(e,t={})=>{let r=Ot(e);return r==="options"?{}:(t[r]||St[r]||Do).filter(o=>o==="files"?vo(e):!0).map(o=>o==="headers"?ko(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},ue=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),K=e=>e instanceof pr.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof $?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Me=e=>(0,sr.isHttpError)(e)?e.statusCode:e instanceof H?400:500,Rt=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
3
3
  ${o.stack}
4
- `,{url:t.url,payload:r})},F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=re(e,"examples")||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},te=(e,t,r)=>e.length&&t.length?(0,le.xprod)(e,t).map(r):e.concat(t),Ne=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Rt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),v=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(Rt).join(""),$e=e=>(0,ar.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),_e=(e,t)=>{try{return typeof e.parse(t)}catch{return}},D=e=>typeof e=="object"&&e!==null;var Pt=require("zod"),Ge=require("ramda"),I=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[I]=(0,Ge.clone)(t._def[I])||{examples:[]},t},Lo=function(e){let t=Ye(this);return t._def[I].examples.push(e),t},jo=function(e){let t=Ye(this);return t._def[I].defaultLabel=e,t};I in globalThis||(globalThis[I]=!0,Object.defineProperty(Pt.z.ZodType.prototype,"example",{get(){return Lo.bind(this)}}),Object.defineProperty(Pt.z.ZodDefault.prototype,"label",{get(){return jo.bind(this)}}));var cr=e=>I in e._def&&D(e._def[I]),re=(e,t)=>cr(e)?e._def[I][t]:void 0,mr=(e,t)=>{if(!cr(e))return t;let r=Ye(t);return r._def[I].examples=te(r._def[I].examples,e._def[I].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,Ge.mergeDeepRight)({...o},{...i}):i),r},E=(e,t)=>{let r=Ye(t);return r._def[I].kind=e,r},Ct=(e,t)=>re(e,"kind")===t,lr=e=>e;var fr=require("zod");var fe=require("zod");var _="File",ur=fe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Uo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ho={buffer:()=>E(_,ur),string:()=>E(_,fe.z.string()),binary:()=>E(_,ur.or(fe.z.string())),base64:()=>{let e=fe.z.string(),t=e.base64?.()instanceof fe.z.ZodString;return E(_,t?e.base64():e.regex(Uo,"Does not match base64 encoding"))}};function Qe(e){return Ho[e||"string"]()}var oe="Raw",yr=()=>E(oe,fr.z.object({raw:Qe("buffer")}));var gr=require("zod");var ve="Upload",hr=()=>E(ve,gr.z.custom(e=>typeof e=="object"&&e!==null&&"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&&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",e=>({message:`Expected file upload, received ${typeof e}`})));var It=({schema:{options:e},next:t})=>e.some(t),br=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),Ko=({schema:e,next:t})=>Object.values(e.shape).some(t),xr=({schema:e,next:t})=>t(e.unwrap()),Fo=({schema:e,next:t})=>t(e.innerType()),qo=({schema:e,next:t})=>t(e.valueSchema),Bo=({schema:e,next:t})=>t(e.element),Vo=({schema:e,next:t})=>t(e._def.innerType),$o={ZodObject:Ko,ZodUnion:It,ZodDiscriminatedUnion:It,ZodIntersection:br,ZodEffects:Fo,ZodOptional:xr,ZodNullable:xr,ZodRecord:qo,ZodArray:Bo,ZodDefault:Vo},Je=({subject:e,condition:t,rules:r=$o,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Je({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},We=e=>Je({subject:e,maxDepth:3,rules:{ZodUnion:It,ZodIntersection:br},condition:t=>t instanceof Tr.z.ZodEffects&&t._def.effect.type!=="refinement"}),Sr=e=>Je({subject:e,condition:t=>Ct(t,ve)}),Or=e=>Je({subject:e,condition:t=>Ct(t,oe),maxDepth:3});var Xe=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
- Original error: ${e.originalError.message}.`:""))};var Ar=require("ramda");var ne=e=>D(e)&&"or"in e,ge=e=>D(e)&&"and"in e,Et=e=>({and:(0,Ar.chain)(t=>ge(t)?t.and:[t],e)}),et=(e,t)=>ge(e)?{and:e.and.map(r=>ne(r)?{or:r.or.map(t)}:t(r))}:ne(e)?{or:e.or.map(r=>ge(r)?{and:r.and.map(t)}:t(r))}:t(e),Zt=e=>e.and.reduce((t,r)=>({or:te(t.or,ne(r)?r.or:[r],Et)}),{or:[]}),ye=(e,t)=>ge(e)?ne(t)?ye(Zt(e),t):Et([e,t]):ne(e)?ge(t)?ye(t,e):ne(t)?{or:te(e.or,t.or,Et)}:ye(e,{and:[t]}):ge(t)||ne(t)?ye(t,e):{and:[e,t]};var ie=class{},rt=class extends ie{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#m;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:u,shortDescription:l}){super(),this.#a=i,this.#p=s,this.#n=d,this.#m=a,this.#o=t,this.#d=p,this.#c=c,this.#e={long:u,short:l},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,zt.default)(!We(T),new V(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:Tt(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[me.positive]}),negative:Tt(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[me.negative]})};for(let[y,T]of Object.entries(this.#t))(0,zt.default)(T.length,new X(`ResultHandler must have at least one ${y} response schema specified.`));this.#i=Sr(r)?"upload":Or(r)?"raw":"json",this.#s={input:[N[this.#i]],positive:this.#t.positive.flatMap(({mimeTypes:y})=>y),negative:this.#t.negative.flatMap(({mimeTypes:y})=>y)}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ye(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#m(t)}#l(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof tt.z.ZodError?new $(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof tt.z.ZodError?new H(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof tt.z.ZodError?new H(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Xe({logger:i,response:o,error:new X(ue(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=St(t),p={},d=null,c=null;if(i.cors){let l=this.#l(s);typeof i.cors=="function"&&(l=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let y in l)r.set(y,l[y])}let u=dr(t,i.inputSources);try{if(await this.#f({method:a,input:u,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:u,logger:o,options:p}))}catch(l){c=ue(l)}await this.#g({input:u,output:d,request:t,response:r,error:c,logger:o,options:p})}};var wt=require("zod");var Rr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>mr(s,i),o)};var Pr=S(require("assert/strict"),1),ot=e=>((0,Pr.default)(!We(e.input),new V("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var k=require("zod");var nt=e=>e,he=nt({getPositiveResponse:e=>{let t=F({schema:e}),r=k.z.object({status:k.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>k.z.object({status:k.z.literal("error"),error:k.z.object({message:k.z.string()})}).example({status:"error",error:{message:K(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(me.positive).json({status:"success",data:r});return}let a=Me(e);At({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:K(e)}})}}),it=nt({getPositiveResponse:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.z.ZodArray?e.shape.items:k.z.array(k.z.any());return t.reduce((o,i)=>D(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>k.z.string().example(K(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Me(r);At({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(me.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var xe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:wt.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,l=>{if(l&&l instanceof Error)return c(o(l));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ot({input:wt.z.object({}),middleware:typeof t=="function"?t:async({logger:r})=>(r.warn("addOptions: Static options are deprecated. Replace with async function or just import the const."),t)})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,u="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,y="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],T="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new rt({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:y,tags:T,methods:u,getOperationId:l,description:i,shortDescription:s,inputSchema:Rr(d,t)})}},Cr=new xe(he),Ir=new xe(it);var Er=require("util");var Zr=require("ramda"),L=require("ansis"),Mt={debug:10,info:20,warn:30,error:40},zr=e=>D(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),st=({level:e,color:t=new L.Ansis().isSupported(),depth:r=2})=>{let o={debug:L.blue,info:L.green,warn:(0,L.hex)("#FFA500"),error:L.red},i=e==="debug",s=e==="silent"?100:Mt[e],a=(p,d,c)=>{if(Mt[p]<s)return;let u=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&u.push((0,Er.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Zr.mapObjIndexed)(({},p)=>(d,c)=>a(p,d,c),Mt)};var be=require("ramda"),Te=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=(0,be.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=(0,be.head)(this.pairs)?.[1],this.siblingMethods=(0,be.tail)(this.pairs).map(([r])=>r)}};var wr=S(require("express"),1),Se=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,wr.default.static(...this.params))}};var Dt=S(require("express"),1),jr=S(require("http"),1),Ur=S(require("https"),1);var Oe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ee(e)},Mr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await Oe(t,r)}catch{}throw new ee(e.map(({moduleName:t})=>t))};var Nt=S(require("assert/strict"),1);var se=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){Nt.default.doesNotMatch(a,/\//,new W(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ie){let c=p.getMethods().slice();i&&c.push("options");for(let u of c)t(p,d,u)}else if(p instanceof Se)r&&p.apply(d,r);else if(p instanceof Te){for(let[c,u]of p.pairs)(0,Nt.default)(u.getMethods().includes(c),new W(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(u,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else se({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var vt=({app:e,rootLogger:t,config:r,routing:o})=>se({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let u=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;u.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:u,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}});var De=S(require("http-errors"),1);var Nr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:(0,De.isHttpError)(o)?o:(0,De.default)(400,ue(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},vr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=(0,De.default)(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Xe({response:i,logger:a,error:new X(ue(p).message,s)})}},Dr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},kr=e=>({log:(t,...r)=>{/not eligible/.test(t)||e.debug(t,...r)}});var z=require("ansis"),Lr=()=>{let e=(0,z.italic)("Proudly supports transgender community.".padStart(109)),t=(0,z.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,z.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,z.italic)("for Victoria".padEnd(20)),i=(0,z.hex)("#F5A9B8"),s=(0,z.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(z.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(z.gray,12,13);return`
4
+ `,{url:t.url,payload:r})},F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=re(e,"examples")||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},te=(e,t,r)=>e.length&&t.length?(0,le.xprod)(e,t).map(r):e.concat(t),Ne=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Pt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),v=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(Pt).join(""),$e=e=>(0,ar.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),_e=(e,t)=>{try{return typeof e.parse(t)}catch{return}},D=e=>typeof e=="object"&&e!==null;var Ct=require("zod"),Ge=require("ramda"),I=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[I]=(0,Ge.clone)(t._def[I])||{examples:[]},t},Lo=function(e){let t=Ye(this);return t._def[I].examples.push(e),t},jo=function(e){let t=Ye(this);return t._def[I].defaultLabel=e,t};I in globalThis||(globalThis[I]=!0,Object.defineProperty(Ct.z.ZodType.prototype,"example",{get(){return Lo.bind(this)}}),Object.defineProperty(Ct.z.ZodDefault.prototype,"label",{get(){return jo.bind(this)}}));var cr=e=>I in e._def&&D(e._def[I]),re=(e,t)=>cr(e)?e._def[I][t]:void 0,mr=(e,t)=>{if(!cr(e))return t;let r=Ye(t);return r._def[I].examples=te(r._def[I].examples,e._def[I].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,Ge.mergeDeepRight)({...o},{...i}):i),r},E=(e,t)=>{let r=Ye(t);return r._def[I].kind=e,r},It=(e,t)=>re(e,"kind")===t,lr=e=>e;var fr=require("zod");var fe=require("zod");var _="File",ur=fe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Uo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ho={buffer:()=>E(_,ur),string:()=>E(_,fe.z.string()),binary:()=>E(_,ur.or(fe.z.string())),base64:()=>{let e=fe.z.string(),t=e.base64?.()instanceof fe.z.ZodString;return E(_,t?e.base64():e.regex(Uo,"Does not match base64 encoding"))}};function Qe(e){return Ho[e||"string"]()}var oe="Raw",yr=()=>E(oe,fr.z.object({raw:Qe("buffer")}));var gr=require("zod");var ve="Upload",hr=()=>E(ve,gr.z.custom(e=>typeof e=="object"&&e!==null&&"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&&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",e=>({message:`Expected file upload, received ${typeof e}`})));var Et=({schema:{options:e},next:t})=>e.some(t),br=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),Ko=({schema:e,next:t})=>Object.values(e.shape).some(t),xr=({schema:e,next:t})=>t(e.unwrap()),Fo=({schema:e,next:t})=>t(e.innerType()),qo=({schema:e,next:t})=>t(e.valueSchema),Bo=({schema:e,next:t})=>t(e.element),Vo=({schema:e,next:t})=>t(e._def.innerType),$o={ZodObject:Ko,ZodUnion:Et,ZodDiscriminatedUnion:Et,ZodIntersection:br,ZodEffects:Fo,ZodOptional:xr,ZodNullable:xr,ZodRecord:qo,ZodArray:Bo,ZodDefault:Vo},Je=({subject:e,condition:t,rules:r=$o,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Je({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},We=e=>Je({subject:e,maxDepth:3,rules:{ZodUnion:Et,ZodIntersection:br},condition:t=>t instanceof Tr.z.ZodEffects&&t._def.effect.type!=="refinement"}),Sr=e=>Je({subject:e,condition:t=>It(t,ve)}),Or=e=>Je({subject:e,condition:t=>It(t,oe),maxDepth:3});var Xe=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
+ Original error: ${e.originalError.message}.`:""))};var Ar=require("ramda");var ne=e=>D(e)&&"or"in e,ge=e=>D(e)&&"and"in e,Zt=e=>({and:(0,Ar.chain)(t=>ge(t)?t.and:[t],e)}),et=(e,t)=>ge(e)?{and:e.and.map(r=>ne(r)?{or:r.or.map(t)}:t(r))}:ne(e)?{or:e.or.map(r=>ge(r)?{and:r.and.map(t)}:t(r))}:t(e),zt=e=>e.and.reduce((t,r)=>({or:te(t.or,ne(r)?r.or:[r],Zt)}),{or:[]}),ye=(e,t)=>ge(e)?ne(t)?ye(zt(e),t):Zt([e,t]):ne(e)?ge(t)?ye(t,e):ne(t)?{or:te(e.or,t.or,Zt)}:ye(e,{and:[t]}):ge(t)||ne(t)?ye(t,e):{and:[e,t]};var ie=class{},rt=class extends ie{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#m;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:u,shortDescription:l}){super(),this.#a=i,this.#p=s,this.#n=d,this.#m=a,this.#o=t,this.#d=p,this.#c=c,this.#e={long:u,short:l},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,wt.default)(!We(T),new V(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:bt(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[me.positive]}),negative:bt(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[me.negative]})};for(let[y,T]of Object.entries(this.#t))(0,wt.default)(T.length,new X(`ResultHandler must have at least one ${y} response schema specified.`));this.#i=Sr(r)?"upload":Or(r)?"raw":"json",this.#s={input:[N[this.#i]],positive:this.#t.positive.flatMap(({mimeTypes:y})=>y),negative:this.#t.negative.flatMap(({mimeTypes:y})=>y)}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ye(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#m(t)}#l(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof tt.z.ZodError?new $(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof tt.z.ZodError?new H(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof tt.z.ZodError?new H(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Xe({logger:i,response:o,error:new X(ue(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=Ot(t),p={},d=null,c=null;if(i.cors){let l=this.#l(s);typeof i.cors=="function"&&(l=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let y in l)r.set(y,l[y])}let u=dr(t,i.inputSources);try{if(await this.#f({method:a,input:u,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:u,logger:o,options:p}))}catch(l){c=ue(l)}await this.#g({input:u,output:d,request:t,response:r,error:c,logger:o,options:p})}};var Mt=require("zod");var Rr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>mr(s,i),o)};var Pr=S(require("assert/strict"),1),ot=e=>((0,Pr.default)(!We(e.input),new V("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var k=require("zod");var nt=e=>e,he=nt({getPositiveResponse:e=>{let t=F({schema:e}),r=k.z.object({status:k.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>k.z.object({status:k.z.literal("error"),error:k.z.object({message:k.z.string()})}).example({status:"error",error:{message:K(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(me.positive).json({status:"success",data:r});return}let a=Me(e);Rt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:K(e)}})}}),it=nt({getPositiveResponse:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.z.ZodArray?e.shape.items:k.z.array(k.z.any());return t.reduce((o,i)=>D(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>k.z.string().example(K(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Me(r);Rt({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(me.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var xe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:Mt.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,l=>{if(l&&l instanceof Error)return c(o(l));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ot({input:Mt.z.object({}),middleware:typeof t=="function"?t:async({logger:r})=>(r.warn("addOptions: Static options are deprecated. Replace with async function or just import the const."),t)})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,u="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,y="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],T="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new rt({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:y,tags:T,methods:u,getOperationId:l,description:i,shortDescription:s,inputSchema:Rr(d,t)})}},Cr=new xe(he),Ir=new xe(it);var Er=require("util");var Zr=require("ramda"),L=require("ansis"),st={debug:10,info:20,warn:30,error:40},zr=e=>D(e)&&Object.keys(st).some(t=>t in e),at=({level:e,color:t=new L.Ansis().isSupported(),depth:r=2})=>{let o={debug:L.blue,info:L.green,warn:(0,L.hex)("#FFA500"),error:L.red},i=e==="debug",s=e==="silent"?100:st[e],a=(p,d,c)=>{if(st[p]<s)return;let u=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&u.push((0,Er.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Zr.mapObjIndexed)(({},p)=>(d,c)=>a(p,d,c),st)};var be=require("ramda"),Te=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=(0,be.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=(0,be.head)(this.pairs)?.[1],this.siblingMethods=(0,be.tail)(this.pairs).map(([r])=>r)}};var wr=S(require("express"),1),Se=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,wr.default.static(...this.params))}};var Dt=S(require("express"),1),jr=S(require("http"),1),Ur=S(require("https"),1);var Oe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ee(e)},Mr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await Oe(t,r)}catch{}throw new ee(e.map(({moduleName:t})=>t))};var Nt=S(require("assert/strict"),1);var se=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){Nt.default.doesNotMatch(a,/\//,new W(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ie){let c=p.getMethods().slice();i&&c.push("options");for(let u of c)t(p,d,u)}else if(p instanceof Se)r&&p.apply(d,r);else if(p instanceof Te){for(let[c,u]of p.pairs)(0,Nt.default)(u.getMethods().includes(c),new W(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(u,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else se({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var vt=({app:e,rootLogger:t,config:r,routing:o})=>se({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let u=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;u.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:u,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}});var De=S(require("http-errors"),1);var Nr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:(0,De.isHttpError)(o)?o:(0,De.default)(400,ue(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},vr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=(0,De.default)(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Xe({response:i,logger:a,error:new X(ue(p).message,s)})}},Dr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},kr=e=>({log:(t,...r)=>{/not eligible/.test(t)||e.debug(t,...r)}});var z=require("ansis"),Lr=()=>{let e=(0,z.italic)("Proudly supports transgender community.".padStart(109)),t=(0,z.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,z.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,z.italic)("for Victoria".padEnd(20)),i=(0,z.hex)("#F5A9B8"),s=(0,z.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(z.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(z.gray,12,13);return`
6
6
  8888888888 8888888888P 888 d8888 8888888b. 8888888
7
7
  888 d88P 888 d88888 888 Y88b 888
8
8
  888 d88P 888 d88P888 888 888 888
@@ -17,7 +17,7 @@ ${o}888${t}
17
17
  ${r}
18
18
  `.split(`
19
19
  `).map((d,c)=>a[c]?a[c](d):d).join(`
20
- `)};var Hr=e=>{e.startupLogo!==!1&&console.log(Lr());let t=zr(e.logger)?st(e.logger):e.logger;t.debug("Running","v18.6.2 (CJS)");let r=e.errorHandler||he,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=vr(i),a=Nr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=Hr(e);return vt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Fr=async(e,t)=>{let r=(0,Dt.default)().disable("x-powered-by");if(e.server.compression){let d=await Oe("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||Dt.default.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=Hr(e);if(e.server.upload){let d=await Oe("express-fileupload"),{limitError:c,beforeUpload:u,...l}={...typeof e.server.upload=="object"&&e.server.upload};u&&u({app:r,logger:o}),r.use(d({...l,abortOnLimit:!1,parseNested:!0,logger:kr(o)})),c&&r.use(Dr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),vt({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(jr.default.createServer(r),e.server.listen),httpsServer:e.https?a(Ur.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};var po=S(require("assert/strict"),1),co=require("openapi3-ts/oas31");var q=S(require("assert/strict"),1),G=require("openapi3-ts/oas31"),m=require("ramda"),x=require("zod");var ke=require("zod");var at=e=>!isNaN(e.getTime()),pt=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Le="DateIn",qr=()=>{let e=ke.z.string(),r=e.date?.()instanceof ke.z.ZodString?ke.z.union([e.date(),e.datetime(),e.datetime({local:!0})]):e.regex(pt);return E(Le,r.transform(o=>new Date(o)).pipe(ke.z.date().refine(at)))};var Br=require("zod");var je="DateOut",Vr=()=>E(je,Br.z.date().refine(at).transform(e=>e.toISOString()));var ae=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=re(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:l=>ae({schema:l,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),u=t&&t({schema:e,prev:c,...p});return u?{...c,...u}:c};var $r=50,Gr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",_o={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Yr=/:([A-Za-z0-9_]+)/g,Qr=e=>e.match(Yr)?.map(t=>t.slice(1))||[],Jr=e=>e.replace(Yr,t=>`{${t.slice(1)}}`),Go=({schema:e,next:t})=>({...t(e._def.innerType),default:re(e,"defaultLabel")||e._def.defaultValue()}),Yo=({schema:{_def:{innerType:e}},next:t})=>t(e),Qo=()=>({format:"any"}),Jo=e=>((0,q.default)(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Wo=({schema:e})=>({type:"string",format:e instanceof x.z.ZodString?e._def.checks.find(t=>t.kind==="regex"||t.kind==="base64")?"byte":"file":"binary"}),Xo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),en=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),tn=e=>{let[t,r]=e.filter(i=>!(0,G.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,m.concat)(i,s):i===s?s:q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=te(t.examples||[],r.examples||[],([i,s])=>(0,m.mergeDeepRight)(i,s))),o},rn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return tn(o)}catch{}return{allOf:o}},on=({schema:e,next:t})=>t(e.unwrap()),nn=({schema:e,next:t})=>t(e._def.innerType),sn=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,G.isReferenceObject)(r)||(r.type=Xr(r)),r},Wr=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},_r=({schema:e})=>({type:Wr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),an=({schema:{value:e}})=>({type:Wr(e),const:e}),pn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ne(p)?p instanceof x.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=dt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},dn=()=>({type:"null"}),cn=e=>((0,q.default)(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:pt.source,externalDocs:{url:Gr}}),mn=e=>((0,q.default)(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Gr}}),ln=e=>q.default.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),un=()=>({type:"boolean"}),fn=()=>({type:"integer",format:"bigint"}),yn=e=>e.every(t=>t instanceof x.z.ZodLiteral),gn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.z.ZodEnum||e instanceof x.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=dt({schema:x.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof x.z.ZodLiteral)return{type:"object",properties:dt({schema:x.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.z.ZodUnion&&yn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),i=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:dt({schema:x.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},hn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},xn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Tn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:u,_def:{checks:l}}})=>{let y=l.find(O=>O.kind==="regex"),T=l.find(O=>O.kind==="datetime"),b=y?y.regex:T?T.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,A={type:"string"},h={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let O in h)if(h[O]){A.format=O;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),b&&(A.pattern=b.source),A},bn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},dt=({schema:{shape:e},next:t})=>(0,m.map)(t,e),Sn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return _o?.[t]},Xr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},On=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,G.isReferenceObject)(o)){let s=_e(e,Sn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(x.z.any())}if(!t&&i.type==="preprocess"&&!(0,G.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},An=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Rn=({schema:e,next:t})=>t(e.unwrap()),Pn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},Cn=({next:e,schema:t})=>e(t.shape.raw),eo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.range)(1,e.length+1).map(t=>`example${t}`),(0,m.map)((0,m.objOf)("value"),e))):void 0,to=(e,t,r=[])=>(0,m.pipe)(F,(0,m.map)((0,m.when)((0,m.both)(D,(0,m.complement)(Array.isArray)),(0,m.omit)(r))),eo)({schema:e,variant:t?"parsed":"original",validate:!0}),In=(e,t)=>(0,m.pipe)(F,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),eo)({schema:e,variant:"original",validate:!0}),Ue=(e,t)=>e instanceof x.z.ZodObject?e:e instanceof x.z.ZodUnion||e instanceof x.z.ZodDiscriminatedUnion?e.options.map(r=>Ue(r,t)).reduce((r,o)=>r.merge(o.partial()),x.z.object({})):e instanceof x.z.ZodEffects?((0,q.default)(e._def.effect.type==="refinement",t),Ue(e._def.schema,t)):Ue(e._def.left,t).merge(Ue(e._def.right,t)),ro=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=Ue(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=Qr(e),l=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),b=h=>y&&u.includes(h),A=h=>T&&Ot(h);return Object.keys(c).filter(h=>l||b(h)).map(h=>{let O=ae({schema:c[h],isResponse:!1,rules:Lt,onEach:jt,onMissing:Ut,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Ce=p==="components"?a(v(d,h),O):O;return{name:h,in:b(h)?"path":A(h)?"header":"query",required:!c[h].isOptional(),description:O.description||d,schema:Ce,examples:In(r,h)}})},Lt={ZodString:Tn,ZodNumber:bn,ZodBigInt:fn,ZodBoolean:un,ZodNull:dn,ZodArray:hn,ZodTuple:xn,ZodRecord:gn,ZodObject:pn,ZodLiteral:an,ZodIntersection:rn,ZodUnion:Xo,ZodAny:Qo,ZodDefault:Go,ZodEnum:_r,ZodNativeEnum:_r,ZodEffects:On,ZodOptional:on,ZodNullable:sn,ZodDiscriminatedUnion:en,ZodBranded:Rn,ZodDate:ln,ZodCatch:Yo,ZodPipeline:An,ZodLazy:Pn,ZodReadonly:nn,[_]:Wo,[ve]:Jo,[je]:mn,[Le]:cn,[oe]:Cn},jt=({schema:e,isResponse:t,prev:r})=>{if((0,G.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof x.z.ZodLazy,s=r.type!==void 0,a=t&&Ne(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Xr(r)),d.length&&(c.examples=d.slice()),c},Ut=({schema:e,...t})=>q.default.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),kt=(e,t)=>{if((0,G.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>kt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>kt(o,t))),r},oo=e=>(0,G.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),no=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:u,description:l=`${e.toUpperCase()} ${t} ${Rt(i)} response ${c?u:""}`.trim()})=>{let y=oo(ae({schema:r,isResponse:!0,rules:Lt,onEach:jt,onMissing:Ut,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(v(l),y):y,examples:to(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[T]))}},En=()=>({type:"http",scheme:"basic"}),Zn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},zn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},wn=({name:e})=>({type:"apiKey",in:"header",name:e}),Mn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Nn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),vn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),io=(e,t)=>{let r={basic:En,bearer:Zn,input:zn,header:wn,cookie:Mn,openid:Nn,oauth2:vn};return et(e,o=>r[o.type](o,t))},ct=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?ct(Zt(e)):ct({or:[e]}),so=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Qr(t),u=oo(kt(ae({schema:r,isResponse:!1,rules:Lt,onEach:jt,onMissing:Ut,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(v(d),u):u,examples:to(r,!1,c)};return{description:d,content:(0,m.fromPairs)((0,m.xprod)(o,[l]))}},ao=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Ht=e=>e.length<=$r?e:e.slice(0,$r-1)+"\u2026";var mt=class extends co.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||v(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&po.default.fail(new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=$e}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});se({routing:t,onEndpoint:(l,y,T)=>{let b=T,A={path:y,method:b,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,O]=["short","long"].map(l.getDescription.bind(l)),Ce=h?Ht(h):p&&O?Ht(O):void 0,Ke=l.getTags(),Ie=r.inputSources?.[b]||bt[b],de=this.ensureUniqOperationId(y,b,l.getOperationId(b)),Fe=ro({...A,inputSources:Ie,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:y,operationId:de})}),qe={};for(let U of["positive","negative"]){let J=l.getResponses(U);for(let{mimeTypes:Ee,schema:R,statusCodes:P}of J)for(let Z of P)qe[Z]=no({...A,variant:U,schema:R,mimeTypes:Ee,statusCode:Z,hasMultipleStatusCodes:J.length>1||P.length>1,description:a?.[`${U}Response`]?.call(null,{method:b,path:y,operationId:de,statusCode:Z})})}let xt=Ie.includes("body")?so({...A,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:y,operationId:de})}):void 0,Be=ct(et(io(l.getSecurity(),Ie),U=>{let J=this.ensureUniqSecuritySchemaName(U),Ee=["oauth2","openIdConnect"].includes(U.type)?l.getScopes():[];return this.addSecurityScheme(J,U),{name:J,scopes:Ee}}));this.addPath(Jr(y),{[b]:{operationId:de,summary:Ce,description:O,tags:Ke.length>0?Ke:void 0,parameters:Fe.length>0?Fe:void 0,requestBody:xt,security:Be.length>0?Be:void 0,responses:qe}})}}),this.rootDoc.tags=r.tags?ao(r.tags):[]}};var Kt=S(require("http"),1);var Dn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),kn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},Ln=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),mo=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Mr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Dn({fnMethod:a,requestProps:t}),d=kn({fnMethod:a,responseProps:r}),c=Ln({fnMethod:a,loggerProps:i}),u={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:u,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};var w=S(require("typescript"),1);var j=S(require("typescript"),1),Ae=require("ramda"),n=j.default.factory,Y=[n.createModifier(j.default.SyntaxKind.ExportKeyword)],jn=[n.createModifier(j.default.SyntaxKind.AsyncKeyword)],Un=[n.createModifier(j.default.SyntaxKind.PublicKeyword),n.createModifier(j.default.SyntaxKind.ReadonlyKeyword)],lo=[n.createModifier(j.default.SyntaxKind.ProtectedKeyword),n.createModifier(j.default.SyntaxKind.ReadonlyKeyword)],Ft=n.createTemplateHead(""),Re=n.createTemplateTail(""),qt=n.createTemplateMiddle(" "),Bt=e=>n.createTemplateLiteralType(Ft,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Re:qt))),Vt=Bt(["M","P"]),lt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ut=(e,t)=>(0,Ae.chain)(([r,o])=>[lt(n.createIdentifier(r),o,t)],(0,Ae.toPairs)(e)),$t=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),uo=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),fo=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Q=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],j.default.NodeFlags.Const),_t=(e,t)=>n.createTypeAliasDeclaration(Y,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ft=(e,t)=>n.createTypeAliasDeclaration(Y,e,void 0,t),yo=(e,t,r)=>n.createPropertyDeclaration(Un,e,void 0,t,r),go=(e,t,r)=>n.createClassDeclaration(Y,e,void 0,void 0,[t,...r]),ho=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),xo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(j.default.SyntaxKind.AnyKeyword)]),To=(e,t,r)=>n.createInterfaceDeclaration(Y,e,void 0,t,r),bo=e=>(0,Ae.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Ae.toPairs)(e)),Gt=(e,t,r)=>n.createArrowFunction(r?jn:void 0,void 0,e.map(o=>lt(o)),void 0,void 0,t),Yt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,ut({acc:void 0,key:void 0}),void 0,void 0,t),r]),So=(...e)=>`"${e.join(" ")}"`;var Oo=["get","post","put","delete","patch"];var g=S(require("typescript"),1),gt=require("zod");var B=S(require("typescript"),1),{factory:yt}=B.default,Qt=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Pe=(e,t,r)=>{let o=yt.createTypeAliasDeclaration(void 0,yt.createIdentifier(t),void 0,e);return r&&Qt(o,r),o},Jt=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},Hn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ao=e=>Hn.test(e)?yt.createIdentifier(e):yt.createStringLiteral(e);var{factory:f}=g.default,Kn={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Fn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),qn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ne(a)?a instanceof gt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,Ao(s),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Qt(d,a.description),d});return f.createTypeLiteralNode(i)},Bn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Vn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Ro=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),$n=e=>Kn?.[e.kind],_n=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=_e(e,$n(o)),a={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||g.default.SyntaxKind.AnyKeyword)}return o},Gn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Yn=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Qn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Jn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Wn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Xn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ei=({next:e,schema:t})=>e(t._def.innerType),pe=e=>()=>f.createKeywordTypeNode(e),ti=({next:e,schema:t})=>e(t.unwrap()),ri=({next:e,schema:t})=>e(t._def.innerType),oi=({next:e,schema:t})=>e(t._def.innerType),ni=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),ii=()=>f.createLiteralTypeNode(f.createNull()),si=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},ai=({schema:e})=>{let t=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),r=f.createTypeReferenceNode("Buffer"),o=f.createUnionTypeNode([t,r]);return e instanceof gt.z.ZodString?t:e instanceof gt.z.ZodUnion?o:r},pi=({next:e,schema:t})=>e(t.shape.raw),di={ZodString:pe(g.default.SyntaxKind.StringKeyword),ZodNumber:pe(g.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(g.default.SyntaxKind.BooleanKeyword),ZodAny:pe(g.default.SyntaxKind.AnyKeyword),[Le]:pe(g.default.SyntaxKind.StringKeyword),[je]:pe(g.default.SyntaxKind.StringKeyword),ZodNull:ii,ZodArray:Bn,ZodTuple:Jn,ZodRecord:Wn,ZodObject:qn,ZodLiteral:Fn,ZodIntersection:Xn,ZodUnion:Ro,ZodDefault:ei,ZodEnum:Vn,ZodNativeEnum:Gn,ZodEffects:_n,ZodOptional:Yn,ZodNullable:Qn,ZodDiscriminatedUnion:Ro,ZodBranded:ti,ZodCatch:oi,ZodPipeline:ni,ZodLazy:si,ZodReadonly:ri,[_]:ai,[oe]:pi},He=({schema:e,...t})=>ae({schema:e,rules:di,onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),...t});var ht=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Pe(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=$e,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){se({routing:t,onEndpoint:(R,P,Z)=>{let ce={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},Ze=v(Z,P,"input"),ze=He({...ce,schema:R.getSchema("input"),isResponse:!1}),M=i?v(Z,P,"positive.response"):void 0,Wt=R.getSchema("positive"),Xt=i?He({...ce,isResponse:!0,schema:Wt}):void 0,we=i?v(Z,P,"negative.response"):void 0,er=R.getSchema("negative"),tr=i?He({...ce,isResponse:!0,schema:er}):void 0,rr=v(Z,P,"response"),Co=M&&we?n.createUnionTypeNode([n.createTypeReferenceNode(M),n.createTypeReferenceNode(we)]):He({...ce,isResponse:!0,schema:Wt.or(er)});this.program.push(Pe(ze,Ze)),Xt&&M&&this.program.push(Pe(Xt,M)),tr&&we&&this.program.push(Pe(tr,we)),this.program.push(Pe(Co,rr)),Z!=="options"&&(this.paths.push(P),this.registry.set({method:Z,path:P},{input:Ze,positive:M,negative:we,response:rr,isJson:R.getMimeTypes("positive").includes(N.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(_t(this.ids.pathType,this.paths)),this.program.push(_t(this.ids.methodType,Oo)),this.program.push(ft(this.ids.methodPathType,Bt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.default.SyntaxKind.ExtendsKeyword,[$t(this.ids.methodPathType,w.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:R,path:P},{isJson:Z,tags:ce,...Ze}]of this.registry){let ze=So(R,P);for(let M of this.interfaces)M.kind in Ze&&M.props.push(fo(ze,Ze[M.kind]));r!=="types"&&(Z&&p.push(n.createPropertyAssignment(ze,n.createTrue())),d.push(n.createPropertyAssignment(ze,n.createArrayLiteralExpression(ce.map(M=>n.createStringLiteral(M))))))}for(let{id:R,props:P}of this.interfaces)this.program.push(To(R,a,P));if(r==="types")return;let c=n.createVariableStatement(Y,Q(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),u=n.createVariableStatement(Y,Q(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),l=ft(this.ids.providerType,n.createFunctionTypeNode(bo({M:this.ids.methodType,P:this.ids.pathType}),ut({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Vt)}),ho(this.ids.responseInterface,Vt))),y=ft(this.ids.implementationType,n.createFunctionTypeNode(void 0,ut({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.default.SyntaxKind.StringKeyword),params:$t(w.default.SyntaxKind.StringKeyword,w.default.SyntaxKind.AnyKeyword)}),xo())),T=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Re)]),b=Yt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[T,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),A=Yt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[T]),w.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),h=go(this.ids.clientClass,uo([lt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),lo)]),[yo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Gt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,A]),!0))]);this.program.push(c,u,l,y,h);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ce=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),Ke=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),Ie=n.createVariableStatement(void 0,Q(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Re)]),n.createObjectLiteralExpression([O,Ce,Ke])])))),de=n.createVariableStatement(void 0,Q(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Fe=n.createVariableStatement(void 0,Q(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Re)])))),[qe,xt]=["json","text"].map(R=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Be=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ft,[n.createTemplateSpan(this.ids.methodParameter,qt),n.createTemplateSpan(this.ids.pathParameter,Re)]),w.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([qe])),U=n.createVariableStatement(Y,Q(this.ids.exampleImplementationConst,Gt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([de,Fe,Ie,Be,xt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),J=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Ee=n.createVariableStatement(void 0,Q(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(U,Ee,J)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Jt(r,t)).join(`
20
+ `)};var Hr=e=>{e.startupLogo!==!1&&console.log(Lr());let t=zr(e.logger)?e.logger:at(e.logger);t.debug("Running","v18.6.3 (CJS)");let r=e.errorHandler||he,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=vr(i),a=Nr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=Hr(e);return vt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Fr=async(e,t)=>{let r=(0,Dt.default)().disable("x-powered-by");if(e.server.compression){let d=await Oe("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||Dt.default.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=Hr(e);if(e.server.upload){let d=await Oe("express-fileupload"),{limitError:c,beforeUpload:u,...l}={...typeof e.server.upload=="object"&&e.server.upload};u&&u({app:r,logger:o}),r.use(d({...l,abortOnLimit:!1,parseNested:!0,logger:kr(o)})),c&&r.use(Dr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),vt({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(jr.default.createServer(r),e.server.listen),httpsServer:e.https?a(Ur.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};var po=S(require("assert/strict"),1),co=require("openapi3-ts/oas31");var q=S(require("assert/strict"),1),G=require("openapi3-ts/oas31"),m=require("ramda"),x=require("zod");var ke=require("zod");var pt=e=>!isNaN(e.getTime()),dt=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Le="DateIn",qr=()=>{let e=ke.z.string(),r=e.date?.()instanceof ke.z.ZodString?ke.z.union([e.date(),e.datetime(),e.datetime({local:!0})]):e.regex(dt);return E(Le,r.transform(o=>new Date(o)).pipe(ke.z.date().refine(pt)))};var Br=require("zod");var je="DateOut",Vr=()=>E(je,Br.z.date().refine(pt).transform(e=>e.toISOString()));var ae=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=re(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:l=>ae({schema:l,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),u=t&&t({schema:e,prev:c,...p});return u?{...c,...u}:c};var $r=50,Gr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",_o={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Yr=/:([A-Za-z0-9_]+)/g,Qr=e=>e.match(Yr)?.map(t=>t.slice(1))||[],Jr=e=>e.replace(Yr,t=>`{${t.slice(1)}}`),Go=({schema:e,next:t})=>({...t(e._def.innerType),default:re(e,"defaultLabel")||e._def.defaultValue()}),Yo=({schema:{_def:{innerType:e}},next:t})=>t(e),Qo=()=>({format:"any"}),Jo=e=>((0,q.default)(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Wo=({schema:e})=>({type:"string",format:e instanceof x.z.ZodString?e._def.checks.find(t=>t.kind==="regex"||t.kind==="base64")?"byte":"file":"binary"}),Xo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),en=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),tn=e=>{let[t,r]=e.filter(i=>!(0,G.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,m.concat)(i,s):i===s?s:q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=te(t.examples||[],r.examples||[],([i,s])=>(0,m.mergeDeepRight)(i,s))),o},rn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return tn(o)}catch{}return{allOf:o}},on=({schema:e,next:t})=>t(e.unwrap()),nn=({schema:e,next:t})=>t(e._def.innerType),sn=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,G.isReferenceObject)(r)||(r.type=Xr(r)),r},Wr=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},_r=({schema:e})=>({type:Wr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),an=({schema:{value:e}})=>({type:Wr(e),const:e}),pn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ne(p)?p instanceof x.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=ct({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},dn=()=>({type:"null"}),cn=e=>((0,q.default)(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:dt.source,externalDocs:{url:Gr}}),mn=e=>((0,q.default)(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Gr}}),ln=e=>q.default.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),un=()=>({type:"boolean"}),fn=()=>({type:"integer",format:"bigint"}),yn=e=>e.every(t=>t instanceof x.z.ZodLiteral),gn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.z.ZodEnum||e instanceof x.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=ct({schema:x.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof x.z.ZodLiteral)return{type:"object",properties:ct({schema:x.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.z.ZodUnion&&yn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),i=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:ct({schema:x.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},hn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},xn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Tn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:u,_def:{checks:l}}})=>{let y=l.find(O=>O.kind==="regex"),T=l.find(O=>O.kind==="datetime"),b=y?y.regex:T?T.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,A={type:"string"},h={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let O in h)if(h[O]){A.format=O;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),b&&(A.pattern=b.source),A},bn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},ct=({schema:{shape:e},next:t})=>(0,m.map)(t,e),Sn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return _o?.[t]},Xr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},On=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,G.isReferenceObject)(o)){let s=_e(e,Sn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(x.z.any())}if(!t&&i.type==="preprocess"&&!(0,G.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},An=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Rn=({schema:e,next:t})=>t(e.unwrap()),Pn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},Cn=({next:e,schema:t})=>e(t.shape.raw),eo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.range)(1,e.length+1).map(t=>`example${t}`),(0,m.map)((0,m.objOf)("value"),e))):void 0,to=(e,t,r=[])=>(0,m.pipe)(F,(0,m.map)((0,m.when)((0,m.both)(D,(0,m.complement)(Array.isArray)),(0,m.omit)(r))),eo)({schema:e,variant:t?"parsed":"original",validate:!0}),In=(e,t)=>(0,m.pipe)(F,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),eo)({schema:e,variant:"original",validate:!0}),Ue=(e,t)=>e instanceof x.z.ZodObject?e:e instanceof x.z.ZodUnion||e instanceof x.z.ZodDiscriminatedUnion?e.options.map(r=>Ue(r,t)).reduce((r,o)=>r.merge(o.partial()),x.z.object({})):e instanceof x.z.ZodEffects?((0,q.default)(e._def.effect.type==="refinement",t),Ue(e._def.schema,t)):Ue(e._def.left,t).merge(Ue(e._def.right,t)),ro=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=Ue(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=Qr(e),l=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),b=h=>y&&u.includes(h),A=h=>T&&At(h);return Object.keys(c).filter(h=>l||b(h)).map(h=>{let O=ae({schema:c[h],isResponse:!1,rules:Lt,onEach:jt,onMissing:Ut,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Ce=p==="components"?a(v(d,h),O):O;return{name:h,in:b(h)?"path":A(h)?"header":"query",required:!c[h].isOptional(),description:O.description||d,schema:Ce,examples:In(r,h)}})},Lt={ZodString:Tn,ZodNumber:bn,ZodBigInt:fn,ZodBoolean:un,ZodNull:dn,ZodArray:hn,ZodTuple:xn,ZodRecord:gn,ZodObject:pn,ZodLiteral:an,ZodIntersection:rn,ZodUnion:Xo,ZodAny:Qo,ZodDefault:Go,ZodEnum:_r,ZodNativeEnum:_r,ZodEffects:On,ZodOptional:on,ZodNullable:sn,ZodDiscriminatedUnion:en,ZodBranded:Rn,ZodDate:ln,ZodCatch:Yo,ZodPipeline:An,ZodLazy:Pn,ZodReadonly:nn,[_]:Wo,[ve]:Jo,[je]:mn,[Le]:cn,[oe]:Cn},jt=({schema:e,isResponse:t,prev:r})=>{if((0,G.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof x.z.ZodLazy,s=r.type!==void 0,a=t&&Ne(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Xr(r)),d.length&&(c.examples=d.slice()),c},Ut=({schema:e,...t})=>q.default.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),kt=(e,t)=>{if((0,G.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>kt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>kt(o,t))),r},oo=e=>(0,G.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),no=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:u,description:l=`${e.toUpperCase()} ${t} ${Pt(i)} response ${c?u:""}`.trim()})=>{let y=oo(ae({schema:r,isResponse:!0,rules:Lt,onEach:jt,onMissing:Ut,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(v(l),y):y,examples:to(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[T]))}},En=()=>({type:"http",scheme:"basic"}),Zn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},zn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},wn=({name:e})=>({type:"apiKey",in:"header",name:e}),Mn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Nn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),vn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),io=(e,t)=>{let r={basic:En,bearer:Zn,input:zn,header:wn,cookie:Mn,openid:Nn,oauth2:vn};return et(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(zt(e)):mt({or:[e]}),so=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Qr(t),u=oo(kt(ae({schema:r,isResponse:!1,rules:Lt,onEach:jt,onMissing:Ut,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(v(d),u):u,examples:to(r,!1,c)};return{description:d,content:(0,m.fromPairs)((0,m.xprod)(o,[l]))}},ao=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Ht=e=>e.length<=$r?e:e.slice(0,$r-1)+"\u2026";var lt=class extends co.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||v(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&po.default.fail(new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=$e}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});se({routing:t,onEndpoint:(l,y,T)=>{let b=T,A={path:y,method:b,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,O]=["short","long"].map(l.getDescription.bind(l)),Ce=h?Ht(h):p&&O?Ht(O):void 0,Ke=l.getTags(),Ie=r.inputSources?.[b]||St[b],de=this.ensureUniqOperationId(y,b,l.getOperationId(b)),Fe=ro({...A,inputSources:Ie,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:y,operationId:de})}),qe={};for(let U of["positive","negative"]){let J=l.getResponses(U);for(let{mimeTypes:Ee,schema:R,statusCodes:P}of J)for(let Z of P)qe[Z]=no({...A,variant:U,schema:R,mimeTypes:Ee,statusCode:Z,hasMultipleStatusCodes:J.length>1||P.length>1,description:a?.[`${U}Response`]?.call(null,{method:b,path:y,operationId:de,statusCode:Z})})}let Tt=Ie.includes("body")?so({...A,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:y,operationId:de})}):void 0,Be=mt(et(io(l.getSecurity(),Ie),U=>{let J=this.ensureUniqSecuritySchemaName(U),Ee=["oauth2","openIdConnect"].includes(U.type)?l.getScopes():[];return this.addSecurityScheme(J,U),{name:J,scopes:Ee}}));this.addPath(Jr(y),{[b]:{operationId:de,summary:Ce,description:O,tags:Ke.length>0?Ke:void 0,parameters:Fe.length>0?Fe:void 0,requestBody:Tt,security:Be.length>0?Be:void 0,responses:qe}})}}),this.rootDoc.tags=r.tags?ao(r.tags):[]}};var Kt=S(require("http"),1);var Dn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),kn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},Ln=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),mo=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Mr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Dn({fnMethod:a,requestProps:t}),d=kn({fnMethod:a,responseProps:r}),c=Ln({fnMethod:a,loggerProps:i}),u={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:u,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};var w=S(require("typescript"),1);var j=S(require("typescript"),1),Ae=require("ramda"),n=j.default.factory,Y=[n.createModifier(j.default.SyntaxKind.ExportKeyword)],jn=[n.createModifier(j.default.SyntaxKind.AsyncKeyword)],Un=[n.createModifier(j.default.SyntaxKind.PublicKeyword),n.createModifier(j.default.SyntaxKind.ReadonlyKeyword)],lo=[n.createModifier(j.default.SyntaxKind.ProtectedKeyword),n.createModifier(j.default.SyntaxKind.ReadonlyKeyword)],Ft=n.createTemplateHead(""),Re=n.createTemplateTail(""),qt=n.createTemplateMiddle(" "),Bt=e=>n.createTemplateLiteralType(Ft,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Re:qt))),Vt=Bt(["M","P"]),ut=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ft=(e,t)=>(0,Ae.chain)(([r,o])=>[ut(n.createIdentifier(r),o,t)],(0,Ae.toPairs)(e)),$t=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),uo=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),fo=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Q=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],j.default.NodeFlags.Const),_t=(e,t)=>n.createTypeAliasDeclaration(Y,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),yt=(e,t)=>n.createTypeAliasDeclaration(Y,e,void 0,t),yo=(e,t,r)=>n.createPropertyDeclaration(Un,e,void 0,t,r),go=(e,t,r)=>n.createClassDeclaration(Y,e,void 0,void 0,[t,...r]),ho=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),xo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(j.default.SyntaxKind.AnyKeyword)]),To=(e,t,r)=>n.createInterfaceDeclaration(Y,e,void 0,t,r),bo=e=>(0,Ae.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Ae.toPairs)(e)),Gt=(e,t,r)=>n.createArrowFunction(r?jn:void 0,void 0,e.map(o=>ut(o)),void 0,void 0,t),Yt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,ft({acc:void 0,key:void 0}),void 0,void 0,t),r]),So=(...e)=>`"${e.join(" ")}"`;var Oo=["get","post","put","delete","patch"];var g=S(require("typescript"),1),ht=require("zod");var B=S(require("typescript"),1),{factory:gt}=B.default,Qt=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Pe=(e,t,r)=>{let o=gt.createTypeAliasDeclaration(void 0,gt.createIdentifier(t),void 0,e);return r&&Qt(o,r),o},Jt=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},Hn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ao=e=>Hn.test(e)?gt.createIdentifier(e):gt.createStringLiteral(e);var{factory:f}=g.default,Kn={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Fn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),qn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ne(a)?a instanceof ht.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,Ao(s),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Qt(d,a.description),d});return f.createTypeLiteralNode(i)},Bn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Vn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Ro=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),$n=e=>Kn?.[e.kind],_n=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=_e(e,$n(o)),a={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||g.default.SyntaxKind.AnyKeyword)}return o},Gn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Yn=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Qn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Jn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Wn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Xn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ei=({next:e,schema:t})=>e(t._def.innerType),pe=e=>()=>f.createKeywordTypeNode(e),ti=({next:e,schema:t})=>e(t.unwrap()),ri=({next:e,schema:t})=>e(t._def.innerType),oi=({next:e,schema:t})=>e(t._def.innerType),ni=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),ii=()=>f.createLiteralTypeNode(f.createNull()),si=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},ai=({schema:e})=>{let t=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),r=f.createTypeReferenceNode("Buffer"),o=f.createUnionTypeNode([t,r]);return e instanceof ht.z.ZodString?t:e instanceof ht.z.ZodUnion?o:r},pi=({next:e,schema:t})=>e(t.shape.raw),di={ZodString:pe(g.default.SyntaxKind.StringKeyword),ZodNumber:pe(g.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(g.default.SyntaxKind.BooleanKeyword),ZodAny:pe(g.default.SyntaxKind.AnyKeyword),[Le]:pe(g.default.SyntaxKind.StringKeyword),[je]:pe(g.default.SyntaxKind.StringKeyword),ZodNull:ii,ZodArray:Bn,ZodTuple:Jn,ZodRecord:Wn,ZodObject:qn,ZodLiteral:Fn,ZodIntersection:Xn,ZodUnion:Ro,ZodDefault:ei,ZodEnum:Vn,ZodNativeEnum:Gn,ZodEffects:_n,ZodOptional:Yn,ZodNullable:Qn,ZodDiscriminatedUnion:Ro,ZodBranded:ti,ZodCatch:oi,ZodPipeline:ni,ZodLazy:si,ZodReadonly:ri,[_]:ai,[oe]:pi},He=({schema:e,...t})=>ae({schema:e,rules:di,onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),...t});var xt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Pe(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=$e,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){se({routing:t,onEndpoint:(R,P,Z)=>{let ce={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},Ze=v(Z,P,"input"),ze=He({...ce,schema:R.getSchema("input"),isResponse:!1}),M=i?v(Z,P,"positive.response"):void 0,Wt=R.getSchema("positive"),Xt=i?He({...ce,isResponse:!0,schema:Wt}):void 0,we=i?v(Z,P,"negative.response"):void 0,er=R.getSchema("negative"),tr=i?He({...ce,isResponse:!0,schema:er}):void 0,rr=v(Z,P,"response"),Co=M&&we?n.createUnionTypeNode([n.createTypeReferenceNode(M),n.createTypeReferenceNode(we)]):He({...ce,isResponse:!0,schema:Wt.or(er)});this.program.push(Pe(ze,Ze)),Xt&&M&&this.program.push(Pe(Xt,M)),tr&&we&&this.program.push(Pe(tr,we)),this.program.push(Pe(Co,rr)),Z!=="options"&&(this.paths.push(P),this.registry.set({method:Z,path:P},{input:Ze,positive:M,negative:we,response:rr,isJson:R.getMimeTypes("positive").includes(N.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(_t(this.ids.pathType,this.paths)),this.program.push(_t(this.ids.methodType,Oo)),this.program.push(yt(this.ids.methodPathType,Bt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.default.SyntaxKind.ExtendsKeyword,[$t(this.ids.methodPathType,w.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:R,path:P},{isJson:Z,tags:ce,...Ze}]of this.registry){let ze=So(R,P);for(let M of this.interfaces)M.kind in Ze&&M.props.push(fo(ze,Ze[M.kind]));r!=="types"&&(Z&&p.push(n.createPropertyAssignment(ze,n.createTrue())),d.push(n.createPropertyAssignment(ze,n.createArrayLiteralExpression(ce.map(M=>n.createStringLiteral(M))))))}for(let{id:R,props:P}of this.interfaces)this.program.push(To(R,a,P));if(r==="types")return;let c=n.createVariableStatement(Y,Q(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),u=n.createVariableStatement(Y,Q(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),l=yt(this.ids.providerType,n.createFunctionTypeNode(bo({M:this.ids.methodType,P:this.ids.pathType}),ft({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Vt)}),ho(this.ids.responseInterface,Vt))),y=yt(this.ids.implementationType,n.createFunctionTypeNode(void 0,ft({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.default.SyntaxKind.StringKeyword),params:$t(w.default.SyntaxKind.StringKeyword,w.default.SyntaxKind.AnyKeyword)}),xo())),T=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Re)]),b=Yt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[T,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),A=Yt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[T]),w.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),h=go(this.ids.clientClass,uo([ut(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),lo)]),[yo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Gt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,A]),!0))]);this.program.push(c,u,l,y,h);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ce=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),Ke=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),Ie=n.createVariableStatement(void 0,Q(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Re)]),n.createObjectLiteralExpression([O,Ce,Ke])])))),de=n.createVariableStatement(void 0,Q(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Fe=n.createVariableStatement(void 0,Q(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Re)])))),[qe,Tt]=["json","text"].map(R=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Be=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ft,[n.createTemplateSpan(this.ids.methodParameter,qt),n.createTemplateSpan(this.ids.pathParameter,Re)]),w.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([qe])),U=n.createVariableStatement(Y,Q(this.ids.exampleImplementationConst,Gt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([de,Fe,Ie,Be,Tt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),J=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Ee=n.createVariableStatement(void 0,Q(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(U,Ee,J)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Jt(r,t)).join(`
21
21
  `):void 0}print(t){let r=this.printUsage(t),o=r&&w.default.addSyntheticLeadingComment(w.default.addSyntheticLeadingComment(n.createEmptyStatement(),w.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),w.default.SyntaxKind.MultiLineCommentTrivia,`
22
22
  ${r}`);return this.program.concat(o||[]).map((i,s)=>Jt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
23
23
 
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- function to(e){return e}import or from"assert/strict";import{z as gt}from"zod";import{z as ro}from"zod";var ne={positive:200,negative:400},st=(e,t)=>e instanceof ro.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));import{z as Oo}from"zod";import{isHttpError as oo}from"http-errors";import{createHash as no}from"crypto";import{flip as io,pickBy as so,xprod as ao}from"ramda";import{z as po}from"zod";var ie=class extends Error{name="RoutingError"},I=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
- Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},k=class extends Error{name="IOSchemaError"},$=class extends k{name="OutputValidationError";originalError;constructor(t){super(j(t)),this.originalError=t}},L=class extends k{name="InputValidationError";originalError;constructor(t){super(j(t)),this.originalError=t}},_=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},se=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var Z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var co=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Z.upload);return"files"in e&&r},at={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},mo=["body","query","params"],pt=e=>e.method.toLowerCase(),dt=e=>e.startsWith("x-"),lo=e=>so(io(dt),e),$t=(e,t={})=>{let r=pt(e);return r==="options"?{}:(t[r]||at[r]||mo).filter(o=>o==="files"?co(e):!0).map(o=>o==="headers"?lo(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},ae=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),j=e=>e instanceof po.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof $?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Le=e=>oo(e)?e.statusCode:e instanceof L?400:500,ct=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
1
+ function to(e){return e}import or from"assert/strict";import{z as ht}from"zod";import{z as ro}from"zod";var ne={positive:200,negative:400},at=(e,t)=>e instanceof ro.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));import{z as Oo}from"zod";import{isHttpError as oo}from"http-errors";import{createHash as no}from"crypto";import{flip as io,pickBy as so,xprod as ao}from"ramda";import{z as po}from"zod";var ie=class extends Error{name="RoutingError"},I=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
+ Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},k=class extends Error{name="IOSchemaError"},$=class extends k{name="OutputValidationError";originalError;constructor(t){super(j(t)),this.originalError=t}},L=class extends k{name="InputValidationError";originalError;constructor(t){super(j(t)),this.originalError=t}},_=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},se=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var Z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var co=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Z.upload);return"files"in e&&r},pt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},mo=["body","query","params"],dt=e=>e.method.toLowerCase(),ct=e=>e.startsWith("x-"),lo=e=>so(io(ct),e),$t=(e,t={})=>{let r=dt(e);return r==="options"?{}:(t[r]||pt[r]||mo).filter(o=>o==="files"?co(e):!0).map(o=>o==="headers"?lo(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},ae=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),j=e=>e instanceof po.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof $?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Le=e=>oo(e)?e.statusCode:e instanceof L?400:500,mt=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
3
3
  ${o.stack}
4
- `,{url:t.url,payload:r})},U=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=Y(e,"examples")||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},G=(e,t,r)=>e.length&&t.length?ao(e,t).map(r):e.concat(t),Se=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,mt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),z=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(mt).join(""),je=e=>no("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ue=(e,t)=>{try{return typeof e.parse(t)}catch{return}},w=e=>typeof e=="object"&&e!==null;import{z as _t}from"zod";import{clone as uo,mergeDeepRight as fo}from"ramda";var R=Symbol.for("express-zod-api"),He=e=>{let t=e.describe(e.description);return t._def[R]=uo(t._def[R])||{examples:[]},t},yo=function(e){let t=He(this);return t._def[R].examples.push(e),t},go=function(e){let t=He(this);return t._def[R].defaultLabel=e,t};R in globalThis||(globalThis[R]=!0,Object.defineProperty(_t.ZodType.prototype,"example",{get(){return yo.bind(this)}}),Object.defineProperty(_t.ZodDefault.prototype,"label",{get(){return go.bind(this)}}));var Gt=e=>R in e._def&&w(e._def[R]),Y=(e,t)=>Gt(e)?e._def[R][t]:void 0,Yt=(e,t)=>{if(!Gt(e))return t;let r=He(t);return r._def[R].examples=G(r._def[R].examples,e._def[R].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?fo({...o},{...i}):i),r},P=(e,t)=>{let r=He(t);return r._def[R].kind=e,r},lt=(e,t)=>Y(e,"kind")===t,ho=e=>e;import{z as bo}from"zod";import{z as Oe}from"zod";var H="File",Qt=Oe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),xo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,To={buffer:()=>P(H,Qt),string:()=>P(H,Oe.string()),binary:()=>P(H,Qt.or(Oe.string())),base64:()=>{let e=Oe.string(),t=e.base64?.()instanceof Oe.ZodString;return P(H,t?e.base64():e.regex(xo,"Does not match base64 encoding"))}};function Ke(e){return To[e||"string"]()}var Q="Raw",Jt=()=>P(Q,bo.object({raw:Ke("buffer")}));import{z as So}from"zod";var Ae="Upload",Wt=()=>P(Ae,So.custom(e=>typeof e=="object"&&e!==null&&"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&&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",e=>({message:`Expected file upload, received ${typeof e}`})));var ut=({schema:{options:e},next:t})=>e.some(t),er=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),Ao=({schema:e,next:t})=>Object.values(e.shape).some(t),Xt=({schema:e,next:t})=>t(e.unwrap()),Ro=({schema:e,next:t})=>t(e.innerType()),Po=({schema:e,next:t})=>t(e.valueSchema),Co=({schema:e,next:t})=>t(e.element),Io=({schema:e,next:t})=>t(e._def.innerType),Eo={ZodObject:Ao,ZodUnion:ut,ZodDiscriminatedUnion:ut,ZodIntersection:er,ZodEffects:Ro,ZodOptional:Xt,ZodNullable:Xt,ZodRecord:Po,ZodArray:Co,ZodDefault:Io},Fe=({subject:e,condition:t,rules:r=Eo,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Fe({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},qe=e=>Fe({subject:e,maxDepth:3,rules:{ZodUnion:ut,ZodIntersection:er},condition:t=>t instanceof Oo.ZodEffects&&t._def.effect.type!=="refinement"}),tr=e=>Fe({subject:e,condition:t=>lt(t,Ae)}),rr=e=>Fe({subject:e,condition:t=>lt(t,Q),maxDepth:3});var Be=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
- Original error: ${e.originalError.message}.`:""))};import{chain as Zo}from"ramda";var J=e=>w(e)&&"or"in e,de=e=>w(e)&&"and"in e,ft=e=>({and:Zo(t=>de(t)?t.and:[t],e)}),Ve=(e,t)=>de(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),yt=e=>e.and.reduce((t,r)=>({or:G(t.or,J(r)?r.or:[r],ft)}),{or:[]}),pe=(e,t)=>de(e)?J(t)?pe(yt(e),t):ft([e,t]):J(e)?de(t)?pe(t,e):J(t)?{or:G(e.or,t.or,ft)}:pe(e,{and:[t]}):de(t)||J(t)?pe(t,e):{and:[e,t]};var ce=class{},$e=class extends ce{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#m;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:m}){super(),this.#a=i,this.#p=s,this.#n=d,this.#m=a,this.#o=t,this.#d=p,this.#c=c,this.#e={long:l,short:m},this.#r={input:r,output:o};for(let[f,h]of Object.entries(this.#r))or(!qe(h),new k(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:st(s.getPositiveResponse(o),{mimeTypes:[Z.json],statusCodes:[ne.positive]}),negative:st(s.getNegativeResponse(),{mimeTypes:[Z.json],statusCodes:[ne.negative]})};for(let[f,h]of Object.entries(this.#t))or(h.length,new _(`ResultHandler must have at least one ${f} response schema specified.`));this.#i=tr(r)?"upload":rr(r)?"raw":"json",this.#s={input:[Z[this.#i]],positive:this.#t.positive.flatMap(({mimeTypes:f})=>f),negative:this.#t.negative.flatMap(({mimeTypes:f})=>f)}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?pe(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#m(t)}#l(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof gt.ZodError?new $(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof gt.ZodError?new L(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof gt.ZodError?new L(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Be({logger:i,response:o,error:new _(ae(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=pt(t),p={},d=null,c=null;if(i.cors){let m=this.#l(s);typeof i.cors=="function"&&(m=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:m}));for(let f in m)r.set(f,m[f])}let l=$t(t,i.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(m){c=ae(m)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as ir}from"zod";var nr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Yt(s,i),o)};import zo from"assert/strict";var ht=e=>(zo(!qe(e.input),new k("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as N}from"zod";var xt=e=>e,Re=xt({getPositiveResponse:e=>{let t=U({schema:e}),r=N.object({status:N.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>N.object({status:N.literal("error"),error:N.object({message:N.string()})}).example({status:"error",error:{message:j(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(ne.positive).json({status:"success",data:r});return}let a=Le(e);ct({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:j(e)}})}}),Tt=xt({getPositiveResponse:e=>{let t=U({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof N.ZodArray?e.shape.items:N.array(N.any());return t.reduce((o,i)=>w(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>N.string().example(j(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);ct({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ne.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Pe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:ir.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,m=>{if(m&&m instanceof Error)return c(o(m));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ht({input:ir.object({}),middleware:typeof t=="function"?t:async({logger:r})=>(r.warn("addOptions: Static options are deprecated. Replace with async function or just import the const."),t)})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],m=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new $e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:h,methods:l,getOperationId:m,description:i,shortDescription:s,inputSchema:nr(d,t)})}},wo=new Pe(Re),Mo=new Pe(Tt);import{inspect as No}from"util";import{mapObjIndexed as vo}from"ramda";import{Ansis as Do,blue as ko,green as Lo,hex as jo,red as Uo}from"ansis";var bt={debug:10,info:20,warn:30,error:40},sr=e=>w(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),St=({level:e,color:t=new Do().isSupported(),depth:r=2})=>{let o={debug:ko,info:Lo,warn:jo("#FFA500"),error:Uo},i=e==="debug",s=e==="silent"?100:bt[e],a=(p,d,c)=>{if(bt[p]<s)return;let l=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&l.push(No(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(l.join(" "))};return vo(({},p)=>(d,c)=>a(p,d,c),bt)};import{head as Ho,tail as Ko,toPairs as Fo}from"ramda";var Ce=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Fo(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=Ho(this.pairs)?.[1],this.siblingMethods=Ko(this.pairs).map(([r])=>r)}};import qo from"express";var Ie=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,qo.static(...this.params))}};import gr from"express";import _o from"http";import Go from"https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new se(e)},ar=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await me(t,r)}catch{}throw new se(e.map(({moduleName:t})=>t))};import pr from"assert/strict";var W=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){pr.doesNotMatch(a,/\//,new ie(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ce){let c=p.getMethods().slice();i&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Ie)r&&p.apply(d,r);else if(p instanceof Ce){for(let[c,l]of p.pairs)pr(l.getMethods().includes(c),new ie(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else W({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Ot=({app:e,rootLogger:t,config:r,routing:o})=>W({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let l=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;l.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:l,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}});import dr,{isHttpError as Bo}from"http-errors";var cr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:Bo(o)?o:dr(400,ae(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},mr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=dr(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Be({response:i,logger:a,error:new _(ae(p).message,s)})}},lr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},ur=e=>({log:(t,...r)=>{/not eligible/.test(t)||e.debug(t,...r)}});import{gray as Vo,hex as fr,italic as _e,whiteBright as $o}from"ansis";var yr=()=>{let e=_e("Proudly supports transgender community.".padStart(109)),t=_e("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=_e("Thank you for choosing Express Zod API for your project.".padStart(132)),o=_e("for Victoria".padEnd(20)),i=fr("#F5A9B8"),s=fr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill($o,5,7).fill(i,7,9).fill(s,9,12).fill(Vo,12,13);return`
4
+ `,{url:t.url,payload:r})},U=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=Y(e,"examples")||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},G=(e,t,r)=>e.length&&t.length?ao(e,t).map(r):e.concat(t),Se=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,lt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),z=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(lt).join(""),je=e=>no("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ue=(e,t)=>{try{return typeof e.parse(t)}catch{return}},w=e=>typeof e=="object"&&e!==null;import{z as _t}from"zod";import{clone as uo,mergeDeepRight as fo}from"ramda";var R=Symbol.for("express-zod-api"),He=e=>{let t=e.describe(e.description);return t._def[R]=uo(t._def[R])||{examples:[]},t},yo=function(e){let t=He(this);return t._def[R].examples.push(e),t},go=function(e){let t=He(this);return t._def[R].defaultLabel=e,t};R in globalThis||(globalThis[R]=!0,Object.defineProperty(_t.ZodType.prototype,"example",{get(){return yo.bind(this)}}),Object.defineProperty(_t.ZodDefault.prototype,"label",{get(){return go.bind(this)}}));var Gt=e=>R in e._def&&w(e._def[R]),Y=(e,t)=>Gt(e)?e._def[R][t]:void 0,Yt=(e,t)=>{if(!Gt(e))return t;let r=He(t);return r._def[R].examples=G(r._def[R].examples,e._def[R].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?fo({...o},{...i}):i),r},P=(e,t)=>{let r=He(t);return r._def[R].kind=e,r},ut=(e,t)=>Y(e,"kind")===t,ho=e=>e;import{z as bo}from"zod";import{z as Oe}from"zod";var H="File",Qt=Oe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),xo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,To={buffer:()=>P(H,Qt),string:()=>P(H,Oe.string()),binary:()=>P(H,Qt.or(Oe.string())),base64:()=>{let e=Oe.string(),t=e.base64?.()instanceof Oe.ZodString;return P(H,t?e.base64():e.regex(xo,"Does not match base64 encoding"))}};function Ke(e){return To[e||"string"]()}var Q="Raw",Jt=()=>P(Q,bo.object({raw:Ke("buffer")}));import{z as So}from"zod";var Ae="Upload",Wt=()=>P(Ae,So.custom(e=>typeof e=="object"&&e!==null&&"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&&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",e=>({message:`Expected file upload, received ${typeof e}`})));var ft=({schema:{options:e},next:t})=>e.some(t),er=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),Ao=({schema:e,next:t})=>Object.values(e.shape).some(t),Xt=({schema:e,next:t})=>t(e.unwrap()),Ro=({schema:e,next:t})=>t(e.innerType()),Po=({schema:e,next:t})=>t(e.valueSchema),Co=({schema:e,next:t})=>t(e.element),Io=({schema:e,next:t})=>t(e._def.innerType),Eo={ZodObject:Ao,ZodUnion:ft,ZodDiscriminatedUnion:ft,ZodIntersection:er,ZodEffects:Ro,ZodOptional:Xt,ZodNullable:Xt,ZodRecord:Po,ZodArray:Co,ZodDefault:Io},Fe=({subject:e,condition:t,rules:r=Eo,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Fe({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},qe=e=>Fe({subject:e,maxDepth:3,rules:{ZodUnion:ft,ZodIntersection:er},condition:t=>t instanceof Oo.ZodEffects&&t._def.effect.type!=="refinement"}),tr=e=>Fe({subject:e,condition:t=>ut(t,Ae)}),rr=e=>Fe({subject:e,condition:t=>ut(t,Q),maxDepth:3});var Be=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
+ Original error: ${e.originalError.message}.`:""))};import{chain as Zo}from"ramda";var J=e=>w(e)&&"or"in e,de=e=>w(e)&&"and"in e,yt=e=>({and:Zo(t=>de(t)?t.and:[t],e)}),Ve=(e,t)=>de(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),gt=e=>e.and.reduce((t,r)=>({or:G(t.or,J(r)?r.or:[r],yt)}),{or:[]}),pe=(e,t)=>de(e)?J(t)?pe(gt(e),t):yt([e,t]):J(e)?de(t)?pe(t,e):J(t)?{or:G(e.or,t.or,yt)}:pe(e,{and:[t]}):de(t)||J(t)?pe(t,e):{and:[e,t]};var ce=class{},$e=class extends ce{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#m;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:m}){super(),this.#a=i,this.#p=s,this.#n=d,this.#m=a,this.#o=t,this.#d=p,this.#c=c,this.#e={long:l,short:m},this.#r={input:r,output:o};for(let[f,h]of Object.entries(this.#r))or(!qe(h),new k(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:at(s.getPositiveResponse(o),{mimeTypes:[Z.json],statusCodes:[ne.positive]}),negative:at(s.getNegativeResponse(),{mimeTypes:[Z.json],statusCodes:[ne.negative]})};for(let[f,h]of Object.entries(this.#t))or(h.length,new _(`ResultHandler must have at least one ${f} response schema specified.`));this.#i=tr(r)?"upload":rr(r)?"raw":"json",this.#s={input:[Z[this.#i]],positive:this.#t.positive.flatMap(({mimeTypes:f})=>f),negative:this.#t.negative.flatMap(({mimeTypes:f})=>f)}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?pe(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#m(t)}#l(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ht.ZodError?new $(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof ht.ZodError?new L(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ht.ZodError?new L(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Be({logger:i,response:o,error:new _(ae(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=dt(t),p={},d=null,c=null;if(i.cors){let m=this.#l(s);typeof i.cors=="function"&&(m=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:m}));for(let f in m)r.set(f,m[f])}let l=$t(t,i.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(m){c=ae(m)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as ir}from"zod";var nr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Yt(s,i),o)};import zo from"assert/strict";var xt=e=>(zo(!qe(e.input),new k("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as N}from"zod";var Tt=e=>e,Re=Tt({getPositiveResponse:e=>{let t=U({schema:e}),r=N.object({status:N.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>N.object({status:N.literal("error"),error:N.object({message:N.string()})}).example({status:"error",error:{message:j(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(ne.positive).json({status:"success",data:r});return}let a=Le(e);mt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:j(e)}})}}),bt=Tt({getPositiveResponse:e=>{let t=U({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof N.ZodArray?e.shape.items:N.array(N.any());return t.reduce((o,i)=>w(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>N.string().example(j(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);mt({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ne.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Pe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:ir.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,m=>{if(m&&m instanceof Error)return c(o(m));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(xt({input:ir.object({}),middleware:typeof t=="function"?t:async({logger:r})=>(r.warn("addOptions: Static options are deprecated. Replace with async function or just import the const."),t)})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],m=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new $e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:h,methods:l,getOperationId:m,description:i,shortDescription:s,inputSchema:nr(d,t)})}},wo=new Pe(Re),Mo=new Pe(bt);import{inspect as No}from"util";import{mapObjIndexed as vo}from"ramda";import{Ansis as Do,blue as ko,green as Lo,hex as jo,red as Uo}from"ansis";var _e={debug:10,info:20,warn:30,error:40},sr=e=>w(e)&&Object.keys(_e).some(t=>t in e),St=({level:e,color:t=new Do().isSupported(),depth:r=2})=>{let o={debug:ko,info:Lo,warn:jo("#FFA500"),error:Uo},i=e==="debug",s=e==="silent"?100:_e[e],a=(p,d,c)=>{if(_e[p]<s)return;let l=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&l.push(No(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(l.join(" "))};return vo(({},p)=>(d,c)=>a(p,d,c),_e)};import{head as Ho,tail as Ko,toPairs as Fo}from"ramda";var Ce=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Fo(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=Ho(this.pairs)?.[1],this.siblingMethods=Ko(this.pairs).map(([r])=>r)}};import qo from"express";var Ie=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,qo.static(...this.params))}};import gr from"express";import _o from"http";import Go from"https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new se(e)},ar=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await me(t,r)}catch{}throw new se(e.map(({moduleName:t})=>t))};import pr from"assert/strict";var W=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){pr.doesNotMatch(a,/\//,new ie(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ce){let c=p.getMethods().slice();i&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Ie)r&&p.apply(d,r);else if(p instanceof Ce){for(let[c,l]of p.pairs)pr(l.getMethods().includes(c),new ie(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else W({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Ot=({app:e,rootLogger:t,config:r,routing:o})=>W({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let l=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;l.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:l,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}});import dr,{isHttpError as Bo}from"http-errors";var cr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:Bo(o)?o:dr(400,ae(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},mr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=dr(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Be({response:i,logger:a,error:new _(ae(p).message,s)})}},lr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},ur=e=>({log:(t,...r)=>{/not eligible/.test(t)||e.debug(t,...r)}});import{gray as Vo,hex as fr,italic as Ge,whiteBright as $o}from"ansis";var yr=()=>{let e=Ge("Proudly supports transgender community.".padStart(109)),t=Ge("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=Ge("Thank you for choosing Express Zod API for your project.".padStart(132)),o=Ge("for Victoria".padEnd(20)),i=fr("#F5A9B8"),s=fr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill($o,5,7).fill(i,7,9).fill(s,9,12).fill(Vo,12,13);return`
6
6
  8888888888 8888888888P 888 d8888 8888888b. 8888888
7
7
  888 d88P 888 d88888 888 Y88b 888
8
8
  888 d88P 888 d88P888 888 888 888
@@ -17,8 +17,8 @@ ${o}888${t}
17
17
  ${r}
18
18
  `.split(`
19
19
  `).map((d,c)=>a[c]?a[c](d):d).join(`
20
- `)};var hr=e=>{e.startupLogo!==!1&&console.log(yr());let t=sr(e.logger)?St(e.logger):e.logger;t.debug("Running","v18.6.2 (ESM)");let r=e.errorHandler||Re,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=mr(i),a=cr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Yo=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=hr(e);return Ot({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Qo=async(e,t)=>{let r=gr().disable("x-powered-by");if(e.server.compression){let d=await me("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||gr.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=hr(e);if(e.server.upload){let d=await me("express-fileupload"),{limitError:c,beforeUpload:l,...m}={...typeof e.server.upload=="object"&&e.server.upload};l&&l({app:r,logger:o}),r.use(d({...m,abortOnLimit:!1,parseNested:!0,logger:ur(o)})),c&&r.use(lr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),Ot({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(_o.createServer(r),e.server.listen),httpsServer:e.https?a(Go.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import oi from"assert/strict";import{OpenApiBuilder as ni}from"openapi3-ts/oas31";import K from"assert/strict";import{isReferenceObject as ee}from"openapi3-ts/oas31";import{both as Wo,complement as Xo,concat as en,type as tn,filter as rn,fromPairs as we,has as on,isNil as nn,map as le,mergeAll as sn,mergeDeepRight as an,mergeDeepWith as pn,objOf as Or,omit as We,pipe as Ar,pluck as dn,range as cn,reject as mn,toLower as ln,union as un,when as fn,xprod as Xe,zip as yn}from"ramda";import{z as T}from"zod";import{z as Qe}from"zod";var Ge=e=>!isNaN(e.getTime()),Ye=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Ee="DateIn",xr=()=>{let e=Qe.string(),r=e.date?.()instanceof Qe.ZodString?Qe.union([e.date(),e.datetime(),e.datetime({local:!0})]):e.regex(Ye);return P(Ee,r.transform(o=>new Date(o)).pipe(Qe.date().refine(Ge)))};import{z as Jo}from"zod";var Ze="DateOut",Tr=()=>P(Ze,Jo.date().refine(Ge).transform(e=>e.toISOString()));var X=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Y(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:m=>X({schema:m,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),l=t&&t({schema:e,prev:c,...p});return l?{...c,...l}:c};var br=50,Rr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",gn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Pr=/:([A-Za-z0-9_]+)/g,Cr=e=>e.match(Pr)?.map(t=>t.slice(1))||[],Ir=e=>e.replace(Pr,t=>`{${t.slice(1)}}`),hn=({schema:e,next:t})=>({...t(e._def.innerType),default:Y(e,"defaultLabel")||e._def.defaultValue()}),xn=({schema:{_def:{innerType:e}},next:t})=>t(e),Tn=()=>({format:"any"}),bn=e=>(K(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Sn=({schema:e})=>({type:"string",format:e instanceof T.ZodString?e._def.checks.find(t=>t.kind==="regex"||t.kind==="base64")?"byte":"file":"binary"}),On=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),An=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Rn=e=>{let[t,r]=e.filter(i=>!ee(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));K(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=pn((i,s)=>Array.isArray(i)&&Array.isArray(s)?en(i,s):i===s?s:K.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=un(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=G(t.examples||[],r.examples||[],([i,s])=>an(i,s))),o},Pn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Rn(o)}catch{}return{allOf:o}},Cn=({schema:e,next:t})=>t(e.unwrap()),In=({schema:e,next:t})=>t(e._def.innerType),En=({schema:e,next:t})=>{let r=t(e.unwrap());return ee(r)||(r.type=Zr(r)),r},Er=e=>{let t=ln(tn(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Sr=({schema:e})=>({type:Er(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Zn=({schema:{value:e}})=>({type:Er(e),const:e}),zn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Se(p)?p instanceof T.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=Je({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},wn=()=>({type:"null"}),Mn=e=>(K(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:Ye.source,externalDocs:{url:Rr}}),Nn=e=>(K(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Rr}}),vn=e=>K.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Dn=()=>({type:"boolean"}),kn=()=>({type:"integer",format:"bigint"}),Ln=e=>e.every(t=>t instanceof T.ZodLiteral),jn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=Je({schema:T.object(we(Xe(o,[t]))),...r}),i.required=o),i}if(e instanceof T.ZodLiteral)return{type:"object",properties:Je({schema:T.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof T.ZodUnion&&Ln(e.options)){let o=le(s=>`${s.value}`,e.options),i=we(Xe(o,[t]));return{type:"object",properties:Je({schema:T.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},Un=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},Hn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Kn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:m}}})=>{let f=m.find(b=>b.kind==="regex"),h=m.find(b=>b.kind==="datetime"),x=f?f.regex:h?h.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,S={type:"string"},g={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let b in g)if(g[b]){S.format=b;break}return r!==null&&(S.minLength=r),o!==null&&(S.maxLength=o),x&&(S.pattern=x.source),S},Fn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},Je=({schema:{shape:e},next:t})=>le(t,e),qn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return gn?.[t]},Zr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Bn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!ee(o)){let s=Ue(e,qn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.any())}if(!t&&i.type==="preprocess"&&!ee(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Vn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),$n=({schema:e,next:t})=>t(e.unwrap()),_n=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},Gn=({next:e,schema:t})=>e(t.shape.raw),zr=e=>e.length?we(yn(cn(1,e.length+1).map(t=>`example${t}`),le(Or("value"),e))):void 0,wr=(e,t,r=[])=>Ar(U,le(fn(Wo(w,Xo(Array.isArray)),We(r))),zr)({schema:e,variant:t?"parsed":"original",validate:!0}),Yn=(e,t)=>Ar(U,rn(on(t)),dn(t),zr)({schema:e,variant:"original",validate:!0}),ze=(e,t)=>e instanceof T.ZodObject?e:e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion?e.options.map(r=>ze(r,t)).reduce((r,o)=>r.merge(o.partial()),T.object({})):e instanceof T.ZodEffects?(K(e._def.effect.type==="refinement",t),ze(e._def.schema,t)):ze(e._def.left,t).merge(ze(e._def.right,t)),Mr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=ze(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Cr(e),m=o.includes("query"),f=o.includes("params"),h=o.includes("headers"),x=g=>f&&l.includes(g),S=g=>h&&dt(g);return Object.keys(c).filter(g=>m||x(g)).map(g=>{let b=X({schema:c[g],isResponse:!1,rules:Rt,onEach:Pt,onMissing:Ct,serializer:i,getRef:s,makeRef:a,path:e,method:t}),ye=p==="components"?a(z(d,g),b):b;return{name:g,in:x(g)?"path":S(g)?"header":"query",required:!c[g].isOptional(),description:b.description||d,schema:ye,examples:Yn(r,g)}})},Rt={ZodString:Kn,ZodNumber:Fn,ZodBigInt:kn,ZodBoolean:Dn,ZodNull:wn,ZodArray:Un,ZodTuple:Hn,ZodRecord:jn,ZodObject:zn,ZodLiteral:Zn,ZodIntersection:Pn,ZodUnion:On,ZodAny:Tn,ZodDefault:hn,ZodEnum:Sr,ZodNativeEnum:Sr,ZodEffects:Bn,ZodOptional:Cn,ZodNullable:En,ZodDiscriminatedUnion:An,ZodBranded:$n,ZodDate:vn,ZodCatch:xn,ZodPipeline:Vn,ZodLazy:_n,ZodReadonly:In,[H]:Sn,[Ae]:bn,[Ze]:Nn,[Ee]:Mn,[Q]:Gn},Pt=({schema:e,isResponse:t,prev:r})=>{if(ee(r))return{};let{description:o}=e,i=e instanceof T.ZodLazy,s=r.type!==void 0,a=t&&Se(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:U({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Zr(r)),d.length&&(c.examples=d.slice()),c},Ct=({schema:e,...t})=>K.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(ee(e))return e;let r={...e};return r.properties&&(r.properties=We(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>We(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},Nr=e=>ee(e)?e:We(["examples"],e),vr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:m=`${e.toUpperCase()} ${t} ${mt(i)} response ${c?l:""}`.trim()})=>{let f=Nr(X({schema:r,isResponse:!0,rules:Rt,onEach:Pt,onMissing:Ct,serializer:s,getRef:a,makeRef:p,path:t,method:e})),h={schema:d==="components"?p(z(m),f):f,examples:wr(r,!0)};return{description:m,content:we(Xe(o,[h]))}},Qn=()=>({type:"http",scheme:"basic"}),Jn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Wn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Xn=({name:e})=>({type:"apiKey",in:"header",name:e}),ei=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ti=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ri=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),mn(nn,e))}),Dr=(e,t)=>{let r={basic:Qn,bearer:Jn,input:Wn,header:Xn,cookie:ei,openid:ti,oauth2:ri};return Ve(e,o=>r[o.type](o,t))},et=e=>"or"in e?e.or.map(t=>"and"in t?sn(le(({name:r,scopes:o})=>Or(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?et(yt(e)):et({or:[e]}),kr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Cr(t),l=Nr(At(X({schema:r,isResponse:!1,rules:Rt,onEach:Pt,onMissing:Ct,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(z(d),l):l,examples:wr(r,!1,c)};return{description:d,content:we(Xe(o,[m]))}},Lr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),It=e=>e.length<=br?e:e.slice(0,br-1)+"\u2026";var Et=class extends ni{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||z(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&oi.fail(new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=je}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});W({routing:t,onEndpoint:(m,f,h)=>{let x=h,S={path:f,method:x,endpoint:m,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[g,b]=["short","long"].map(m.getDescription.bind(m)),ye=g?It(g):p&&b?It(b):void 0,Ne=m.getTags(),ge=r.inputSources?.[x]||at[x],re=this.ensureUniqOperationId(f,x,m.getOperationId(x)),ve=Mr({...S,inputSources:ge,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:x,path:f,operationId:re})}),De={};for(let v of["positive","negative"]){let V=m.getResponses(v);for(let{mimeTypes:he,schema:O,statusCodes:A}of V)for(let C of A)De[C]=vr({...S,variant:v,schema:O,mimeTypes:he,statusCode:C,hasMultipleStatusCodes:V.length>1||A.length>1,description:a?.[`${v}Response`]?.call(null,{method:x,path:f,operationId:re,statusCode:C})})}let it=ge.includes("body")?kr({...S,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:x,path:f,operationId:re})}):void 0,ke=et(Ve(Dr(m.getSecurity(),ge),v=>{let V=this.ensureUniqSecuritySchemaName(v),he=["oauth2","openIdConnect"].includes(v.type)?m.getScopes():[];return this.addSecurityScheme(V,v),{name:V,scopes:he}}));this.addPath(Ir(f),{[x]:{operationId:re,summary:ye,description:b,tags:Ne.length>0?Ne:void 0,parameters:ve.length>0?ve:void 0,requestBody:it,security:ke.length>0?ke:void 0,responses:De}})}}),this.rootDoc.tags=r.tags?Lr(r.tags):[]}};import jr from"http";var ii=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>Z.json),...t}),si=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:jr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=jr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},ai=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),pi=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await ar([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=ii({fnMethod:a,requestProps:t}),d=si({fnMethod:a,responseProps:r}),c=ai({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import M from"typescript";import D from"typescript";import{chain as Ur,toPairs as Hr}from"ramda";var n=D.factory,F=[n.createModifier(D.SyntaxKind.ExportKeyword)],di=[n.createModifier(D.SyntaxKind.AsyncKeyword)],ci=[n.createModifier(D.SyntaxKind.PublicKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],Kr=[n.createModifier(D.SyntaxKind.ProtectedKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],Zt=n.createTemplateHead(""),ue=n.createTemplateTail(""),zt=n.createTemplateMiddle(" "),wt=e=>n.createTemplateLiteralType(Zt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ue:zt))),Mt=wt(["M","P"]),tt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),rt=(e,t)=>Ur(([r,o])=>[tt(n.createIdentifier(r),o,t)],Hr(e)),Nt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Fr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),qr=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),q=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.NodeFlags.Const),vt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ot=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,t),Br=(e,t,r)=>n.createPropertyDeclaration(ci,e,void 0,t,r),Vr=(e,t,r)=>n.createClassDeclaration(F,e,void 0,void 0,[t,...r]),$r=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),_r=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.SyntaxKind.AnyKeyword)]),Gr=(e,t,r)=>n.createInterfaceDeclaration(F,e,void 0,t,r),Yr=e=>Ur(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Hr(e)),Dt=(e,t,r)=>n.createArrowFunction(r?di:void 0,void 0,e.map(o=>tt(o)),void 0,void 0,t),kt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,rt({acc:void 0,key:void 0}),void 0,void 0,t),r]),Qr=(...e)=>`"${e.join(" ")}"`;var Jr=["get","post","put","delete","patch"];import y from"typescript";import{z as Ut}from"zod";import B from"typescript";var{factory:nt}=B,Lt=(e,t)=>{B.addSyntheticLeadingComment(e,B.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},fe=(e,t,r)=>{let o=nt.createTypeAliasDeclaration(void 0,nt.createIdentifier(t),void 0,e);return r&&Lt(o,r),o},jt=(e,t)=>{let r=B.createSourceFile("print.ts","",B.ScriptTarget.Latest,!1,B.ScriptKind.TS);return B.createPrinter(t).printNode(B.EmitHint.Unspecified,e,r)},mi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Wr=e=>mi.test(e)?nt.createIdentifier(e):nt.createStringLiteral(e);var{factory:u}=y,li={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},ui=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),fi=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Se(a)?a instanceof Ut.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Wr(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},yi=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),gi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Xr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),hi=e=>li?.[e.kind],xi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Ue(e,hi(o)),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||y.SyntaxKind.AnyKeyword)}return o},Ti=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),bi=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Si=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Oi=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Ai=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Ri=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Pi=({next:e,schema:t})=>e(t._def.innerType),te=e=>()=>u.createKeywordTypeNode(e),Ci=({next:e,schema:t})=>e(t.unwrap()),Ii=({next:e,schema:t})=>e(t._def.innerType),Ei=({next:e,schema:t})=>e(t._def.innerType),Zi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),zi=()=>u.createLiteralTypeNode(u.createNull()),wi=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},Mi=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof Ut.ZodString?t:e instanceof Ut.ZodUnion?o:r},Ni=({next:e,schema:t})=>e(t.shape.raw),vi={ZodString:te(y.SyntaxKind.StringKeyword),ZodNumber:te(y.SyntaxKind.NumberKeyword),ZodBigInt:te(y.SyntaxKind.BigIntKeyword),ZodBoolean:te(y.SyntaxKind.BooleanKeyword),ZodAny:te(y.SyntaxKind.AnyKeyword),[Ee]:te(y.SyntaxKind.StringKeyword),[Ze]:te(y.SyntaxKind.StringKeyword),ZodNull:zi,ZodArray:yi,ZodTuple:Oi,ZodRecord:Ai,ZodObject:fi,ZodLiteral:ui,ZodIntersection:Ri,ZodUnion:Xr,ZodDefault:Pi,ZodEnum:gi,ZodNativeEnum:Ti,ZodEffects:xi,ZodOptional:bi,ZodNullable:Si,ZodDiscriminatedUnion:Xr,ZodBranded:Ci,ZodCatch:Ei,ZodPipeline:Zi,ZodLazy:wi,ZodReadonly:Ii,[H]:Mi,[Q]:Ni},Me=({schema:e,...t})=>X({schema:e,rules:vi,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Ht=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,fe(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=je,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(O,A,C)=>{let oe={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},xe=z(C,A,"input"),Te=Me({...oe,schema:O.getSchema("input"),isResponse:!1}),E=i?z(C,A,"positive.response"):void 0,Kt=O.getSchema("positive"),Ft=i?Me({...oe,isResponse:!0,schema:Kt}):void 0,be=i?z(C,A,"negative.response"):void 0,qt=O.getSchema("negative"),Bt=i?Me({...oe,isResponse:!0,schema:qt}):void 0,Vt=z(C,A,"response"),eo=E&&be?n.createUnionTypeNode([n.createTypeReferenceNode(E),n.createTypeReferenceNode(be)]):Me({...oe,isResponse:!0,schema:Kt.or(qt)});this.program.push(fe(Te,xe)),Ft&&E&&this.program.push(fe(Ft,E)),Bt&&be&&this.program.push(fe(Bt,be)),this.program.push(fe(eo,Vt)),C!=="options"&&(this.paths.push(A),this.registry.set({method:C,path:A},{input:xe,positive:E,negative:be,response:Vt,isJson:O.getMimeTypes("positive").includes(Z.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(vt(this.ids.pathType,this.paths)),this.program.push(vt(this.ids.methodType,Jr)),this.program.push(ot(this.ids.methodPathType,wt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(M.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,M.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:O,path:A},{isJson:C,tags:oe,...xe}]of this.registry){let Te=Qr(O,A);for(let E of this.interfaces)E.kind in xe&&E.props.push(qr(Te,xe[E.kind]));r!=="types"&&(C&&p.push(n.createPropertyAssignment(Te,n.createTrue())),d.push(n.createPropertyAssignment(Te,n.createArrayLiteralExpression(oe.map(E=>n.createStringLiteral(E))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(Gr(O,a,A));if(r==="types")return;let c=n.createVariableStatement(F,q(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),l=n.createVariableStatement(F,q(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),m=ot(this.ids.providerType,n.createFunctionTypeNode(Yr({M:this.ids.methodType,P:this.ids.pathType}),rt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Mt)}),$r(this.ids.responseInterface,Mt))),f=ot(this.ids.implementationType,n.createFunctionTypeNode(void 0,rt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(M.SyntaxKind.StringKeyword),params:Nt(M.SyntaxKind.StringKeyword,M.SyntaxKind.AnyKeyword)}),_r())),h=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ue)]),x=kt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[h,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),S=kt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[h]),M.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),g=Vr(this.ids.clientClass,Fr([tt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Kr)]),[Br(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Dt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,x,S]),!0))]);this.program.push(c,l,m,f,g);let b=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ye=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(Z.json))]),void 0,this.ids.undefinedValue)),Ne=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ge=n.createVariableStatement(void 0,q(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,ue)]),n.createObjectLiteralExpression([b,ye,Ne])])))),re=n.createVariableStatement(void 0,q(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=n.createVariableStatement(void 0,q(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),ue)])))),[De,it]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),ke=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Zt,[n.createTemplateSpan(this.ids.methodParameter,zt),n.createTemplateSpan(this.ids.pathParameter,ue)]),M.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([De])),v=n.createVariableStatement(F,q(this.ids.exampleImplementationConst,Dt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([re,ve,ge,ke,it]),!0),n.createTypeReferenceNode(this.ids.implementationType))),V=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),he=n.createVariableStatement(void 0,q(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(v,he,V)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:jt(r,t)).join(`
20
+ `)};var hr=e=>{e.startupLogo!==!1&&console.log(yr());let t=sr(e.logger)?e.logger:St(e.logger);t.debug("Running","v18.6.3 (ESM)");let r=e.errorHandler||Re,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=mr(i),a=cr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Yo=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=hr(e);return Ot({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Qo=async(e,t)=>{let r=gr().disable("x-powered-by");if(e.server.compression){let d=await me("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||gr.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=hr(e);if(e.server.upload){let d=await me("express-fileupload"),{limitError:c,beforeUpload:l,...m}={...typeof e.server.upload=="object"&&e.server.upload};l&&l({app:r,logger:o}),r.use(d({...m,abortOnLimit:!1,parseNested:!0,logger:ur(o)})),c&&r.use(lr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),Ot({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(_o.createServer(r),e.server.listen),httpsServer:e.https?a(Go.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import oi from"assert/strict";import{OpenApiBuilder as ni}from"openapi3-ts/oas31";import K from"assert/strict";import{isReferenceObject as ee}from"openapi3-ts/oas31";import{both as Wo,complement as Xo,concat as en,type as tn,filter as rn,fromPairs as we,has as on,isNil as nn,map as le,mergeAll as sn,mergeDeepRight as an,mergeDeepWith as pn,objOf as Or,omit as Xe,pipe as Ar,pluck as dn,range as cn,reject as mn,toLower as ln,union as un,when as fn,xprod as et,zip as yn}from"ramda";import{z as T}from"zod";import{z as Je}from"zod";var Ye=e=>!isNaN(e.getTime()),Qe=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Ee="DateIn",xr=()=>{let e=Je.string(),r=e.date?.()instanceof Je.ZodString?Je.union([e.date(),e.datetime(),e.datetime({local:!0})]):e.regex(Qe);return P(Ee,r.transform(o=>new Date(o)).pipe(Je.date().refine(Ye)))};import{z as Jo}from"zod";var Ze="DateOut",Tr=()=>P(Ze,Jo.date().refine(Ye).transform(e=>e.toISOString()));var X=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Y(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:m=>X({schema:m,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),l=t&&t({schema:e,prev:c,...p});return l?{...c,...l}:c};var br=50,Rr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",gn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Pr=/:([A-Za-z0-9_]+)/g,Cr=e=>e.match(Pr)?.map(t=>t.slice(1))||[],Ir=e=>e.replace(Pr,t=>`{${t.slice(1)}}`),hn=({schema:e,next:t})=>({...t(e._def.innerType),default:Y(e,"defaultLabel")||e._def.defaultValue()}),xn=({schema:{_def:{innerType:e}},next:t})=>t(e),Tn=()=>({format:"any"}),bn=e=>(K(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Sn=({schema:e})=>({type:"string",format:e instanceof T.ZodString?e._def.checks.find(t=>t.kind==="regex"||t.kind==="base64")?"byte":"file":"binary"}),On=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),An=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Rn=e=>{let[t,r]=e.filter(i=>!ee(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));K(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=pn((i,s)=>Array.isArray(i)&&Array.isArray(s)?en(i,s):i===s?s:K.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=un(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=G(t.examples||[],r.examples||[],([i,s])=>an(i,s))),o},Pn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Rn(o)}catch{}return{allOf:o}},Cn=({schema:e,next:t})=>t(e.unwrap()),In=({schema:e,next:t})=>t(e._def.innerType),En=({schema:e,next:t})=>{let r=t(e.unwrap());return ee(r)||(r.type=Zr(r)),r},Er=e=>{let t=ln(tn(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Sr=({schema:e})=>({type:Er(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Zn=({schema:{value:e}})=>({type:Er(e),const:e}),zn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Se(p)?p instanceof T.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=We({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},wn=()=>({type:"null"}),Mn=e=>(K(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:Qe.source,externalDocs:{url:Rr}}),Nn=e=>(K(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Rr}}),vn=e=>K.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Dn=()=>({type:"boolean"}),kn=()=>({type:"integer",format:"bigint"}),Ln=e=>e.every(t=>t instanceof T.ZodLiteral),jn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=We({schema:T.object(we(et(o,[t]))),...r}),i.required=o),i}if(e instanceof T.ZodLiteral)return{type:"object",properties:We({schema:T.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof T.ZodUnion&&Ln(e.options)){let o=le(s=>`${s.value}`,e.options),i=we(et(o,[t]));return{type:"object",properties:We({schema:T.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},Un=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},Hn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Kn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:m}}})=>{let f=m.find(b=>b.kind==="regex"),h=m.find(b=>b.kind==="datetime"),x=f?f.regex:h?h.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,S={type:"string"},g={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let b in g)if(g[b]){S.format=b;break}return r!==null&&(S.minLength=r),o!==null&&(S.maxLength=o),x&&(S.pattern=x.source),S},Fn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},We=({schema:{shape:e},next:t})=>le(t,e),qn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return gn?.[t]},Zr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Bn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!ee(o)){let s=Ue(e,qn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.any())}if(!t&&i.type==="preprocess"&&!ee(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Vn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),$n=({schema:e,next:t})=>t(e.unwrap()),_n=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},Gn=({next:e,schema:t})=>e(t.shape.raw),zr=e=>e.length?we(yn(cn(1,e.length+1).map(t=>`example${t}`),le(Or("value"),e))):void 0,wr=(e,t,r=[])=>Ar(U,le(fn(Wo(w,Xo(Array.isArray)),Xe(r))),zr)({schema:e,variant:t?"parsed":"original",validate:!0}),Yn=(e,t)=>Ar(U,rn(on(t)),dn(t),zr)({schema:e,variant:"original",validate:!0}),ze=(e,t)=>e instanceof T.ZodObject?e:e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion?e.options.map(r=>ze(r,t)).reduce((r,o)=>r.merge(o.partial()),T.object({})):e instanceof T.ZodEffects?(K(e._def.effect.type==="refinement",t),ze(e._def.schema,t)):ze(e._def.left,t).merge(ze(e._def.right,t)),Mr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=ze(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Cr(e),m=o.includes("query"),f=o.includes("params"),h=o.includes("headers"),x=g=>f&&l.includes(g),S=g=>h&&ct(g);return Object.keys(c).filter(g=>m||x(g)).map(g=>{let b=X({schema:c[g],isResponse:!1,rules:Rt,onEach:Pt,onMissing:Ct,serializer:i,getRef:s,makeRef:a,path:e,method:t}),ye=p==="components"?a(z(d,g),b):b;return{name:g,in:x(g)?"path":S(g)?"header":"query",required:!c[g].isOptional(),description:b.description||d,schema:ye,examples:Yn(r,g)}})},Rt={ZodString:Kn,ZodNumber:Fn,ZodBigInt:kn,ZodBoolean:Dn,ZodNull:wn,ZodArray:Un,ZodTuple:Hn,ZodRecord:jn,ZodObject:zn,ZodLiteral:Zn,ZodIntersection:Pn,ZodUnion:On,ZodAny:Tn,ZodDefault:hn,ZodEnum:Sr,ZodNativeEnum:Sr,ZodEffects:Bn,ZodOptional:Cn,ZodNullable:En,ZodDiscriminatedUnion:An,ZodBranded:$n,ZodDate:vn,ZodCatch:xn,ZodPipeline:Vn,ZodLazy:_n,ZodReadonly:In,[H]:Sn,[Ae]:bn,[Ze]:Nn,[Ee]:Mn,[Q]:Gn},Pt=({schema:e,isResponse:t,prev:r})=>{if(ee(r))return{};let{description:o}=e,i=e instanceof T.ZodLazy,s=r.type!==void 0,a=t&&Se(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:U({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Zr(r)),d.length&&(c.examples=d.slice()),c},Ct=({schema:e,...t})=>K.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(ee(e))return e;let r={...e};return r.properties&&(r.properties=Xe(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Xe(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},Nr=e=>ee(e)?e:Xe(["examples"],e),vr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:m=`${e.toUpperCase()} ${t} ${lt(i)} response ${c?l:""}`.trim()})=>{let f=Nr(X({schema:r,isResponse:!0,rules:Rt,onEach:Pt,onMissing:Ct,serializer:s,getRef:a,makeRef:p,path:t,method:e})),h={schema:d==="components"?p(z(m),f):f,examples:wr(r,!0)};return{description:m,content:we(et(o,[h]))}},Qn=()=>({type:"http",scheme:"basic"}),Jn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Wn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Xn=({name:e})=>({type:"apiKey",in:"header",name:e}),ei=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ti=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ri=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),mn(nn,e))}),Dr=(e,t)=>{let r={basic:Qn,bearer:Jn,input:Wn,header:Xn,cookie:ei,openid:ti,oauth2:ri};return Ve(e,o=>r[o.type](o,t))},tt=e=>"or"in e?e.or.map(t=>"and"in t?sn(le(({name:r,scopes:o})=>Or(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?tt(gt(e)):tt({or:[e]}),kr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Cr(t),l=Nr(At(X({schema:r,isResponse:!1,rules:Rt,onEach:Pt,onMissing:Ct,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(z(d),l):l,examples:wr(r,!1,c)};return{description:d,content:we(et(o,[m]))}},Lr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),It=e=>e.length<=br?e:e.slice(0,br-1)+"\u2026";var Et=class extends ni{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||z(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&oi.fail(new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=je}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});W({routing:t,onEndpoint:(m,f,h)=>{let x=h,S={path:f,method:x,endpoint:m,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[g,b]=["short","long"].map(m.getDescription.bind(m)),ye=g?It(g):p&&b?It(b):void 0,Ne=m.getTags(),ge=r.inputSources?.[x]||pt[x],re=this.ensureUniqOperationId(f,x,m.getOperationId(x)),ve=Mr({...S,inputSources:ge,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:x,path:f,operationId:re})}),De={};for(let v of["positive","negative"]){let V=m.getResponses(v);for(let{mimeTypes:he,schema:O,statusCodes:A}of V)for(let C of A)De[C]=vr({...S,variant:v,schema:O,mimeTypes:he,statusCode:C,hasMultipleStatusCodes:V.length>1||A.length>1,description:a?.[`${v}Response`]?.call(null,{method:x,path:f,operationId:re,statusCode:C})})}let st=ge.includes("body")?kr({...S,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:x,path:f,operationId:re})}):void 0,ke=tt(Ve(Dr(m.getSecurity(),ge),v=>{let V=this.ensureUniqSecuritySchemaName(v),he=["oauth2","openIdConnect"].includes(v.type)?m.getScopes():[];return this.addSecurityScheme(V,v),{name:V,scopes:he}}));this.addPath(Ir(f),{[x]:{operationId:re,summary:ye,description:b,tags:Ne.length>0?Ne:void 0,parameters:ve.length>0?ve:void 0,requestBody:st,security:ke.length>0?ke:void 0,responses:De}})}}),this.rootDoc.tags=r.tags?Lr(r.tags):[]}};import jr from"http";var ii=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>Z.json),...t}),si=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:jr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=jr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},ai=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),pi=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await ar([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=ii({fnMethod:a,requestProps:t}),d=si({fnMethod:a,responseProps:r}),c=ai({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import M from"typescript";import D from"typescript";import{chain as Ur,toPairs as Hr}from"ramda";var n=D.factory,F=[n.createModifier(D.SyntaxKind.ExportKeyword)],di=[n.createModifier(D.SyntaxKind.AsyncKeyword)],ci=[n.createModifier(D.SyntaxKind.PublicKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],Kr=[n.createModifier(D.SyntaxKind.ProtectedKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],Zt=n.createTemplateHead(""),ue=n.createTemplateTail(""),zt=n.createTemplateMiddle(" "),wt=e=>n.createTemplateLiteralType(Zt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ue:zt))),Mt=wt(["M","P"]),rt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ot=(e,t)=>Ur(([r,o])=>[rt(n.createIdentifier(r),o,t)],Hr(e)),Nt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Fr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),qr=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),q=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.NodeFlags.Const),vt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),nt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,t),Br=(e,t,r)=>n.createPropertyDeclaration(ci,e,void 0,t,r),Vr=(e,t,r)=>n.createClassDeclaration(F,e,void 0,void 0,[t,...r]),$r=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),_r=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.SyntaxKind.AnyKeyword)]),Gr=(e,t,r)=>n.createInterfaceDeclaration(F,e,void 0,t,r),Yr=e=>Ur(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Hr(e)),Dt=(e,t,r)=>n.createArrowFunction(r?di:void 0,void 0,e.map(o=>rt(o)),void 0,void 0,t),kt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,ot({acc:void 0,key:void 0}),void 0,void 0,t),r]),Qr=(...e)=>`"${e.join(" ")}"`;var Jr=["get","post","put","delete","patch"];import y from"typescript";import{z as Ut}from"zod";import B from"typescript";var{factory:it}=B,Lt=(e,t)=>{B.addSyntheticLeadingComment(e,B.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},fe=(e,t,r)=>{let o=it.createTypeAliasDeclaration(void 0,it.createIdentifier(t),void 0,e);return r&&Lt(o,r),o},jt=(e,t)=>{let r=B.createSourceFile("print.ts","",B.ScriptTarget.Latest,!1,B.ScriptKind.TS);return B.createPrinter(t).printNode(B.EmitHint.Unspecified,e,r)},mi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Wr=e=>mi.test(e)?it.createIdentifier(e):it.createStringLiteral(e);var{factory:u}=y,li={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},ui=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),fi=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Se(a)?a instanceof Ut.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Wr(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},yi=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),gi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Xr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),hi=e=>li?.[e.kind],xi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Ue(e,hi(o)),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||y.SyntaxKind.AnyKeyword)}return o},Ti=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),bi=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Si=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Oi=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Ai=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Ri=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Pi=({next:e,schema:t})=>e(t._def.innerType),te=e=>()=>u.createKeywordTypeNode(e),Ci=({next:e,schema:t})=>e(t.unwrap()),Ii=({next:e,schema:t})=>e(t._def.innerType),Ei=({next:e,schema:t})=>e(t._def.innerType),Zi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),zi=()=>u.createLiteralTypeNode(u.createNull()),wi=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},Mi=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof Ut.ZodString?t:e instanceof Ut.ZodUnion?o:r},Ni=({next:e,schema:t})=>e(t.shape.raw),vi={ZodString:te(y.SyntaxKind.StringKeyword),ZodNumber:te(y.SyntaxKind.NumberKeyword),ZodBigInt:te(y.SyntaxKind.BigIntKeyword),ZodBoolean:te(y.SyntaxKind.BooleanKeyword),ZodAny:te(y.SyntaxKind.AnyKeyword),[Ee]:te(y.SyntaxKind.StringKeyword),[Ze]:te(y.SyntaxKind.StringKeyword),ZodNull:zi,ZodArray:yi,ZodTuple:Oi,ZodRecord:Ai,ZodObject:fi,ZodLiteral:ui,ZodIntersection:Ri,ZodUnion:Xr,ZodDefault:Pi,ZodEnum:gi,ZodNativeEnum:Ti,ZodEffects:xi,ZodOptional:bi,ZodNullable:Si,ZodDiscriminatedUnion:Xr,ZodBranded:Ci,ZodCatch:Ei,ZodPipeline:Zi,ZodLazy:wi,ZodReadonly:Ii,[H]:Mi,[Q]:Ni},Me=({schema:e,...t})=>X({schema:e,rules:vi,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Ht=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,fe(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=je,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(O,A,C)=>{let oe={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},xe=z(C,A,"input"),Te=Me({...oe,schema:O.getSchema("input"),isResponse:!1}),E=i?z(C,A,"positive.response"):void 0,Kt=O.getSchema("positive"),Ft=i?Me({...oe,isResponse:!0,schema:Kt}):void 0,be=i?z(C,A,"negative.response"):void 0,qt=O.getSchema("negative"),Bt=i?Me({...oe,isResponse:!0,schema:qt}):void 0,Vt=z(C,A,"response"),eo=E&&be?n.createUnionTypeNode([n.createTypeReferenceNode(E),n.createTypeReferenceNode(be)]):Me({...oe,isResponse:!0,schema:Kt.or(qt)});this.program.push(fe(Te,xe)),Ft&&E&&this.program.push(fe(Ft,E)),Bt&&be&&this.program.push(fe(Bt,be)),this.program.push(fe(eo,Vt)),C!=="options"&&(this.paths.push(A),this.registry.set({method:C,path:A},{input:xe,positive:E,negative:be,response:Vt,isJson:O.getMimeTypes("positive").includes(Z.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(vt(this.ids.pathType,this.paths)),this.program.push(vt(this.ids.methodType,Jr)),this.program.push(nt(this.ids.methodPathType,wt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(M.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,M.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:O,path:A},{isJson:C,tags:oe,...xe}]of this.registry){let Te=Qr(O,A);for(let E of this.interfaces)E.kind in xe&&E.props.push(qr(Te,xe[E.kind]));r!=="types"&&(C&&p.push(n.createPropertyAssignment(Te,n.createTrue())),d.push(n.createPropertyAssignment(Te,n.createArrayLiteralExpression(oe.map(E=>n.createStringLiteral(E))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(Gr(O,a,A));if(r==="types")return;let c=n.createVariableStatement(F,q(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),l=n.createVariableStatement(F,q(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),m=nt(this.ids.providerType,n.createFunctionTypeNode(Yr({M:this.ids.methodType,P:this.ids.pathType}),ot({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Mt)}),$r(this.ids.responseInterface,Mt))),f=nt(this.ids.implementationType,n.createFunctionTypeNode(void 0,ot({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(M.SyntaxKind.StringKeyword),params:Nt(M.SyntaxKind.StringKeyword,M.SyntaxKind.AnyKeyword)}),_r())),h=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ue)]),x=kt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[h,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),S=kt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[h]),M.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),g=Vr(this.ids.clientClass,Fr([rt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Kr)]),[Br(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Dt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,x,S]),!0))]);this.program.push(c,l,m,f,g);let b=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ye=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(Z.json))]),void 0,this.ids.undefinedValue)),Ne=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ge=n.createVariableStatement(void 0,q(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,ue)]),n.createObjectLiteralExpression([b,ye,Ne])])))),re=n.createVariableStatement(void 0,q(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=n.createVariableStatement(void 0,q(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),ue)])))),[De,st]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),ke=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Zt,[n.createTemplateSpan(this.ids.methodParameter,zt),n.createTemplateSpan(this.ids.pathParameter,ue)]),M.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([De])),v=n.createVariableStatement(F,q(this.ids.exampleImplementationConst,Dt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([re,ve,ge,ke,st]),!0),n.createTypeReferenceNode(this.ids.implementationType))),V=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),he=n.createVariableStatement(void 0,q(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(v,he,V)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:jt(r,t)).join(`
21
21
  `):void 0}print(t){let r=this.printUsage(t),o=r&&M.addSyntheticLeadingComment(M.addSyntheticLeadingComment(n.createEmptyStatement(),M.SyntaxKind.SingleLineCommentTrivia," Usage example:"),M.SyntaxKind.MultiLineCommentTrivia,`
22
22
  ${r}`);return this.program.concat(o||[]).map((i,s)=>jt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
23
23
 
24
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await me("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Di={dateIn:xr,dateOut:Tr,file:Ke,upload:Wt,raw:Jt};export{ce as AbstractEndpoint,Ce as DependsOnMethod,Et as Documentation,I as DocumentationError,Pe as EndpointsFactory,L as InputValidationError,Ht as Integration,se as MissingPeerError,$ as OutputValidationError,ie as RoutingError,Ie as ServeStatic,Mo as arrayEndpointsFactory,Tt as arrayResultHandler,Yo as attachRouting,to as createConfig,St as createLogger,ht as createMiddleware,xt as createResultHandler,Qo as createServer,wo as defaultEndpointsFactory,Re as defaultResultHandler,Di as ez,U as getExamples,j as getMessageFromError,Le as getStatusCodeFromError,pi as testEndpoint,ho as withMeta};
24
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await me("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Di={dateIn:xr,dateOut:Tr,file:Ke,upload:Wt,raw:Jt};export{ce as AbstractEndpoint,Ce as DependsOnMethod,Et as Documentation,I as DocumentationError,Pe as EndpointsFactory,L as InputValidationError,Ht as Integration,se as MissingPeerError,$ as OutputValidationError,ie as RoutingError,Ie as ServeStatic,Mo as arrayEndpointsFactory,bt as arrayResultHandler,Yo as attachRouting,to as createConfig,St as createLogger,xt as createMiddleware,Tt as createResultHandler,Qo as createServer,wo as defaultEndpointsFactory,Re as defaultResultHandler,Di as ez,U as getExamples,j as getMessageFromError,Le as getStatusCodeFromError,pi as testEndpoint,ho as withMeta};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "18.6.2",
3
+ "version": "18.6.3",
4
4
  "description": "A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {