express-zod-api 18.5.2 → 18.6.0
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 +18 -0
- package/README.md +5 -3
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +12 -2
- package/dist/index.d.ts +12 -2
- package/dist/index.js +8 -8
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 18
|
|
4
4
|
|
|
5
|
+
### v18.6.0
|
|
6
|
+
|
|
7
|
+
- Feat: Supporting async functon as an argument for `EndpointsFactory::addOptions()`:
|
|
8
|
+
- I realized that it does not make sense for `.addOptions` just to proxy the static data;
|
|
9
|
+
- In case your options are static you can just `import` the corresponding `const` instead;
|
|
10
|
+
- Static options are deprecated and its support will be removed in v19.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { readFile } from "node:fs/promises";
|
|
14
|
+
import { defaultEndpointsFactory } from "express-zod-api";
|
|
15
|
+
|
|
16
|
+
const endpointsFactory = defaultEndpointsFactory.addOptions(async () => {
|
|
17
|
+
const db = mongoose.connect("mongodb://connection.string");
|
|
18
|
+
const privateKey = await readFile("private-key.pem", "utf-8");
|
|
19
|
+
return { db, privateKey };
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
5
23
|
### v18.5.2
|
|
6
24
|
|
|
7
25
|
- Muted uploader logs related to non-eligible requests;
|
package/README.md
CHANGED
|
@@ -296,11 +296,13 @@ In case you'd like to provide your endpoints with options that do not depend on
|
|
|
296
296
|
instance, consider shorthand method `addOptions`.
|
|
297
297
|
|
|
298
298
|
```typescript
|
|
299
|
+
import { readFile } from "node:fs/promises";
|
|
299
300
|
import { defaultEndpointsFactory } from "express-zod-api";
|
|
300
301
|
|
|
301
|
-
const endpointsFactory = defaultEndpointsFactory.addOptions({
|
|
302
|
-
db
|
|
303
|
-
privateKey
|
|
302
|
+
const endpointsFactory = defaultEndpointsFactory.addOptions(async () => {
|
|
303
|
+
const db = mongoose.connect("mongodb://connection.string");
|
|
304
|
+
const privateKey = await readFile("private-key.pem", "utf-8");
|
|
305
|
+
return { db, privateKey };
|
|
304
306
|
});
|
|
305
307
|
```
|
|
306
308
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},
|
|
1
|
+
"use strict";var Io=Object.create;var Ve=Object.defineProperty;var Zo=Object.getOwnPropertyDescriptor;var Eo=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 Eo(t))!wo.call(e,i)&&i!==r&&Ve(e,i,{get:()=>t[i],enumerable:!(o=Zo(t,i))||o.enumerable});return e};var O=(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=O(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
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};var Ir=require("ramda");var ne=e=>N(e)&&"or"in e,ge=e=>N(e)&&"and"in e,zt=e=>({and:(0,Ir.chain)(t=>ge(t)?t.and:[t],e)}),tt=(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),wt=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(wt(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{},ot=class extends ie{#e;#o;#n;#i;#t;#s;#a;#r;#p;#d;#c;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.#s=i,this.#a=s,this.#n=d,this.#c=a,this.#o=t,this.#p=p,this.#d=c,this.#e={long:u,short:l},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,Mt.default)(!Xe(T),new B(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:St(s.getPositiveResponse(o),{mimeTypes:[U],statusCodes:[me.positive]}),negative:St(s.getNegativeResponse(),{mimeTypes:[U],statusCodes:[me.negative]})};for(let[y,T]of Object.entries(this.#t))(0,Mt.default)(T.length,new X(`ResultHandler must have at least one ${y} response schema specified.`));this.#i={input:Rr(r)?[$e]:Pr(r)?[pr]:[U],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.#i[t]}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ye(t,r.security):t,{and:[]})}getScopes(){return this.#p}getTags(){return this.#d}getOperationId(t){return this.#c(t)}#m(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#l(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof rt.z.ZodError?new V(r):r}}async#u({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 rt.z.ZodError?new j(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#f({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof rt.z.ZodError?new j(s):s}return this.#s({input:i,options:r,logger:o})}async#y({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#a.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){et({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=At(t),p={},d=null,c=null;if(i.cors){let l=this.#m(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=lr(t,i.inputSources);try{if(await this.#u({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.#l(await this.#f({input:u,logger:o,options:p}))}catch(l){c=ue(l)}await this.#y({input:u,output:d,request:t,response:r,error:c,logger:o,options:p})}};var Nt=require("zod");var Cr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>fr(s,i),o)};var Zr=R(require("assert/strict"),1),nt=e=>((0,Zr.default)(!Xe(e.input),new B("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var v=require("zod");var it=e=>e,he=it({getPositiveResponse:e=>{let t=K({schema:e}),r=v.z.object({status:v.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>v.z.object({status:v.z.literal("error"),error:v.z.object({message:v.z.string()})}).example({status:"error",error:{message:H(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);Pt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:H(e)}})}}),st=it({getPositiveResponse:e=>{let t=K({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.z.ZodArray?e.shape.items:v.z.array(v.z.any());return t.reduce((o,i)=>N(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>v.z.string().example(H(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Me(r);Pt({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:Nt.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(nt({input:Nt.z.object({}),middleware:async()=>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 ot({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:y,tags:T,methods:u,getOperationId:l,description:i,shortDescription:s,inputSchema:Cr(d,t)})}},Er=new xe(he),zr=new xe(st);var wr=require("util");var Mr=require("ramda"),D=require("ansis"),vt={debug:10,info:20,warn:30,error:40},Nr=e=>N(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"),at=({level:e,color:t=new D.Ansis().isSupported(),depth:r=2})=>{let o={debug:D.blue,info:D.green,warn:(0,D.hex)("#FFA500"),error:D.red},i=e==="debug",s=e==="silent"?100:vt[e],a=(p,d,c)=>{if(vt[p]<s)return;let u=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&u.push((0,wr.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Mr.mapObjIndexed)(({},p)=>(d,c)=>a(p,d,c),vt)};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 vr=R(require("express"),1),Se=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,vr.default.static(...this.params))}};var Lt=R(require("express"),1),Kr=R(require("http"),1),Fr=R(require("https"),1);var Oe=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>require(e)[t])}catch{}throw new ee(e)},Dr=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 Dt=R(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){Dt.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,Dt.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 kt=({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=R(require("http-errors"),1);var kr=({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})},Lr=({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){et({response:i,logger:a,error:new X(ue(p).message,s)})}},jr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Hr=e=>({log:(t,...r)=>{/not eligible/.test(t)||e.debug(t,...r)}});var z=require("ansis"),Ur=()=>{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,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},Z=(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:()=>Z(_,ur),string:()=>Z(_,fe.z.string()),binary:()=>Z(_,ur.or(fe.z.string())),base64:()=>{let e=fe.z.string(),t=e.base64?.()instanceof fe.z.ZodString;return Z(_,t?e.base64():e.regex(Uo,"Does not match base64 encoding"))}};function Qe(e){return Ho[e||"string"]()}var oe="Raw",yr=()=>Z(oe,fr.z.object({raw:Qe("buffer")}));var gr=require("zod");var ve="Upload",hr=()=>Z(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,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),Et=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(Et(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,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=O(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 Zr=require("util");var Er=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,Zr.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Er.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=O(require("express"),1),Se=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,wr.default.static(...this.params))}};var Dt=O(require("express"),1),jr=O(require("http"),1),Ur=O(require("https"),1);var Oe=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>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=O(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=O(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,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 qr=e=>{e.startupLogo!==!1&&console.log(Ur());let t=Nr(e.logger)?at(e.logger):e.logger;t.debug("Running","v18.5.2 (CJS)");let r=e.errorHandler||he,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=Lr(i),a=kr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Br=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=qr(e);return kt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Vr=async(e,t)=>{let r=(0,Lt.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||Lt.default.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=qr(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:Hr(o)})),c&&r.use(jr(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}),kt({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(Kr.default.createServer(r),e.server.listen),httpsServer:e.https?a(Fr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};var lo=R(require("assert/strict"),1),uo=require("openapi3-ts/oas31");var F=R(require("assert/strict"),1),_=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",$r=()=>{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 Z(Le,r.transform(o=>new Date(o)).pipe(ke.z.date().refine(pt)))};var _r=require("zod");var je="DateOut",Gr=()=>Z(je,_r.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 Yr=50,Qr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Yo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Wr=/:([A-Za-z0-9_]+)/g,Xr=e=>e.match(Wr)?.map(t=>t.slice(1))||[],eo=e=>e.replace(Wr,t=>`{${t.slice(1)}}`),Jo=({schema:e,next:t})=>({...t(e._def.innerType),default:re(e,"defaultLabel")||e._def.defaultValue()}),Qo=({schema:{_def:{innerType:e}},next:t})=>t(e),Wo=()=>({format:"any"}),Xo=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),en=({schema:e})=>({type:"string",format:e instanceof x.z.ZodString?e._def.checks.find(t=>t.kind==="regex"||t.kind==="base64")?"byte":"file":"binary"}),tn=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),rn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),on=e=>{let[t,r]=e.filter(i=>!(0,_.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,F.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:F.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},nn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return on(o)}catch{}return{allOf:o}},sn=({schema:e,next:t})=>t(e.unwrap()),an=({schema:e,next:t})=>t(e._def.innerType),pn=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=ro(r)),r},to=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},Jr=({schema:e})=>({type:to(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),dn=({schema:{value:e}})=>({type:to(e),const:e}),cn=({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},mn=()=>({type:"null"}),ln=e=>((0,F.default)(!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:dt.source,externalDocs:{url:Qr}}),un=e=>((0,F.default)(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:Qr}}),fn=e=>F.default.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})),yn=()=>({type:"boolean"}),gn=()=>({type:"integer",format:"bigint"}),hn=e=>e.every(t=>t instanceof x.z.ZodLiteral),xn=({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&&hn(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)}},Tn=({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},bn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Sn=({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(S=>S.kind==="regex"),T=l.find(S=>S.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,P={type:"string"},h={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let S in h)if(h[S]){P.format=S;break}return r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),b&&(P.pattern=b.source),P},On=({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),An=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Yo?.[t]},ro=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Rn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=Ge(e,An(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(x.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Pn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),In=({schema:e,next:t})=>t(e.unwrap()),Cn=({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)))},Zn=({next:e,schema:t})=>e(t.shape.raw),oo=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,no=(e,t,r=[])=>(0,m.pipe)(K,(0,m.map)((0,m.when)((0,m.both)(N,(0,m.complement)(Array.isArray)),(0,m.omit)(r))),oo)({schema:e,variant:t?"parsed":"original",validate:!0}),En=(e,t)=>(0,m.pipe)(K,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),oo)({schema:e,variant:"original",validate:!0}),He=(e,t)=>e instanceof x.z.ZodObject?e:e instanceof x.z.ZodUnion||e instanceof x.z.ZodDiscriminatedUnion?e.options.map(r=>He(r,t)).reduce((r,o)=>r.merge(o.partial()),x.z.object({})):e instanceof x.z.ZodEffects?((0,F.default)(e._def.effect.type==="refinement",t),He(e._def.schema,t)):He(e._def.left,t).merge(He(e._def.right,t)),io=({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}=He(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=Xr(e),l=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),b=h=>y&&u.includes(h),P=h=>T&&Rt(h);return Object.keys(c).filter(h=>l||b(h)).map(h=>{let S=ae({schema:c[h],isResponse:!1,rules:Ht,onEach:Ut,onMissing:Kt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Ie=p==="components"?a(M(d,h),S):S;return{name:h,in:b(h)?"path":P(h)?"header":"query",required:!c[h].isOptional(),description:S.description||d,schema:Ie,examples:En(r,h)}})},Ht={ZodString:Sn,ZodNumber:On,ZodBigInt:gn,ZodBoolean:yn,ZodNull:mn,ZodArray:Tn,ZodTuple:bn,ZodRecord:xn,ZodObject:cn,ZodLiteral:dn,ZodIntersection:nn,ZodUnion:tn,ZodAny:Wo,ZodDefault:Jo,ZodEnum:Jr,ZodNativeEnum:Jr,ZodEffects:Rn,ZodOptional:sn,ZodNullable:pn,ZodDiscriminatedUnion:rn,ZodBranded:In,ZodDate:fn,ZodCatch:Qo,ZodPipeline:Pn,ZodLazy:Cn,ZodReadonly:an,[$]:en,[ve]:Xo,[je]:un,[Le]:ln,[oe]:Zn},Ut=({schema:e,isResponse:t,prev:r})=>{if((0,_.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?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=ro(r)),d.length&&(c.examples=d.slice()),c},Kt=({schema:e,...t})=>F.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),jt=(e,t)=>{if((0,_.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=>jt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>jt(o,t))),r},so=e=>(0,_.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),ao=({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} ${It(i)} response ${c?u:""}`.trim()})=>{let y=so(ae({schema:r,isResponse:!0,rules:Ht,onEach:Ut,onMissing:Kt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(M(l),y):y,examples:no(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[T]))}},zn=()=>({type:"http",scheme:"basic"}),wn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Mn=({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},Nn=({name:e})=>({type:"apiKey",in:"header",name:e}),vn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Dn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),kn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),po=(e,t)=>{let r={basic:zn,bearer:wn,input:Mn,header:Nn,cookie:vn,openid:Dn,oauth2:kn};return tt(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(wt(e)):mt({or:[e]}),co=({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=Xr(t),u=so(jt(ae({schema:r,isResponse:!1,rules:Ht,onEach:Ut,onMissing:Kt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(M(d),u):u,examples:no(r,!1,c)};return{description:d,content:(0,m.fromPairs)((0,m.xprod)(o,[l]))}},mo=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}),Ft=e=>e.length<=Yr?e:e.slice(0,Yr-1)+"\u2026";var lt=class extends uo.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||M(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&lo.default.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=_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,P={path:y,method:b,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,S]=["short","long"].map(l.getDescription.bind(l)),Ie=h?Ft(h):p&&S?Ft(S):void 0,Ke=l.getTags(),Ce=r.inputSources?.[b]||Ot[b],de=this.ensureUniqOperationId(y,b,l.getOperationId(b)),Fe=io({...P,inputSources:Ce,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:y,operationId:de})}),qe={};for(let L of["positive","negative"]){let J=l.getResponses(L);for(let{mimeTypes:Ze,schema:O,statusCodes:A}of J)for(let E of A)qe[E]=ao({...P,variant:L,schema:O,mimeTypes:Ze,statusCode:E,hasMultipleStatusCodes:J.length>1||A.length>1,description:a?.[`${L}Response`]?.call(null,{method:b,path:y,operationId:de,statusCode:E})})}let bt=Ce.includes("body")?co({...P,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:y,operationId:de})}):void 0,Be=mt(tt(po(l.getSecurity(),Ce),L=>{let J=this.ensureUniqSecuritySchemaName(L),Ze=["oauth2","openIdConnect"].includes(L.type)?l.getScopes():[];return this.addSecurityScheme(J,L),{name:J,scopes:Ze}}));this.addPath(eo(y),{[b]:{operationId:de,summary:Ie,description:S,tags:Ke.length>0?Ke:void 0,parameters:Fe.length>0?Fe:void 0,requestBody:bt,security:Be.length>0?Be:void 0,responses:qe}})}}),this.rootDoc.tags=r.tags?mo(r.tags):[]}};var qt=R(require("http"),1);var Ln=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>U),...t}),jn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:qt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=qt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},Hn=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),fo=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Dr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Ln({fnMethod:a,requestProps:t}),d=jn({fnMethod:a,responseProps:r}),c=Hn({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=R(require("typescript"),1);var k=R(require("typescript"),1),Ae=require("ramda"),n=k.default.factory,G=[n.createModifier(k.default.SyntaxKind.ExportKeyword)],Un=[n.createModifier(k.default.SyntaxKind.AsyncKeyword)],Kn=[n.createModifier(k.default.SyntaxKind.PublicKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],yo=[n.createModifier(k.default.SyntaxKind.ProtectedKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],Bt=n.createTemplateHead(""),Re=n.createTemplateTail(""),Vt=n.createTemplateMiddle(" "),$t=e=>n.createTemplateLiteralType(Bt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Re:Vt))),_t=$t(["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)),Gt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),go=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),ho=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Y=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.default.NodeFlags.Const),Yt=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),yt=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,t),xo=(e,t,r)=>n.createPropertyDeclaration(Kn,e,void 0,t,r),To=(e,t,r)=>n.createClassDeclaration(G,e,void 0,void 0,[t,...r]),bo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),So=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.default.SyntaxKind.AnyKeyword)]),Oo=(e,t,r)=>n.createInterfaceDeclaration(G,e,void 0,t,r),Ao=e=>(0,Ae.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Ae.toPairs)(e)),Jt=(e,t,r)=>n.createArrowFunction(r?Un:void 0,void 0,e.map(o=>ut(o)),void 0,void 0,t),Qt=(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]),gt=(...e)=>`"${e.join(" ")}"`;var Ro=["get","post","put","delete","patch"];var g=R(require("typescript"),1),xt=require("zod");var q=R(require("typescript"),1),{factory:ht}=q.default,Wt=(e,t)=>{q.default.addSyntheticLeadingComment(e,q.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Pe=(e,t,r)=>{let o=ht.createTypeAliasDeclaration(void 0,ht.createIdentifier(t),void 0,e);return r&&Wt(o,r),o},Xt=(e,t)=>{let r=q.default.createSourceFile("print.ts","",q.default.ScriptTarget.Latest,!1,q.default.ScriptKind.TS);return q.default.createPrinter(t).printNode(q.default.EmitHint.Unspecified,e,r)},Fn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Po=e=>Fn.test(e)?ht.createIdentifier(e):ht.createStringLiteral(e);var{factory:f}=g.default,qn={[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},Bn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),Vn=({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 xt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,Po(s),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Wt(d,a.description),d});return f.createTypeLiteralNode(i)},$n=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),_n=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Io=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),Gn=e=>qn?.[e.kind],Yn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Ge(e,Gn(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},Jn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Qn=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Wn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Xn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),ei=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),ti=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ri=({next:e,schema:t})=>e(t._def.innerType),pe=e=>()=>f.createKeywordTypeNode(e),oi=({next:e,schema:t})=>e(t.unwrap()),ni=({next:e,schema:t})=>e(t._def.innerType),ii=({next:e,schema:t})=>e(t._def.innerType),si=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),ai=()=>f.createLiteralTypeNode(f.createNull()),pi=({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)))},di=({schema:e})=>{let t=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),r=f.createTypeReferenceNode("Buffer"),o=f.createUnionTypeNode([t,r]);return e instanceof xt.z.ZodString?t:e instanceof xt.z.ZodUnion?o:r},ci=({next:e,schema:t})=>e(t.shape.raw),mi={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:ai,ZodArray:$n,ZodTuple:Xn,ZodRecord:ei,ZodObject:Vn,ZodLiteral:Bn,ZodIntersection:ti,ZodUnion:Io,ZodDefault:ri,ZodEnum:_n,ZodNativeEnum:Jn,ZodEffects:Yn,ZodOptional:Qn,ZodNullable:Wn,ZodDiscriminatedUnion:Io,ZodBranded:oi,ZodCatch:ii,ZodPipeline:si,ZodLazy:pi,ZodReadonly:ni,[$]:di,[oe]:ci},Ue=({schema:e,...t})=>ae({schema:e,rules:mi,onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),...t});var Tt=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:(O,A,E)=>{let ce={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},Ee=M(E,A,"input"),Q=Ue({...ce,schema:O.getSchema("input"),isResponse:!1}),ze=i?M(E,A,"positive.response"):void 0,er=O.getSchema("positive"),tr=i?Ue({...ce,isResponse:!0,schema:er}):void 0,we=i?M(E,A,"negative.response"):void 0,rr=O.getSchema("negative"),or=i?Ue({...ce,isResponse:!0,schema:rr}):void 0,nr=M(E,A,"response"),Zo=ze&&we?n.createUnionTypeNode([n.createTypeReferenceNode(ze),n.createTypeReferenceNode(we)]):Ue({...ce,isResponse:!0,schema:er.or(rr)});this.program.push(Pe(Q,Ee)),tr&&ze&&this.program.push(Pe(tr,ze)),or&&we&&this.program.push(Pe(or,we)),this.program.push(Pe(Zo,nr)),E!=="options"&&(this.paths.push(A),this.registry.set({method:E,path:A},{input:Ee,positive:ze,negative:we,response:nr,isJson:O.getMimeTypes("positive").includes(U),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Yt(this.ids.pathType,this.paths)),this.program.push(Yt(this.ids.methodType,Ro)),this.program.push(yt(this.ids.methodPathType,$t([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.default.SyntaxKind.ExtendsKeyword,[Gt(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:O,path:A},{isJson:E,tags:ce,...Ee}]of this.registry){for(let Q of this.interfaces)Q.kind in Ee&&Q.props.push(ho(gt(O,A),Ee[Q.kind]));r!=="types"&&(E&&p.push(n.createPropertyAssignment(gt(O,A),n.createTrue())),d.push(n.createPropertyAssignment(gt(O,A),n.createArrayLiteralExpression(ce.map(Q=>n.createStringLiteral(Q))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(Oo(O,a,A));if(r==="types")return;let c=n.createVariableStatement(G,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),u=n.createVariableStatement(G,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),l=yt(this.ids.providerType,n.createFunctionTypeNode(Ao({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),_t)}),bo(this.ids.responseInterface,_t))),y=yt(this.ids.implementationType,n.createFunctionTypeNode(void 0,ft({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.default.SyntaxKind.StringKeyword),params:Gt(w.default.SyntaxKind.StringKeyword,w.default.SyntaxKind.AnyKeyword)}),So())),T=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Re)]),b=Qt(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),P=Qt(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=To(this.ids.clientClass,go([ut(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),yo)]),[xo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Jt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,P]),!0))]);this.program.push(c,u,l,y,h);let S=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ie=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(U))]),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)),Ce=n.createVariableStatement(void 0,Y(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([S,Ie,Ke])])))),de=n.createVariableStatement(void 0,Y(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,Y(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,bt]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),Be=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Bt,[n.createTemplateSpan(this.ids.methodParameter,Vt),n.createTemplateSpan(this.ids.pathParameter,Re)]),w.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([qe])),L=n.createVariableStatement(G,Y(this.ids.exampleImplementationConst,Jt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([de,Fe,Ce,Be,bt]),!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"))])])),Ze=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(L,Ze,J)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Xt(r,t)).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.0 (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=O(require("assert/strict"),1),co=require("openapi3-ts/oas31");var q=O(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 Z(Le,r.transform(o=>new Date(o)).pipe(ke.z.date().refine(at)))};var Br=require("zod");var je="DateOut",Vr=()=>Z(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(S=>S.kind==="regex"),T=l.find(S=>S.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 S in h)if(h[S]){A.format=S;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 S=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),S):S;return{name:h,in:b(h)?"path":A(h)?"header":"query",required:!c[h].isOptional(),description:S.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]))}},Zn=()=>({type:"http",scheme:"basic"}),En=({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:Zn,bearer:En,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(Et(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,S]=["short","long"].map(l.getDescription.bind(l)),Ce=h?Ht(h):p&&S?Ht(S):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:Ze,schema:R,statusCodes:P}of J)for(let E of P)qe[E]=no({...A,variant:U,schema:R,mimeTypes:Ze,statusCode:E,hasMultipleStatusCodes:J.length>1||P.length>1,description:a?.[`${U}Response`]?.call(null,{method:b,path:y,operationId:de,statusCode:E})})}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),Ze=["oauth2","openIdConnect"].includes(U.type)?l.getScopes():[];return this.addSecurityScheme(J,U),{name:J,scopes:Ze}}));this.addPath(Jr(y),{[b]:{operationId:de,summary:Ce,description:S,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=O(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=O(require("typescript"),1);var j=O(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=O(require("typescript"),1),gt=require("zod");var B=O(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,E)=>{let ce={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},Ee=v(E,P,"input"),ze=He({...ce,schema:R.getSchema("input"),isResponse:!1}),M=i?v(E,P,"positive.response"):void 0,Wt=R.getSchema("positive"),Xt=i?He({...ce,isResponse:!0,schema:Wt}):void 0,we=i?v(E,P,"negative.response"):void 0,er=R.getSchema("negative"),tr=i?He({...ce,isResponse:!0,schema:er}):void 0,rr=v(E,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,Ee)),Xt&&M&&this.program.push(Pe(Xt,M)),tr&&we&&this.program.push(Pe(tr,we)),this.program.push(Pe(Co,rr)),E!=="options"&&(this.paths.push(P),this.registry.set({method:E,path:P},{input:Ee,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:E,tags:ce,...Ee}]of this.registry){let ze=So(R,P);for(let M of this.interfaces)M.kind in Ee&&M.props.push(fo(ze,Ee[M.kind]));r!=="types"&&(E&&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 S=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([S,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"))])])),Ze=n.createVariableStatement(void 0,Q(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(U,Ze,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
|
-
${r}`);return this.program.concat(o||[]).map((i,s)=>
|
|
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 Oe("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
|
|
24
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Oe("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 Po={dateIn:qr,dateOut:Vr,file:Qe,upload:hr,raw:yr};0&&(module.exports={AbstractEndpoint,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,MissingPeerError,OutputValidationError,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createLogger,createMiddleware,createResultHandler,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint,withMeta});
|
package/dist/index.d.cts
CHANGED
|
@@ -206,6 +206,13 @@ type ProbableIntersection<A extends IOSchema<"strip"> | null, B extends IOSchema
|
|
|
206
206
|
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
207
207
|
type Method = (typeof methods)[number];
|
|
208
208
|
|
|
209
|
+
declare const contentTypes: {
|
|
210
|
+
json: string;
|
|
211
|
+
upload: string;
|
|
212
|
+
raw: string;
|
|
213
|
+
};
|
|
214
|
+
type ContentType = keyof typeof contentTypes;
|
|
215
|
+
|
|
209
216
|
interface ResultHandlerParams<RES> {
|
|
210
217
|
/** null in case of failure to parse or to find the matching endpoint (error: not found) */
|
|
211
218
|
input: FlatObject | null;
|
|
@@ -290,6 +297,7 @@ declare abstract class AbstractEndpoint {
|
|
|
290
297
|
abstract getScopes(): string[];
|
|
291
298
|
abstract getTags(): string[];
|
|
292
299
|
abstract getOperationId(method: Method): string | undefined;
|
|
300
|
+
abstract getRequestType(): ContentType;
|
|
293
301
|
}
|
|
294
302
|
declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends FlatObject, SCO extends string, TAG extends string> extends AbstractEndpoint {
|
|
295
303
|
#private;
|
|
@@ -312,6 +320,7 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
312
320
|
getSchema(variant: "output"): OUT;
|
|
313
321
|
getSchema(variant: ResponseVariant): z.ZodTypeAny;
|
|
314
322
|
getMimeTypes(variant: MimeVariant): string[];
|
|
323
|
+
getRequestType(): "raw" | "json" | "upload";
|
|
315
324
|
getResponses(variant: ResponseVariant): Required<Pick<ApiResponse<z.ZodTypeAny>, "schema" | "statusCodes" | "mimeTypes">>[];
|
|
316
325
|
getSecurity(): LogicalContainer<Security>;
|
|
317
326
|
getScopes(): SCO[];
|
|
@@ -494,7 +503,8 @@ declare class EndpointsFactory<IN extends IOSchema<"strip"> | null = null, OUT e
|
|
|
494
503
|
addMiddleware<AIN extends IOSchema<"strip">, AOUT extends FlatObject, ASCO extends string>(subject: MiddlewareDefinition<AIN, OUT, AOUT, ASCO>): EndpointsFactory<ProbableIntersection<IN, AIN>, OUT & AOUT, SCO & ASCO, TAG>;
|
|
495
504
|
use: <R extends Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>>, S extends Response<any, Record<string, any>>, AOUT extends FlatObject = {}>(middleware: ExpressMiddleware<R, S>, features?: ExpressMiddlewareFeatures<R, S, AOUT>) => EndpointsFactory<IN, OUT & AOUT, SCO, TAG>;
|
|
496
505
|
addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = {}>(middleware: ExpressMiddleware<R, S>, features?: ExpressMiddlewareFeatures<R, S, AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO, TAG>;
|
|
497
|
-
|
|
506
|
+
/** @todo remove the static options in v19 - it makes no sense */
|
|
507
|
+
addOptions<AOUT extends FlatObject>(options: AOUT | (() => Promise<AOUT>)): EndpointsFactory<IN, OUT & AOUT, SCO, TAG>;
|
|
498
508
|
build<BIN extends IOSchema, BOUT extends IOSchema>({ input, handler, output: outputSchema, description, shortDescription, operationId, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO, TAG>): Endpoint<ProbableIntersection<IN, BIN>, BOUT, OUT, SCO, TAG>;
|
|
499
509
|
}
|
|
500
510
|
declare const defaultEndpointsFactory: EndpointsFactory<null, {}, string, string>;
|
|
@@ -724,7 +734,7 @@ declare const testEndpoint: <LOG extends Record<string, any>, REQ extends Record
|
|
|
724
734
|
writableEnded: boolean;
|
|
725
735
|
statusCode: number;
|
|
726
736
|
statusMessage: string;
|
|
727
|
-
} & Record<"status" | "set" | "header" | "
|
|
737
|
+
} & Record<"status" | "set" | "header" | "json" | "end" | "setHeader" | "send", MockOverrides> & RES;
|
|
728
738
|
loggerMock: Record<"error" | "info" | "debug" | "warn", MockOverrides> & LOG;
|
|
729
739
|
}>;
|
|
730
740
|
|
package/dist/index.d.ts
CHANGED
|
@@ -206,6 +206,13 @@ type ProbableIntersection<A extends IOSchema<"strip"> | null, B extends IOSchema
|
|
|
206
206
|
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
207
207
|
type Method = (typeof methods)[number];
|
|
208
208
|
|
|
209
|
+
declare const contentTypes: {
|
|
210
|
+
json: string;
|
|
211
|
+
upload: string;
|
|
212
|
+
raw: string;
|
|
213
|
+
};
|
|
214
|
+
type ContentType = keyof typeof contentTypes;
|
|
215
|
+
|
|
209
216
|
interface ResultHandlerParams<RES> {
|
|
210
217
|
/** null in case of failure to parse or to find the matching endpoint (error: not found) */
|
|
211
218
|
input: FlatObject | null;
|
|
@@ -290,6 +297,7 @@ declare abstract class AbstractEndpoint {
|
|
|
290
297
|
abstract getScopes(): string[];
|
|
291
298
|
abstract getTags(): string[];
|
|
292
299
|
abstract getOperationId(method: Method): string | undefined;
|
|
300
|
+
abstract getRequestType(): ContentType;
|
|
293
301
|
}
|
|
294
302
|
declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends FlatObject, SCO extends string, TAG extends string> extends AbstractEndpoint {
|
|
295
303
|
#private;
|
|
@@ -312,6 +320,7 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
312
320
|
getSchema(variant: "output"): OUT;
|
|
313
321
|
getSchema(variant: ResponseVariant): z.ZodTypeAny;
|
|
314
322
|
getMimeTypes(variant: MimeVariant): string[];
|
|
323
|
+
getRequestType(): "raw" | "json" | "upload";
|
|
315
324
|
getResponses(variant: ResponseVariant): Required<Pick<ApiResponse<z.ZodTypeAny>, "schema" | "statusCodes" | "mimeTypes">>[];
|
|
316
325
|
getSecurity(): LogicalContainer<Security>;
|
|
317
326
|
getScopes(): SCO[];
|
|
@@ -494,7 +503,8 @@ declare class EndpointsFactory<IN extends IOSchema<"strip"> | null = null, OUT e
|
|
|
494
503
|
addMiddleware<AIN extends IOSchema<"strip">, AOUT extends FlatObject, ASCO extends string>(subject: MiddlewareDefinition<AIN, OUT, AOUT, ASCO>): EndpointsFactory<ProbableIntersection<IN, AIN>, OUT & AOUT, SCO & ASCO, TAG>;
|
|
495
504
|
use: <R extends Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>>, S extends Response<any, Record<string, any>>, AOUT extends FlatObject = {}>(middleware: ExpressMiddleware<R, S>, features?: ExpressMiddlewareFeatures<R, S, AOUT>) => EndpointsFactory<IN, OUT & AOUT, SCO, TAG>;
|
|
496
505
|
addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = {}>(middleware: ExpressMiddleware<R, S>, features?: ExpressMiddlewareFeatures<R, S, AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO, TAG>;
|
|
497
|
-
|
|
506
|
+
/** @todo remove the static options in v19 - it makes no sense */
|
|
507
|
+
addOptions<AOUT extends FlatObject>(options: AOUT | (() => Promise<AOUT>)): EndpointsFactory<IN, OUT & AOUT, SCO, TAG>;
|
|
498
508
|
build<BIN extends IOSchema, BOUT extends IOSchema>({ input, handler, output: outputSchema, description, shortDescription, operationId, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO, TAG>): Endpoint<ProbableIntersection<IN, BIN>, BOUT, OUT, SCO, TAG>;
|
|
499
509
|
}
|
|
500
510
|
declare const defaultEndpointsFactory: EndpointsFactory<null, {}, string, string>;
|
|
@@ -724,7 +734,7 @@ declare const testEndpoint: <LOG extends Record<string, any>, REQ extends Record
|
|
|
724
734
|
writableEnded: boolean;
|
|
725
735
|
statusCode: number;
|
|
726
736
|
statusMessage: string;
|
|
727
|
-
} & Record<"status" | "set" | "header" | "
|
|
737
|
+
} & Record<"status" | "set" | "header" | "json" | "end" | "setHeader" | "send", MockOverrides> & RES;
|
|
728
738
|
loggerMock: Record<"error" | "info" | "debug" | "warn", MockOverrides> & LOG;
|
|
729
739
|
}>;
|
|
730
740
|
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},
|
|
1
|
+
var $t=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function ro(e){return e}import nr from"assert/strict";import{z as gt}from"zod";import{z as oo}from"zod";var ne={positive:200,negative:400},st=(e,t)=>e instanceof oo.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 Ao}from"zod";import{isHttpError as no}from"http-errors";import{createHash as io}from"crypto";import{flip as so,pickBy as ao,xprod as po}from"ramda";import{z as co}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 E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var mo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},at={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},lo=["body","query","params"],pt=e=>e.method.toLowerCase(),dt=e=>e.startsWith("x-"),uo=e=>ao(so(dt),e),_t=(e,t={})=>{let r=pt(e);return r==="options"?{}:(t[r]||at[r]||lo).filter(o=>o==="files"?mo(e):!0).map(o=>o==="headers"?uo(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 co.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=>no(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
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};import{chain as Mo}from"ramda";var Q=e=>E(e)&&"or"in e,de=e=>E(e)&&"and"in e,gt=e=>({and:Mo(t=>de(t)?t.and:[t],e)}),$e=(e,t)=>de(e)?{and:e.and.map(r=>Q(r)?{or:r.or.map(t)}:t(r))}:Q(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),ht=e=>e.and.reduce((t,r)=>({or:G(t.or,Q(r)?r.or:[r],gt)}),{or:[]}),pe=(e,t)=>de(e)?Q(t)?pe(ht(e),t):gt([e,t]):Q(e)?de(t)?pe(t,e):Q(t)?{or:G(e.or,t.or,gt)}:pe(e,{and:[t]}):de(t)||Q(t)?pe(t,e):{and:[e,t]};var ce=class{},_e=class extends ce{#e;#o;#n;#i;#t;#s;#a;#r;#p;#d;#c;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.#s=i,this.#a=s,this.#n=d,this.#c=a,this.#o=t,this.#p=p,this.#d=c,this.#e={long:l,short:m},this.#r={input:r,output:o};for(let[f,h]of Object.entries(this.#r))ar(!Be(h),new D(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:pt(s.getPositiveResponse(o),{mimeTypes:[N],statusCodes:[ne.positive]}),negative:pt(s.getNegativeResponse(),{mimeTypes:[N],statusCodes:[ne.negative]})};for(let[f,h]of Object.entries(this.#t))ar(h.length,new _(`ResultHandler must have at least one ${f} response schema specified.`));this.#i={input:ir(r)?[Le]:sr(r)?[Yt]:[N],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.#i[t]}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?pe(t,r.security):t,{and:[]})}getScopes(){return this.#p}getTags(){return this.#d}getOperationId(t){return this.#c(t)}#m(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#l(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof xt.ZodError?new $(r):r}}async#u({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 xt.ZodError?new k(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#f({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof xt.ZodError?new k(s):s}return this.#s({input:i,options:r,logger:o})}async#y({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#a.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Ve({logger:i,response:o,error:new _(ae(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=ct(t),p={},d=null,c=null;if(i.cors){let m=this.#m(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=Jt(t,i.inputSources);try{if(await this.#u({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.#l(await this.#f({input:l,logger:o,options:p}))}catch(m){c=ae(m)}await this.#y({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as dr}from"zod";var pr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Xt(s,i),o)};import No from"assert/strict";var Tt=e=>(No(!Be(e.input),new D("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as w}from"zod";var bt=e=>e,Re=bt({getPositiveResponse:e=>{let t=j({schema:e}),r=w.object({status:w.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>w.object({status:w.literal("error"),error:w.object({message:w.string()})}).example({status:"error",error:{message:L(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=je(e);lt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:L(e)}})}}),St=bt({getPositiveResponse:e=>{let t=j({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof w.ZodArray?e.shape.items:w.array(w.any());return t.reduce((o,i)=>E(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>w.string().example(L(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=je(r);lt({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:dr.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(Tt({input:dr.object({}),middleware:async()=>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:pr(d,t)})}},vo=new Pe(Re),Do=new Pe(St);import{inspect as ko}from"util";import{mapObjIndexed as Lo}from"ramda";import{Ansis as jo,blue as Ho,green as Uo,hex as Ko,red as Fo}from"ansis";var Ot={debug:10,info:20,warn:30,error:40},cr=e=>E(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"),At=({level:e,color:t=new jo().isSupported(),depth:r=2})=>{let o={debug:Ho,info:Uo,warn:Ko("#FFA500"),error:Fo},i=e==="debug",s=e==="silent"?100:Ot[e],a=(p,d,c)=>{if(Ot[p]<s)return;let l=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&l.push(ko(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(l.join(" "))};return Lo(({},p)=>(d,c)=>a(p,d,c),Ot)};import{head as qo,tail as Bo,toPairs as Vo}from"ramda";var Ie=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Vo(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=qo(this.pairs)?.[1],this.siblingMethods=Bo(this.pairs).map(([r])=>r)}};import $o from"express";var Ce=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,$o.static(...this.params))}};import br from"express";import Jo from"http";import Qo from"https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>Gt(e)[t])}catch{}throw new se(e)},mr=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 lr 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){lr.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 Ce)r&&p.apply(d,r);else if(p instanceof Ie){for(let[c,l]of p.pairs)lr(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 Rt=({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 ur,{isHttpError as _o}from"http-errors";var fr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:_o(o)?o:ur(400,ae(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},yr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=ur(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){Ve({response:i,logger:a,error:new _(ae(p).message,s)})}},gr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},hr=e=>({log:(t,...r)=>{/not eligible/.test(t)||e.debug(t,...r)}});import{gray as Go,hex as xr,italic as Ge,whiteBright as Yo}from"ansis";var Tr=()=>{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=xr("#F5A9B8"),s=xr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(Yo,5,7).fill(i,7,9).fill(s,9,12).fill(Go,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?po(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=>io("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 Gt}from"zod";import{clone as fo,mergeDeepRight as yo}from"ramda";var R=Symbol.for("express-zod-api"),He=e=>{let t=e.describe(e.description);return t._def[R]=fo(t._def[R])||{examples:[]},t},go=function(e){let t=He(this);return t._def[R].examples.push(e),t},ho=function(e){let t=He(this);return t._def[R].defaultLabel=e,t};R in globalThis||(globalThis[R]=!0,Object.defineProperty(Gt.ZodType.prototype,"example",{get(){return go.bind(this)}}),Object.defineProperty(Gt.ZodDefault.prototype,"label",{get(){return ho.bind(this)}}));var Yt=e=>R in e._def&&w(e._def[R]),Y=(e,t)=>Yt(e)?e._def[R][t]:void 0,Qt=(e,t)=>{if(!Yt(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"?yo({...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,xo=e=>e;import{z as So}from"zod";import{z as Oe}from"zod";var H="File",Jt=Oe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),To=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,bo={buffer:()=>P(H,Jt),string:()=>P(H,Oe.string()),binary:()=>P(H,Jt.or(Oe.string())),base64:()=>{let e=Oe.string(),t=e.base64?.()instanceof Oe.ZodString;return P(H,t?e.base64():e.regex(To,"Does not match base64 encoding"))}};function Ke(e){return bo[e||"string"]()}var Q="Raw",Wt=()=>P(Q,So.object({raw:Ke("buffer")}));import{z as Oo}from"zod";var Ae="Upload",Xt=()=>P(Ae,Oo.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),tr=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),Ro=({schema:e,next:t})=>Object.values(e.shape).some(t),er=({schema:e,next:t})=>t(e.unwrap()),Po=({schema:e,next:t})=>t(e.innerType()),Co=({schema:e,next:t})=>t(e.valueSchema),Io=({schema:e,next:t})=>t(e.element),Zo=({schema:e,next:t})=>t(e._def.innerType),Eo={ZodObject:Ro,ZodUnion:ut,ZodDiscriminatedUnion:ut,ZodIntersection:tr,ZodEffects:Po,ZodOptional:er,ZodNullable:er,ZodRecord:Co,ZodArray:Io,ZodDefault:Zo},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:tr},condition:t=>t instanceof Ao.ZodEffects&&t._def.effect.type!=="refinement"}),rr=e=>Fe({subject:e,condition:t=>lt(t,Ae)}),or=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))nr(!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:[E.json],statusCodes:[ne.positive]}),negative:st(s.getNegativeResponse(),{mimeTypes:[E.json],statusCodes:[ne.negative]})};for(let[f,h]of Object.entries(this.#t))nr(h.length,new _(`ResultHandler must have at least one ${f} response schema specified.`));this.#i=rr(r)?"upload":or(r)?"raw":"json",this.#s={input:[E[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 sr}from"zod";var ir=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Qt(s,i),o)};import wo from"assert/strict";var ht=e=>(wo(!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:sr.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:sr.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:ir(d,t)})}},Mo=new Pe(Re),No=new Pe(Tt);import{inspect as vo}from"util";import{mapObjIndexed as Do}from"ramda";import{Ansis as ko,blue as Lo,green as jo,hex as Uo,red as Ho}from"ansis";var bt={debug:10,info:20,warn:30,error:40},ar=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 ko().isSupported(),depth:r=2})=>{let o={debug:Lo,info:jo,warn:Uo("#FFA500"),error:Ho},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(vo(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(l.join(" "))};return Do(({},p)=>(d,c)=>a(p,d,c),bt)};import{head as Ko,tail as Fo,toPairs as qo}from"ramda";var Ce=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=qo(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=Ko(this.pairs)?.[1],this.siblingMethods=Fo(this.pairs).map(([r])=>r)}};import Bo from"express";var Ie=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Bo.static(...this.params))}};import hr from"express";import Go from"http";import Yo from"https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>$t(e)[t])}catch{}throw new se(e)},pr=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 dr 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){dr.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)dr(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 cr,{isHttpError as Vo}from"http-errors";var mr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:Vo(o)?o:cr(400,ae(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},lr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=cr(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)})}},ur=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},fr=e=>({log:(t,...r)=>{/not eligible/.test(t)||e.debug(t,...r)}});import{gray as $o,hex as yr,italic as _e,whiteBright as _o}from"ansis";var gr=()=>{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=yr("#F5A9B8"),s=yr("#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($o,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 Sr=e=>{e.startupLogo!==!1&&console.log(Tr());let t=cr(e.logger)?At(e.logger):e.logger;t.debug("Running","v18.5.2 (ESM)");let r=e.errorHandler||Re,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=yr(i),a=fr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Wo=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=Sr(e);return Rt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Xo=async(e,t)=>{let r=br().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||br.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=Sr(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:hr(o)})),c&&r.use(gr(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}),Rt({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(Jo.createServer(r),e.server.listen),httpsServer:e.https?a(Qo.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import si from"assert/strict";import{OpenApiBuilder as ai}from"openapi3-ts/oas31";import U from"assert/strict";import{isReferenceObject as ee}from"openapi3-ts/oas31";import{both as tn,complement as rn,concat as on,type as nn,filter as sn,fromPairs as we,has as an,isNil as pn,map as le,mergeAll as dn,mergeDeepRight as cn,mergeDeepWith as mn,objOf as Ir,omit as Xe,pipe as Cr,pluck as ln,range as un,reject as fn,toLower as yn,union as gn,when as hn,xprod as et,zip as xn}from"ramda";import{z as T}from"zod";import{z as Qe}from"zod";var Ye=e=>!isNaN(e.getTime()),Je=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Ze="DateIn",Or=()=>{let e=Qe.string(),r=e.date?.()instanceof Qe.ZodString?Qe.union([e.date(),e.datetime(),e.datetime({local:!0})]):e.regex(Je);return P(Ze,r.transform(o=>new Date(o)).pipe(Qe.date().refine(Ye)))};import{z as en}from"zod";var Ee="DateOut",Ar=()=>P(Ee,en.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 Rr=50,Zr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Tn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Er=/:([A-Za-z0-9_]+)/g,zr=e=>e.match(Er)?.map(t=>t.slice(1))||[],wr=e=>e.replace(Er,t=>`{${t.slice(1)}}`),bn=({schema:e,next:t})=>({...t(e._def.innerType),default:Y(e,"defaultLabel")||e._def.defaultValue()}),Sn=({schema:{_def:{innerType:e}},next:t})=>t(e),On=()=>({format:"any"}),An=e=>(U(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Rn=({schema:e})=>({type:"string",format:e instanceof T.ZodString?e._def.checks.find(t=>t.kind==="regex"||t.kind==="base64")?"byte":"file":"binary"}),Pn=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),In=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Cn=e=>{let[t,r]=e.filter(i=>!ee(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));U(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=mn((i,s)=>Array.isArray(i)&&Array.isArray(s)?on(i,s):i===s?s:U.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=gn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=G(t.examples||[],r.examples||[],([i,s])=>cn(i,s))),o},Zn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Cn(o)}catch{}return{allOf:o}},En=({schema:e,next:t})=>t(e.unwrap()),zn=({schema:e,next:t})=>t(e._def.innerType),wn=({schema:e,next:t})=>{let r=t(e.unwrap());return ee(r)||(r.type=Nr(r)),r},Mr=e=>{let t=yn(nn(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Pr=({schema:e})=>({type:Mr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Mn=({schema:{value:e}})=>({type:Mr(e),const:e}),Nn=({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},vn=()=>({type:"null"}),Dn=e=>(U(!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:Je.source,externalDocs:{url:Zr}}),kn=e=>(U(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:Zr}}),Ln=e=>U.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})),jn=()=>({type:"boolean"}),Hn=()=>({type:"integer",format:"bigint"}),Un=e=>e.every(t=>t instanceof T.ZodLiteral),Kn=({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&&Un(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)}},Fn=({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},qn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Bn=({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,A={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]){A.format=b;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),x&&(A.pattern=x.source),A},Vn=({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),$n=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Tn?.[t]},Nr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},_n=({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,$n(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},Gn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Yn=({schema:e,next:t})=>t(e.unwrap()),Jn=({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)))},Qn=({next:e,schema:t})=>e(t.shape.raw),vr=e=>e.length?we(xn(un(1,e.length+1).map(t=>`example${t}`),le(Ir("value"),e))):void 0,Dr=(e,t,r=[])=>Cr(j,le(hn(tn(E,rn(Array.isArray)),Xe(r))),vr)({schema:e,variant:t?"parsed":"original",validate:!0}),Wn=(e,t)=>Cr(j,sn(an(t)),ln(t),vr)({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?(U(e._def.effect.type==="refinement",t),ze(e._def.schema,t)):ze(e._def.left,t).merge(ze(e._def.right,t)),kr=({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 C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=zr(e),m=o.includes("query"),f=o.includes("params"),h=o.includes("headers"),x=g=>f&&l.includes(g),A=g=>h&&mt(g);return Object.keys(c).filter(g=>m||x(g)).map(g=>{let b=X({schema:c[g],isResponse:!1,rules:It,onEach:Ct,onMissing:Zt,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":A(g)?"header":"query",required:!c[g].isOptional(),description:b.description||d,schema:ye,examples:Wn(r,g)}})},It={ZodString:Bn,ZodNumber:Vn,ZodBigInt:Hn,ZodBoolean:jn,ZodNull:vn,ZodArray:Fn,ZodTuple:qn,ZodRecord:Kn,ZodObject:Nn,ZodLiteral:Mn,ZodIntersection:Zn,ZodUnion:Pn,ZodAny:On,ZodDefault:bn,ZodEnum:Pr,ZodNativeEnum:Pr,ZodEffects:_n,ZodOptional:En,ZodNullable:wn,ZodDiscriminatedUnion:In,ZodBranded:Yn,ZodDate:Ln,ZodCatch:Sn,ZodPipeline:Gn,ZodLazy:Jn,ZodReadonly:zn,[H]:Rn,[Ae]:An,[Ee]:kn,[Ze]:Dn,[J]:Qn},Ct=({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?[]:j({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Nr(r)),d.length&&(c.examples=d.slice()),c},Zt=({schema:e,...t})=>U.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Pt=(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=>Pt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Pt(o,t))),r},Lr=e=>ee(e)?e:Xe(["examples"],e),jr=({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} ${ut(i)} response ${c?l:""}`.trim()})=>{let f=Lr(X({schema:r,isResponse:!0,rules:It,onEach:Ct,onMissing:Zt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),h={schema:d==="components"?p(Z(m),f):f,examples:Dr(r,!0)};return{description:m,content:we(et(o,[h]))}},Xn=()=>({type:"http",scheme:"basic"}),ei=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ti=({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},ri=({name:e})=>({type:"apiKey",in:"header",name:e}),oi=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ni=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ii=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),fn(pn,e))}),Hr=(e,t)=>{let r={basic:Xn,bearer:ei,input:ti,header:ri,cookie:oi,openid:ni,oauth2:ii};return $e(e,o=>r[o.type](o,t))},tt=e=>"or"in e?e.or.map(t=>"and"in t?dn(le(({name:r,scopes:o})=>Ir(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?tt(ht(e)):tt({or:[e]}),Ur=({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=zr(t),l=Lr(Pt(X({schema:r,isResponse:!1,rules:It,onEach:Ct,onMissing:Zt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(Z(d),l):l,examples:Dr(r,!1,c)};return{description:d,content:we(et(o,[m]))}},Kr=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}),Et=e=>e.length<=Rr?e:e.slice(0,Rr-1)+"\u2026";var zt=class extends ai{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&&si.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=He}){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,A={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?Et(g):p&&b?Et(b):void 0,Ne=m.getTags(),ge=r.inputSources?.[x]||dt[x],re=this.ensureUniqOperationId(f,x,m.getOperationId(x)),ve=kr({...A,inputSources:ge,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:x,path:f,operationId:re})}),De={};for(let M of["positive","negative"]){let B=m.getResponses(M);for(let{mimeTypes:he,schema:S,statusCodes:O}of B)for(let I of O)De[I]=jr({...A,variant:M,schema:S,mimeTypes:he,statusCode:I,hasMultipleStatusCodes:B.length>1||O.length>1,description:a?.[`${M}Response`]?.call(null,{method:x,path:f,operationId:re,statusCode:I})})}let at=ge.includes("body")?Ur({...A,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:x,path:f,operationId:re})}):void 0,ke=tt($e(Hr(m.getSecurity(),ge),M=>{let B=this.ensureUniqSecuritySchemaName(M),he=["oauth2","openIdConnect"].includes(M.type)?m.getScopes():[];return this.addSecurityScheme(B,M),{name:B,scopes:he}}));this.addPath(wr(f),{[x]:{operationId:re,summary:ye,description:b,tags:Ne.length>0?Ne:void 0,parameters:ve.length>0?ve:void 0,requestBody:at,security:ke.length>0?ke:void 0,responses:De}})}}),this.rootDoc.tags=r.tags?Kr(r.tags):[]}};import Fr from"http";var pi=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N),...t}),di=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Fr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Fr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},ci=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),mi=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=pi({fnMethod:a,requestProps:t}),d=di({fnMethod:a,responseProps:r}),c=ci({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 z from"typescript";import v from"typescript";import{chain as qr,toPairs as Br}from"ramda";var n=v.factory,K=[n.createModifier(v.SyntaxKind.ExportKeyword)],li=[n.createModifier(v.SyntaxKind.AsyncKeyword)],ui=[n.createModifier(v.SyntaxKind.PublicKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],Vr=[n.createModifier(v.SyntaxKind.ProtectedKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],wt=n.createTemplateHead(""),ue=n.createTemplateTail(""),Mt=n.createTemplateMiddle(" "),Nt=e=>n.createTemplateLiteralType(wt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ue:Mt))),vt=Nt(["M","P"]),rt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ot=(e,t)=>qr(([r,o])=>[rt(n.createIdentifier(r),o,t)],Br(e)),Dt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),$r=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),_r=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),F=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],v.NodeFlags.Const),kt=(e,t)=>n.createTypeAliasDeclaration(K,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),nt=(e,t)=>n.createTypeAliasDeclaration(K,e,void 0,t),Gr=(e,t,r)=>n.createPropertyDeclaration(ui,e,void 0,t,r),Yr=(e,t,r)=>n.createClassDeclaration(K,e,void 0,void 0,[t,...r]),Jr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Qr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(v.SyntaxKind.AnyKeyword)]),Wr=(e,t,r)=>n.createInterfaceDeclaration(K,e,void 0,t,r),Xr=e=>qr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Br(e)),Lt=(e,t,r)=>n.createArrowFunction(r?li:void 0,void 0,e.map(o=>rt(o)),void 0,void 0,t),jt=(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]),it=(...e)=>`"${e.join(" ")}"`;var eo=["get","post","put","delete","patch"];import y from"typescript";import{z as Kt}from"zod";import q from"typescript";var{factory:st}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},fe=(e,t,r)=>{let o=st.createTypeAliasDeclaration(void 0,st.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Ut=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},fi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,to=e=>fi.test(e)?st.createIdentifier(e):st.createStringLiteral(e);var{factory:u}=y,yi={[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},gi=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),hi=({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 Kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,to(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(i)},xi=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),Ti=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),ro=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),bi=e=>yi?.[e.kind],Si=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Ue(e,bi(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},Oi=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Ai=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Ri=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Pi=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Ii=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Ci=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Zi=({next:e,schema:t})=>e(t._def.innerType),te=e=>()=>u.createKeywordTypeNode(e),Ei=({next:e,schema:t})=>e(t.unwrap()),zi=({next:e,schema:t})=>e(t._def.innerType),wi=({next:e,schema:t})=>e(t._def.innerType),Mi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Ni=()=>u.createLiteralTypeNode(u.createNull()),vi=({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)))},Di=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof Kt.ZodString?t:e instanceof Kt.ZodUnion?o:r},ki=({next:e,schema:t})=>e(t.shape.raw),Li={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),[Ze]:te(y.SyntaxKind.StringKeyword),[Ee]:te(y.SyntaxKind.StringKeyword),ZodNull:Ni,ZodArray:xi,ZodTuple:Pi,ZodRecord:Ii,ZodObject:hi,ZodLiteral:gi,ZodIntersection:Ci,ZodUnion:ro,ZodDefault:Zi,ZodEnum:Ti,ZodNativeEnum:Oi,ZodEffects:Si,ZodOptional:Ai,ZodNullable:Ri,ZodDiscriminatedUnion:ro,ZodBranded:Ei,ZodCatch:wi,ZodPipeline:Mi,ZodLazy:vi,ZodReadonly:zi,[H]:Di,[J]:ki},Me=({schema:e,...t})=>X({schema:e,rules:Li,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Ft=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=He,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(S,O,I)=>{let oe={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},xe=Z(I,O,"input"),V=Me({...oe,schema:S.getSchema("input"),isResponse:!1}),Te=i?Z(I,O,"positive.response"):void 0,qt=S.getSchema("positive"),Bt=i?Me({...oe,isResponse:!0,schema:qt}):void 0,be=i?Z(I,O,"negative.response"):void 0,Vt=S.getSchema("negative"),$t=i?Me({...oe,isResponse:!0,schema:Vt}):void 0,_t=Z(I,O,"response"),oo=Te&&be?n.createUnionTypeNode([n.createTypeReferenceNode(Te),n.createTypeReferenceNode(be)]):Me({...oe,isResponse:!0,schema:qt.or(Vt)});this.program.push(fe(V,xe)),Bt&&Te&&this.program.push(fe(Bt,Te)),$t&&be&&this.program.push(fe($t,be)),this.program.push(fe(oo,_t)),I!=="options"&&(this.paths.push(O),this.registry.set({method:I,path:O},{input:xe,positive:Te,negative:be,response:_t,isJson:S.getMimeTypes("positive").includes(N),tags:S.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,eo)),this.program.push(nt(this.ids.methodPathType,Nt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[Dt(this.ids.methodPathType,z.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:S,path:O},{isJson:I,tags:oe,...xe}]of this.registry){for(let V of this.interfaces)V.kind in xe&&V.props.push(_r(it(S,O),xe[V.kind]));r!=="types"&&(I&&p.push(n.createPropertyAssignment(it(S,O),n.createTrue())),d.push(n.createPropertyAssignment(it(S,O),n.createArrayLiteralExpression(oe.map(V=>n.createStringLiteral(V))))))}for(let{id:S,props:O}of this.interfaces)this.program.push(Wr(S,a,O));if(r==="types")return;let c=n.createVariableStatement(K,F(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),l=n.createVariableStatement(K,F(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),m=nt(this.ids.providerType,n.createFunctionTypeNode(Xr({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),vt)}),Jr(this.ids.responseInterface,vt))),f=nt(this.ids.implementationType,n.createFunctionTypeNode(void 0,ot({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:Dt(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),Qr())),h=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ue)]),x=jt(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),A=jt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[h]),z.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=Yr(this.ids.clientClass,$r([rt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Vr)]),[Gr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Lt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,x,A]),!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(N))]),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,F(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,F(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,F(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,at]=["json","text"].map(S=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,S),void 0,void 0))),ke=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(wt,[n.createTemplateSpan(this.ids.methodParameter,Mt),n.createTemplateSpan(this.ids.pathParameter,ue)]),z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([De])),M=n.createVariableStatement(K,F(this.ids.exampleImplementationConst,Lt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([re,ve,ge,ke,at]),!0),n.createTypeReferenceNode(this.ids.implementationType))),B=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,F(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(M,he,B)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Ut(r,t)).join(`
|
|
21
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
22
|
-
${r}`);return this.program.concat(o||[]).map((i,s)=>
|
|
20
|
+
`)};var xr=e=>{e.startupLogo!==!1&&console.log(gr());let t=ar(e.logger)?St(e.logger):e.logger;t.debug("Running","v18.6.0 (ESM)");let r=e.errorHandler||Re,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=lr(i),a=mr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Qo=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=xr(e);return Ot({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Jo=async(e,t)=>{let r=hr().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||hr.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=xr(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:fr(o)})),c&&r.use(ur(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(Go.createServer(r),e.server.listen),httpsServer:e.https?a(Yo.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import ni from"assert/strict";import{OpenApiBuilder as ii}from"openapi3-ts/oas31";import K from"assert/strict";import{isReferenceObject as ee}from"openapi3-ts/oas31";import{both as Xo,complement as en,concat as tn,type as rn,filter as on,fromPairs as we,has as nn,isNil as sn,map as le,mergeAll as an,mergeDeepRight as pn,mergeDeepWith as dn,objOf as Ar,omit as We,pipe as Rr,pluck as cn,range as mn,reject as ln,toLower as un,union as fn,when as yn,xprod as Xe,zip as gn}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 Ze="DateIn",Tr=()=>{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(Ze,r.transform(o=>new Date(o)).pipe(Qe.date().refine(Ge)))};import{z as Wo}from"zod";var Ee="DateOut",br=()=>P(Ee,Wo.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 Sr=50,Pr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",hn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Cr=/:([A-Za-z0-9_]+)/g,Ir=e=>e.match(Cr)?.map(t=>t.slice(1))||[],Zr=e=>e.replace(Cr,t=>`{${t.slice(1)}}`),xn=({schema:e,next:t})=>({...t(e._def.innerType),default:Y(e,"defaultLabel")||e._def.defaultValue()}),Tn=({schema:{_def:{innerType:e}},next:t})=>t(e),bn=()=>({format:"any"}),Sn=e=>(K(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),On=({schema:e})=>({type:"string",format:e instanceof T.ZodString?e._def.checks.find(t=>t.kind==="regex"||t.kind==="base64")?"byte":"file":"binary"}),An=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Rn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Pn=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=dn((i,s)=>Array.isArray(i)&&Array.isArray(s)?tn(i,s):i===s?s:K.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=fn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=G(t.examples||[],r.examples||[],([i,s])=>pn(i,s))),o},Cn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Pn(o)}catch{}return{allOf:o}},In=({schema:e,next:t})=>t(e.unwrap()),Zn=({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=un(rn(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Or=({schema:e})=>({type:Er(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),zn=({schema:{value:e}})=>({type:Er(e),const:e}),wn=({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},Mn=()=>({type:"null"}),Nn=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:Pr}}),vn=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:Pr}}),Dn=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})),kn=()=>({type:"boolean"}),Ln=()=>({type:"integer",format:"bigint"}),jn=e=>e.every(t=>t instanceof T.ZodLiteral),Un=({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&&jn(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)}},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},Kn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Fn=({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},qn=({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),Bn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return hn?.[t]},zr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Vn=({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,Bn(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},$n=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),_n=({schema:e,next:t})=>t(e.unwrap()),Gn=({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)))},Yn=({next:e,schema:t})=>e(t.shape.raw),wr=e=>e.length?we(gn(mn(1,e.length+1).map(t=>`example${t}`),le(Ar("value"),e))):void 0,Mr=(e,t,r=[])=>Rr(U,le(yn(Xo(w,en(Array.isArray)),We(r))),wr)({schema:e,variant:t?"parsed":"original",validate:!0}),Qn=(e,t)=>Rr(U,on(nn(t)),cn(t),wr)({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)),Nr=({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=Ir(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:Qn(r,g)}})},Rt={ZodString:Fn,ZodNumber:qn,ZodBigInt:Ln,ZodBoolean:kn,ZodNull:Mn,ZodArray:Hn,ZodTuple:Kn,ZodRecord:Un,ZodObject:wn,ZodLiteral:zn,ZodIntersection:Cn,ZodUnion:An,ZodAny:bn,ZodDefault:xn,ZodEnum:Or,ZodNativeEnum:Or,ZodEffects:Vn,ZodOptional:In,ZodNullable:En,ZodDiscriminatedUnion:Rn,ZodBranded:_n,ZodDate:Dn,ZodCatch:Tn,ZodPipeline:$n,ZodLazy:Gn,ZodReadonly:Zn,[H]:On,[Ae]:Sn,[Ee]:vn,[Ze]:Nn,[Q]:Yn},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},vr=e=>ee(e)?e:We(["examples"],e),Dr=({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=vr(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:Mr(r,!0)};return{description:m,content:we(Xe(o,[h]))}},Jn=()=>({type:"http",scheme:"basic"}),Wn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Xn=({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},ei=({name:e})=>({type:"apiKey",in:"header",name:e}),ti=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ri=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),oi=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),ln(sn,e))}),kr=(e,t)=>{let r={basic:Jn,bearer:Wn,input:Xn,header:ei,cookie:ti,openid:ri,oauth2:oi};return Ve(e,o=>r[o.type](o,t))},et=e=>"or"in e?e.or.map(t=>"and"in t?an(le(({name:r,scopes:o})=>Ar(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?et(yt(e)):et({or:[e]}),Lr=({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=Ir(t),l=vr(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:Mr(r,!1,c)};return{description:d,content:we(Xe(o,[m]))}},jr=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<=Sr?e:e.slice(0,Sr-1)+"\u2026";var Zt=class extends ii{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&&ni.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=Nr({...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]=Dr({...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")?Lr({...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(kr(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(Zr(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?jr(r.tags):[]}};import Ur from"http";var si=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>E.json),...t}),ai=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Ur.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Ur.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},pi=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),di=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await pr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=si({fnMethod:a,requestProps:t}),d=ai({fnMethod:a,responseProps:r}),c=pi({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 Hr,toPairs as Kr}from"ramda";var n=D.factory,F=[n.createModifier(D.SyntaxKind.ExportKeyword)],ci=[n.createModifier(D.SyntaxKind.AsyncKeyword)],mi=[n.createModifier(D.SyntaxKind.PublicKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],Fr=[n.createModifier(D.SyntaxKind.ProtectedKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],Et=n.createTemplateHead(""),ue=n.createTemplateTail(""),zt=n.createTemplateMiddle(" "),wt=e=>n.createTemplateLiteralType(Et,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)=>Hr(([r,o])=>[tt(n.createIdentifier(r),o,t)],Kr(e)),Nt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),qr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Br=(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),Vr=(e,t,r)=>n.createPropertyDeclaration(mi,e,void 0,t,r),$r=(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)]),Gr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.SyntaxKind.AnyKeyword)]),Yr=(e,t,r)=>n.createInterfaceDeclaration(F,e,void 0,t,r),Qr=e=>Hr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Kr(e)),Dt=(e,t,r)=>n.createArrowFunction(r?ci: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]),Jr=(...e)=>`"${e.join(" ")}"`;var Wr=["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)},li=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Xr=e=>li.test(e)?nt.createIdentifier(e):nt.createStringLiteral(e);var{factory:u}=y,ui={[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},fi=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),yi=({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,Xr(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},gi=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),hi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),eo=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),xi=e=>ui?.[e.kind],Ti=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Ue(e,xi(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},bi=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Si=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Oi=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ai=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Ri=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Pi=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Ci=({next:e,schema:t})=>e(t._def.innerType),te=e=>()=>u.createKeywordTypeNode(e),Ii=({next:e,schema:t})=>e(t.unwrap()),Zi=({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"]),wi=()=>u.createLiteralTypeNode(u.createNull()),Mi=({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)))},Ni=({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},vi=({next:e,schema:t})=>e(t.shape.raw),Di={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),[Ze]:te(y.SyntaxKind.StringKeyword),[Ee]:te(y.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:gi,ZodTuple:Ai,ZodRecord:Ri,ZodObject:yi,ZodLiteral:fi,ZodIntersection:Pi,ZodUnion:eo,ZodDefault:Ci,ZodEnum:hi,ZodNativeEnum:bi,ZodEffects:Ti,ZodOptional:Si,ZodNullable:Oi,ZodDiscriminatedUnion:eo,ZodBranded:Ii,ZodCatch:Ei,ZodPipeline:zi,ZodLazy:Mi,ZodReadonly:Zi,[H]:Ni,[Q]:vi},Me=({schema:e,...t})=>X({schema:e,rules:Di,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}),Z=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"),to=Z&&be?n.createUnionTypeNode([n.createTypeReferenceNode(Z),n.createTypeReferenceNode(be)]):Me({...oe,isResponse:!0,schema:Kt.or(qt)});this.program.push(fe(Te,xe)),Ft&&Z&&this.program.push(fe(Ft,Z)),Bt&&be&&this.program.push(fe(Bt,be)),this.program.push(fe(to,Vt)),C!=="options"&&(this.paths.push(A),this.registry.set({method:C,path:A},{input:xe,positive:Z,negative:be,response:Vt,isJson:O.getMimeTypes("positive").includes(E.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,Wr)),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=Jr(O,A);for(let Z of this.interfaces)Z.kind in xe&&Z.props.push(Br(Te,xe[Z.kind]));r!=="types"&&(C&&p.push(n.createPropertyAssignment(Te,n.createTrue())),d.push(n.createPropertyAssignment(Te,n.createArrayLiteralExpression(oe.map(Z=>n.createStringLiteral(Z))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(Yr(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(Qr({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)}),Gr())),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=$r(this.ids.clientClass,qr([tt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Fr)]),[Vr(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(E.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(Et,[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(`
|
|
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
|
+
${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
|
|
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 ki={dateIn:Tr,dateOut:br,file:Ke,upload:Xt,raw:Wt};export{ce as AbstractEndpoint,Ce as DependsOnMethod,Zt 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,No as arrayEndpointsFactory,Tt as arrayResultHandler,Qo as attachRouting,ro as createConfig,St as createLogger,ht as createMiddleware,xt as createResultHandler,Jo as createServer,Mo as defaultEndpointsFactory,Re as defaultResultHandler,ki as ez,U as getExamples,j as getMessageFromError,Le as getStatusCodeFromError,di as testEndpoint,xo as withMeta};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "18.
|
|
3
|
+
"version": "18.6.0",
|
|
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": {
|
|
@@ -144,7 +144,7 @@
|
|
|
144
144
|
"eslint-config-prettier": "^9.0.0",
|
|
145
145
|
"eslint-plugin-import": "^2.28.1",
|
|
146
146
|
"eslint-plugin-prettier": "^5.0.0",
|
|
147
|
-
"eslint-plugin-unicorn": "^
|
|
147
|
+
"eslint-plugin-unicorn": "^53.0.0",
|
|
148
148
|
"express": "^4.18.2",
|
|
149
149
|
"express-fileupload": "^1.4.3",
|
|
150
150
|
"http-errors": "^2.0.0",
|