express-zod-api 20.0.0-beta.4 → 20.0.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 CHANGED
@@ -23,11 +23,11 @@
23
23
  - Or follow the code samples below in order to rename/remove entities manually as described above.
24
24
 
25
25
  ```js
26
- // eslint.config.mjs — minimal config to apply migrations automatically using "eslint --fix" (at least ESLint 8)
26
+ // eslint.config.mjs — minimal config to apply migrations automatically using "eslint . --fix" (at least ESLint 8)
27
27
  import parser from "@typescript-eslint/parser";
28
28
  import migration from "express-zod-api/migration";
29
29
 
30
- export default [{ languageOptions: { parser } }, migration];
30
+ export default [{ languageOptions: { parser }, files: ["**/*.ts"] }, migration];
31
31
  ```
32
32
 
33
33
  ```ts
package/SECURITY.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Version | Release | Supported |
6
6
  | ------: | :------ | :----------------: |
7
- | 20.x.x | 07.2024 | :white_check_mark: |
7
+ | 20.x.x | 06.2024 | :white_check_mark: |
8
8
  | 19.x.x | 05.2024 | :white_check_mark: |
9
9
  | 18.x.x | 04.2024 | :white_check_mark: |
10
10
  | 17.x.x | 02.2024 | :white_check_mark: |
package/dist/index.cjs CHANGED
@@ -17,7 +17,7 @@ ${o}888${t}
17
17
  ${r}
18
18
  `.split(`
19
19
  `).map((d,l)=>a[l]?a[l](d):d).join(`
20
- `)};var Dr=e=>{e.startupLogo!==!1&&console.log(Mr());let t=e.errorHandler||xe,r=wr(e.logger)?e.logger:new Se(e.logger);r.debug("Running","v20.0.0-beta.4 (CJS)");let o=kr({rootLogger:r,config:e}),i=Lr({rootLogger:r,errorHandler:t}),s=vr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},Fr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=Dr(e);return jt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Kr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=Dr(e),a=(0,ct.default)().disable("x-powered-by").use(s);if(e.server.compression){let m=await Pe("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||ct.default.json()],raw:[e.server.rawParser||ct.default.raw(),jr],upload:e.server.upload?await Nr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),jt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,y)=>m.listen(y,()=>{r.info("Listening",y)}),l={httpServer:d(Ur.default.createServer(a),e.server.listen),httpsServer:e.https?d(Hr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...l,logger:r}};var ao=O(require("assert/strict"),1),po=require("openapi3-ts/oas31"),co=require("ramda");var q=O(require("assert/strict"),1),$=require("openapi3-ts/oas31"),c=require("ramda"),S=require("zod");var Ie=require("zod");var dt=e=>!isNaN(e.getTime());var $e=Symbol("DateIn"),Br=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(dt)).brand($e);var qr=require("zod");var Ve=Symbol("DateOut"),$r=()=>qr.z.date().refine(dt).transform(e=>e.toISOString()).brand(Ve);var ae=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:l=>ae(l,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),d=t&&t(e,{prev:p,...i});return d?{...p,...d}:p};var Vr=50,_r="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Yr=/:([A-Za-z0-9_]+)/g,$o=e=>e.match(Yr)?.map(t=>t.slice(1))||[],Qr=e=>e.replace(Yr,t=>`{${t.slice(1)}}`),Vo=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Go=({_def:{innerType:e}},{next:t})=>t(e),_o=()=>({format:"any"}),Yo=({},e)=>((0,q.default)(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Qo=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Jo=({options:e},{next:t})=>({oneOf:e.map(t)}),Wo=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Xo=e=>{let[t,r]=e.filter($.isSchemaObject).filter(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,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=oe(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},en=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Xo(o)}catch{}return{allOf:o}},tn=(e,{next:t})=>t(e.unwrap()),rn=(e,{next:t})=>t(e.unwrap()),on=(e,{next:t})=>{let r=t(e.unwrap());return(0,$.isSchemaObject)(r)&&(r.type=Wr(r)),r},Jr=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Gr=e=>({type:Jr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),nn=({value:e})=>({type:Jr(e),const:e}),sn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=lt(e,r)),s.length&&(a.required=s),a},an=()=>({type:"null"}),pn=({},e)=>((0,q.default)(!e.isResponse,new P({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:_r}}),cn=({},e)=>((0,q.default)(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:_r}}),dn=({},e)=>q.default.fail(new P({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})),ln=()=>({type:"boolean"}),mn=()=>({type:"integer",format:"bigint"}),un=e=>e.every(t=>t instanceof S.z.ZodLiteral),fn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=lt(S.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),r),i.required=o),i}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:lt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&un(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:lt(S.z.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},yn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},gn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),hn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:l,isDatetime:m,_def:{checks:y}})=>{let f=y.find(I=>I.kind==="regex"),b=y.find(I=>I.kind==="datetime"),v=f?f.regex:b?b.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,T={type:"string"},k={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:l};for(let I in k)if(k[I]){T.format=I;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),v&&(T.pattern=v.source),T},xn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(y=>y.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(y=>y.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,l=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,l?m.maximum=d:m.exclusiveMaximum=d,m},lt=({shape:e},t)=>(0,c.map)(t,e),bn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},Wr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Tn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&(0,$.isSchemaObject)(o)){let s=We(e,bn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.z.any())}if(!t&&i.type==="preprocess"&&(0,$.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Sn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),On=(e,{next:t})=>t(e.unwrap()),Rn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},An=(e,{next:t})=>t(e.unwrap().shape.raw),Xr=e=>e.length?(0,c.fromPairs)((0,c.zip)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e))):void 0,eo=(e,t,r=[])=>(0,c.pipe)(F,(0,c.map)((0,c.when)((0,c.both)(K,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),Xr)({schema:e,variant:t?"parsed":"original",validate:!0}),Pn=(e,t)=>(0,c.pipe)(F,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),Xr)({schema:e,variant:"original",validate:!0}),Ce=(e,t)=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?Ce(e.unwrap(),t):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(r=>Ce(r,t)).reduce((r,o)=>r.merge(o.partial()),S.z.object({})):e instanceof S.z.ZodEffects?((0,q.default)(e._def.effect.type==="refinement",t),Ce(e._def.schema,t)):Ce(e._def.left,t).merge(Ce(e._def.right,t)),to=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=Ce(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),y=$o(e),f=o.includes("query"),b=o.includes("params"),v=o.includes("headers"),T=x=>b&&y.includes(x),k=x=>v&&At(x);return Object.keys(m).map(x=>({name:x,location:T(x)?"path":k(x)?"header":f?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:Ee})=>{let G=ae(m[x],{rules:{...d,...Mt},onEach:Ut,onMissing:Ht,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),ee=p==="components"?a(N(l,x),G):G;return{name:x,in:Ee,required:!m[x].isOptional(),description:G.description||l,schema:ee,examples:Pn(r,x)}})},Mt={ZodString:hn,ZodNumber:xn,ZodBigInt:mn,ZodBoolean:ln,ZodNull:an,ZodArray:yn,ZodTuple:gn,ZodRecord:fn,ZodObject:sn,ZodLiteral:nn,ZodIntersection:en,ZodUnion:Jo,ZodAny:_o,ZodDefault:Vo,ZodEnum:Gr,ZodNativeEnum:Gr,ZodEffects:Tn,ZodOptional:tn,ZodNullable:on,ZodDiscriminatedUnion:Wo,ZodBranded:On,ZodDate:dn,ZodCatch:Go,ZodPipeline:Sn,ZodLazy:Rn,ZodReadonly:rn,[J]:Qo,[Fe]:Yo,[Ve]:cn,[$e]:pn,[ne]:An},Ut=(e,{isResponse:t,prev:r})=>{if((0,$.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof S.z.ZodLazy,s=r.type!==void 0,a=t&&Ue(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),l={};return o&&(l.description=o),p&&(l.type=Wr(r)),d.length&&(l.examples=d.slice()),l},Ht=(e,t)=>q.default.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),kt=(e,t)=>{if((0,$.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.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},ro=e=>(0,$.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),oo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:l,statusCode:m,brandHandling:y,description:f=`${e.toUpperCase()} ${t} ${It(i)} response ${l?m:""}`.trim()})=>{let b=ro(ae(r,{rules:{...y,...Mt},onEach:Ut,onMissing:Ht,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),v={schema:d==="components"?p(N(f),b):b,examples:eo(r,!0)};return{description:f,content:(0,c.fromPairs)((0,c.xprod)(o,[v]))}},In=()=>({type:"http",scheme:"basic"}),Cn=({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}),Zn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),En=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),vn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),no=(e,t)=>{let r={basic:In,bearer:Cn,input:zn,header:wn,cookie:Zn,openid:En,oauth2:vn};return it(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(wt(e)):mt({or:[e]}),io=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,paramNames:l,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=ro(kt(ae(r,{rules:{...d,...Mt},onEach:Ut,onMissing:Ht,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),l)),f={schema:p==="components"?a(N(m),y):y,examples:eo(r,!1,l)};return{description:m,content:(0,c.fromPairs)((0,c.xprod)(o,[f]))}},so=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}),Dt=e=>e.length<=Vr?e:e.slice(0,Vr-1)+"\u2026";var ut=class extends po.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||N(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ao.default.fail(new P({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,brandHandling:p,hasSummaryFromDescription:d=!0,composition:l="inline",serializer:m=Je}){super(),this.addInfo({title:o,version:i});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});se({routing:t,onEndpoint:(f,b,v)=>{let T=v,k={path:b,method:T,endpoint:f,composition:l,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[I,x]=["short","long"].map(f.getDescription.bind(f)),Ee=I?Dt(I):d&&x?Dt(x):void 0,G=f.getTags(),ee=r.inputSources?.[T]||Ot[T],ce=this.ensureUniqOperationId(b,T,f.getOperationId(T)),ve=to({...k,inputSources:ee,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:b,operationId:ce})}),_e={};for(let H of["positive","negative"]){let te=f.getResponses(H);for(let{mimeTypes:Le,schema:R,statusCodes:A}of te)for(let C of A)_e[C]=oo({...k,variant:H,schema:R,mimeTypes:Le,statusCode:C,hasMultipleStatusCodes:te.length>1||A.length>1,description:a?.[`${H}Response`]?.call(null,{method:T,path:b,operationId:ce,statusCode:C})})}let St=ee.includes("body")?io({...k,paramNames:(0,co.pluck)("name",ve),schema:f.getSchema("input"),mimeTypes:f.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:b,operationId:ce})}):void 0,Ye=mt(it(no(f.getSecurity(),ee),H=>{let te=this.ensureUniqSecuritySchemaName(H),Le=["oauth2","openIdConnect"].includes(H.type)?f.getScopes().slice():[];return this.addSecurityScheme(te,H),{name:te,scopes:Le}}));this.addPath(Qr(b),{[T]:{operationId:ce,summary:Ee,description:x,tags:G.length>0?G:void 0,parameters:ve.length>0?ve:void 0,requestBody:St,security:Ye.length>0?Ye:void 0,responses:_e}})}}),this.rootDoc.tags=r.tags?so(r.tags):[]}};var ft=require("node-mocks-http"),Ln=e=>(0,ft.createRequest)({...e,headers:{"content-type":z.json,...e?.headers}}),Nn=e=>(0,ft.createResponse)(e),jn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,i){return o==="_getLogs"?()=>t:o in Te?(...s)=>t[o].push(s):Reflect.get(r,o,i)}})},lo=async({endpoint:e,requestProps:t,responseOptions:r,configProps:o,loggerProps:i})=>{let s=Ln(t),a=Nn({req:s,...r}),p=jn(i),d={cors:!1,logger:p,...o};return await e.execute({request:s,response:a,config:d,logger:p}),{requestMock:s,responseMock:a,loggerMock:p}};var E=O(require("typescript"),1);var U=O(require("typescript"),1),ze=require("ramda"),n=U.default.factory,W=[n.createModifier(U.default.SyntaxKind.ExportKeyword)],kn=[n.createModifier(U.default.SyntaxKind.AsyncKeyword)],Mn=[n.createModifier(U.default.SyntaxKind.PublicKeyword),n.createModifier(U.default.SyntaxKind.ReadonlyKeyword)],mo=[n.createModifier(U.default.SyntaxKind.ProtectedKeyword),n.createModifier(U.default.SyntaxKind.ReadonlyKeyword)],Ft=n.createTemplateHead(""),we=n.createTemplateTail(""),Kt=n.createTemplateMiddle(" "),Bt=e=>n.createTemplateLiteralType(Ft,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?we:Kt))),qt=Bt(["M","P"]),yt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),gt=(e,t)=>(0,ze.chain)(([r,o])=>[yt(n.createIdentifier(r),o,t)],(0,ze.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)),X=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],U.default.NodeFlags.Const),Vt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ht=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,t),yo=(e,t,r)=>n.createPropertyDeclaration(Mn,e,void 0,t,r),go=(e,t,r)=>n.createClassDeclaration(W,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(U.default.SyntaxKind.AnyKeyword)]),bo=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),To=e=>(0,ze.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,ze.toPairs)(e)),Gt=(e,t,r)=>n.createArrowFunction(r?kn:void 0,void 0,e.map(o=>yt(o)),void 0,void 0,t),_t=(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,gt({acc:void 0,key:void 0}),void 0,void 0,t),r]),So=(...e)=>`"${e.join(" ")}"`;var Oo=["get","post","put","delete","patch"];var h=O(require("typescript"),1),bt=require("zod");var V=O(require("typescript"),1),{factory:xt}=V.default,Yt=(e,t)=>{V.default.addSyntheticLeadingComment(e,V.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ze=(e,t,r)=>{let o=xt.createTypeAliasDeclaration(void 0,xt.createIdentifier(t),void 0,e);return r&&Yt(o,r),o},Qt=(e,t)=>{let r=V.default.createSourceFile("print.ts","",V.default.ScriptTarget.Latest,!1,V.default.ScriptKind.TS);return V.default.createPrinter(t).printNode(V.default.EmitHint.Unspecified,e,r)},Un=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ro=e=>Un.test(e)?xt.createIdentifier(e):xt.createStringLiteral(e);var{factory:u}=h.default,Hn={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Dn=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Fn=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ue(a)?a instanceof bt.z.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Ro(s),p&&o?u.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Yt(d,a.description),d});return u.createTypeLiteralNode(i)},Kn=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Bn=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Ao=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),qn=e=>Hn?.[e.kind],$n=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let i=We(e,qn(o)),s={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(i&&s[i]||h.default.SyntaxKind.AnyKeyword)}return o},Vn=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Gn=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},_n=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Yn=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),Qn=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Jn=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Wn=({_def:e},{next:t})=>t(e.innerType),pe=e=>()=>u.createKeywordTypeNode(e),Xn=(e,{next:t})=>t(e.unwrap()),ei=(e,{next:t})=>t(e.unwrap()),ti=({_def:e},{next:t})=>t(e.innerType),ri=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),oi=()=>u.createLiteralTypeNode(u.createNull()),ni=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,u.createLiteralTypeNode(u.createNull())),r(s,o(e)))},ii=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof bt.z.ZodString?r:t instanceof bt.z.ZodUnion?i:o},si=(e,{next:t})=>t(e.unwrap().shape.raw),ai={ZodString:pe(h.default.SyntaxKind.StringKeyword),ZodNumber:pe(h.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(h.default.SyntaxKind.BooleanKeyword),ZodAny:pe(h.default.SyntaxKind.AnyKeyword),[$e]:pe(h.default.SyntaxKind.StringKeyword),[Ve]:pe(h.default.SyntaxKind.StringKeyword),ZodNull:oi,ZodArray:Kn,ZodTuple:Yn,ZodRecord:Qn,ZodObject:Fn,ZodLiteral:Dn,ZodIntersection:Jn,ZodUnion:Ao,ZodDefault:Wn,ZodEnum:Bn,ZodNativeEnum:Vn,ZodEffects:$n,ZodOptional:Gn,ZodNullable:_n,ZodDiscriminatedUnion:Ao,ZodBranded:Xn,ZodCatch:ti,ZodPipeline:ri,ZodLazy:ni,ZodReadonly:ei,[J]:ii,[ne]:si},Ge=(e,{brandHandling:t,ctx:r})=>ae(e,{rules:{...t,...ai},onMissing:()=>u.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),ctx:r});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,Ze(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=Je,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){se({routing:t,onEndpoint:(R,A,C)=>{let de={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Ne=N(C,A,"input"),je=Ge(R.getSchema("input"),{brandHandling:r,ctx:{...de,isResponse:!1}}),L=s?N(C,A,"positive.response"):void 0,Jt=R.getSchema("positive"),Wt=s?Ge(Jt,{brandHandling:r,ctx:{...de,isResponse:!0}}):void 0,ke=s?N(C,A,"negative.response"):void 0,Xt=R.getSchema("negative"),er=s?Ge(Xt,{brandHandling:r,ctx:{...de,isResponse:!0}}):void 0,tr=N(C,A,"response"),Io=L&&ke?n.createUnionTypeNode([n.createTypeReferenceNode(L),n.createTypeReferenceNode(ke)]):Ge(Jt.or(Xt),{brandHandling:r,ctx:{...de,isResponse:!0}});this.program.push(Ze(je,Ne)),Wt&&L&&this.program.push(Ze(Wt,L)),er&&ke&&this.program.push(Ze(er,ke)),this.program.push(Ze(Io,tr)),C!=="options"&&(this.paths.push(A),this.registry.set({method:C,path:A},{input:Ne,positive:L,negative:ke,response:tr,isJson:R.getMimeTypes("positive").includes(z.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Vt(this.ids.pathType,this.paths)),this.program.push(Vt(this.ids.methodType,Oo)),this.program.push(ht(this.ids.methodPathType,Bt([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(E.default.SyntaxKind.ExtendsKeyword,[$t(this.ids.methodPathType,E.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&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 d=[],l=[];for(let[{method:R,path:A},{isJson:C,tags:de,...Ne}]of this.registry){let je=So(R,A);for(let L of this.interfaces)L.kind in Ne&&L.props.push(fo(je,Ne[L.kind]));o!=="types"&&(C&&d.push(n.createPropertyAssignment(je,n.createTrue())),l.push(n.createPropertyAssignment(je,n.createArrayLiteralExpression(de.map(L=>n.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(bo(R,p,A));if(o==="types")return;let m=n.createVariableStatement(W,X(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(d))),y=n.createVariableStatement(W,X(this.ids.endpointTagsConst,n.createObjectLiteralExpression(l))),f=ht(this.ids.providerType,n.createFunctionTypeNode(To({M:this.ids.methodType,P:this.ids.pathType}),gt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),qt)}),ho(this.ids.responseInterface,qt))),b=ht(this.ids.implementationType,n.createFunctionTypeNode(void 0,gt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(E.default.SyntaxKind.StringKeyword),params:$t(E.default.SyntaxKind.StringKeyword,E.default.SyntaxKind.AnyKeyword)}),xo())),v=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,we)]),T=_t(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[v,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),k=_t(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[v]),E.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()),I=go(this.ids.clientClass,uo([yt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),mo)]),[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,T,k]),!0))]);this.program.push(m,y,f,b,I);let x=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ee=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(z.json))]),void 0,this.ids.undefinedValue)),G=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)),ee=n.createVariableStatement(void 0,X(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,we)]),n.createObjectLiteralExpression([x,Ee,G])])))),ce=n.createVariableStatement(void 0,X(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,X(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]),we)])))),[_e,St]=["json","text"].map(R=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Ye=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ft,[n.createTemplateSpan(this.ids.methodParameter,Kt),n.createTemplateSpan(this.ids.pathParameter,we)]),E.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([_e])),H=n.createVariableStatement(W,X(this.ids.exampleImplementationConst,Gt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([ce,ve,ee,Ye,St]),!0),n.createTypeReferenceNode(this.ids.implementationType))),te=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"))])])),Le=n.createVariableStatement(void 0,X(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(H,Le,te)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Qt(r,t)).join(`
20
+ `)};var Dr=e=>{e.startupLogo!==!1&&console.log(Mr());let t=e.errorHandler||xe,r=wr(e.logger)?e.logger:new Se(e.logger);r.debug("Running","v20.0.0 (CJS)");let o=kr({rootLogger:r,config:e}),i=Lr({rootLogger:r,errorHandler:t}),s=vr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},Fr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=Dr(e);return jt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Kr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=Dr(e),a=(0,ct.default)().disable("x-powered-by").use(s);if(e.server.compression){let m=await Pe("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||ct.default.json()],raw:[e.server.rawParser||ct.default.raw(),jr],upload:e.server.upload?await Nr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),jt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,y)=>m.listen(y,()=>{r.info("Listening",y)}),l={httpServer:d(Ur.default.createServer(a),e.server.listen),httpsServer:e.https?d(Hr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...l,logger:r}};var ao=O(require("assert/strict"),1),po=require("openapi3-ts/oas31"),co=require("ramda");var q=O(require("assert/strict"),1),$=require("openapi3-ts/oas31"),c=require("ramda"),S=require("zod");var Ie=require("zod");var dt=e=>!isNaN(e.getTime());var $e=Symbol("DateIn"),Br=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(dt)).brand($e);var qr=require("zod");var Ve=Symbol("DateOut"),$r=()=>qr.z.date().refine(dt).transform(e=>e.toISOString()).brand(Ve);var ae=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:l=>ae(l,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),d=t&&t(e,{prev:p,...i});return d?{...p,...d}:p};var Vr=50,_r="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Yr=/:([A-Za-z0-9_]+)/g,$o=e=>e.match(Yr)?.map(t=>t.slice(1))||[],Qr=e=>e.replace(Yr,t=>`{${t.slice(1)}}`),Vo=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Go=({_def:{innerType:e}},{next:t})=>t(e),_o=()=>({format:"any"}),Yo=({},e)=>((0,q.default)(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Qo=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Jo=({options:e},{next:t})=>({oneOf:e.map(t)}),Wo=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Xo=e=>{let[t,r]=e.filter($.isSchemaObject).filter(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,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=oe(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},en=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Xo(o)}catch{}return{allOf:o}},tn=(e,{next:t})=>t(e.unwrap()),rn=(e,{next:t})=>t(e.unwrap()),on=(e,{next:t})=>{let r=t(e.unwrap());return(0,$.isSchemaObject)(r)&&(r.type=Wr(r)),r},Jr=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Gr=e=>({type:Jr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),nn=({value:e})=>({type:Jr(e),const:e}),sn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=lt(e,r)),s.length&&(a.required=s),a},an=()=>({type:"null"}),pn=({},e)=>((0,q.default)(!e.isResponse,new P({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:_r}}),cn=({},e)=>((0,q.default)(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:_r}}),dn=({},e)=>q.default.fail(new P({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})),ln=()=>({type:"boolean"}),mn=()=>({type:"integer",format:"bigint"}),un=e=>e.every(t=>t instanceof S.z.ZodLiteral),fn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=lt(S.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),r),i.required=o),i}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:lt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&un(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:lt(S.z.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},yn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},gn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),hn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:l,isDatetime:m,_def:{checks:y}})=>{let f=y.find(I=>I.kind==="regex"),b=y.find(I=>I.kind==="datetime"),v=f?f.regex:b?b.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,T={type:"string"},k={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:l};for(let I in k)if(k[I]){T.format=I;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),v&&(T.pattern=v.source),T},xn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(y=>y.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(y=>y.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,l=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,l?m.maximum=d:m.exclusiveMaximum=d,m},lt=({shape:e},t)=>(0,c.map)(t,e),bn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},Wr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Tn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&(0,$.isSchemaObject)(o)){let s=We(e,bn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.z.any())}if(!t&&i.type==="preprocess"&&(0,$.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Sn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),On=(e,{next:t})=>t(e.unwrap()),Rn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},An=(e,{next:t})=>t(e.unwrap().shape.raw),Xr=e=>e.length?(0,c.fromPairs)((0,c.zip)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e))):void 0,eo=(e,t,r=[])=>(0,c.pipe)(F,(0,c.map)((0,c.when)((0,c.both)(K,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),Xr)({schema:e,variant:t?"parsed":"original",validate:!0}),Pn=(e,t)=>(0,c.pipe)(F,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),Xr)({schema:e,variant:"original",validate:!0}),Ce=(e,t)=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?Ce(e.unwrap(),t):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(r=>Ce(r,t)).reduce((r,o)=>r.merge(o.partial()),S.z.object({})):e instanceof S.z.ZodEffects?((0,q.default)(e._def.effect.type==="refinement",t),Ce(e._def.schema,t)):Ce(e._def.left,t).merge(Ce(e._def.right,t)),to=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=Ce(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),y=$o(e),f=o.includes("query"),b=o.includes("params"),v=o.includes("headers"),T=x=>b&&y.includes(x),k=x=>v&&At(x);return Object.keys(m).map(x=>({name:x,location:T(x)?"path":k(x)?"header":f?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:Ee})=>{let G=ae(m[x],{rules:{...d,...Mt},onEach:Ut,onMissing:Ht,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),ee=p==="components"?a(N(l,x),G):G;return{name:x,in:Ee,required:!m[x].isOptional(),description:G.description||l,schema:ee,examples:Pn(r,x)}})},Mt={ZodString:hn,ZodNumber:xn,ZodBigInt:mn,ZodBoolean:ln,ZodNull:an,ZodArray:yn,ZodTuple:gn,ZodRecord:fn,ZodObject:sn,ZodLiteral:nn,ZodIntersection:en,ZodUnion:Jo,ZodAny:_o,ZodDefault:Vo,ZodEnum:Gr,ZodNativeEnum:Gr,ZodEffects:Tn,ZodOptional:tn,ZodNullable:on,ZodDiscriminatedUnion:Wo,ZodBranded:On,ZodDate:dn,ZodCatch:Go,ZodPipeline:Sn,ZodLazy:Rn,ZodReadonly:rn,[J]:Qo,[Fe]:Yo,[Ve]:cn,[$e]:pn,[ne]:An},Ut=(e,{isResponse:t,prev:r})=>{if((0,$.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof S.z.ZodLazy,s=r.type!==void 0,a=t&&Ue(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),l={};return o&&(l.description=o),p&&(l.type=Wr(r)),d.length&&(l.examples=d.slice()),l},Ht=(e,t)=>q.default.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),kt=(e,t)=>{if((0,$.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.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},ro=e=>(0,$.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),oo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:l,statusCode:m,brandHandling:y,description:f=`${e.toUpperCase()} ${t} ${It(i)} response ${l?m:""}`.trim()})=>{let b=ro(ae(r,{rules:{...y,...Mt},onEach:Ut,onMissing:Ht,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),v={schema:d==="components"?p(N(f),b):b,examples:eo(r,!0)};return{description:f,content:(0,c.fromPairs)((0,c.xprod)(o,[v]))}},In=()=>({type:"http",scheme:"basic"}),Cn=({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}),Zn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),En=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),vn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),no=(e,t)=>{let r={basic:In,bearer:Cn,input:zn,header:wn,cookie:Zn,openid:En,oauth2:vn};return it(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(wt(e)):mt({or:[e]}),io=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,paramNames:l,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=ro(kt(ae(r,{rules:{...d,...Mt},onEach:Ut,onMissing:Ht,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),l)),f={schema:p==="components"?a(N(m),y):y,examples:eo(r,!1,l)};return{description:m,content:(0,c.fromPairs)((0,c.xprod)(o,[f]))}},so=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}),Dt=e=>e.length<=Vr?e:e.slice(0,Vr-1)+"\u2026";var ut=class extends po.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||N(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ao.default.fail(new P({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,brandHandling:p,hasSummaryFromDescription:d=!0,composition:l="inline",serializer:m=Je}){super(),this.addInfo({title:o,version:i});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});se({routing:t,onEndpoint:(f,b,v)=>{let T=v,k={path:b,method:T,endpoint:f,composition:l,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[I,x]=["short","long"].map(f.getDescription.bind(f)),Ee=I?Dt(I):d&&x?Dt(x):void 0,G=f.getTags(),ee=r.inputSources?.[T]||Ot[T],ce=this.ensureUniqOperationId(b,T,f.getOperationId(T)),ve=to({...k,inputSources:ee,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:b,operationId:ce})}),_e={};for(let H of["positive","negative"]){let te=f.getResponses(H);for(let{mimeTypes:Le,schema:R,statusCodes:A}of te)for(let C of A)_e[C]=oo({...k,variant:H,schema:R,mimeTypes:Le,statusCode:C,hasMultipleStatusCodes:te.length>1||A.length>1,description:a?.[`${H}Response`]?.call(null,{method:T,path:b,operationId:ce,statusCode:C})})}let St=ee.includes("body")?io({...k,paramNames:(0,co.pluck)("name",ve),schema:f.getSchema("input"),mimeTypes:f.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:b,operationId:ce})}):void 0,Ye=mt(it(no(f.getSecurity(),ee),H=>{let te=this.ensureUniqSecuritySchemaName(H),Le=["oauth2","openIdConnect"].includes(H.type)?f.getScopes().slice():[];return this.addSecurityScheme(te,H),{name:te,scopes:Le}}));this.addPath(Qr(b),{[T]:{operationId:ce,summary:Ee,description:x,tags:G.length>0?G:void 0,parameters:ve.length>0?ve:void 0,requestBody:St,security:Ye.length>0?Ye:void 0,responses:_e}})}}),this.rootDoc.tags=r.tags?so(r.tags):[]}};var ft=require("node-mocks-http"),Ln=e=>(0,ft.createRequest)({...e,headers:{"content-type":z.json,...e?.headers}}),Nn=e=>(0,ft.createResponse)(e),jn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,i){return o==="_getLogs"?()=>t:o in Te?(...s)=>t[o].push(s):Reflect.get(r,o,i)}})},lo=async({endpoint:e,requestProps:t,responseOptions:r,configProps:o,loggerProps:i})=>{let s=Ln(t),a=Nn({req:s,...r}),p=jn(i),d={cors:!1,logger:p,...o};return await e.execute({request:s,response:a,config:d,logger:p}),{requestMock:s,responseMock:a,loggerMock:p}};var E=O(require("typescript"),1);var U=O(require("typescript"),1),ze=require("ramda"),n=U.default.factory,W=[n.createModifier(U.default.SyntaxKind.ExportKeyword)],kn=[n.createModifier(U.default.SyntaxKind.AsyncKeyword)],Mn=[n.createModifier(U.default.SyntaxKind.PublicKeyword),n.createModifier(U.default.SyntaxKind.ReadonlyKeyword)],mo=[n.createModifier(U.default.SyntaxKind.ProtectedKeyword),n.createModifier(U.default.SyntaxKind.ReadonlyKeyword)],Ft=n.createTemplateHead(""),we=n.createTemplateTail(""),Kt=n.createTemplateMiddle(" "),Bt=e=>n.createTemplateLiteralType(Ft,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?we:Kt))),qt=Bt(["M","P"]),yt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),gt=(e,t)=>(0,ze.chain)(([r,o])=>[yt(n.createIdentifier(r),o,t)],(0,ze.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)),X=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],U.default.NodeFlags.Const),Vt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ht=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,t),yo=(e,t,r)=>n.createPropertyDeclaration(Mn,e,void 0,t,r),go=(e,t,r)=>n.createClassDeclaration(W,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(U.default.SyntaxKind.AnyKeyword)]),bo=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),To=e=>(0,ze.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,ze.toPairs)(e)),Gt=(e,t,r)=>n.createArrowFunction(r?kn:void 0,void 0,e.map(o=>yt(o)),void 0,void 0,t),_t=(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,gt({acc:void 0,key:void 0}),void 0,void 0,t),r]),So=(...e)=>`"${e.join(" ")}"`;var Oo=["get","post","put","delete","patch"];var h=O(require("typescript"),1),bt=require("zod");var V=O(require("typescript"),1),{factory:xt}=V.default,Yt=(e,t)=>{V.default.addSyntheticLeadingComment(e,V.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ze=(e,t,r)=>{let o=xt.createTypeAliasDeclaration(void 0,xt.createIdentifier(t),void 0,e);return r&&Yt(o,r),o},Qt=(e,t)=>{let r=V.default.createSourceFile("print.ts","",V.default.ScriptTarget.Latest,!1,V.default.ScriptKind.TS);return V.default.createPrinter(t).printNode(V.default.EmitHint.Unspecified,e,r)},Un=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ro=e=>Un.test(e)?xt.createIdentifier(e):xt.createStringLiteral(e);var{factory:u}=h.default,Hn={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Dn=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Fn=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ue(a)?a instanceof bt.z.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Ro(s),p&&o?u.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Yt(d,a.description),d});return u.createTypeLiteralNode(i)},Kn=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Bn=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Ao=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),qn=e=>Hn?.[e.kind],$n=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let i=We(e,qn(o)),s={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(i&&s[i]||h.default.SyntaxKind.AnyKeyword)}return o},Vn=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Gn=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},_n=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Yn=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),Qn=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Jn=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Wn=({_def:e},{next:t})=>t(e.innerType),pe=e=>()=>u.createKeywordTypeNode(e),Xn=(e,{next:t})=>t(e.unwrap()),ei=(e,{next:t})=>t(e.unwrap()),ti=({_def:e},{next:t})=>t(e.innerType),ri=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),oi=()=>u.createLiteralTypeNode(u.createNull()),ni=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,u.createLiteralTypeNode(u.createNull())),r(s,o(e)))},ii=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof bt.z.ZodString?r:t instanceof bt.z.ZodUnion?i:o},si=(e,{next:t})=>t(e.unwrap().shape.raw),ai={ZodString:pe(h.default.SyntaxKind.StringKeyword),ZodNumber:pe(h.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(h.default.SyntaxKind.BooleanKeyword),ZodAny:pe(h.default.SyntaxKind.AnyKeyword),[$e]:pe(h.default.SyntaxKind.StringKeyword),[Ve]:pe(h.default.SyntaxKind.StringKeyword),ZodNull:oi,ZodArray:Kn,ZodTuple:Yn,ZodRecord:Qn,ZodObject:Fn,ZodLiteral:Dn,ZodIntersection:Jn,ZodUnion:Ao,ZodDefault:Wn,ZodEnum:Bn,ZodNativeEnum:Vn,ZodEffects:$n,ZodOptional:Gn,ZodNullable:_n,ZodDiscriminatedUnion:Ao,ZodBranded:Xn,ZodCatch:ti,ZodPipeline:ri,ZodLazy:ni,ZodReadonly:ei,[J]:ii,[ne]:si},Ge=(e,{brandHandling:t,ctx:r})=>ae(e,{rules:{...t,...ai},onMissing:()=>u.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),ctx:r});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,Ze(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=Je,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){se({routing:t,onEndpoint:(R,A,C)=>{let de={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Ne=N(C,A,"input"),je=Ge(R.getSchema("input"),{brandHandling:r,ctx:{...de,isResponse:!1}}),L=s?N(C,A,"positive.response"):void 0,Jt=R.getSchema("positive"),Wt=s?Ge(Jt,{brandHandling:r,ctx:{...de,isResponse:!0}}):void 0,ke=s?N(C,A,"negative.response"):void 0,Xt=R.getSchema("negative"),er=s?Ge(Xt,{brandHandling:r,ctx:{...de,isResponse:!0}}):void 0,tr=N(C,A,"response"),Io=L&&ke?n.createUnionTypeNode([n.createTypeReferenceNode(L),n.createTypeReferenceNode(ke)]):Ge(Jt.or(Xt),{brandHandling:r,ctx:{...de,isResponse:!0}});this.program.push(Ze(je,Ne)),Wt&&L&&this.program.push(Ze(Wt,L)),er&&ke&&this.program.push(Ze(er,ke)),this.program.push(Ze(Io,tr)),C!=="options"&&(this.paths.push(A),this.registry.set({method:C,path:A},{input:Ne,positive:L,negative:ke,response:tr,isJson:R.getMimeTypes("positive").includes(z.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Vt(this.ids.pathType,this.paths)),this.program.push(Vt(this.ids.methodType,Oo)),this.program.push(ht(this.ids.methodPathType,Bt([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(E.default.SyntaxKind.ExtendsKeyword,[$t(this.ids.methodPathType,E.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&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 d=[],l=[];for(let[{method:R,path:A},{isJson:C,tags:de,...Ne}]of this.registry){let je=So(R,A);for(let L of this.interfaces)L.kind in Ne&&L.props.push(fo(je,Ne[L.kind]));o!=="types"&&(C&&d.push(n.createPropertyAssignment(je,n.createTrue())),l.push(n.createPropertyAssignment(je,n.createArrayLiteralExpression(de.map(L=>n.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(bo(R,p,A));if(o==="types")return;let m=n.createVariableStatement(W,X(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(d))),y=n.createVariableStatement(W,X(this.ids.endpointTagsConst,n.createObjectLiteralExpression(l))),f=ht(this.ids.providerType,n.createFunctionTypeNode(To({M:this.ids.methodType,P:this.ids.pathType}),gt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),qt)}),ho(this.ids.responseInterface,qt))),b=ht(this.ids.implementationType,n.createFunctionTypeNode(void 0,gt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(E.default.SyntaxKind.StringKeyword),params:$t(E.default.SyntaxKind.StringKeyword,E.default.SyntaxKind.AnyKeyword)}),xo())),v=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,we)]),T=_t(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[v,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),k=_t(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[v]),E.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()),I=go(this.ids.clientClass,uo([yt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),mo)]),[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,T,k]),!0))]);this.program.push(m,y,f,b,I);let x=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ee=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(z.json))]),void 0,this.ids.undefinedValue)),G=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)),ee=n.createVariableStatement(void 0,X(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,we)]),n.createObjectLiteralExpression([x,Ee,G])])))),ce=n.createVariableStatement(void 0,X(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,X(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]),we)])))),[_e,St]=["json","text"].map(R=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Ye=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ft,[n.createTemplateSpan(this.ids.methodParameter,Kt),n.createTemplateSpan(this.ids.pathParameter,we)]),E.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([_e])),H=n.createVariableStatement(W,X(this.ids.exampleImplementationConst,Gt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([ce,ve,ee,Ye,St]),!0),n.createTypeReferenceNode(this.ids.implementationType))),te=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"))])])),Le=n.createVariableStatement(void 0,X(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(H,Le,te)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Qt(r,t)).join(`
21
21
  `):void 0}print(t){let r=this.printUsage(t),o=r&&E.default.addSyntheticLeadingComment(E.default.addSyntheticLeadingComment(n.createEmptyStatement(),E.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.default.SyntaxKind.MultiLineCommentTrivia,`
22
22
  ${r}`);return this.program.concat(o||[]).map((i,s)=>Qt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
23
23
 
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ ${o}888${t}
17
17
  ${r}
18
18
  `.split(`
19
19
  `).map((c,d)=>a[d]?a[d](c):c).join(`
20
- `)};var gr=e=>{e.startupLogo!==!1&&console.log(yr());let t=e.errorHandler||ze,r=sr(e.logger)?e.logger:new Ze(e.logger);r.debug("Running","v20.0.0-beta.4 (ESM)");let o=ur({rootLogger:r,config:e}),i=dr({rootLogger:r,errorHandler:t}),s=cr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},Vo=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=gr(e);return Ot({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Go=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=gr(e),a=Rt().disable("x-powered-by").use(s);if(e.server.compression){let l=await le("compression");a.use(l(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),mr],upload:e.server.upload?await lr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Ot({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let c=(l,f)=>l.listen(f,()=>{r.info("Listening",f)}),d={httpServer:c(qo.createServer(a),e.server.listen),httpsServer:e.https?c($o.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...d,logger:r}};import ti from"assert/strict";import{OpenApiBuilder as ri}from"openapi3-ts/oas31";import{pluck as oi}from"ramda";import q from"assert/strict";import{isReferenceObject as Pt,isSchemaObject as rt}from"openapi3-ts/oas31";import{both as Yo,complement as Qo,concat as Jo,type as Wo,filter as Xo,fromPairs as ke,has as en,isNil as tn,map as ue,mergeAll as rn,mergeDeepRight as on,mergeDeepWith as nn,objOf as Sr,omit as ot,pipe as Or,pluck as sn,range as an,reject as pn,toLower as cn,union as dn,when as ln,xprod as nt,zip as mn}from"ramda";import{z as T}from"zod";import{z as Le}from"zod";var et=e=>!isNaN(e.getTime());var Ne=Symbol("DateIn"),hr=()=>Le.union([Le.string().date(),Le.string().datetime(),Le.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Le.date().refine(et)).brand(Ne);import{z as _o}from"zod";var je=Symbol("DateOut"),xr=()=>_o.date().refine(et).transform(e=>e.toISOString()).brand(je);var te=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:d=>te(d,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),c=t&&t(e,{prev:p,...i});return c?{...p,...c}:p};var br=50,Rr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",un={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ar=/:([A-Za-z0-9_]+)/g,fn=e=>e.match(Ar)?.map(t=>t.slice(1))||[],Pr=e=>e.replace(Ar,t=>`{${t.slice(1)}}`),yn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),gn=({_def:{innerType:e}},{next:t})=>t(e),hn=()=>({format:"any"}),xn=({},e)=>(q(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),bn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof T.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Tn=({options:e},{next:t})=>({oneOf:e.map(t)}),Sn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),On=e=>{let[t,r]=e.filter(rt).filter(i=>i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));q(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=nn((i,s)=>Array.isArray(i)&&Array.isArray(s)?Jo(i,s):i===s?s:q.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=dn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=J(t.examples||[],r.examples||[],([i,s])=>on(i,s))),o},Rn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return On(o)}catch{}return{allOf:o}},An=(e,{next:t})=>t(e.unwrap()),Pn=(e,{next:t})=>t(e.unwrap()),In=(e,{next:t})=>{let r=t(e.unwrap());return rt(r)&&(r.type=Cr(r)),r},Ir=e=>{let t=cn(Wo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Tr=e=>({type:Ir(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Cn=({value:e})=>({type:Ir(e),const:e}),zn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Re(p)?p instanceof T.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=tt(e,r)),s.length&&(a.required=s),a},wn=()=>({type:"null"}),Zn=({},e)=>(q(!e.isResponse,new P({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Rr}}),En=({},e)=>(q(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Rr}}),vn=({},e)=>q.fail(new P({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})),Ln=()=>({type:"boolean"}),Nn=()=>({type:"integer",format:"bigint"}),jn=e=>e.every(t=>t instanceof T.ZodLiteral),kn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=tt(T.object(ke(nt(o,[t]))),r),i.required=o),i}if(e instanceof T.ZodLiteral)return{type:"object",properties:tt(T.object({[e.value]:t}),r),required:[e.value]};if(e instanceof T.ZodUnion&&jn(e.options)){let o=ue(s=>`${s.value}`,e.options),i=ke(nt(o,[t]));return{type:"object",properties:tt(T.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},Mn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},Un=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Hn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:c,isEmoji:d,isDatetime:l,_def:{checks:f}})=>{let u=f.find(R=>R.kind==="regex"),x=f.find(R=>R.kind==="datetime"),C=u?u.regex:x?x.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,b={type:"string"},E={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:c,emoji:d};for(let R in E)if(E[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},Dn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(f=>f.kind==="max"),c=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,d=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,d?l.maximum=c:l.exclusiveMaximum=c,l},tt=({shape:e},t)=>ue(t,e),Fn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return un?.[t]},Cr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Kn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&rt(o)){let s=Ke(e,Fn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.any())}if(!t&&i.type==="preprocess"&&rt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Bn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),qn=(e,{next:t})=>t(e.unwrap()),$n=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},Vn=(e,{next:t})=>t(e.unwrap().shape.raw),zr=e=>e.length?ke(mn(an(1,e.length+1).map(t=>`example${t}`),ue(Sr("value"),e))):void 0,wr=(e,t,r=[])=>Or(F,ue(ln(Yo(j,Qo(Array.isArray)),ot(r))),zr)({schema:e,variant:t?"parsed":"original",validate:!0}),Gn=(e,t)=>Or(F,Xo(en(t)),sn(t),zr)({schema:e,variant:"original",validate:!0}),me=(e,t)=>e instanceof T.ZodObject?e:e instanceof T.ZodBranded?me(e.unwrap(),t):e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion?e.options.map(r=>me(r,t)).reduce((r,o)=>r.merge(o.partial()),T.object({})):e instanceof T.ZodEffects?(q(e._def.effect.type==="refinement",t),me(e._def.schema,t)):me(e._def.left,t).merge(me(e._def.right,t)),Zr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:c,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=me(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),f=fn(e),u=o.includes("query"),x=o.includes("params"),C=o.includes("headers"),b=h=>x&&f.includes(h),E=h=>C&&ut(h);return Object.keys(l).map(h=>({name:h,location:b(h)?"path":E(h)?"header":u?"query":void 0})).filter(h=>h.location!==void 0).map(({name:h,location:ge})=>{let M=te(l[h],{rules:{...c,...It},onEach:Ct,onMissing:zt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),_=p==="components"?a(w(d,h),M):M;return{name:h,in:ge,required:!l[h].isOptional(),description:M.description||d,schema:_,examples:Gn(r,h)}})},It={ZodString:Hn,ZodNumber:Dn,ZodBigInt:Nn,ZodBoolean:Ln,ZodNull:wn,ZodArray:Mn,ZodTuple:Un,ZodRecord:kn,ZodObject:zn,ZodLiteral:Cn,ZodIntersection:Rn,ZodUnion:Tn,ZodAny:hn,ZodDefault:yn,ZodEnum:Tr,ZodNativeEnum:Tr,ZodEffects:Kn,ZodOptional:An,ZodNullable:In,ZodDiscriminatedUnion:Sn,ZodBranded:qn,ZodDate:vn,ZodCatch:gn,ZodPipeline:Bn,ZodLazy:$n,ZodReadonly:Pn,[K]:bn,[Ae]:xn,[je]:En,[Ne]:Zn,[W]:Vn},Ct=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,i=e instanceof T.ZodLazy,s=r.type!==void 0,a=t&&Re(e),p=!i&&s&&!a&&e.isNullable(),c=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),d={};return o&&(d.description=o),p&&(d.type=Cr(r)),c.length&&(d.examples=c.slice()),d},zt=(e,t)=>q.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=ot(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>ot(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},Er=e=>Pt(e)?e:ot(["examples"],e),vr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:c,hasMultipleStatusCodes:d,statusCode:l,brandHandling:f,description:u=`${e.toUpperCase()} ${t} ${yt(i)} response ${d?l:""}`.trim()})=>{let x=Er(te(r,{rules:{...f,...It},onEach:Ct,onMissing:zt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),C={schema:c==="components"?p(w(u),x):x,examples:wr(r,!0)};return{description:u,content:ke(nt(o,[C]))}},_n=()=>({type:"http",scheme:"basic"}),Yn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Qn=({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},Jn=({name:e})=>({type:"apiKey",in:"header",name:e}),Wn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Xn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ei=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),pn(tn,e))}),Lr=(e,t)=>{let r={basic:_n,bearer:Yn,input:Qn,header:Jn,cookie:Wn,openid:Xn,oauth2:ei};return Qe(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?rn(ue(({name:r,scopes:o})=>Sr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(xt(e)):it({or:[e]}),Nr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:c,paramNames:d,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=Er(At(te(r,{rules:{...c,...It},onEach:Ct,onMissing:zt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),d)),u={schema:p==="components"?a(w(l),f):f,examples:wr(r,!1,d)};return{description:l,content:ke(nt(o,[u]))}},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}),wt=e=>e.length<=br?e:e.slice(0,br-1)+"\u2026";var Zt=class extends ri{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||w(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ti.fail(new P({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,brandHandling:p,hasSummaryFromDescription:c=!0,composition:d="inline",serializer:l=Fe}){super(),this.addInfo({title:o,version:i});for(let u of typeof s=="string"?[s]:s)this.addServer({url:u});ee({routing:t,onEndpoint:(u,x,C)=>{let b=C,E={path:x,method:b,endpoint:u,composition:d,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,h]=["short","long"].map(u.getDescription.bind(u)),ge=R?wt(R):c&&h?wt(h):void 0,M=u.getTags(),_=r.inputSources?.[b]||lt[b],oe=this.ensureUniqOperationId(x,b,u.getOperationId(b)),he=Zr({...E,inputSources:_,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:x,operationId:oe})}),Ue={};for(let L of["positive","negative"]){let Y=u.getResponses(L);for(let{mimeTypes:xe,schema:S,statusCodes:O}of Y)for(let A of O)Ue[A]=vr({...E,variant:L,schema:S,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:Y.length>1||O.length>1,description:a?.[`${L}Response`]?.call(null,{method:b,path:x,operationId:oe,statusCode:A})})}let dt=_.includes("body")?Nr({...E,paramNames:oi("name",he),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:x,operationId:oe})}):void 0,He=it(Qe(Lr(u.getSecurity(),_),L=>{let Y=this.ensureUniqSecuritySchemaName(L),xe=["oauth2","openIdConnect"].includes(L.type)?u.getScopes().slice():[];return this.addSecurityScheme(Y,L),{name:Y,scopes:xe}}));this.addPath(Pr(x),{[b]:{operationId:oe,summary:ge,description:h,tags:M.length>0?M:void 0,parameters:he.length>0?he:void 0,requestBody:dt,security:He.length>0?He:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?jr(r.tags):[]}};import{createRequest as ni,createResponse as ii}from"node-mocks-http";var si=e=>ni({...e,headers:{"content-type":I.json,...e?.headers}}),ai=e=>ii(e),pi=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,i){return o==="_getLogs"?()=>t:o in de?(...s)=>t[o].push(s):Reflect.get(r,o,i)}})},ci=async({endpoint:e,requestProps:t,responseOptions:r,configProps:o,loggerProps:i})=>{let s=si(t),a=ai({req:s,...r}),p=pi(i),c={cors:!1,logger:p,...o};return await e.execute({request:s,response:a,config:c,logger:p}),{requestMock:s,responseMock:a,loggerMock:p}};import Z from"typescript";import k from"typescript";import{chain as kr,toPairs as Mr}from"ramda";var n=k.factory,$=[n.createModifier(k.SyntaxKind.ExportKeyword)],di=[n.createModifier(k.SyntaxKind.AsyncKeyword)],li=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Ur=[n.createModifier(k.SyntaxKind.ProtectedKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Et=n.createTemplateHead(""),fe=n.createTemplateTail(""),vt=n.createTemplateMiddle(" "),Lt=e=>n.createTemplateLiteralType(Et,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Nt=Lt(["M","P"]),st=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),at=(e,t)=>kr(([r,o])=>[st(n.createIdentifier(r),o,t)],Mr(e)),jt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Hr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Dr=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),V=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.NodeFlags.Const),kt=(e,t)=>n.createTypeAliasDeclaration($,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),pt=(e,t)=>n.createTypeAliasDeclaration($,e,void 0,t),Fr=(e,t,r)=>n.createPropertyDeclaration(li,e,void 0,t,r),Kr=(e,t,r)=>n.createClassDeclaration($,e,void 0,void 0,[t,...r]),Br=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),qr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),$r=(e,t,r)=>n.createInterfaceDeclaration($,e,void 0,t,r),Vr=e=>kr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Mr(e)),Mt=(e,t,r)=>n.createArrowFunction(r?di:void 0,void 0,e.map(o=>st(o)),void 0,void 0,t),Ut=(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,at({acc:void 0,key:void 0}),void 0,void 0,t),r]),Gr=(...e)=>`"${e.join(" ")}"`;var _r=["get","post","put","delete","patch"];import g from"typescript";import{z as Ft}from"zod";import G from"typescript";var{factory:ct}=G,Ht=(e,t)=>{G.addSyntheticLeadingComment(e,G.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=ct.createTypeAliasDeclaration(void 0,ct.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=G.createSourceFile("print.ts","",G.ScriptTarget.Latest,!1,G.ScriptKind.TS);return G.createPrinter(t).printNode(G.EmitHint.Unspecified,e,r)},mi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yr=e=>mi.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:m}=g,ui={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},fi=({value:e})=>m.createLiteralTypeNode(typeof e=="number"?m.createNumericLiteral(e):typeof e=="boolean"?e?m.createTrue():m.createFalse():m.createStringLiteral(e)),yi=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),c=m.createPropertySignature(void 0,Yr(s),p&&o?m.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(c,a.description),c});return m.createTypeLiteralNode(i)},gi=({element:e},{next:t})=>m.createArrayTypeNode(t(e)),hi=({options:e})=>m.createUnionTypeNode(e.map(t=>m.createLiteralTypeNode(m.createStringLiteral(t)))),Qr=({options:e},{next:t})=>m.createUnionTypeNode(e.map(t)),xi=e=>ui?.[e.kind],bi=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let i=Ke(e,xi(o)),s={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return m.createKeywordTypeNode(i&&s[i]||g.SyntaxKind.AnyKeyword)}return o},Ti=e=>m.createUnionTypeNode(Object.values(e.enum).map(t=>m.createLiteralTypeNode(typeof t=="number"?m.createNumericLiteral(t):m.createStringLiteral(t)))),Si=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?m.createUnionTypeNode([o,m.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},Oi=(e,{next:t})=>m.createUnionTypeNode([t(e.unwrap()),m.createLiteralTypeNode(m.createNull())]),Ri=({items:e,_def:{rest:t}},{next:r})=>m.createTupleTypeNode(e.map(r).concat(t===null?[]:m.createRestTypeNode(r(t)))),Ai=({keySchema:e,valueSchema:t},{next:r})=>m.createExpressionWithTypeArguments(m.createIdentifier("Record"),[e,t].map(r)),Pi=({_def:e},{next:t})=>m.createIntersectionTypeNode([e.left,e.right].map(t)),Ii=({_def:e},{next:t})=>t(e.innerType),re=e=>()=>m.createKeywordTypeNode(e),Ci=(e,{next:t})=>t(e.unwrap()),zi=(e,{next:t})=>t(e.unwrap()),wi=({_def:e},{next:t})=>t(e.innerType),Zi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ei=()=>m.createLiteralTypeNode(m.createNull()),vi=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,m.createLiteralTypeNode(m.createNull())),r(s,o(e)))},Li=e=>{let t=e.unwrap(),r=m.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=m.createTypeReferenceNode("Buffer"),i=m.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?i:o},Ni=(e,{next:t})=>t(e.unwrap().shape.raw),ji={ZodString:re(g.SyntaxKind.StringKeyword),ZodNumber:re(g.SyntaxKind.NumberKeyword),ZodBigInt:re(g.SyntaxKind.BigIntKeyword),ZodBoolean:re(g.SyntaxKind.BooleanKeyword),ZodAny:re(g.SyntaxKind.AnyKeyword),[Ne]:re(g.SyntaxKind.StringKeyword),[je]:re(g.SyntaxKind.StringKeyword),ZodNull:Ei,ZodArray:gi,ZodTuple:Ri,ZodRecord:Ai,ZodObject:yi,ZodLiteral:fi,ZodIntersection:Pi,ZodUnion:Qr,ZodDefault:Ii,ZodEnum:hi,ZodNativeEnum:Ti,ZodEffects:bi,ZodOptional:Si,ZodNullable:Oi,ZodDiscriminatedUnion:Qr,ZodBranded:Ci,ZodCatch:wi,ZodPipeline:Zi,ZodLazy:vi,ZodReadonly:zi,[K]:Li,[W]:Ni},Me=(e,{brandHandling:t,ctx:r})=>te(e,{rules:{...t,...ji},onMissing:()=>m.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),ctx:r});var Kt=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,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=Fe,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){ee({routing:t,onEndpoint:(S,O,A)=>{let ne={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Te=Me(S.getSchema("input"),{brandHandling:r,ctx:{...ne,isResponse:!1}}),z=s?w(A,O,"positive.response"):void 0,Bt=S.getSchema("positive"),qt=s?Me(Bt,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Se=s?w(A,O,"negative.response"):void 0,$t=S.getSchema("negative"),Vt=s?Me($t,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Gt=w(A,O,"response"),Jr=z&&Se?n.createUnionTypeNode([n.createTypeReferenceNode(z),n.createTypeReferenceNode(Se)]):Me(Bt.or($t),{brandHandling:r,ctx:{...ne,isResponse:!0}});this.program.push(ye(Te,be)),qt&&z&&this.program.push(ye(qt,z)),Vt&&Se&&this.program.push(ye(Vt,Se)),this.program.push(ye(Jr,Gt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:z,negative:Se,response:Gt,isJson:S.getMimeTypes("positive").includes(I.json),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,_r)),this.program.push(pt(this.ids.methodPathType,Lt([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(Z.SyntaxKind.ExtendsKeyword,[jt(this.ids.methodPathType,Z.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&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 c=[],d=[];for(let[{method:S,path:O},{isJson:A,tags:ne,...be}]of this.registry){let Te=Gr(S,O);for(let z of this.interfaces)z.kind in be&&z.props.push(Dr(Te,be[z.kind]));o!=="types"&&(A&&c.push(n.createPropertyAssignment(Te,n.createTrue())),d.push(n.createPropertyAssignment(Te,n.createArrayLiteralExpression(ne.map(z=>n.createStringLiteral(z))))))}for(let{id:S,props:O}of this.interfaces)this.program.push($r(S,p,O));if(o==="types")return;let l=n.createVariableStatement($,V(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(c))),f=n.createVariableStatement($,V(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),u=pt(this.ids.providerType,n.createFunctionTypeNode(Vr({M:this.ids.methodType,P:this.ids.pathType}),at({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Nt)}),Br(this.ids.responseInterface,Nt))),x=pt(this.ids.implementationType,n.createFunctionTypeNode(void 0,at({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(Z.SyntaxKind.StringKeyword),params:jt(Z.SyntaxKind.StringKeyword,Z.SyntaxKind.AnyKeyword)}),qr())),C=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),E=Ut(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),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()),R=Kr(this.ids.clientClass,Hr([st(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Ur)]),[Fr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,E]),!0))]);this.program.push(l,f,u,x,R);let h=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(I.json))]),void 0,this.ids.undefinedValue)),M=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)),_=n.createVariableStatement(void 0,V(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,fe)]),n.createObjectLiteralExpression([h,ge,M])])))),oe=n.createVariableStatement(void 0,V(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=n.createVariableStatement(void 0,V(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]),fe)])))),[Ue,dt]=["json","text"].map(S=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,S),void 0,void 0))),He=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Et,[n.createTemplateSpan(this.ids.methodParameter,vt),n.createTemplateSpan(this.ids.pathParameter,fe)]),Z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Ue])),L=n.createVariableStatement($,V(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([oe,he,_,He,dt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Y=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"))])])),xe=n.createVariableStatement(void 0,V(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(L,xe,Y)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
20
+ `)};var gr=e=>{e.startupLogo!==!1&&console.log(yr());let t=e.errorHandler||ze,r=sr(e.logger)?e.logger:new Ze(e.logger);r.debug("Running","v20.0.0 (ESM)");let o=ur({rootLogger:r,config:e}),i=dr({rootLogger:r,errorHandler:t}),s=cr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},Vo=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=gr(e);return Ot({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Go=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=gr(e),a=Rt().disable("x-powered-by").use(s);if(e.server.compression){let l=await le("compression");a.use(l(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),mr],upload:e.server.upload?await lr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Ot({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let c=(l,f)=>l.listen(f,()=>{r.info("Listening",f)}),d={httpServer:c(qo.createServer(a),e.server.listen),httpsServer:e.https?c($o.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...d,logger:r}};import ti from"assert/strict";import{OpenApiBuilder as ri}from"openapi3-ts/oas31";import{pluck as oi}from"ramda";import q from"assert/strict";import{isReferenceObject as Pt,isSchemaObject as rt}from"openapi3-ts/oas31";import{both as Yo,complement as Qo,concat as Jo,type as Wo,filter as Xo,fromPairs as ke,has as en,isNil as tn,map as ue,mergeAll as rn,mergeDeepRight as on,mergeDeepWith as nn,objOf as Sr,omit as ot,pipe as Or,pluck as sn,range as an,reject as pn,toLower as cn,union as dn,when as ln,xprod as nt,zip as mn}from"ramda";import{z as T}from"zod";import{z as Le}from"zod";var et=e=>!isNaN(e.getTime());var Ne=Symbol("DateIn"),hr=()=>Le.union([Le.string().date(),Le.string().datetime(),Le.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Le.date().refine(et)).brand(Ne);import{z as _o}from"zod";var je=Symbol("DateOut"),xr=()=>_o.date().refine(et).transform(e=>e.toISOString()).brand(je);var te=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:d=>te(d,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),c=t&&t(e,{prev:p,...i});return c?{...p,...c}:p};var br=50,Rr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",un={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ar=/:([A-Za-z0-9_]+)/g,fn=e=>e.match(Ar)?.map(t=>t.slice(1))||[],Pr=e=>e.replace(Ar,t=>`{${t.slice(1)}}`),yn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),gn=({_def:{innerType:e}},{next:t})=>t(e),hn=()=>({format:"any"}),xn=({},e)=>(q(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),bn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof T.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Tn=({options:e},{next:t})=>({oneOf:e.map(t)}),Sn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),On=e=>{let[t,r]=e.filter(rt).filter(i=>i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));q(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=nn((i,s)=>Array.isArray(i)&&Array.isArray(s)?Jo(i,s):i===s?s:q.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=dn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=J(t.examples||[],r.examples||[],([i,s])=>on(i,s))),o},Rn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return On(o)}catch{}return{allOf:o}},An=(e,{next:t})=>t(e.unwrap()),Pn=(e,{next:t})=>t(e.unwrap()),In=(e,{next:t})=>{let r=t(e.unwrap());return rt(r)&&(r.type=Cr(r)),r},Ir=e=>{let t=cn(Wo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Tr=e=>({type:Ir(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Cn=({value:e})=>({type:Ir(e),const:e}),zn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Re(p)?p instanceof T.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=tt(e,r)),s.length&&(a.required=s),a},wn=()=>({type:"null"}),Zn=({},e)=>(q(!e.isResponse,new P({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Rr}}),En=({},e)=>(q(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Rr}}),vn=({},e)=>q.fail(new P({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})),Ln=()=>({type:"boolean"}),Nn=()=>({type:"integer",format:"bigint"}),jn=e=>e.every(t=>t instanceof T.ZodLiteral),kn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=tt(T.object(ke(nt(o,[t]))),r),i.required=o),i}if(e instanceof T.ZodLiteral)return{type:"object",properties:tt(T.object({[e.value]:t}),r),required:[e.value]};if(e instanceof T.ZodUnion&&jn(e.options)){let o=ue(s=>`${s.value}`,e.options),i=ke(nt(o,[t]));return{type:"object",properties:tt(T.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},Mn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},Un=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Hn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:c,isEmoji:d,isDatetime:l,_def:{checks:f}})=>{let u=f.find(R=>R.kind==="regex"),x=f.find(R=>R.kind==="datetime"),C=u?u.regex:x?x.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,b={type:"string"},E={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:c,emoji:d};for(let R in E)if(E[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},Dn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(f=>f.kind==="max"),c=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,d=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,d?l.maximum=c:l.exclusiveMaximum=c,l},tt=({shape:e},t)=>ue(t,e),Fn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return un?.[t]},Cr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Kn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&rt(o)){let s=Ke(e,Fn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.any())}if(!t&&i.type==="preprocess"&&rt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Bn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),qn=(e,{next:t})=>t(e.unwrap()),$n=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},Vn=(e,{next:t})=>t(e.unwrap().shape.raw),zr=e=>e.length?ke(mn(an(1,e.length+1).map(t=>`example${t}`),ue(Sr("value"),e))):void 0,wr=(e,t,r=[])=>Or(F,ue(ln(Yo(j,Qo(Array.isArray)),ot(r))),zr)({schema:e,variant:t?"parsed":"original",validate:!0}),Gn=(e,t)=>Or(F,Xo(en(t)),sn(t),zr)({schema:e,variant:"original",validate:!0}),me=(e,t)=>e instanceof T.ZodObject?e:e instanceof T.ZodBranded?me(e.unwrap(),t):e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion?e.options.map(r=>me(r,t)).reduce((r,o)=>r.merge(o.partial()),T.object({})):e instanceof T.ZodEffects?(q(e._def.effect.type==="refinement",t),me(e._def.schema,t)):me(e._def.left,t).merge(me(e._def.right,t)),Zr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:c,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=me(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),f=fn(e),u=o.includes("query"),x=o.includes("params"),C=o.includes("headers"),b=h=>x&&f.includes(h),E=h=>C&&ut(h);return Object.keys(l).map(h=>({name:h,location:b(h)?"path":E(h)?"header":u?"query":void 0})).filter(h=>h.location!==void 0).map(({name:h,location:ge})=>{let M=te(l[h],{rules:{...c,...It},onEach:Ct,onMissing:zt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),_=p==="components"?a(w(d,h),M):M;return{name:h,in:ge,required:!l[h].isOptional(),description:M.description||d,schema:_,examples:Gn(r,h)}})},It={ZodString:Hn,ZodNumber:Dn,ZodBigInt:Nn,ZodBoolean:Ln,ZodNull:wn,ZodArray:Mn,ZodTuple:Un,ZodRecord:kn,ZodObject:zn,ZodLiteral:Cn,ZodIntersection:Rn,ZodUnion:Tn,ZodAny:hn,ZodDefault:yn,ZodEnum:Tr,ZodNativeEnum:Tr,ZodEffects:Kn,ZodOptional:An,ZodNullable:In,ZodDiscriminatedUnion:Sn,ZodBranded:qn,ZodDate:vn,ZodCatch:gn,ZodPipeline:Bn,ZodLazy:$n,ZodReadonly:Pn,[K]:bn,[Ae]:xn,[je]:En,[Ne]:Zn,[W]:Vn},Ct=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,i=e instanceof T.ZodLazy,s=r.type!==void 0,a=t&&Re(e),p=!i&&s&&!a&&e.isNullable(),c=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),d={};return o&&(d.description=o),p&&(d.type=Cr(r)),c.length&&(d.examples=c.slice()),d},zt=(e,t)=>q.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=ot(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>ot(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},Er=e=>Pt(e)?e:ot(["examples"],e),vr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:c,hasMultipleStatusCodes:d,statusCode:l,brandHandling:f,description:u=`${e.toUpperCase()} ${t} ${yt(i)} response ${d?l:""}`.trim()})=>{let x=Er(te(r,{rules:{...f,...It},onEach:Ct,onMissing:zt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),C={schema:c==="components"?p(w(u),x):x,examples:wr(r,!0)};return{description:u,content:ke(nt(o,[C]))}},_n=()=>({type:"http",scheme:"basic"}),Yn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Qn=({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},Jn=({name:e})=>({type:"apiKey",in:"header",name:e}),Wn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Xn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ei=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),pn(tn,e))}),Lr=(e,t)=>{let r={basic:_n,bearer:Yn,input:Qn,header:Jn,cookie:Wn,openid:Xn,oauth2:ei};return Qe(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?rn(ue(({name:r,scopes:o})=>Sr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(xt(e)):it({or:[e]}),Nr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:c,paramNames:d,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=Er(At(te(r,{rules:{...c,...It},onEach:Ct,onMissing:zt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),d)),u={schema:p==="components"?a(w(l),f):f,examples:wr(r,!1,d)};return{description:l,content:ke(nt(o,[u]))}},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}),wt=e=>e.length<=br?e:e.slice(0,br-1)+"\u2026";var Zt=class extends ri{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||w(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ti.fail(new P({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,brandHandling:p,hasSummaryFromDescription:c=!0,composition:d="inline",serializer:l=Fe}){super(),this.addInfo({title:o,version:i});for(let u of typeof s=="string"?[s]:s)this.addServer({url:u});ee({routing:t,onEndpoint:(u,x,C)=>{let b=C,E={path:x,method:b,endpoint:u,composition:d,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,h]=["short","long"].map(u.getDescription.bind(u)),ge=R?wt(R):c&&h?wt(h):void 0,M=u.getTags(),_=r.inputSources?.[b]||lt[b],oe=this.ensureUniqOperationId(x,b,u.getOperationId(b)),he=Zr({...E,inputSources:_,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:x,operationId:oe})}),Ue={};for(let L of["positive","negative"]){let Y=u.getResponses(L);for(let{mimeTypes:xe,schema:S,statusCodes:O}of Y)for(let A of O)Ue[A]=vr({...E,variant:L,schema:S,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:Y.length>1||O.length>1,description:a?.[`${L}Response`]?.call(null,{method:b,path:x,operationId:oe,statusCode:A})})}let dt=_.includes("body")?Nr({...E,paramNames:oi("name",he),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:x,operationId:oe})}):void 0,He=it(Qe(Lr(u.getSecurity(),_),L=>{let Y=this.ensureUniqSecuritySchemaName(L),xe=["oauth2","openIdConnect"].includes(L.type)?u.getScopes().slice():[];return this.addSecurityScheme(Y,L),{name:Y,scopes:xe}}));this.addPath(Pr(x),{[b]:{operationId:oe,summary:ge,description:h,tags:M.length>0?M:void 0,parameters:he.length>0?he:void 0,requestBody:dt,security:He.length>0?He:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?jr(r.tags):[]}};import{createRequest as ni,createResponse as ii}from"node-mocks-http";var si=e=>ni({...e,headers:{"content-type":I.json,...e?.headers}}),ai=e=>ii(e),pi=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,i){return o==="_getLogs"?()=>t:o in de?(...s)=>t[o].push(s):Reflect.get(r,o,i)}})},ci=async({endpoint:e,requestProps:t,responseOptions:r,configProps:o,loggerProps:i})=>{let s=si(t),a=ai({req:s,...r}),p=pi(i),c={cors:!1,logger:p,...o};return await e.execute({request:s,response:a,config:c,logger:p}),{requestMock:s,responseMock:a,loggerMock:p}};import Z from"typescript";import k from"typescript";import{chain as kr,toPairs as Mr}from"ramda";var n=k.factory,$=[n.createModifier(k.SyntaxKind.ExportKeyword)],di=[n.createModifier(k.SyntaxKind.AsyncKeyword)],li=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Ur=[n.createModifier(k.SyntaxKind.ProtectedKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Et=n.createTemplateHead(""),fe=n.createTemplateTail(""),vt=n.createTemplateMiddle(" "),Lt=e=>n.createTemplateLiteralType(Et,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Nt=Lt(["M","P"]),st=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),at=(e,t)=>kr(([r,o])=>[st(n.createIdentifier(r),o,t)],Mr(e)),jt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Hr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Dr=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),V=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.NodeFlags.Const),kt=(e,t)=>n.createTypeAliasDeclaration($,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),pt=(e,t)=>n.createTypeAliasDeclaration($,e,void 0,t),Fr=(e,t,r)=>n.createPropertyDeclaration(li,e,void 0,t,r),Kr=(e,t,r)=>n.createClassDeclaration($,e,void 0,void 0,[t,...r]),Br=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),qr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),$r=(e,t,r)=>n.createInterfaceDeclaration($,e,void 0,t,r),Vr=e=>kr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Mr(e)),Mt=(e,t,r)=>n.createArrowFunction(r?di:void 0,void 0,e.map(o=>st(o)),void 0,void 0,t),Ut=(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,at({acc:void 0,key:void 0}),void 0,void 0,t),r]),Gr=(...e)=>`"${e.join(" ")}"`;var _r=["get","post","put","delete","patch"];import g from"typescript";import{z as Ft}from"zod";import G from"typescript";var{factory:ct}=G,Ht=(e,t)=>{G.addSyntheticLeadingComment(e,G.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=ct.createTypeAliasDeclaration(void 0,ct.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=G.createSourceFile("print.ts","",G.ScriptTarget.Latest,!1,G.ScriptKind.TS);return G.createPrinter(t).printNode(G.EmitHint.Unspecified,e,r)},mi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yr=e=>mi.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:m}=g,ui={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},fi=({value:e})=>m.createLiteralTypeNode(typeof e=="number"?m.createNumericLiteral(e):typeof e=="boolean"?e?m.createTrue():m.createFalse():m.createStringLiteral(e)),yi=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),c=m.createPropertySignature(void 0,Yr(s),p&&o?m.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(c,a.description),c});return m.createTypeLiteralNode(i)},gi=({element:e},{next:t})=>m.createArrayTypeNode(t(e)),hi=({options:e})=>m.createUnionTypeNode(e.map(t=>m.createLiteralTypeNode(m.createStringLiteral(t)))),Qr=({options:e},{next:t})=>m.createUnionTypeNode(e.map(t)),xi=e=>ui?.[e.kind],bi=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let i=Ke(e,xi(o)),s={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return m.createKeywordTypeNode(i&&s[i]||g.SyntaxKind.AnyKeyword)}return o},Ti=e=>m.createUnionTypeNode(Object.values(e.enum).map(t=>m.createLiteralTypeNode(typeof t=="number"?m.createNumericLiteral(t):m.createStringLiteral(t)))),Si=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?m.createUnionTypeNode([o,m.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},Oi=(e,{next:t})=>m.createUnionTypeNode([t(e.unwrap()),m.createLiteralTypeNode(m.createNull())]),Ri=({items:e,_def:{rest:t}},{next:r})=>m.createTupleTypeNode(e.map(r).concat(t===null?[]:m.createRestTypeNode(r(t)))),Ai=({keySchema:e,valueSchema:t},{next:r})=>m.createExpressionWithTypeArguments(m.createIdentifier("Record"),[e,t].map(r)),Pi=({_def:e},{next:t})=>m.createIntersectionTypeNode([e.left,e.right].map(t)),Ii=({_def:e},{next:t})=>t(e.innerType),re=e=>()=>m.createKeywordTypeNode(e),Ci=(e,{next:t})=>t(e.unwrap()),zi=(e,{next:t})=>t(e.unwrap()),wi=({_def:e},{next:t})=>t(e.innerType),Zi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ei=()=>m.createLiteralTypeNode(m.createNull()),vi=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,m.createLiteralTypeNode(m.createNull())),r(s,o(e)))},Li=e=>{let t=e.unwrap(),r=m.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=m.createTypeReferenceNode("Buffer"),i=m.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?i:o},Ni=(e,{next:t})=>t(e.unwrap().shape.raw),ji={ZodString:re(g.SyntaxKind.StringKeyword),ZodNumber:re(g.SyntaxKind.NumberKeyword),ZodBigInt:re(g.SyntaxKind.BigIntKeyword),ZodBoolean:re(g.SyntaxKind.BooleanKeyword),ZodAny:re(g.SyntaxKind.AnyKeyword),[Ne]:re(g.SyntaxKind.StringKeyword),[je]:re(g.SyntaxKind.StringKeyword),ZodNull:Ei,ZodArray:gi,ZodTuple:Ri,ZodRecord:Ai,ZodObject:yi,ZodLiteral:fi,ZodIntersection:Pi,ZodUnion:Qr,ZodDefault:Ii,ZodEnum:hi,ZodNativeEnum:Ti,ZodEffects:bi,ZodOptional:Si,ZodNullable:Oi,ZodDiscriminatedUnion:Qr,ZodBranded:Ci,ZodCatch:wi,ZodPipeline:Zi,ZodLazy:vi,ZodReadonly:zi,[K]:Li,[W]:Ni},Me=(e,{brandHandling:t,ctx:r})=>te(e,{rules:{...t,...ji},onMissing:()=>m.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),ctx:r});var Kt=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,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=Fe,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){ee({routing:t,onEndpoint:(S,O,A)=>{let ne={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Te=Me(S.getSchema("input"),{brandHandling:r,ctx:{...ne,isResponse:!1}}),z=s?w(A,O,"positive.response"):void 0,Bt=S.getSchema("positive"),qt=s?Me(Bt,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Se=s?w(A,O,"negative.response"):void 0,$t=S.getSchema("negative"),Vt=s?Me($t,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Gt=w(A,O,"response"),Jr=z&&Se?n.createUnionTypeNode([n.createTypeReferenceNode(z),n.createTypeReferenceNode(Se)]):Me(Bt.or($t),{brandHandling:r,ctx:{...ne,isResponse:!0}});this.program.push(ye(Te,be)),qt&&z&&this.program.push(ye(qt,z)),Vt&&Se&&this.program.push(ye(Vt,Se)),this.program.push(ye(Jr,Gt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:z,negative:Se,response:Gt,isJson:S.getMimeTypes("positive").includes(I.json),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,_r)),this.program.push(pt(this.ids.methodPathType,Lt([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(Z.SyntaxKind.ExtendsKeyword,[jt(this.ids.methodPathType,Z.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&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 c=[],d=[];for(let[{method:S,path:O},{isJson:A,tags:ne,...be}]of this.registry){let Te=Gr(S,O);for(let z of this.interfaces)z.kind in be&&z.props.push(Dr(Te,be[z.kind]));o!=="types"&&(A&&c.push(n.createPropertyAssignment(Te,n.createTrue())),d.push(n.createPropertyAssignment(Te,n.createArrayLiteralExpression(ne.map(z=>n.createStringLiteral(z))))))}for(let{id:S,props:O}of this.interfaces)this.program.push($r(S,p,O));if(o==="types")return;let l=n.createVariableStatement($,V(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(c))),f=n.createVariableStatement($,V(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),u=pt(this.ids.providerType,n.createFunctionTypeNode(Vr({M:this.ids.methodType,P:this.ids.pathType}),at({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Nt)}),Br(this.ids.responseInterface,Nt))),x=pt(this.ids.implementationType,n.createFunctionTypeNode(void 0,at({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(Z.SyntaxKind.StringKeyword),params:jt(Z.SyntaxKind.StringKeyword,Z.SyntaxKind.AnyKeyword)}),qr())),C=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),E=Ut(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),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()),R=Kr(this.ids.clientClass,Hr([st(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Ur)]),[Fr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,E]),!0))]);this.program.push(l,f,u,x,R);let h=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(I.json))]),void 0,this.ids.undefinedValue)),M=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)),_=n.createVariableStatement(void 0,V(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,fe)]),n.createObjectLiteralExpression([h,ge,M])])))),oe=n.createVariableStatement(void 0,V(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=n.createVariableStatement(void 0,V(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]),fe)])))),[Ue,dt]=["json","text"].map(S=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,S),void 0,void 0))),He=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Et,[n.createTemplateSpan(this.ids.methodParameter,vt),n.createTemplateSpan(this.ids.pathParameter,fe)]),Z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Ue])),L=n.createVariableStatement($,V(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([oe,he,_,He,dt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Y=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"))])])),xe=n.createVariableStatement(void 0,V(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(L,xe,Y)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
21
21
  `):void 0}print(t){let r=this.printUsage(t),o=r&&Z.addSyntheticLeadingComment(Z.addSyntheticLeadingComment(n.createEmptyStatement(),Z.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Z.SyntaxKind.MultiLineCommentTrivia,`
22
22
  ${r}`);return this.program.concat(o||[]).map((i,s)=>Dt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
23
23
 
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var f=(t,r)=>{for(var e in r)p(t,e,{get:r[e],enumerable:!0})},g=(t,r,e,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of m(r))!c.call(t,n)&&n!==e&&p(t,n,{get:()=>r[n],enumerable:!(a=l(r,n))||a.enumerable});return t};var y=t=>g(p({},"__esModule",{value:!0}),t);var x={};f(x,{default:()=>$});module.exports=y(x);var u="ez-migration",d="express-zod-api",k="testEndpoint",s={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},i={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},v={fnMethod:null},o=(t,r)=>typeof t=="string"&&t in r,h={meta:{type:"problem",fixable:"code"},create:t=>({ImportDeclaration:r=>{if(r.source.value===d){for(let e of r.specifiers)if(e.type==="ImportSpecifier"&&o(e.imported.name,s)){let a=s[e.imported.name];t.report({node:e.imported,message:`Change import "${e.imported.name}" to "${a}".`,fix:n=>n.replaceText(e,a)})}}},CallExpression:r=>{if(r.callee.type==="Identifier"&&o(r.callee.name,s)){let e=`new ${s[r.callee.name]}`;t.report({node:r.callee,message:`Change "${r.callee.name}" to "${e}".`,fix:a=>a.replaceText(r.callee,e)})}if(r.callee.type==="Identifier"&&r.callee.name===k&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(o(e.key.name,i)){let a=i[e.key.name];t.report({node:e,message:`Change property "${e.key.name}" to "${a}".`,fix:n=>n.replaceText(e.key,a)})}o(e.key.name,v)&&t.report({node:e,message:`Remove property "${e.key.name}".`,fix:a=>t.sourceCode.getTokenAfter(e)?.value===","&&e.range?a.removeRange([e.range[0],e.range[1]+1]):a.remove(e)})}}},NewExpression:r=>{if(r.callee.type==="Identifier"&&[s.createResultHandler,s.createMiddleware].includes(r.callee.name)&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&o(e.key.name,i)){let a=i[e.key.name];t.report({node:e,message:`Change property "${e.key.name}" to "${a}".`,fix:n=>n.replaceText(e.key,a)})}}},Identifier:r=>{r.name==="MockOverrides"&&r.parent.type==="TSInterfaceDeclaration"&&t.report({node:r,message:`Remove augmentation of the "${r.name}" interface \u2014 no longer needed.`,fix:e=>e.remove(r.parent)})}})},R={v20:h},$={rules:{"ez-migration/v20":"error"},plugins:{[u]:{rules:R}}};
1
+ "use strict";var p=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var f=(t,r)=>{for(var e in r)p(t,e,{get:r[e],enumerable:!0})},g=(t,r,e,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of m(r))!c.call(t,n)&&n!==e&&p(t,n,{get:()=>r[n],enumerable:!(a=l(r,n))||a.enumerable});return t};var y=t=>g(p({},"__esModule",{value:!0}),t);var x={};f(x,{default:()=>R});module.exports=y(x);var u="ez-migration",d="express-zod-api",k="testEndpoint",o={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},i={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},v={fnMethod:null},s=(t,r)=>typeof t=="string"&&t in r,$={meta:{type:"problem",fixable:"code"},create:t=>({ImportDeclaration:r=>{if(r.source.value===d){for(let e of r.specifiers)if(e.type==="ImportSpecifier"&&s(e.imported.name,o)){let a=o[e.imported.name];t.report({node:e.imported,message:`Change import "${e.imported.name}" to "${a}".`,fix:n=>n.replaceText(e,a)})}}},CallExpression:r=>{if(r.callee.type==="Identifier"&&s(r.callee.name,o)){let e=`new ${o[r.callee.name]}`;t.report({node:r.callee,message:`Change "${r.callee.name}" to "${e}".`,fix:a=>a.replaceText(r.callee,e)})}if(r.callee.type==="Identifier"&&r.callee.name===k&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(s(e.key.name,i)){let a=i[e.key.name];t.report({node:e,message:`Change property "${e.key.name}" to "${a}".`,fix:n=>n.replaceText(e.key,a)})}s(e.key.name,v)&&t.report({node:e,message:`Remove property "${e.key.name}".`,fix:a=>t.sourceCode.getTokenAfter(e)?.value===","&&e.range?a.removeRange([e.range[0],e.range[1]+1]):a.remove(e)})}}},NewExpression:r=>{if(r.callee.type==="Identifier"&&[o.createResultHandler,o.createMiddleware].includes(r.callee.name)&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&s(e.key.name,i)){let a=i[e.key.name];t.report({node:e,message:`Change property "${e.key.name}" to "${a}".`,fix:n=>n.replaceText(e.key,a)})}}},Identifier:r=>{r.name==="MockOverrides"&&`${r.parent.type}`=="TSInterfaceDeclaration"&&t.report({node:r,message:`Remove augmentation of the "${r.name}" interface \u2014 no longer needed.`,fix:e=>e.remove(r.parent)})}})},h={v20:$},R={rules:{"ez-migration/v20":"error"},plugins:{[u]:{rules:h}}};
@@ -2,11 +2,12 @@ import { Rule } from 'eslint';
2
2
 
3
3
  /**
4
4
  * @desc ESLint flat config entry for migrating to this version (from previous), requires at least ESLint 8 or higher
5
+ * @deprecated Single-use tool that can be removed and changed regardless SemVer. Remember to delete it after use.
5
6
  * @example
6
7
  * // eslint.config.mjs:
7
8
  * import parser from "@typescript-eslint/parser";
8
9
  * import migration from "express-zod-api/migration";
9
- * export default [{ languageOptions: { parser } }, migration];
10
+ * export default [{ languageOptions: { parser }, files: ["**\/*.ts"] }, migration];
10
11
  * */
11
12
  declare const _default: {
12
13
  rules: {
@@ -2,11 +2,12 @@ import { Rule } from 'eslint';
2
2
 
3
3
  /**
4
4
  * @desc ESLint flat config entry for migrating to this version (from previous), requires at least ESLint 8 or higher
5
+ * @deprecated Single-use tool that can be removed and changed regardless SemVer. Remember to delete it after use.
5
6
  * @example
6
7
  * // eslint.config.mjs:
7
8
  * import parser from "@typescript-eslint/parser";
8
9
  * import migration from "express-zod-api/migration";
9
- * export default [{ languageOptions: { parser } }, migration];
10
+ * export default [{ languageOptions: { parser }, files: ["**\/*.ts"] }, migration];
10
11
  * */
11
12
  declare const _default: {
12
13
  rules: {
@@ -22,4 +23,3 @@ declare const _default: {
22
23
  };
23
24
 
24
25
  export { _default as default };
25
- export = _default;
@@ -1 +1 @@
1
- var p="ez-migration",l="express-zod-api",m="testEndpoint",n={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},i={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},c={fnMethod:null},o=(a,r)=>typeof a=="string"&&a in r,f={meta:{type:"problem",fixable:"code"},create:a=>({ImportDeclaration:r=>{if(r.source.value===l){for(let e of r.specifiers)if(e.type==="ImportSpecifier"&&o(e.imported.name,n)){let t=n[e.imported.name];a.report({node:e.imported,message:`Change import "${e.imported.name}" to "${t}".`,fix:s=>s.replaceText(e,t)})}}},CallExpression:r=>{if(r.callee.type==="Identifier"&&o(r.callee.name,n)){let e=`new ${n[r.callee.name]}`;a.report({node:r.callee,message:`Change "${r.callee.name}" to "${e}".`,fix:t=>t.replaceText(r.callee,e)})}if(r.callee.type==="Identifier"&&r.callee.name===m&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(o(e.key.name,i)){let t=i[e.key.name];a.report({node:e,message:`Change property "${e.key.name}" to "${t}".`,fix:s=>s.replaceText(e.key,t)})}o(e.key.name,c)&&a.report({node:e,message:`Remove property "${e.key.name}".`,fix:t=>a.sourceCode.getTokenAfter(e)?.value===","&&e.range?t.removeRange([e.range[0],e.range[1]+1]):t.remove(e)})}}},NewExpression:r=>{if(r.callee.type==="Identifier"&&[n.createResultHandler,n.createMiddleware].includes(r.callee.name)&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&o(e.key.name,i)){let t=i[e.key.name];a.report({node:e,message:`Change property "${e.key.name}" to "${t}".`,fix:s=>s.replaceText(e.key,t)})}}},Identifier:r=>{r.name==="MockOverrides"&&r.parent.type==="TSInterfaceDeclaration"&&a.report({node:r,message:`Remove augmentation of the "${r.name}" interface \u2014 no longer needed.`,fix:e=>e.remove(r.parent)})}})},g={v20:f},y={rules:{"ez-migration/v20":"error"},plugins:{[p]:{rules:g}}};export{y as default};
1
+ var p="ez-migration",l="express-zod-api",m="testEndpoint",n={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},i={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},c={fnMethod:null},s=(a,r)=>typeof a=="string"&&a in r,f={meta:{type:"problem",fixable:"code"},create:a=>({ImportDeclaration:r=>{if(r.source.value===l){for(let e of r.specifiers)if(e.type==="ImportSpecifier"&&s(e.imported.name,n)){let t=n[e.imported.name];a.report({node:e.imported,message:`Change import "${e.imported.name}" to "${t}".`,fix:o=>o.replaceText(e,t)})}}},CallExpression:r=>{if(r.callee.type==="Identifier"&&s(r.callee.name,n)){let e=`new ${n[r.callee.name]}`;a.report({node:r.callee,message:`Change "${r.callee.name}" to "${e}".`,fix:t=>t.replaceText(r.callee,e)})}if(r.callee.type==="Identifier"&&r.callee.name===m&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(s(e.key.name,i)){let t=i[e.key.name];a.report({node:e,message:`Change property "${e.key.name}" to "${t}".`,fix:o=>o.replaceText(e.key,t)})}s(e.key.name,c)&&a.report({node:e,message:`Remove property "${e.key.name}".`,fix:t=>a.sourceCode.getTokenAfter(e)?.value===","&&e.range?t.removeRange([e.range[0],e.range[1]+1]):t.remove(e)})}}},NewExpression:r=>{if(r.callee.type==="Identifier"&&[n.createResultHandler,n.createMiddleware].includes(r.callee.name)&&r.arguments.length===1&&r.arguments[0].type==="ObjectExpression"){for(let e of r.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&s(e.key.name,i)){let t=i[e.key.name];a.report({node:e,message:`Change property "${e.key.name}" to "${t}".`,fix:o=>o.replaceText(e.key,t)})}}},Identifier:r=>{r.name==="MockOverrides"&&`${r.parent.type}`=="TSInterfaceDeclaration"&&a.report({node:r,message:`Remove augmentation of the "${r.name}" interface \u2014 no longer needed.`,fix:e=>e.remove(r.parent)})}})},g={v20:f},y={rules:{"ez-migration/v20":"error"},plugins:{[p]:{rules:g}}};export{y as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "20.0.0-beta.4",
3
+ "version": "20.0.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": {
@@ -89,9 +89,9 @@
89
89
  "@types/http-errors": "^2.0.2",
90
90
  "@types/node": "*",
91
91
  "compression": "^1.7.4",
92
+ "eslint": "^8.57.0 || ^9.0.0",
92
93
  "express": "^4.19.2",
93
94
  "express-fileupload": "^1.5.0",
94
- "eslint": "^8.57.0 || ^9.0.0",
95
95
  "http-errors": "^2.0.0",
96
96
  "prettier": "^3.1.0",
97
97
  "typescript": "^5.1.3",
@@ -162,12 +162,12 @@
162
162
  "tsup": "^8.0.0",
163
163
  "tsx": "^4.6.2",
164
164
  "typescript": "^5.5.2",
165
- "typescript-eslint": "^8.0.0-alpha.33",
165
+ "typescript-eslint": "^8.0.0-alpha.34",
166
166
  "vitest": "^1.5.0",
167
167
  "zod": "^3.23.0"
168
168
  },
169
169
  "resolutions": {
170
- "**/@typescript-eslint/utils": "^8.0.0-alpha.33"
170
+ "**/@typescript-eslint/utils": "^8.0.0-alpha.34"
171
171
  },
172
172
  "keywords": [
173
173
  "nodejs",