express-zod-api 21.6.0 → 21.6.1
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 +6 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 21
|
|
4
4
|
|
|
5
|
+
### v21.6.1
|
|
6
|
+
|
|
7
|
+
- `node-mocks-http` version is `^1.16.2`;
|
|
8
|
+
- Fixed possible duplicates in the `Path` type generated by `Integration`:
|
|
9
|
+
- Duplicates used to be possible when using `DependsOnMethod` instance within specified `routing`.
|
|
10
|
+
|
|
5
11
|
### v21.6.0
|
|
6
12
|
|
|
7
13
|
- Supporting the following `z.string()` formats by the `Documentation` generator:
|
package/dist/index.cjs
CHANGED
|
@@ -15,7 +15,7 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,l)=>c[l]?c[l](p):p).join(`
|
|
18
|
-
`))};var ao=e=>{e.startupLogo!==!1&&no(process.stdout);let t=e.errorHandler||Me,r=kr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v21.6.0 (CJS)",env:process.env.NODE_ENV||"development"}),ro(r);let o=eo({logger:r,config:e}),i={getLogger:to(r),errorHandler:t},a=Qr(i),c=Yr(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},po=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=ao(e);return or({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},co=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=ao(e),c=(0,Rt.default)().disable("x-powered-by").use(a);if(e.compression){let y=await Fe("compression");c.use(y(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Rt.default.json()],raw:[e.rawParser||Rt.default.raw(),Xr],upload:e.upload?await Wr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),or({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],l=(y,b)=>()=>y.listen(b,()=>r.info("Listening",b)),u=[];if(e.http){let y=so.default.createServer(c);p.push(y),u.push(l(y,e.http.listen))}if(e.https){let y=io.default.createServer(e.https.options,c);p.push(y),u.push(l(y,e.https.listen))}return e.gracefulShutdown&&oo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:u.map(y=>y())}};var wo=require("openapi3-ts/oas31"),Et=require("ramda");var Q=require("openapi3-ts/oas31"),m=require("ramda"),T=require("zod");var Ae=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[x]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>Ae(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var mo=50,uo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Pn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},fo=/:([A-Za-z0-9_]+)/g,wn=/^\d{4}-\d{2}-\d{2}$/,En=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,In=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,zn=e=>e.match(fo)?.map(t=>t.slice(1))||[],yo=e=>e.replace(fo,t=>`{${t.slice(1)}}`),Cn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),Zn=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),Nn=({},e)=>{if(e.isResponse)throw new j("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},jn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof T.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Ln=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Hn=e=>{let[t,r]=e.filter(Q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Mn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ye(t.examples||[],r.examples||[],([n,i])=>(0,m.mergeDeepRight)(n,i))),o},Un=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Hn(o)}catch{}return{allOf:o}},Kn=(e,{next:t})=>t(e.unwrap()),Dn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return(0,Q.isSchemaObject)(r)&&(r.type=ho(r)),r},go=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},lo=e=>({type:go(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Bn=({value:e})=>({type:go(e),const:e}),qn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ye(c)?c instanceof T.z.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=At(e,r)),i.length&&(a.required=i),a},$n=()=>({type:"null"}),Gn=({},e)=>{if(e.isResponse)throw new j("Please use ez.dateOut() for output.",e);return{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:uo}}},Vn=({},e)=>{if(!e.isResponse)throw new j("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:uo}}},_n=({},e)=>{throw new j(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Jn=()=>({type:"boolean"}),Yn=()=>({type:"integer",format:"bigint"}),Qn=e=>e.every(t=>t instanceof T.z.ZodLiteral),Wn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof T.z.ZodEnum||e instanceof T.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=At(T.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof T.z.ZodLiteral)return{type:"object",properties:At(T.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof T.z.ZodUnion&&Qn(e.options)){let o=(0,m.map)(i=>`${i.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:At(T.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Xn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ts=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:u,isDate:y,isTime:b,isBase64:P,isNANOID:C,isBase64url:h,isDuration:W,_def:{checks:I}})=>{let Z=I.find(S=>S.kind==="regex"),H=I.find(S=>S.kind==="datetime"),$=I.some(S=>S.kind==="jwt"),X=I.find(S=>S.kind==="length"),z={type:"string"},ce={"date-time":l,byte:P,base64url:h,date:y,time:b,duration:W,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:C,jwt:$,ip:d,cidr:u,emoji:p};for(let S in ce)if(ce[S]){z.format=S;break}return X&&([z.minLength,z.maxLength]=[X.value,X.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),y&&(z.pattern=wn.source),b&&(z.pattern=En.source),l&&(z.pattern=In(H?.offset).source),Z&&(z.pattern=Z.regex.source),z},rs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(u=>u.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(u=>u.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,p?l.maximum=d:l.exclusiveMaximum=d,l},At=({shape:e},t)=>(0,m.map)(t,e),os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Pn?.[t]},ho=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ns=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,Q.isSchemaObject)(o)){let i=pt(e,os(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(T.z.any())}if(!t&&n.type==="preprocess"&&(0,Q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ss=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),is=(e,{next:t})=>t(e.unwrap()),as=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ps=(e,{next:t})=>t(e.unwrap().shape.raw),xo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.range)(1,e.length+1).map(t=>`example${t}`),(0,m.map)((0,m.objOf)("value"),e))):void 0,bo=(e,t,r=[])=>(0,m.pipe)(Y,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),xo)({schema:e,variant:t?"parsed":"original",validate:!0}),cs=(e,t)=>(0,m.pipe)(Y,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),xo)({schema:e,variant:"original",validate:!0}),Pe=e=>e instanceof T.z.ZodObject?e:e instanceof T.z.ZodBranded?Pe(e.unwrap()):e instanceof T.z.ZodUnion||e instanceof T.z.ZodDiscriminatedUnion?e.options.map(t=>Pe(t)).reduce((t,r)=>t.merge(r.partial()),T.z.object({})):e instanceof T.z.ZodEffects?Pe(e._def.schema):e instanceof T.z.ZodPipeline?Pe(e._def.in):Pe(e._def.left).merge(Pe(e._def.right)),So=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:d}=Pe(r),p=zn(e),l=o.includes("query"),u=o.includes("params"),y=o.includes("headers"),b=h=>u&&p.includes(h),P=h=>y&&qt(h);return Object.keys(d).map(h=>({name:h,location:b(h)?"path":P(h)?"header":l?"query":void 0})).filter(h=>h.location!==void 0).map(({name:h,location:W})=>{let I=Ae(d[h],{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),Z=i==="components"?n(d[h],I,ne(c,h)):I;return{name:h,in:W,required:!d[h].isOptional(),description:I.description||c,schema:Z,examples:cs(r,h)}})},sr={ZodString:ts,ZodNumber:rs,ZodBigInt:Yn,ZodBoolean:Jn,ZodNull:$n,ZodArray:Xn,ZodTuple:es,ZodRecord:Wn,ZodObject:qn,ZodLiteral:Bn,ZodIntersection:Un,ZodUnion:kn,ZodAny:vn,ZodDefault:Cn,ZodEnum:lo,ZodNativeEnum:lo,ZodEffects:ns,ZodOptional:Kn,ZodNullable:Fn,ZodDiscriminatedUnion:Ln,ZodBranded:is,ZodDate:_n,ZodCatch:Zn,ZodPipeline:ss,ZodLazy:as,ZodReadonly:Dn,[V]:jn,[ve]:Nn,[be]:Vn,[xe]:Gn,[se]:ps},ir=(e,{isResponse:t,prev:r})=>{if((0,Q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof T.z.ZodLazy,i=r.type!==void 0,a=t&&Ye(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=ho(r)),!n){let p=Y({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},ar=(e,t)=>{throw new j(`Zod type ${e.constructor.name} is unsupported.`,t)},nr=(e,t)=>{if((0,Q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>nr(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>nr(o,t))),r},To=e=>(0,Q.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),Oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${$t(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let u=To(Ae(r,{rules:{...p,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),y={schema:a==="components"?i(r,u,ne(l)):u,examples:bo(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[y]))}},ds=()=>({type:"http",scheme:"basic"}),ms=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({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},us=({name:e})=>({type:"apiKey",in:"header",name:e}),fs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ys=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),gs=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Ro=(e,t)=>{let r={basic:ds,bearer:ms,input:ls,header:us,cookie:fs,openid:ys,oauth2:gs};return ht(e,o=>r[o.type](o,t))},Pt=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?Pt(Yt(e)):Pt({or:[e]}),Ao=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=To(nr(Ae(r,{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:i==="components"?n(r,p,ne(d)):p,examples:bo(r,!1,c)};return{description:d,content:{[o]:l}}},Po=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}),pr=e=>e.length<=mo?e:e.slice(0,mo-1)+"\u2026";var wt=class extends wo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=(0,Et.keys)(Re);references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||ne(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new j(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;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:n,serverUrl:i,descriptions:a,brandHandling:c,hasSummaryFromDescription:d=!0,composition:p="inline"}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});Be({routing:t,onEndpoint:(u,y,b)=>{let P={path:y,method:b,endpoint:u,composition:p,brandHandling:c,makeRef:this.makeRef.bind(this)},[C,h]=["short","long"].map(u.getDescription.bind(u)),W=C?pr(C):d&&h?pr(h):void 0,I=u.getTags(),Z=r.inputSources?.[b]||Ft[b],H=this.ensureUniqOperationId(y,b,u.getOperationId(b)),$=So({...P,inputSources:Z,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:y,operationId:H})}),X={};for(let S of this.responseVariants){let de=u.getResponses(S);for(let{mimeTypes:_e,schema:Ut,statusCodes:ot}of de)for(let Je of ot)X[Je]=Oo({...P,variant:S,schema:Ut,mimeTypes:_e,statusCode:Je,hasMultipleStatusCodes:de.length>1||ot.length>1,description:a?.[`${S}Response`]?.call(null,{method:b,path:y,operationId:H,statusCode:Je})})}let z=Z.includes("body")?Ao({...P,paramNames:(0,Et.pluck)("name",$),schema:u.getSchema("input"),mimeType:R[u.getRequestType()],description:a?.requestBody?.call(null,{method:b,path:y,operationId:H})}):void 0,ce=Pt(ht(Ro(u.getSecurity(),Z),S=>{let de=this.ensureUniqSecuritySchemaName(S),_e=["oauth2","openIdConnect"].includes(S.type)?u.getScopes().slice():[];return this.addSecurityScheme(de,S),{name:de,scopes:_e}}));this.addPath(yo(y),{[b]:{operationId:H,summary:W,description:h,tags:I.length>0?I:void 0,parameters:$.length>0?$:void 0,requestBody:z,security:ce.length>0?ce:void 0,responses:X}})}}),this.rootDoc.tags=r.tags?Po(r.tags):[]}};var It=require("node-mocks-http"),hs=e=>(0,It.createRequest)({...e,headers:{"content-type":R.json,...e?.headers}}),xs=e=>(0,It.createResponse)(e),bs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Lr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Eo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=hs(e),i=xs({req:n,...t});i.req=t?.req||n,n.res=i;let a=bs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Io=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Eo(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},zo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=Eo(o),d=at(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(oe(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};var M=v(require("typescript"),1),Vo=require("zod");var A=v(require("typescript"),1);var O=v(require("typescript"),1),{factory:Co}=O.default,qe=(e,t)=>O.default.addSyntheticLeadingComment(e,O.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=O.default.createSourceFile("print.ts","",O.default.ScriptTarget.Latest,!1,O.default.ScriptKind.TS);return O.default.createPrinter(t).printNode(O.default.EmitHint.Unspecified,e,r)},Ss=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Zo=e=>Ss.test(e)?Co.createIdentifier(e):Co.createStringLiteral(e),Ts=[O.default.SyntaxKind.AnyKeyword,O.default.SyntaxKind.BigIntKeyword,O.default.SyntaxKind.BooleanKeyword,O.default.SyntaxKind.NeverKeyword,O.default.SyntaxKind.NumberKeyword,O.default.SyntaxKind.ObjectKeyword,O.default.SyntaxKind.StringKeyword,O.default.SyntaxKind.SymbolKeyword,O.default.SyntaxKind.UndefinedKeyword,O.default.SyntaxKind.UnknownKeyword,O.default.SyntaxKind.VoidKeyword],vo=e=>Ts.includes(e.kind);var s=A.default.factory,we=[s.createModifier(A.default.SyntaxKind.ExportKeyword)],Os=[s.createModifier(A.default.SyntaxKind.AsyncKeyword)],Rs=[s.createModifier(A.default.SyntaxKind.PublicKeyword)],No=[s.createModifier(A.default.SyntaxKind.ProtectedKeyword),s.createModifier(A.default.SyntaxKind.ReadonlyKeyword)],jo=s.createToken(A.default.SyntaxKind.DotDotDotToken),As=s.createTemplateHead(""),Ps=s.createTemplateMiddle(" "),rt=s.createTemplateTail(""),$e=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(A.default.SyntaxKind.StringKeyword),s.createKeywordTypeNode(A.default.SyntaxKind.AnyKeyword)]),ws=e=>s.createTemplateLiteralType(As,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?rt:Ps))),zt=ws(["M","P"]),Ct=(e,t,r)=>s.createParameterDeclaration(Array.isArray(r)?r:void 0,Array.isArray(r)?void 0:r,e,void 0,t,void 0),Ge=(e,t)=>Object.entries(e).map(([r,o])=>Ct(s.createIdentifier(r),o,t)),ko=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Lo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),Mo=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),F=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],A.default.NodeFlags.Const),dr=(e,t)=>B(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{isPublic:!0}),B=(e,t,{isPublic:r,comment:o}={})=>{let n=s.createTypeAliasDeclaration(r?we:void 0,e,void 0,t);return o?qe(n,o):n},Zt=(e,t,r,o,n)=>s.createMethodDeclaration(Rs,void 0,e,void 0,o,t,n,r),Ho=(e,t,r)=>s.createClassDeclaration(we,e,void 0,void 0,[t,...r]),vt=e=>s.createTypeOperatorNode(A.default.SyntaxKind.KeyOfKeyword,s.createTypeReferenceNode(e)),Uo=(e,t,r)=>s.createConditionalTypeNode(t,vt(e),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t),r),Nt=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(A.default.SyntaxKind.AnyKeyword):e]),Ko=(e,t)=>s.createInterfaceDeclaration(we,e,void 0,void 0,t),mr=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,s.createTypeReferenceNode(r))),Do=(e,t,r)=>s.createArrowFunction(r?Os:void 0,void 0,e.map(o=>Ct(o)),void 0,void 0,t),lr=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier(Object.name),E("keys")),void 0,[e]),E("reduce")),void 0,[s.createArrowFunction(void 0,void 0,Ge({acc:void 0,key:void 0}),void 0,void 0,t),r]),Fo=(...e)=>`"${e.join(" ")}"`,E=e=>e,Ve=(e,t,r)=>s.createConditionalExpression(e,s.createToken(A.default.SyntaxKind.QuestionToken),t,s.createToken(A.default.SyntaxKind.ColonToken),r),q=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),Bo=(e,t)=>s.createBinaryExpression(e,s.createToken(A.default.SyntaxKind.AmpersandAmpersandToken),t),qo=(e,t)=>s.createBinaryExpression(e,s.createToken(A.default.SyntaxKind.EqualsEqualsEqualsToken),t);var $o=["get","post","put","delete","patch"];var kt=require("ramda"),g=v(require("typescript"),1),jt=require("zod");var{factory:f}=g.default,Es={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Is=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),zs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&Ye(a)?a instanceof jt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,Zo(i),c&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description?qe(d,a.description):d});return f.createTypeLiteralNode(n)},Cs=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),Zs=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Go=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(vo(n)?n.kind:n,n)}return f.createUnionTypeNode(Array.from(r.values()))},vs=e=>Es?.[e.kind],Ns=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=pt(e,vs(o)),i={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},js=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ks=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Ls=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),Ms=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),Hs=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),Us=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(g.default.isTypeLiteralNode)?f.createTypeLiteralNode((0,kt.chain)((0,kt.prop)("members"),o)):f.createIntersectionTypeNode(o)},Ks=({_def:e},{next:t})=>t(e.innerType),pe=e=>()=>f.createKeywordTypeNode(e),Ds=(e,{next:t})=>t(e.unwrap()),Fs=(e,{next:t})=>t(e.unwrap()),Bs=({_def:e},{next:t})=>t(e.innerType),qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),$s=()=>f.createLiteralTypeNode(f.createNull()),Gs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Vs=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof jt.z.ZodString?r:t instanceof jt.z.ZodUnion?n:o},_s=(e,{next:t})=>t(e.unwrap().shape.raw),Js={ZodString:pe(g.default.SyntaxKind.StringKeyword),ZodNumber:pe(g.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(g.default.SyntaxKind.BooleanKeyword),ZodAny:pe(g.default.SyntaxKind.AnyKeyword),ZodUndefined:pe(g.default.SyntaxKind.UndefinedKeyword),[xe]:pe(g.default.SyntaxKind.StringKeyword),[be]:pe(g.default.SyntaxKind.StringKeyword),ZodNull:$s,ZodArray:Cs,ZodTuple:Ms,ZodRecord:Hs,ZodObject:zs,ZodLiteral:Is,ZodIntersection:Us,ZodUnion:Go,ZodDefault:Ks,ZodEnum:Zs,ZodNativeEnum:js,ZodEffects:Ns,ZodOptional:ks,ZodNullable:Ls,ZodDiscriminatedUnion:Go,ZodBranded:Ds,ZodCatch:Bs,ZodPipeline:qs,ZodLazy:Gs,ZodReadonly:Fs,[V]:Vs,[se]:_s},Lt=(e,{brandHandling:t,ctx:r})=>Ae(e,{rules:{...t,...Js},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var Mt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),args:s.createIdentifier("args"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces=[];makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,B(o,n)),this.aliases.set(t,B(o,r()))}return s.createTypeReferenceNode(o)}constructor({routing:t,brandHandling:r,variant:o="client",optionalPropStyle:n={withQuestionMark:!0,withUndefined:!0},noContent:i=Vo.z.undefined()}){let a={makeAlias:this.makeAlias.bind(this),optionalPropStyle:n},c={brandHandling:r,ctx:{...a,isResponse:!1}},d={brandHandling:r,ctx:{...a,isResponse:!0}};Be({routing:t,onEndpoint:(U,me,nt)=>{let Ie=ne.bind(null,nt,me),le=B(Ie("input"),Lt(U.getSchema("input"),c)),rn=U.getResponses("positive").map(({schema:_,mimeTypes:ue})=>ue?_:i).reduce((_,ue)=>_.or(ue)),Kt=B(Ie("positive.response"),Lt(rn,d)),on=U.getResponses("negative").map(({schema:_,mimeTypes:ue})=>ue?_:i).reduce((_,ue)=>_.or(ue)),Dt=B(Ie("negative.response"),Lt(on,d)),ur=B(Ie("response"),s.createUnionTypeNode([s.createTypeReferenceNode(Kt.name.text),s.createTypeReferenceNode(Dt.name.text)]));this.program.push(le,Kt,Dt,ur),this.paths.push(me);let nn=U.getResponses("positive").some(({mimeTypes:_})=>_?.includes(R.json));this.registry.set(Fo(nt,me),{input:le.name.text,positive:Kt.name.text,negative:Dt.name.text,response:ur.name.text,tags:U.getTags(),isJson:nn})}}),this.program.unshift(...this.aliases.values()),this.program.push(dr(this.ids.pathType,this.paths)),this.program.push(dr(this.ids.methodType,$o)),this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]},{id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]},{id:this.ids.responseInterface,kind:"response",props:[]});let l=[],u=[];for(let[U,{isJson:me,tags:nt,...Ie}]of this.registry){for(let le of this.interfaces)le.props.push(Lo(U,Ie[le.kind]));o!=="types"&&(me&&l.push(s.createPropertyAssignment(U,s.createTrue())),u.push(s.createPropertyAssignment(U,s.createArrayLiteralExpression(nt.map(le=>s.createStringLiteral(le))))))}for(let{id:U,props:me}of this.interfaces)this.program.push(Ko(U,me));if(this.program.push(B(this.ids.methodPathType,vt(this.ids.inputInterface),{isPublic:!0})),o==="types")return;let y=s.createVariableStatement(we,F(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),b=s.createVariableStatement(we,F(this.ids.endpointTagsConst,s.createObjectLiteralExpression(u))),P=B(this.ids.implementationType,s.createFunctionTypeNode(void 0,Ge({[this.ids.methodParameter.text]:s.createTypeReferenceNode(this.ids.methodType),[this.ids.pathParameter.text]:s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:$e}),Nt("any")),{isPublic:!0}),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,rt)]),h=lr(this.ids.paramsArgument,q(this.ids.accumulator,E("replace"),[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),W=lr(this.ids.paramsArgument,q(s.createIdentifier(Object.name),E("assign"),[this.ids.accumulator,Bo(s.createPrefixUnaryExpression(M.default.SyntaxKind.ExclamationToken,q(this.ids.pathParameter,E("includes"),[C])),s.createObjectLiteralExpression([s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))],!1))]),s.createObjectLiteralExpression()),I=qe(Zt(this.ids.provideMethod,Ge({[this.ids.methodParameter.text]:s.createTypeReferenceNode("M"),[this.ids.pathParameter.text]:s.createTypeReferenceNode("P"),[this.ids.paramsArgument.text]:s.createConditionalTypeNode(zt,vt(this.ids.inputInterface),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),zt),$e)}),void 0,mr({M:this.ids.methodType,P:this.ids.pathType}),Nt(Uo(this.ids.responseInterface,zt,s.createKeywordTypeNode(M.default.SyntaxKind.UnknownKeyword)))),"@deprecated use the overload with 2 arguments instead"),Z=Zt(this.ids.provideMethod,Ge({[this.ids.requestParameter.text]:s.createTypeReferenceNode("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),s.createTypeReferenceNode("K"))}),void 0,mr({K:this.ids.methodPathType}),Nt(s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.responseInterface),s.createTypeReferenceNode("K")))),H=Zt(this.ids.provideMethod,Ge({[this.ids.args.text]:s.createUnionTypeNode([s.createTupleTypeNode([s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),$e]),s.createTupleTypeNode([s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),$e])])},jo),s.createBlock([s.createVariableStatement(void 0,F(Mo(this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument),s.createAsExpression(s.createParenthesizedExpression(Ve(qo(s.createPropertyAccessExpression(this.ids.args,E("length")),s.createNumericLiteral(2)),s.createArrayLiteralExpression([s.createSpreadElement(q(s.createElementAccessExpression(this.ids.args,0),E("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)])),s.createElementAccessExpression(this.ids.args,1)]),this.ids.args)),s.createTupleTypeNode([s.createTypeReferenceNode(this.ids.methodType),s.createTypeReferenceNode(this.ids.pathType),$e])))),s.createReturnStatement(q(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,h,W]))])),$=Ho(this.ids.clientClass,ko([Ct(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),No)]),[I,Z,H]),X=B(this.ids.providerType,s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.clientClass),s.createLiteralTypeNode(s.createStringLiteral(this.ids.provideMethod.text))),{isPublic:!0,comment:"@deprecated will be removed in v22"});this.program.push(y,b,P,$,X);let z=s.createPropertyAssignment(this.ids.methodParameter,q(this.ids.methodParameter,E("toUpperCase"))),ce=s.createPropertyAssignment(this.ids.headersProperty,Ve(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(R.json))]),this.ids.undefinedValue)),S=s.createPropertyAssignment(this.ids.bodyProperty,Ve(this.ids.hasBodyConst,q(s.createIdentifier("JSON"),E("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),de=s.createVariableStatement(void 0,F(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,rt)]),s.createObjectLiteralExpression([z,ce,S])])))),_e=s.createVariableStatement(void 0,F(this.ids.hasBodyConst,s.createLogicalNot(q(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),E("includes"),[this.ids.methodParameter])))),Ut=s.createVariableStatement(void 0,F(this.ids.searchParamsConst,Ve(this.ids.hasBodyConst,s.createStringLiteral(""),s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier(URLSearchParams.name),void 0,[this.ids.paramsArgument]),rt)])))),ot=s.createVariableStatement(void 0,F(this.ids.contentTypeConst,q([this.ids.responseConst,this.ids.headersProperty],E("get"),[s.createStringLiteral("content-type")]))),Je=s.createIfStatement(s.createPrefixUnaryExpression(M.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement(void 0),void 0),Qo=s.createVariableStatement(void 0,F(this.ids.isJsonConst,s.createCallChain(s.createPropertyAccessChain(this.ids.contentTypeConst,void 0,E("startsWith")),void 0,void 0,[s.createStringLiteral(R.json)]))),Wo=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,Ve(this.ids.isJsonConst,s.createStringLiteral(E("json")),s.createStringLiteral(E("text")))),void 0,[])),Xo=s.createVariableStatement(we,F(this.ids.exampleImplementationConst,Do([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([_e,Ut,de,ot,Je,Qo,Wo]),!0),s.createTypeReferenceNode(this.ids.implementationType))),en=s.createExpressionStatement(q(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),tn=s.createVariableStatement(void 0,F(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(Xo,tn,en)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:cr(r,t)).join(`
|
|
18
|
+
`))};var ao=e=>{e.startupLogo!==!1&&no(process.stdout);let t=e.errorHandler||Me,r=kr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v21.6.1 (CJS)",env:process.env.NODE_ENV||"development"}),ro(r);let o=eo({logger:r,config:e}),i={getLogger:to(r),errorHandler:t},a=Qr(i),c=Yr(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},po=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=ao(e);return or({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},co=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=ao(e),c=(0,Rt.default)().disable("x-powered-by").use(a);if(e.compression){let y=await Fe("compression");c.use(y(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Rt.default.json()],raw:[e.rawParser||Rt.default.raw(),Xr],upload:e.upload?await Wr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),or({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],l=(y,b)=>()=>y.listen(b,()=>r.info("Listening",b)),u=[];if(e.http){let y=so.default.createServer(c);p.push(y),u.push(l(y,e.http.listen))}if(e.https){let y=io.default.createServer(e.https.options,c);p.push(y),u.push(l(y,e.https.listen))}return e.gracefulShutdown&&oo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:u.map(y=>y())}};var wo=require("openapi3-ts/oas31"),Et=require("ramda");var Q=require("openapi3-ts/oas31"),m=require("ramda"),T=require("zod");var Ae=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[x]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>Ae(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var mo=50,uo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Pn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},fo=/:([A-Za-z0-9_]+)/g,wn=/^\d{4}-\d{2}-\d{2}$/,En=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,In=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,zn=e=>e.match(fo)?.map(t=>t.slice(1))||[],yo=e=>e.replace(fo,t=>`{${t.slice(1)}}`),Cn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),Zn=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),Nn=({},e)=>{if(e.isResponse)throw new j("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},jn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof T.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Ln=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Hn=e=>{let[t,r]=e.filter(Q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Mn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ye(t.examples||[],r.examples||[],([n,i])=>(0,m.mergeDeepRight)(n,i))),o},Un=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Hn(o)}catch{}return{allOf:o}},Kn=(e,{next:t})=>t(e.unwrap()),Dn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return(0,Q.isSchemaObject)(r)&&(r.type=ho(r)),r},go=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},lo=e=>({type:go(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Bn=({value:e})=>({type:go(e),const:e}),qn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ye(c)?c instanceof T.z.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=At(e,r)),i.length&&(a.required=i),a},$n=()=>({type:"null"}),Gn=({},e)=>{if(e.isResponse)throw new j("Please use ez.dateOut() for output.",e);return{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:uo}}},Vn=({},e)=>{if(!e.isResponse)throw new j("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:uo}}},_n=({},e)=>{throw new j(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Jn=()=>({type:"boolean"}),Yn=()=>({type:"integer",format:"bigint"}),Qn=e=>e.every(t=>t instanceof T.z.ZodLiteral),Wn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof T.z.ZodEnum||e instanceof T.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=At(T.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof T.z.ZodLiteral)return{type:"object",properties:At(T.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof T.z.ZodUnion&&Qn(e.options)){let o=(0,m.map)(i=>`${i.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:At(T.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Xn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ts=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:u,isDate:y,isTime:b,isBase64:P,isNANOID:C,isBase64url:h,isDuration:W,_def:{checks:I}})=>{let Z=I.find(S=>S.kind==="regex"),H=I.find(S=>S.kind==="datetime"),$=I.some(S=>S.kind==="jwt"),X=I.find(S=>S.kind==="length"),z={type:"string"},ce={"date-time":l,byte:P,base64url:h,date:y,time:b,duration:W,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:C,jwt:$,ip:d,cidr:u,emoji:p};for(let S in ce)if(ce[S]){z.format=S;break}return X&&([z.minLength,z.maxLength]=[X.value,X.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),y&&(z.pattern=wn.source),b&&(z.pattern=En.source),l&&(z.pattern=In(H?.offset).source),Z&&(z.pattern=Z.regex.source),z},rs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(u=>u.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(u=>u.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,p?l.maximum=d:l.exclusiveMaximum=d,l},At=({shape:e},t)=>(0,m.map)(t,e),os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Pn?.[t]},ho=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ns=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,Q.isSchemaObject)(o)){let i=pt(e,os(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(T.z.any())}if(!t&&n.type==="preprocess"&&(0,Q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ss=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),is=(e,{next:t})=>t(e.unwrap()),as=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ps=(e,{next:t})=>t(e.unwrap().shape.raw),xo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.range)(1,e.length+1).map(t=>`example${t}`),(0,m.map)((0,m.objOf)("value"),e))):void 0,bo=(e,t,r=[])=>(0,m.pipe)(Y,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),xo)({schema:e,variant:t?"parsed":"original",validate:!0}),cs=(e,t)=>(0,m.pipe)(Y,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),xo)({schema:e,variant:"original",validate:!0}),Pe=e=>e instanceof T.z.ZodObject?e:e instanceof T.z.ZodBranded?Pe(e.unwrap()):e instanceof T.z.ZodUnion||e instanceof T.z.ZodDiscriminatedUnion?e.options.map(t=>Pe(t)).reduce((t,r)=>t.merge(r.partial()),T.z.object({})):e instanceof T.z.ZodEffects?Pe(e._def.schema):e instanceof T.z.ZodPipeline?Pe(e._def.in):Pe(e._def.left).merge(Pe(e._def.right)),So=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:d}=Pe(r),p=zn(e),l=o.includes("query"),u=o.includes("params"),y=o.includes("headers"),b=h=>u&&p.includes(h),P=h=>y&&qt(h);return Object.keys(d).map(h=>({name:h,location:b(h)?"path":P(h)?"header":l?"query":void 0})).filter(h=>h.location!==void 0).map(({name:h,location:W})=>{let I=Ae(d[h],{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),Z=i==="components"?n(d[h],I,ne(c,h)):I;return{name:h,in:W,required:!d[h].isOptional(),description:I.description||c,schema:Z,examples:cs(r,h)}})},sr={ZodString:ts,ZodNumber:rs,ZodBigInt:Yn,ZodBoolean:Jn,ZodNull:$n,ZodArray:Xn,ZodTuple:es,ZodRecord:Wn,ZodObject:qn,ZodLiteral:Bn,ZodIntersection:Un,ZodUnion:kn,ZodAny:vn,ZodDefault:Cn,ZodEnum:lo,ZodNativeEnum:lo,ZodEffects:ns,ZodOptional:Kn,ZodNullable:Fn,ZodDiscriminatedUnion:Ln,ZodBranded:is,ZodDate:_n,ZodCatch:Zn,ZodPipeline:ss,ZodLazy:as,ZodReadonly:Dn,[V]:jn,[ve]:Nn,[be]:Vn,[xe]:Gn,[se]:ps},ir=(e,{isResponse:t,prev:r})=>{if((0,Q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof T.z.ZodLazy,i=r.type!==void 0,a=t&&Ye(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=ho(r)),!n){let p=Y({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},ar=(e,t)=>{throw new j(`Zod type ${e.constructor.name} is unsupported.`,t)},nr=(e,t)=>{if((0,Q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>nr(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>nr(o,t))),r},To=e=>(0,Q.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),Oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${$t(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let u=To(Ae(r,{rules:{...p,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),y={schema:a==="components"?i(r,u,ne(l)):u,examples:bo(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[y]))}},ds=()=>({type:"http",scheme:"basic"}),ms=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({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},us=({name:e})=>({type:"apiKey",in:"header",name:e}),fs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ys=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),gs=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Ro=(e,t)=>{let r={basic:ds,bearer:ms,input:ls,header:us,cookie:fs,openid:ys,oauth2:gs};return ht(e,o=>r[o.type](o,t))},Pt=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?Pt(Yt(e)):Pt({or:[e]}),Ao=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=To(nr(Ae(r,{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:i==="components"?n(r,p,ne(d)):p,examples:bo(r,!1,c)};return{description:d,content:{[o]:l}}},Po=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}),pr=e=>e.length<=mo?e:e.slice(0,mo-1)+"\u2026";var wt=class extends wo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=(0,Et.keys)(Re);references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||ne(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new j(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;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:n,serverUrl:i,descriptions:a,brandHandling:c,hasSummaryFromDescription:d=!0,composition:p="inline"}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});Be({routing:t,onEndpoint:(u,y,b)=>{let P={path:y,method:b,endpoint:u,composition:p,brandHandling:c,makeRef:this.makeRef.bind(this)},[C,h]=["short","long"].map(u.getDescription.bind(u)),W=C?pr(C):d&&h?pr(h):void 0,I=u.getTags(),Z=r.inputSources?.[b]||Ft[b],H=this.ensureUniqOperationId(y,b,u.getOperationId(b)),$=So({...P,inputSources:Z,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:y,operationId:H})}),X={};for(let S of this.responseVariants){let de=u.getResponses(S);for(let{mimeTypes:_e,schema:Ut,statusCodes:ot}of de)for(let Je of ot)X[Je]=Oo({...P,variant:S,schema:Ut,mimeTypes:_e,statusCode:Je,hasMultipleStatusCodes:de.length>1||ot.length>1,description:a?.[`${S}Response`]?.call(null,{method:b,path:y,operationId:H,statusCode:Je})})}let z=Z.includes("body")?Ao({...P,paramNames:(0,Et.pluck)("name",$),schema:u.getSchema("input"),mimeType:R[u.getRequestType()],description:a?.requestBody?.call(null,{method:b,path:y,operationId:H})}):void 0,ce=Pt(ht(Ro(u.getSecurity(),Z),S=>{let de=this.ensureUniqSecuritySchemaName(S),_e=["oauth2","openIdConnect"].includes(S.type)?u.getScopes().slice():[];return this.addSecurityScheme(de,S),{name:de,scopes:_e}}));this.addPath(yo(y),{[b]:{operationId:H,summary:W,description:h,tags:I.length>0?I:void 0,parameters:$.length>0?$:void 0,requestBody:z,security:ce.length>0?ce:void 0,responses:X}})}}),this.rootDoc.tags=r.tags?Po(r.tags):[]}};var It=require("node-mocks-http"),hs=e=>(0,It.createRequest)({...e,headers:{"content-type":R.json,...e?.headers}}),xs=e=>(0,It.createResponse)(e),bs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Lr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Eo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=hs(e),i=xs({req:n,...t});i.req=t?.req||n,n.res=i;let a=bs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Io=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Eo(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},zo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=Eo(o),d=at(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(oe(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};var M=v(require("typescript"),1),Vo=require("zod");var A=v(require("typescript"),1);var O=v(require("typescript"),1),{factory:Co}=O.default,qe=(e,t)=>O.default.addSyntheticLeadingComment(e,O.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=O.default.createSourceFile("print.ts","",O.default.ScriptTarget.Latest,!1,O.default.ScriptKind.TS);return O.default.createPrinter(t).printNode(O.default.EmitHint.Unspecified,e,r)},Ss=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Zo=e=>Ss.test(e)?Co.createIdentifier(e):Co.createStringLiteral(e),Ts=[O.default.SyntaxKind.AnyKeyword,O.default.SyntaxKind.BigIntKeyword,O.default.SyntaxKind.BooleanKeyword,O.default.SyntaxKind.NeverKeyword,O.default.SyntaxKind.NumberKeyword,O.default.SyntaxKind.ObjectKeyword,O.default.SyntaxKind.StringKeyword,O.default.SyntaxKind.SymbolKeyword,O.default.SyntaxKind.UndefinedKeyword,O.default.SyntaxKind.UnknownKeyword,O.default.SyntaxKind.VoidKeyword],vo=e=>Ts.includes(e.kind);var s=A.default.factory,we=[s.createModifier(A.default.SyntaxKind.ExportKeyword)],Os=[s.createModifier(A.default.SyntaxKind.AsyncKeyword)],Rs=[s.createModifier(A.default.SyntaxKind.PublicKeyword)],No=[s.createModifier(A.default.SyntaxKind.ProtectedKeyword),s.createModifier(A.default.SyntaxKind.ReadonlyKeyword)],jo=s.createToken(A.default.SyntaxKind.DotDotDotToken),As=s.createTemplateHead(""),Ps=s.createTemplateMiddle(" "),rt=s.createTemplateTail(""),$e=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(A.default.SyntaxKind.StringKeyword),s.createKeywordTypeNode(A.default.SyntaxKind.AnyKeyword)]),ws=e=>s.createTemplateLiteralType(As,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?rt:Ps))),zt=ws(["M","P"]),Ct=(e,t,r)=>s.createParameterDeclaration(Array.isArray(r)?r:void 0,Array.isArray(r)?void 0:r,e,void 0,t,void 0),Ge=(e,t)=>Object.entries(e).map(([r,o])=>Ct(s.createIdentifier(r),o,t)),ko=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Lo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),Mo=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),F=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],A.default.NodeFlags.Const),dr=(e,t)=>B(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{isPublic:!0}),B=(e,t,{isPublic:r,comment:o}={})=>{let n=s.createTypeAliasDeclaration(r?we:void 0,e,void 0,t);return o?qe(n,o):n},Zt=(e,t,r,o,n)=>s.createMethodDeclaration(Rs,void 0,e,void 0,o,t,n,r),Ho=(e,t,r)=>s.createClassDeclaration(we,e,void 0,void 0,[t,...r]),vt=e=>s.createTypeOperatorNode(A.default.SyntaxKind.KeyOfKeyword,s.createTypeReferenceNode(e)),Uo=(e,t,r)=>s.createConditionalTypeNode(t,vt(e),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t),r),Nt=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(A.default.SyntaxKind.AnyKeyword):e]),Ko=(e,t)=>s.createInterfaceDeclaration(we,e,void 0,void 0,t),mr=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,s.createTypeReferenceNode(r))),Do=(e,t,r)=>s.createArrowFunction(r?Os:void 0,void 0,e.map(o=>Ct(o)),void 0,void 0,t),lr=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier(Object.name),E("keys")),void 0,[e]),E("reduce")),void 0,[s.createArrowFunction(void 0,void 0,Ge({acc:void 0,key:void 0}),void 0,void 0,t),r]),Fo=(...e)=>`"${e.join(" ")}"`,E=e=>e,Ve=(e,t,r)=>s.createConditionalExpression(e,s.createToken(A.default.SyntaxKind.QuestionToken),t,s.createToken(A.default.SyntaxKind.ColonToken),r),q=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),Bo=(e,t)=>s.createBinaryExpression(e,s.createToken(A.default.SyntaxKind.AmpersandAmpersandToken),t),qo=(e,t)=>s.createBinaryExpression(e,s.createToken(A.default.SyntaxKind.EqualsEqualsEqualsToken),t);var $o=["get","post","put","delete","patch"];var kt=require("ramda"),g=v(require("typescript"),1),jt=require("zod");var{factory:f}=g.default,Es={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Is=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),zs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&Ye(a)?a instanceof jt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,Zo(i),c&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description?qe(d,a.description):d});return f.createTypeLiteralNode(n)},Cs=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),Zs=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Go=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(vo(n)?n.kind:n,n)}return f.createUnionTypeNode(Array.from(r.values()))},vs=e=>Es?.[e.kind],Ns=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=pt(e,vs(o)),i={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},js=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ks=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Ls=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),Ms=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),Hs=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),Us=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(g.default.isTypeLiteralNode)?f.createTypeLiteralNode((0,kt.chain)((0,kt.prop)("members"),o)):f.createIntersectionTypeNode(o)},Ks=({_def:e},{next:t})=>t(e.innerType),pe=e=>()=>f.createKeywordTypeNode(e),Ds=(e,{next:t})=>t(e.unwrap()),Fs=(e,{next:t})=>t(e.unwrap()),Bs=({_def:e},{next:t})=>t(e.innerType),qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),$s=()=>f.createLiteralTypeNode(f.createNull()),Gs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Vs=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof jt.z.ZodString?r:t instanceof jt.z.ZodUnion?n:o},_s=(e,{next:t})=>t(e.unwrap().shape.raw),Js={ZodString:pe(g.default.SyntaxKind.StringKeyword),ZodNumber:pe(g.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(g.default.SyntaxKind.BooleanKeyword),ZodAny:pe(g.default.SyntaxKind.AnyKeyword),ZodUndefined:pe(g.default.SyntaxKind.UndefinedKeyword),[xe]:pe(g.default.SyntaxKind.StringKeyword),[be]:pe(g.default.SyntaxKind.StringKeyword),ZodNull:$s,ZodArray:Cs,ZodTuple:Ms,ZodRecord:Hs,ZodObject:zs,ZodLiteral:Is,ZodIntersection:Us,ZodUnion:Go,ZodDefault:Ks,ZodEnum:Zs,ZodNativeEnum:js,ZodEffects:Ns,ZodOptional:ks,ZodNullable:Ls,ZodDiscriminatedUnion:Go,ZodBranded:Ds,ZodCatch:Bs,ZodPipeline:qs,ZodLazy:Gs,ZodReadonly:Fs,[V]:Vs,[se]:_s},Lt=(e,{brandHandling:t,ctx:r})=>Ae(e,{rules:{...t,...Js},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var Mt=class{program=[];usage=[];registry=new Map;paths=new Set;aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),args:s.createIdentifier("args"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces=[];makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,B(o,n)),this.aliases.set(t,B(o,r()))}return s.createTypeReferenceNode(o)}constructor({routing:t,brandHandling:r,variant:o="client",optionalPropStyle:n={withQuestionMark:!0,withUndefined:!0},noContent:i=Vo.z.undefined()}){let a={makeAlias:this.makeAlias.bind(this),optionalPropStyle:n},c={brandHandling:r,ctx:{...a,isResponse:!1}},d={brandHandling:r,ctx:{...a,isResponse:!0}};Be({routing:t,onEndpoint:(U,me,nt)=>{let Ie=ne.bind(null,nt,me),le=B(Ie("input"),Lt(U.getSchema("input"),c)),rn=U.getResponses("positive").map(({schema:_,mimeTypes:ue})=>ue?_:i).reduce((_,ue)=>_.or(ue)),Kt=B(Ie("positive.response"),Lt(rn,d)),on=U.getResponses("negative").map(({schema:_,mimeTypes:ue})=>ue?_:i).reduce((_,ue)=>_.or(ue)),Dt=B(Ie("negative.response"),Lt(on,d)),ur=B(Ie("response"),s.createUnionTypeNode([s.createTypeReferenceNode(Kt.name.text),s.createTypeReferenceNode(Dt.name.text)]));this.program.push(le,Kt,Dt,ur),this.paths.add(me);let nn=U.getResponses("positive").some(({mimeTypes:_})=>_?.includes(R.json));this.registry.set(Fo(nt,me),{input:le.name.text,positive:Kt.name.text,negative:Dt.name.text,response:ur.name.text,tags:U.getTags(),isJson:nn})}}),this.program.unshift(...this.aliases.values()),this.program.push(dr(this.ids.pathType,Array.from(this.paths))),this.program.push(dr(this.ids.methodType,$o)),this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]},{id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]},{id:this.ids.responseInterface,kind:"response",props:[]});let l=[],u=[];for(let[U,{isJson:me,tags:nt,...Ie}]of this.registry){for(let le of this.interfaces)le.props.push(Lo(U,Ie[le.kind]));o!=="types"&&(me&&l.push(s.createPropertyAssignment(U,s.createTrue())),u.push(s.createPropertyAssignment(U,s.createArrayLiteralExpression(nt.map(le=>s.createStringLiteral(le))))))}for(let{id:U,props:me}of this.interfaces)this.program.push(Ko(U,me));if(this.program.push(B(this.ids.methodPathType,vt(this.ids.inputInterface),{isPublic:!0})),o==="types")return;let y=s.createVariableStatement(we,F(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),b=s.createVariableStatement(we,F(this.ids.endpointTagsConst,s.createObjectLiteralExpression(u))),P=B(this.ids.implementationType,s.createFunctionTypeNode(void 0,Ge({[this.ids.methodParameter.text]:s.createTypeReferenceNode(this.ids.methodType),[this.ids.pathParameter.text]:s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:$e}),Nt("any")),{isPublic:!0}),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,rt)]),h=lr(this.ids.paramsArgument,q(this.ids.accumulator,E("replace"),[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),W=lr(this.ids.paramsArgument,q(s.createIdentifier(Object.name),E("assign"),[this.ids.accumulator,Bo(s.createPrefixUnaryExpression(M.default.SyntaxKind.ExclamationToken,q(this.ids.pathParameter,E("includes"),[C])),s.createObjectLiteralExpression([s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))],!1))]),s.createObjectLiteralExpression()),I=qe(Zt(this.ids.provideMethod,Ge({[this.ids.methodParameter.text]:s.createTypeReferenceNode("M"),[this.ids.pathParameter.text]:s.createTypeReferenceNode("P"),[this.ids.paramsArgument.text]:s.createConditionalTypeNode(zt,vt(this.ids.inputInterface),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),zt),$e)}),void 0,mr({M:this.ids.methodType,P:this.ids.pathType}),Nt(Uo(this.ids.responseInterface,zt,s.createKeywordTypeNode(M.default.SyntaxKind.UnknownKeyword)))),"@deprecated use the overload with 2 arguments instead"),Z=Zt(this.ids.provideMethod,Ge({[this.ids.requestParameter.text]:s.createTypeReferenceNode("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),s.createTypeReferenceNode("K"))}),void 0,mr({K:this.ids.methodPathType}),Nt(s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.responseInterface),s.createTypeReferenceNode("K")))),H=Zt(this.ids.provideMethod,Ge({[this.ids.args.text]:s.createUnionTypeNode([s.createTupleTypeNode([s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),$e]),s.createTupleTypeNode([s.createKeywordTypeNode(M.default.SyntaxKind.StringKeyword),$e])])},jo),s.createBlock([s.createVariableStatement(void 0,F(Mo(this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument),s.createAsExpression(s.createParenthesizedExpression(Ve(qo(s.createPropertyAccessExpression(this.ids.args,E("length")),s.createNumericLiteral(2)),s.createArrayLiteralExpression([s.createSpreadElement(q(s.createElementAccessExpression(this.ids.args,0),E("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)])),s.createElementAccessExpression(this.ids.args,1)]),this.ids.args)),s.createTupleTypeNode([s.createTypeReferenceNode(this.ids.methodType),s.createTypeReferenceNode(this.ids.pathType),$e])))),s.createReturnStatement(q(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,h,W]))])),$=Ho(this.ids.clientClass,ko([Ct(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),No)]),[I,Z,H]),X=B(this.ids.providerType,s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.clientClass),s.createLiteralTypeNode(s.createStringLiteral(this.ids.provideMethod.text))),{isPublic:!0,comment:"@deprecated will be removed in v22"});this.program.push(y,b,P,$,X);let z=s.createPropertyAssignment(this.ids.methodParameter,q(this.ids.methodParameter,E("toUpperCase"))),ce=s.createPropertyAssignment(this.ids.headersProperty,Ve(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(R.json))]),this.ids.undefinedValue)),S=s.createPropertyAssignment(this.ids.bodyProperty,Ve(this.ids.hasBodyConst,q(s.createIdentifier("JSON"),E("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),de=s.createVariableStatement(void 0,F(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,rt)]),s.createObjectLiteralExpression([z,ce,S])])))),_e=s.createVariableStatement(void 0,F(this.ids.hasBodyConst,s.createLogicalNot(q(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),E("includes"),[this.ids.methodParameter])))),Ut=s.createVariableStatement(void 0,F(this.ids.searchParamsConst,Ve(this.ids.hasBodyConst,s.createStringLiteral(""),s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier(URLSearchParams.name),void 0,[this.ids.paramsArgument]),rt)])))),ot=s.createVariableStatement(void 0,F(this.ids.contentTypeConst,q([this.ids.responseConst,this.ids.headersProperty],E("get"),[s.createStringLiteral("content-type")]))),Je=s.createIfStatement(s.createPrefixUnaryExpression(M.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement(void 0),void 0),Qo=s.createVariableStatement(void 0,F(this.ids.isJsonConst,s.createCallChain(s.createPropertyAccessChain(this.ids.contentTypeConst,void 0,E("startsWith")),void 0,void 0,[s.createStringLiteral(R.json)]))),Wo=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,Ve(this.ids.isJsonConst,s.createStringLiteral(E("json")),s.createStringLiteral(E("text")))),void 0,[])),Xo=s.createVariableStatement(we,F(this.ids.exampleImplementationConst,Do([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([_e,Ut,de,ot,Je,Qo,Wo]),!0),s.createTypeReferenceNode(this.ids.implementationType))),en=s.createExpressionStatement(q(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),tn=s.createVariableStatement(void 0,F(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(Xo,tn,en)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:cr(r,t)).join(`
|
|
19
19
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&M.default.addSyntheticLeadingComment(M.default.addSyntheticLeadingComment(s.createEmptyStatement(),M.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),M.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
20
|
${r}`);return this.program.concat(o||[]).map((n,i)=>cr(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
package/dist/index.d.cts
CHANGED
|
@@ -970,7 +970,7 @@ declare class Integration {
|
|
|
970
970
|
isJson: boolean;
|
|
971
971
|
tags: ReadonlyArray<string>;
|
|
972
972
|
}>;
|
|
973
|
-
protected paths: string
|
|
973
|
+
protected paths: Set<string>;
|
|
974
974
|
protected aliases: Map<z.ZodTypeAny, ts.TypeAliasDeclaration>;
|
|
975
975
|
protected ids: {
|
|
976
976
|
pathType: ts.Identifier;
|
package/dist/index.d.ts
CHANGED
|
@@ -970,7 +970,7 @@ declare class Integration {
|
|
|
970
970
|
isJson: boolean;
|
|
971
971
|
tags: ReadonlyArray<string>;
|
|
972
972
|
}>;
|
|
973
|
-
protected paths: string
|
|
973
|
+
protected paths: Set<string>;
|
|
974
974
|
protected aliases: Map<z.ZodTypeAny, ts.TypeAliasDeclaration>;
|
|
975
975
|
protected ids: {
|
|
976
976
|
pathType: ts.Identifier;
|
package/dist/index.js
CHANGED
|
@@ -15,7 +15,7 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,m)=>c[m]?c[m](p):p).join(`
|
|
18
|
-
`))};var Fr=e=>{e.startupLogo!==!1&&Dr(process.stdout);let t=e.errorHandler||Fe,r=xr(e.logger)?e.logger:new Be(e.logger);r.debug("Running",{build:"v21.6.0 (ESM)",env:process.env.NODE_ENV||"development"}),Hr(r);let o=Lr({logger:r,config:e}),i={getLogger:Mr(r),errorHandler:t},a=Nr(i),c=vr(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},jn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=Fr(e);return Mt({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},kn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Fr(e),c=Ht().disable("x-powered-by").use(a);if(e.compression){let f=await Ee("compression");c.use(f(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Ht.json()],raw:[e.rawParser||Ht.raw(),kr],upload:e.upload?await jr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Mt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],m=(f,x)=>()=>f.listen(x,()=>r.info("Listening",x)),l=[];if(e.http){let f=vn.createServer(c);p.push(f),l.push(m(f,e.http.listen))}if(e.https){let f=Nn.createServer(e.https.options,c);p.push(f),l.push(m(f,e.https.listen))}return e.gracefulShutdown&&Ur({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:l.map(f=>f())}};import{OpenApiBuilder as Fs}from"openapi3-ts/oas31";import{keys as Bs,pluck as qs}from"ramda";import{isReferenceObject as Dt,isSchemaObject as lt}from"openapi3-ts/oas31";import{concat as Ln,type as $r,filter as Mn,fromPairs as ut,has as Hn,isNil as Un,map as ze,mergeAll as Kn,mergeDeepRight as Dn,mergeDeepWith as Fn,objOf as Gr,omit as ft,pipe as Vr,pluck as Bn,range as qn,reject as $n,toLower as Gn,union as Vn,when as _n,xprod as Ut,zip as Jn}from"ramda";import{z as S}from"zod";var fe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>fe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var Br=50,_r="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Yn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Jr=/:([A-Za-z0-9_]+)/g,Qn=/^\d{4}-\d{2}-\d{2}$/,Wn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Xn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,es=e=>e.match(Jr)?.map(t=>t.slice(1))||[],Yr=e=>e.replace(Jr,t=>`{${t.slice(1)}}`),ts=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),rs=({_def:{innerType:e}},{next:t})=>t(e),os=()=>({format:"any"}),ns=({},e)=>{if(e.isResponse)throw new N("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},ss=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},is=({options:e},{next:t})=>({oneOf:e.map(t)}),as=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ps=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Ln(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},cs=e=>{let[t,r]=e.filter(lt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Fn(ps,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Vn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,i])=>Dn(n,i))),o},ds=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return cs(o)}catch{}return{allOf:o}},ms=(e,{next:t})=>t(e.unwrap()),ls=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t})=>{let r=t(e.unwrap());return lt(r)&&(r.type=Wr(r)),r},Qr=e=>{let t=Gn($r(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},qr=e=>({type:Qr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),fs=({value:e})=>({type:Qr(e),const:e}),ys=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&He(c)?c instanceof S.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=mt(e,r)),i.length&&(a.required=i),a},gs=()=>({type:"null"}),hs=({},e)=>{if(e.isResponse)throw new N("Please use ez.dateOut() for output.",e);return{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}}},xs=({},e)=>{if(!e.isResponse)throw new N("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:_r}}},bs=({},e)=>{throw new N(`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)},Ss=()=>({type:"boolean"}),Ts=()=>({type:"integer",format:"bigint"}),Os=e=>e.every(t=>t instanceof S.ZodLiteral),Rs=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=mt(S.object(ut(Ut(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:mt(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Os(e.options)){let o=ze(i=>`${i.value}`,e.options),n=ut(Ut(o,[t]));return{type:"object",properties:mt(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},As=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Ps=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ws=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:l,isDate:f,isTime:x,isBase64:A,isNANOID:z,isBase64url:g,isDuration:q,_def:{checks:w}})=>{let C=w.find(b=>b.kind==="regex"),Z=w.find(b=>b.kind==="datetime"),H=w.some(b=>b.kind==="jwt"),$=w.find(b=>b.kind==="length"),E={type:"string"},W={"date-time":m,byte:A,base64url:g,date:f,time:x,duration:q,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:z,jwt:H,ip:d,cidr:l,emoji:p};for(let b in W)if(W[b]){E.format=b;break}return $&&([E.minLength,E.maxLength]=[$.value,$.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),f&&(E.pattern=Qn.source),x&&(E.pattern=Wn.source),m&&(E.pattern=Xn(Z?.offset).source),C&&(E.pattern=C.regex.source),E},Es=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(l=>l.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(l=>l.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,p?m.maximum=d:m.exclusiveMaximum=d,m},mt=({shape:e},t)=>ze(t,e),Is=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Yn?.[t]},Wr=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",zs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&<(o)){let i=Qe(e,Is(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&<(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Cs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Zs=(e,{next:t})=>t(e.unwrap()),vs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ns=(e,{next:t})=>t(e.unwrap().shape.raw),Xr=e=>e.length?ut(Jn(qn(1,e.length+1).map(t=>`example${t}`),ze(Gr("value"),e))):void 0,eo=(e,t,r=[])=>Vr(_,ze(_n(o=>$r(o)==="Object",ft(r))),Xr)({schema:e,variant:t?"parsed":"original",validate:!0}),js=(e,t)=>Vr(_,Mn(Hn(t)),Bn(t),Xr)({schema:e,variant:"original",validate:!0}),ye=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?ye(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>ye(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?ye(e._def.schema):e instanceof S.ZodPipeline?ye(e._def.in):ye(e._def.left).merge(ye(e._def.right)),to=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:d}=ye(r),p=es(e),m=o.includes("query"),l=o.includes("params"),f=o.includes("headers"),x=g=>l&&p.includes(g),A=g=>f&&Et(g);return Object.keys(d).map(g=>({name:g,location:x(g)?"path":A(g)?"header":m?"query":void 0})).filter(g=>g.location!==void 0).map(({name:g,location:q})=>{let w=fe(d[g],{rules:{...a,...Ft},onEach:Bt,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),C=i==="components"?n(d[g],w,J(c,g)):w;return{name:g,in:q,required:!d[g].isOptional(),description:w.description||c,schema:C,examples:js(r,g)}})},Ft={ZodString:ws,ZodNumber:Es,ZodBigInt:Ts,ZodBoolean:Ss,ZodNull:gs,ZodArray:As,ZodTuple:Ps,ZodRecord:Rs,ZodObject:ys,ZodLiteral:fs,ZodIntersection:ds,ZodUnion:is,ZodAny:os,ZodDefault:ts,ZodEnum:qr,ZodNativeEnum:qr,ZodEffects:zs,ZodOptional:ms,ZodNullable:us,ZodDiscriminatedUnion:as,ZodBranded:Zs,ZodDate:bs,ZodCatch:rs,ZodPipeline:Cs,ZodLazy:vs,ZodReadonly:ls,[U]:ss,[Te]:ns,[pe]:xs,[ae]:hs,[Y]:Ns},Bt=(e,{isResponse:t,prev:r})=>{if(Dt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&He(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=Wr(r)),!n){let p=_({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},qt=(e,t)=>{throw new N(`Zod type ${e.constructor.name} is unsupported.`,t)},Kt=(e,t)=>{if(Dt(e))return e;let r={...e};return r.properties&&(r.properties=ft(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>ft(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=>Dt(e)?e:ft(["examples"],e),oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${It(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let l=ro(fe(r,{rules:{...p,...Ft},onEach:Bt,onMissing:qt,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),f={schema:a==="components"?i(r,l,J(m)):l,examples:eo(r,!0)};return{description:m,content:ut(Ut(o,[f]))}},ks=()=>({type:"http",scheme:"basic"}),Ls=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ms=({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},Hs=({name:e})=>({type:"apiKey",in:"header",name:e}),Us=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ks=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ds=({flows:e={}})=>({type:"oauth2",flows:ze(t=>({...t,scopes:t.scopes||{}}),$n(Un,e))}),no=(e,t)=>{let r={basic:ks,bearer:Ls,input:Ms,header:Hs,cookie:Us,openid:Ks,oauth2:Ds};return st(e,o=>r[o.type](o,t))},yt=e=>"or"in e?e.or.map(t=>"and"in t?Kn(ze(({name:r,scopes:o})=>Gr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?yt(Nt(e)):yt({or:[e]}),so=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=ro(Kt(fe(r,{rules:{...a,...Ft},onEach:Bt,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:i==="components"?n(r,p,J(d)):p,examples:eo(r,!1,c)};return{description:d,content:{[o]:m}}},io=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}),$t=e=>e.length<=Br?e:e.slice(0,Br-1)+"\u2026";var Gt=class extends Fs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=Bs(me);references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||J(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new N(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;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:n,serverUrl:i,descriptions:a,brandHandling:c,hasSummaryFromDescription:d=!0,composition:p="inline"}){super(),this.addInfo({title:o,version:n});for(let l of typeof i=="string"?[i]:i)this.addServer({url:l});Ie({routing:t,onEndpoint:(l,f,x)=>{let A={path:f,method:x,endpoint:l,composition:p,brandHandling:c,makeRef:this.makeRef.bind(this)},[z,g]=["short","long"].map(l.getDescription.bind(l)),q=z?$t(z):d&&g?$t(g):void 0,w=l.getTags(),C=r.inputSources?.[x]||Pt[x],Z=this.ensureUniqOperationId(f,x,l.getOperationId(x)),H=to({...A,inputSources:C,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:x,path:f,operationId:Z})}),$={};for(let b of this.responseVariants){let X=l.getResponses(b);for(let{mimeTypes:ke,schema:Ot,statusCodes:Ve}of X)for(let Le of Ve)$[Le]=oo({...A,variant:b,schema:Ot,mimeTypes:ke,statusCode:Le,hasMultipleStatusCodes:X.length>1||Ve.length>1,description:a?.[`${b}Response`]?.call(null,{method:x,path:f,operationId:Z,statusCode:Le})})}let E=C.includes("body")?so({...A,paramNames:qs("name",H),schema:l.getSchema("input"),mimeType:O[l.getRequestType()],description:a?.requestBody?.call(null,{method:x,path:f,operationId:Z})}):void 0,W=yt(st(no(l.getSecurity(),C),b=>{let X=this.ensureUniqSecuritySchemaName(b),ke=["oauth2","openIdConnect"].includes(b.type)?l.getScopes().slice():[];return this.addSecurityScheme(X,b),{name:X,scopes:ke}}));this.addPath(Yr(f),{[x]:{operationId:Z,summary:q,description:g,tags:w.length>0?w:void 0,parameters:H.length>0?H:void 0,requestBody:E,security:W.length>0?W:void 0,responses:$}})}}),this.rootDoc.tags=r.tags?io(r.tags):[]}};import{createRequest as $s,createResponse as Gs}from"node-mocks-http";var Vs=e=>$s({...e,headers:{"content-type":O.json,...e?.headers}}),_s=e=>Gs(e),Js=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:br(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},ao=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Vs(e),i=_s({req:n,...t});i.req=t?.req||n,n.res=i;let a=Js(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Ys=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=ao(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Qs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=ao(o),d=Ye(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(V(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};import M from"typescript";import{z as Ci}from"zod";import R from"typescript";import T from"typescript";var{factory:po}=T,Ce=(e,t)=>T.addSyntheticLeadingComment(e,T.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Vt=(e,t)=>{let r=T.createSourceFile("print.ts","",T.ScriptTarget.Latest,!1,T.ScriptKind.TS);return T.createPrinter(t).printNode(T.EmitHint.Unspecified,e,r)},Ws=/^[A-Za-z_$][A-Za-z0-9_$]*$/,co=e=>Ws.test(e)?po.createIdentifier(e):po.createStringLiteral(e),Xs=[T.SyntaxKind.AnyKeyword,T.SyntaxKind.BigIntKeyword,T.SyntaxKind.BooleanKeyword,T.SyntaxKind.NeverKeyword,T.SyntaxKind.NumberKeyword,T.SyntaxKind.ObjectKeyword,T.SyntaxKind.StringKeyword,T.SyntaxKind.SymbolKeyword,T.SyntaxKind.UndefinedKeyword,T.SyntaxKind.UnknownKeyword,T.SyntaxKind.VoidKeyword],mo=e=>Xs.includes(e.kind);var s=R.factory,ge=[s.createModifier(R.SyntaxKind.ExportKeyword)],ei=[s.createModifier(R.SyntaxKind.AsyncKeyword)],ti=[s.createModifier(R.SyntaxKind.PublicKeyword)],lo=[s.createModifier(R.SyntaxKind.ProtectedKeyword),s.createModifier(R.SyntaxKind.ReadonlyKeyword)],uo=s.createToken(R.SyntaxKind.DotDotDotToken),ri=s.createTemplateHead(""),oi=s.createTemplateMiddle(" "),Ge=s.createTemplateTail(""),Ze=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(R.SyntaxKind.StringKeyword),s.createKeywordTypeNode(R.SyntaxKind.AnyKeyword)]),ni=e=>s.createTemplateLiteralType(ri,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?Ge:oi))),gt=ni(["M","P"]),ht=(e,t,r)=>s.createParameterDeclaration(Array.isArray(r)?r:void 0,Array.isArray(r)?void 0:r,e,void 0,t,void 0),ve=(e,t)=>Object.entries(e).map(([r,o])=>ht(s.createIdentifier(r),o,t)),fo=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),yo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),go=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),j=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],R.NodeFlags.Const),_t=(e,t)=>k(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{isPublic:!0}),k=(e,t,{isPublic:r,comment:o}={})=>{let n=s.createTypeAliasDeclaration(r?ge:void 0,e,void 0,t);return o?Ce(n,o):n},xt=(e,t,r,o,n)=>s.createMethodDeclaration(ti,void 0,e,void 0,o,t,n,r),ho=(e,t,r)=>s.createClassDeclaration(ge,e,void 0,void 0,[t,...r]),bt=e=>s.createTypeOperatorNode(R.SyntaxKind.KeyOfKeyword,s.createTypeReferenceNode(e)),xo=(e,t,r)=>s.createConditionalTypeNode(t,bt(e),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t),r),St=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(R.SyntaxKind.AnyKeyword):e]),bo=(e,t)=>s.createInterfaceDeclaration(ge,e,void 0,void 0,t),Jt=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,s.createTypeReferenceNode(r))),So=(e,t,r)=>s.createArrowFunction(r?ei:void 0,void 0,e.map(o=>ht(o)),void 0,void 0,t),Yt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier(Object.name),P("keys")),void 0,[e]),P("reduce")),void 0,[s.createArrowFunction(void 0,void 0,ve({acc:void 0,key:void 0}),void 0,void 0,t),r]),To=(...e)=>`"${e.join(" ")}"`,P=e=>e,Ne=(e,t,r)=>s.createConditionalExpression(e,s.createToken(R.SyntaxKind.QuestionToken),t,s.createToken(R.SyntaxKind.ColonToken),r),L=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),Oo=(e,t)=>s.createBinaryExpression(e,s.createToken(R.SyntaxKind.AmpersandAmpersandToken),t),Ro=(e,t)=>s.createBinaryExpression(e,s.createToken(R.SyntaxKind.EqualsEqualsEqualsToken),t);var Ao=["get","post","put","delete","patch"];import{chain as si,prop as ii}from"ramda";import y from"typescript";import{z as Qt}from"zod";var{factory:u}=y,ai={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},pi=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),ci=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&He(a)?a instanceof Qt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,co(i),c&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description?Ce(d,a.description):d});return u.createTypeLiteralNode(n)},di=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),mi=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Po=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(mo(n)?n.kind:n,n)}return u.createUnionTypeNode(Array.from(r.values()))},li=e=>ai?.[e.kind],ui=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Qe(e,li(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},fi=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),yi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},gi=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),hi=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),xi=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),bi=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(y.isTypeLiteralNode)?u.createTypeLiteralNode(si(ii("members"),o)):u.createIntersectionTypeNode(o)},Si=({_def:e},{next:t})=>t(e.innerType),Q=e=>()=>u.createKeywordTypeNode(e),Ti=(e,{next:t})=>t(e.unwrap()),Oi=(e,{next:t})=>t(e.unwrap()),Ri=({_def:e},{next:t})=>t(e.innerType),Ai=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Pi=()=>u.createLiteralTypeNode(u.createNull()),wi=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ei=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Qt.ZodString?r:t instanceof Qt.ZodUnion?n:o},Ii=(e,{next:t})=>t(e.unwrap().shape.raw),zi={ZodString:Q(y.SyntaxKind.StringKeyword),ZodNumber:Q(y.SyntaxKind.NumberKeyword),ZodBigInt:Q(y.SyntaxKind.BigIntKeyword),ZodBoolean:Q(y.SyntaxKind.BooleanKeyword),ZodAny:Q(y.SyntaxKind.AnyKeyword),ZodUndefined:Q(y.SyntaxKind.UndefinedKeyword),[ae]:Q(y.SyntaxKind.StringKeyword),[pe]:Q(y.SyntaxKind.StringKeyword),ZodNull:Pi,ZodArray:di,ZodTuple:hi,ZodRecord:xi,ZodObject:ci,ZodLiteral:pi,ZodIntersection:bi,ZodUnion:Po,ZodDefault:Si,ZodEnum:mi,ZodNativeEnum:fi,ZodEffects:ui,ZodOptional:yi,ZodNullable:gi,ZodDiscriminatedUnion:Po,ZodBranded:Ti,ZodCatch:Ri,ZodPipeline:Ai,ZodLazy:wi,ZodReadonly:Oi,[U]:Ei,[Y]:Ii},Tt=(e,{brandHandling:t,ctx:r})=>fe(e,{rules:{...t,...zi},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Wt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),args:s.createIdentifier("args"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces=[];makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,k(o,n)),this.aliases.set(t,k(o,r()))}return s.createTypeReferenceNode(o)}constructor({routing:t,brandHandling:r,variant:o="client",optionalPropStyle:n={withQuestionMark:!0,withUndefined:!0},noContent:i=Ci.undefined()}){let a={makeAlias:this.makeAlias.bind(this),optionalPropStyle:n},c={brandHandling:r,ctx:{...a,isResponse:!1}},d={brandHandling:r,ctx:{...a,isResponse:!0}};Ie({routing:t,onEndpoint:(v,ee,_e)=>{let he=J.bind(null,_e,ee),te=k(he("input"),Tt(v.getSchema("input"),c)),No=v.getResponses("positive").map(({schema:F,mimeTypes:re})=>re?F:i).reduce((F,re)=>F.or(re)),Rt=k(he("positive.response"),Tt(No,d)),jo=v.getResponses("negative").map(({schema:F,mimeTypes:re})=>re?F:i).reduce((F,re)=>F.or(re)),At=k(he("negative.response"),Tt(jo,d)),er=k(he("response"),s.createUnionTypeNode([s.createTypeReferenceNode(Rt.name.text),s.createTypeReferenceNode(At.name.text)]));this.program.push(te,Rt,At,er),this.paths.push(ee);let ko=v.getResponses("positive").some(({mimeTypes:F})=>F?.includes(O.json));this.registry.set(To(_e,ee),{input:te.name.text,positive:Rt.name.text,negative:At.name.text,response:er.name.text,tags:v.getTags(),isJson:ko})}}),this.program.unshift(...this.aliases.values()),this.program.push(_t(this.ids.pathType,this.paths)),this.program.push(_t(this.ids.methodType,Ao)),this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]},{id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]},{id:this.ids.responseInterface,kind:"response",props:[]});let m=[],l=[];for(let[v,{isJson:ee,tags:_e,...he}]of this.registry){for(let te of this.interfaces)te.props.push(yo(v,he[te.kind]));o!=="types"&&(ee&&m.push(s.createPropertyAssignment(v,s.createTrue())),l.push(s.createPropertyAssignment(v,s.createArrayLiteralExpression(_e.map(te=>s.createStringLiteral(te))))))}for(let{id:v,props:ee}of this.interfaces)this.program.push(bo(v,ee));if(this.program.push(k(this.ids.methodPathType,bt(this.ids.inputInterface),{isPublic:!0})),o==="types")return;let f=s.createVariableStatement(ge,j(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(m))),x=s.createVariableStatement(ge,j(this.ids.endpointTagsConst,s.createObjectLiteralExpression(l))),A=k(this.ids.implementationType,s.createFunctionTypeNode(void 0,ve({[this.ids.methodParameter.text]:s.createTypeReferenceNode(this.ids.methodType),[this.ids.pathParameter.text]:s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:Ze}),St("any")),{isPublic:!0}),z=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,Ge)]),g=Yt(this.ids.paramsArgument,L(this.ids.accumulator,P("replace"),[z,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),q=Yt(this.ids.paramsArgument,L(s.createIdentifier(Object.name),P("assign"),[this.ids.accumulator,Oo(s.createPrefixUnaryExpression(M.SyntaxKind.ExclamationToken,L(this.ids.pathParameter,P("includes"),[z])),s.createObjectLiteralExpression([s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))],!1))]),s.createObjectLiteralExpression()),w=Ce(xt(this.ids.provideMethod,ve({[this.ids.methodParameter.text]:s.createTypeReferenceNode("M"),[this.ids.pathParameter.text]:s.createTypeReferenceNode("P"),[this.ids.paramsArgument.text]:s.createConditionalTypeNode(gt,bt(this.ids.inputInterface),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),gt),Ze)}),void 0,Jt({M:this.ids.methodType,P:this.ids.pathType}),St(xo(this.ids.responseInterface,gt,s.createKeywordTypeNode(M.SyntaxKind.UnknownKeyword)))),"@deprecated use the overload with 2 arguments instead"),C=xt(this.ids.provideMethod,ve({[this.ids.requestParameter.text]:s.createTypeReferenceNode("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),s.createTypeReferenceNode("K"))}),void 0,Jt({K:this.ids.methodPathType}),St(s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.responseInterface),s.createTypeReferenceNode("K")))),Z=xt(this.ids.provideMethod,ve({[this.ids.args.text]:s.createUnionTypeNode([s.createTupleTypeNode([s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),Ze]),s.createTupleTypeNode([s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),Ze])])},uo),s.createBlock([s.createVariableStatement(void 0,j(go(this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument),s.createAsExpression(s.createParenthesizedExpression(Ne(Ro(s.createPropertyAccessExpression(this.ids.args,P("length")),s.createNumericLiteral(2)),s.createArrayLiteralExpression([s.createSpreadElement(L(s.createElementAccessExpression(this.ids.args,0),P("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)])),s.createElementAccessExpression(this.ids.args,1)]),this.ids.args)),s.createTupleTypeNode([s.createTypeReferenceNode(this.ids.methodType),s.createTypeReferenceNode(this.ids.pathType),Ze])))),s.createReturnStatement(L(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,g,q]))])),H=ho(this.ids.clientClass,fo([ht(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),lo)]),[w,C,Z]),$=k(this.ids.providerType,s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.clientClass),s.createLiteralTypeNode(s.createStringLiteral(this.ids.provideMethod.text))),{isPublic:!0,comment:"@deprecated will be removed in v22"});this.program.push(f,x,A,H,$);let E=s.createPropertyAssignment(this.ids.methodParameter,L(this.ids.methodParameter,P("toUpperCase"))),W=s.createPropertyAssignment(this.ids.headersProperty,Ne(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(O.json))]),this.ids.undefinedValue)),b=s.createPropertyAssignment(this.ids.bodyProperty,Ne(this.ids.hasBodyConst,L(s.createIdentifier("JSON"),P("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),X=s.createVariableStatement(void 0,j(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,Ge)]),s.createObjectLiteralExpression([E,W,b])])))),ke=s.createVariableStatement(void 0,j(this.ids.hasBodyConst,s.createLogicalNot(L(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),P("includes"),[this.ids.methodParameter])))),Ot=s.createVariableStatement(void 0,j(this.ids.searchParamsConst,Ne(this.ids.hasBodyConst,s.createStringLiteral(""),s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier(URLSearchParams.name),void 0,[this.ids.paramsArgument]),Ge)])))),Ve=s.createVariableStatement(void 0,j(this.ids.contentTypeConst,L([this.ids.responseConst,this.ids.headersProperty],P("get"),[s.createStringLiteral("content-type")]))),Le=s.createIfStatement(s.createPrefixUnaryExpression(M.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement(void 0),void 0),Io=s.createVariableStatement(void 0,j(this.ids.isJsonConst,s.createCallChain(s.createPropertyAccessChain(this.ids.contentTypeConst,void 0,P("startsWith")),void 0,void 0,[s.createStringLiteral(O.json)]))),zo=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,Ne(this.ids.isJsonConst,s.createStringLiteral(P("json")),s.createStringLiteral(P("text")))),void 0,[])),Co=s.createVariableStatement(ge,j(this.ids.exampleImplementationConst,So([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([ke,Ot,X,Ve,Le,Io,zo]),!0),s.createTypeReferenceNode(this.ids.implementationType))),Zo=s.createExpressionStatement(L(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),vo=s.createVariableStatement(void 0,j(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(Co,vo,Zo)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Vt(r,t)).join(`
|
|
18
|
+
`))};var Fr=e=>{e.startupLogo!==!1&&Dr(process.stdout);let t=e.errorHandler||Fe,r=xr(e.logger)?e.logger:new Be(e.logger);r.debug("Running",{build:"v21.6.1 (ESM)",env:process.env.NODE_ENV||"development"}),Hr(r);let o=Lr({logger:r,config:e}),i={getLogger:Mr(r),errorHandler:t},a=Nr(i),c=vr(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},jn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=Fr(e);return Mt({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},kn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Fr(e),c=Ht().disable("x-powered-by").use(a);if(e.compression){let f=await Ee("compression");c.use(f(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Ht.json()],raw:[e.rawParser||Ht.raw(),kr],upload:e.upload?await jr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Mt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],m=(f,x)=>()=>f.listen(x,()=>r.info("Listening",x)),l=[];if(e.http){let f=vn.createServer(c);p.push(f),l.push(m(f,e.http.listen))}if(e.https){let f=Nn.createServer(e.https.options,c);p.push(f),l.push(m(f,e.https.listen))}return e.gracefulShutdown&&Ur({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:l.map(f=>f())}};import{OpenApiBuilder as Fs}from"openapi3-ts/oas31";import{keys as Bs,pluck as qs}from"ramda";import{isReferenceObject as Dt,isSchemaObject as lt}from"openapi3-ts/oas31";import{concat as Ln,type as $r,filter as Mn,fromPairs as ut,has as Hn,isNil as Un,map as ze,mergeAll as Kn,mergeDeepRight as Dn,mergeDeepWith as Fn,objOf as Gr,omit as ft,pipe as Vr,pluck as Bn,range as qn,reject as $n,toLower as Gn,union as Vn,when as _n,xprod as Ut,zip as Jn}from"ramda";import{z as S}from"zod";var fe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>fe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var Br=50,_r="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Yn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Jr=/:([A-Za-z0-9_]+)/g,Qn=/^\d{4}-\d{2}-\d{2}$/,Wn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Xn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,es=e=>e.match(Jr)?.map(t=>t.slice(1))||[],Yr=e=>e.replace(Jr,t=>`{${t.slice(1)}}`),ts=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),rs=({_def:{innerType:e}},{next:t})=>t(e),os=()=>({format:"any"}),ns=({},e)=>{if(e.isResponse)throw new N("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},ss=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},is=({options:e},{next:t})=>({oneOf:e.map(t)}),as=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ps=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Ln(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},cs=e=>{let[t,r]=e.filter(lt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Fn(ps,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Vn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,i])=>Dn(n,i))),o},ds=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return cs(o)}catch{}return{allOf:o}},ms=(e,{next:t})=>t(e.unwrap()),ls=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t})=>{let r=t(e.unwrap());return lt(r)&&(r.type=Wr(r)),r},Qr=e=>{let t=Gn($r(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},qr=e=>({type:Qr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),fs=({value:e})=>({type:Qr(e),const:e}),ys=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&He(c)?c instanceof S.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=mt(e,r)),i.length&&(a.required=i),a},gs=()=>({type:"null"}),hs=({},e)=>{if(e.isResponse)throw new N("Please use ez.dateOut() for output.",e);return{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}}},xs=({},e)=>{if(!e.isResponse)throw new N("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:_r}}},bs=({},e)=>{throw new N(`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)},Ss=()=>({type:"boolean"}),Ts=()=>({type:"integer",format:"bigint"}),Os=e=>e.every(t=>t instanceof S.ZodLiteral),Rs=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=mt(S.object(ut(Ut(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:mt(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Os(e.options)){let o=ze(i=>`${i.value}`,e.options),n=ut(Ut(o,[t]));return{type:"object",properties:mt(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},As=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Ps=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ws=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:l,isDate:f,isTime:x,isBase64:A,isNANOID:z,isBase64url:g,isDuration:q,_def:{checks:w}})=>{let C=w.find(b=>b.kind==="regex"),Z=w.find(b=>b.kind==="datetime"),H=w.some(b=>b.kind==="jwt"),$=w.find(b=>b.kind==="length"),E={type:"string"},W={"date-time":m,byte:A,base64url:g,date:f,time:x,duration:q,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:z,jwt:H,ip:d,cidr:l,emoji:p};for(let b in W)if(W[b]){E.format=b;break}return $&&([E.minLength,E.maxLength]=[$.value,$.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),f&&(E.pattern=Qn.source),x&&(E.pattern=Wn.source),m&&(E.pattern=Xn(Z?.offset).source),C&&(E.pattern=C.regex.source),E},Es=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(l=>l.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(l=>l.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,p?m.maximum=d:m.exclusiveMaximum=d,m},mt=({shape:e},t)=>ze(t,e),Is=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Yn?.[t]},Wr=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",zs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&<(o)){let i=Qe(e,Is(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&<(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Cs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Zs=(e,{next:t})=>t(e.unwrap()),vs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ns=(e,{next:t})=>t(e.unwrap().shape.raw),Xr=e=>e.length?ut(Jn(qn(1,e.length+1).map(t=>`example${t}`),ze(Gr("value"),e))):void 0,eo=(e,t,r=[])=>Vr(_,ze(_n(o=>$r(o)==="Object",ft(r))),Xr)({schema:e,variant:t?"parsed":"original",validate:!0}),js=(e,t)=>Vr(_,Mn(Hn(t)),Bn(t),Xr)({schema:e,variant:"original",validate:!0}),ye=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?ye(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>ye(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?ye(e._def.schema):e instanceof S.ZodPipeline?ye(e._def.in):ye(e._def.left).merge(ye(e._def.right)),to=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:d}=ye(r),p=es(e),m=o.includes("query"),l=o.includes("params"),f=o.includes("headers"),x=g=>l&&p.includes(g),A=g=>f&&Et(g);return Object.keys(d).map(g=>({name:g,location:x(g)?"path":A(g)?"header":m?"query":void 0})).filter(g=>g.location!==void 0).map(({name:g,location:q})=>{let w=fe(d[g],{rules:{...a,...Ft},onEach:Bt,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),C=i==="components"?n(d[g],w,J(c,g)):w;return{name:g,in:q,required:!d[g].isOptional(),description:w.description||c,schema:C,examples:js(r,g)}})},Ft={ZodString:ws,ZodNumber:Es,ZodBigInt:Ts,ZodBoolean:Ss,ZodNull:gs,ZodArray:As,ZodTuple:Ps,ZodRecord:Rs,ZodObject:ys,ZodLiteral:fs,ZodIntersection:ds,ZodUnion:is,ZodAny:os,ZodDefault:ts,ZodEnum:qr,ZodNativeEnum:qr,ZodEffects:zs,ZodOptional:ms,ZodNullable:us,ZodDiscriminatedUnion:as,ZodBranded:Zs,ZodDate:bs,ZodCatch:rs,ZodPipeline:Cs,ZodLazy:vs,ZodReadonly:ls,[U]:ss,[Te]:ns,[pe]:xs,[ae]:hs,[Y]:Ns},Bt=(e,{isResponse:t,prev:r})=>{if(Dt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&He(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=Wr(r)),!n){let p=_({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},qt=(e,t)=>{throw new N(`Zod type ${e.constructor.name} is unsupported.`,t)},Kt=(e,t)=>{if(Dt(e))return e;let r={...e};return r.properties&&(r.properties=ft(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>ft(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=>Dt(e)?e:ft(["examples"],e),oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${It(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let l=ro(fe(r,{rules:{...p,...Ft},onEach:Bt,onMissing:qt,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),f={schema:a==="components"?i(r,l,J(m)):l,examples:eo(r,!0)};return{description:m,content:ut(Ut(o,[f]))}},ks=()=>({type:"http",scheme:"basic"}),Ls=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ms=({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},Hs=({name:e})=>({type:"apiKey",in:"header",name:e}),Us=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ks=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ds=({flows:e={}})=>({type:"oauth2",flows:ze(t=>({...t,scopes:t.scopes||{}}),$n(Un,e))}),no=(e,t)=>{let r={basic:ks,bearer:Ls,input:Ms,header:Hs,cookie:Us,openid:Ks,oauth2:Ds};return st(e,o=>r[o.type](o,t))},yt=e=>"or"in e?e.or.map(t=>"and"in t?Kn(ze(({name:r,scopes:o})=>Gr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?yt(Nt(e)):yt({or:[e]}),so=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=ro(Kt(fe(r,{rules:{...a,...Ft},onEach:Bt,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:i==="components"?n(r,p,J(d)):p,examples:eo(r,!1,c)};return{description:d,content:{[o]:m}}},io=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}),$t=e=>e.length<=Br?e:e.slice(0,Br-1)+"\u2026";var Gt=class extends Fs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=Bs(me);references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||J(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new N(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;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:n,serverUrl:i,descriptions:a,brandHandling:c,hasSummaryFromDescription:d=!0,composition:p="inline"}){super(),this.addInfo({title:o,version:n});for(let l of typeof i=="string"?[i]:i)this.addServer({url:l});Ie({routing:t,onEndpoint:(l,f,x)=>{let A={path:f,method:x,endpoint:l,composition:p,brandHandling:c,makeRef:this.makeRef.bind(this)},[z,g]=["short","long"].map(l.getDescription.bind(l)),q=z?$t(z):d&&g?$t(g):void 0,w=l.getTags(),C=r.inputSources?.[x]||Pt[x],Z=this.ensureUniqOperationId(f,x,l.getOperationId(x)),H=to({...A,inputSources:C,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:x,path:f,operationId:Z})}),$={};for(let b of this.responseVariants){let X=l.getResponses(b);for(let{mimeTypes:ke,schema:Ot,statusCodes:Ve}of X)for(let Le of Ve)$[Le]=oo({...A,variant:b,schema:Ot,mimeTypes:ke,statusCode:Le,hasMultipleStatusCodes:X.length>1||Ve.length>1,description:a?.[`${b}Response`]?.call(null,{method:x,path:f,operationId:Z,statusCode:Le})})}let E=C.includes("body")?so({...A,paramNames:qs("name",H),schema:l.getSchema("input"),mimeType:O[l.getRequestType()],description:a?.requestBody?.call(null,{method:x,path:f,operationId:Z})}):void 0,W=yt(st(no(l.getSecurity(),C),b=>{let X=this.ensureUniqSecuritySchemaName(b),ke=["oauth2","openIdConnect"].includes(b.type)?l.getScopes().slice():[];return this.addSecurityScheme(X,b),{name:X,scopes:ke}}));this.addPath(Yr(f),{[x]:{operationId:Z,summary:q,description:g,tags:w.length>0?w:void 0,parameters:H.length>0?H:void 0,requestBody:E,security:W.length>0?W:void 0,responses:$}})}}),this.rootDoc.tags=r.tags?io(r.tags):[]}};import{createRequest as $s,createResponse as Gs}from"node-mocks-http";var Vs=e=>$s({...e,headers:{"content-type":O.json,...e?.headers}}),_s=e=>Gs(e),Js=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:br(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},ao=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Vs(e),i=_s({req:n,...t});i.req=t?.req||n,n.res=i;let a=Js(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Ys=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=ao(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Qs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=ao(o),d=Ye(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(V(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};import M from"typescript";import{z as Ci}from"zod";import R from"typescript";import T from"typescript";var{factory:po}=T,Ce=(e,t)=>T.addSyntheticLeadingComment(e,T.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Vt=(e,t)=>{let r=T.createSourceFile("print.ts","",T.ScriptTarget.Latest,!1,T.ScriptKind.TS);return T.createPrinter(t).printNode(T.EmitHint.Unspecified,e,r)},Ws=/^[A-Za-z_$][A-Za-z0-9_$]*$/,co=e=>Ws.test(e)?po.createIdentifier(e):po.createStringLiteral(e),Xs=[T.SyntaxKind.AnyKeyword,T.SyntaxKind.BigIntKeyword,T.SyntaxKind.BooleanKeyword,T.SyntaxKind.NeverKeyword,T.SyntaxKind.NumberKeyword,T.SyntaxKind.ObjectKeyword,T.SyntaxKind.StringKeyword,T.SyntaxKind.SymbolKeyword,T.SyntaxKind.UndefinedKeyword,T.SyntaxKind.UnknownKeyword,T.SyntaxKind.VoidKeyword],mo=e=>Xs.includes(e.kind);var s=R.factory,ge=[s.createModifier(R.SyntaxKind.ExportKeyword)],ei=[s.createModifier(R.SyntaxKind.AsyncKeyword)],ti=[s.createModifier(R.SyntaxKind.PublicKeyword)],lo=[s.createModifier(R.SyntaxKind.ProtectedKeyword),s.createModifier(R.SyntaxKind.ReadonlyKeyword)],uo=s.createToken(R.SyntaxKind.DotDotDotToken),ri=s.createTemplateHead(""),oi=s.createTemplateMiddle(" "),Ge=s.createTemplateTail(""),Ze=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(R.SyntaxKind.StringKeyword),s.createKeywordTypeNode(R.SyntaxKind.AnyKeyword)]),ni=e=>s.createTemplateLiteralType(ri,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?Ge:oi))),gt=ni(["M","P"]),ht=(e,t,r)=>s.createParameterDeclaration(Array.isArray(r)?r:void 0,Array.isArray(r)?void 0:r,e,void 0,t,void 0),ve=(e,t)=>Object.entries(e).map(([r,o])=>ht(s.createIdentifier(r),o,t)),fo=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),yo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),go=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),j=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],R.NodeFlags.Const),_t=(e,t)=>k(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{isPublic:!0}),k=(e,t,{isPublic:r,comment:o}={})=>{let n=s.createTypeAliasDeclaration(r?ge:void 0,e,void 0,t);return o?Ce(n,o):n},xt=(e,t,r,o,n)=>s.createMethodDeclaration(ti,void 0,e,void 0,o,t,n,r),ho=(e,t,r)=>s.createClassDeclaration(ge,e,void 0,void 0,[t,...r]),bt=e=>s.createTypeOperatorNode(R.SyntaxKind.KeyOfKeyword,s.createTypeReferenceNode(e)),xo=(e,t,r)=>s.createConditionalTypeNode(t,bt(e),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t),r),St=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(R.SyntaxKind.AnyKeyword):e]),bo=(e,t)=>s.createInterfaceDeclaration(ge,e,void 0,void 0,t),Jt=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,s.createTypeReferenceNode(r))),So=(e,t,r)=>s.createArrowFunction(r?ei:void 0,void 0,e.map(o=>ht(o)),void 0,void 0,t),Yt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier(Object.name),P("keys")),void 0,[e]),P("reduce")),void 0,[s.createArrowFunction(void 0,void 0,ve({acc:void 0,key:void 0}),void 0,void 0,t),r]),To=(...e)=>`"${e.join(" ")}"`,P=e=>e,Ne=(e,t,r)=>s.createConditionalExpression(e,s.createToken(R.SyntaxKind.QuestionToken),t,s.createToken(R.SyntaxKind.ColonToken),r),L=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),Oo=(e,t)=>s.createBinaryExpression(e,s.createToken(R.SyntaxKind.AmpersandAmpersandToken),t),Ro=(e,t)=>s.createBinaryExpression(e,s.createToken(R.SyntaxKind.EqualsEqualsEqualsToken),t);var Ao=["get","post","put","delete","patch"];import{chain as si,prop as ii}from"ramda";import y from"typescript";import{z as Qt}from"zod";var{factory:u}=y,ai={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},pi=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),ci=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&He(a)?a instanceof Qt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,co(i),c&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description?Ce(d,a.description):d});return u.createTypeLiteralNode(n)},di=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),mi=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Po=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(mo(n)?n.kind:n,n)}return u.createUnionTypeNode(Array.from(r.values()))},li=e=>ai?.[e.kind],ui=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Qe(e,li(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},fi=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),yi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},gi=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),hi=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),xi=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),bi=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(y.isTypeLiteralNode)?u.createTypeLiteralNode(si(ii("members"),o)):u.createIntersectionTypeNode(o)},Si=({_def:e},{next:t})=>t(e.innerType),Q=e=>()=>u.createKeywordTypeNode(e),Ti=(e,{next:t})=>t(e.unwrap()),Oi=(e,{next:t})=>t(e.unwrap()),Ri=({_def:e},{next:t})=>t(e.innerType),Ai=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Pi=()=>u.createLiteralTypeNode(u.createNull()),wi=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ei=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Qt.ZodString?r:t instanceof Qt.ZodUnion?n:o},Ii=(e,{next:t})=>t(e.unwrap().shape.raw),zi={ZodString:Q(y.SyntaxKind.StringKeyword),ZodNumber:Q(y.SyntaxKind.NumberKeyword),ZodBigInt:Q(y.SyntaxKind.BigIntKeyword),ZodBoolean:Q(y.SyntaxKind.BooleanKeyword),ZodAny:Q(y.SyntaxKind.AnyKeyword),ZodUndefined:Q(y.SyntaxKind.UndefinedKeyword),[ae]:Q(y.SyntaxKind.StringKeyword),[pe]:Q(y.SyntaxKind.StringKeyword),ZodNull:Pi,ZodArray:di,ZodTuple:hi,ZodRecord:xi,ZodObject:ci,ZodLiteral:pi,ZodIntersection:bi,ZodUnion:Po,ZodDefault:Si,ZodEnum:mi,ZodNativeEnum:fi,ZodEffects:ui,ZodOptional:yi,ZodNullable:gi,ZodDiscriminatedUnion:Po,ZodBranded:Ti,ZodCatch:Ri,ZodPipeline:Ai,ZodLazy:wi,ZodReadonly:Oi,[U]:Ei,[Y]:Ii},Tt=(e,{brandHandling:t,ctx:r})=>fe(e,{rules:{...t,...zi},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Wt=class{program=[];usage=[];registry=new Map;paths=new Set;aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),args:s.createIdentifier("args"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces=[];makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,k(o,n)),this.aliases.set(t,k(o,r()))}return s.createTypeReferenceNode(o)}constructor({routing:t,brandHandling:r,variant:o="client",optionalPropStyle:n={withQuestionMark:!0,withUndefined:!0},noContent:i=Ci.undefined()}){let a={makeAlias:this.makeAlias.bind(this),optionalPropStyle:n},c={brandHandling:r,ctx:{...a,isResponse:!1}},d={brandHandling:r,ctx:{...a,isResponse:!0}};Ie({routing:t,onEndpoint:(v,ee,_e)=>{let he=J.bind(null,_e,ee),te=k(he("input"),Tt(v.getSchema("input"),c)),No=v.getResponses("positive").map(({schema:F,mimeTypes:re})=>re?F:i).reduce((F,re)=>F.or(re)),Rt=k(he("positive.response"),Tt(No,d)),jo=v.getResponses("negative").map(({schema:F,mimeTypes:re})=>re?F:i).reduce((F,re)=>F.or(re)),At=k(he("negative.response"),Tt(jo,d)),er=k(he("response"),s.createUnionTypeNode([s.createTypeReferenceNode(Rt.name.text),s.createTypeReferenceNode(At.name.text)]));this.program.push(te,Rt,At,er),this.paths.add(ee);let ko=v.getResponses("positive").some(({mimeTypes:F})=>F?.includes(O.json));this.registry.set(To(_e,ee),{input:te.name.text,positive:Rt.name.text,negative:At.name.text,response:er.name.text,tags:v.getTags(),isJson:ko})}}),this.program.unshift(...this.aliases.values()),this.program.push(_t(this.ids.pathType,Array.from(this.paths))),this.program.push(_t(this.ids.methodType,Ao)),this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]},{id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]},{id:this.ids.responseInterface,kind:"response",props:[]});let m=[],l=[];for(let[v,{isJson:ee,tags:_e,...he}]of this.registry){for(let te of this.interfaces)te.props.push(yo(v,he[te.kind]));o!=="types"&&(ee&&m.push(s.createPropertyAssignment(v,s.createTrue())),l.push(s.createPropertyAssignment(v,s.createArrayLiteralExpression(_e.map(te=>s.createStringLiteral(te))))))}for(let{id:v,props:ee}of this.interfaces)this.program.push(bo(v,ee));if(this.program.push(k(this.ids.methodPathType,bt(this.ids.inputInterface),{isPublic:!0})),o==="types")return;let f=s.createVariableStatement(ge,j(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(m))),x=s.createVariableStatement(ge,j(this.ids.endpointTagsConst,s.createObjectLiteralExpression(l))),A=k(this.ids.implementationType,s.createFunctionTypeNode(void 0,ve({[this.ids.methodParameter.text]:s.createTypeReferenceNode(this.ids.methodType),[this.ids.pathParameter.text]:s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:Ze}),St("any")),{isPublic:!0}),z=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,Ge)]),g=Yt(this.ids.paramsArgument,L(this.ids.accumulator,P("replace"),[z,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),q=Yt(this.ids.paramsArgument,L(s.createIdentifier(Object.name),P("assign"),[this.ids.accumulator,Oo(s.createPrefixUnaryExpression(M.SyntaxKind.ExclamationToken,L(this.ids.pathParameter,P("includes"),[z])),s.createObjectLiteralExpression([s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))],!1))]),s.createObjectLiteralExpression()),w=Ce(xt(this.ids.provideMethod,ve({[this.ids.methodParameter.text]:s.createTypeReferenceNode("M"),[this.ids.pathParameter.text]:s.createTypeReferenceNode("P"),[this.ids.paramsArgument.text]:s.createConditionalTypeNode(gt,bt(this.ids.inputInterface),s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),gt),Ze)}),void 0,Jt({M:this.ids.methodType,P:this.ids.pathType}),St(xo(this.ids.responseInterface,gt,s.createKeywordTypeNode(M.SyntaxKind.UnknownKeyword)))),"@deprecated use the overload with 2 arguments instead"),C=xt(this.ids.provideMethod,ve({[this.ids.requestParameter.text]:s.createTypeReferenceNode("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),s.createTypeReferenceNode("K"))}),void 0,Jt({K:this.ids.methodPathType}),St(s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.responseInterface),s.createTypeReferenceNode("K")))),Z=xt(this.ids.provideMethod,ve({[this.ids.args.text]:s.createUnionTypeNode([s.createTupleTypeNode([s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),Ze]),s.createTupleTypeNode([s.createKeywordTypeNode(M.SyntaxKind.StringKeyword),Ze])])},uo),s.createBlock([s.createVariableStatement(void 0,j(go(this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument),s.createAsExpression(s.createParenthesizedExpression(Ne(Ro(s.createPropertyAccessExpression(this.ids.args,P("length")),s.createNumericLiteral(2)),s.createArrayLiteralExpression([s.createSpreadElement(L(s.createElementAccessExpression(this.ids.args,0),P("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)])),s.createElementAccessExpression(this.ids.args,1)]),this.ids.args)),s.createTupleTypeNode([s.createTypeReferenceNode(this.ids.methodType),s.createTypeReferenceNode(this.ids.pathType),Ze])))),s.createReturnStatement(L(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,g,q]))])),H=ho(this.ids.clientClass,fo([ht(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),lo)]),[w,C,Z]),$=k(this.ids.providerType,s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.clientClass),s.createLiteralTypeNode(s.createStringLiteral(this.ids.provideMethod.text))),{isPublic:!0,comment:"@deprecated will be removed in v22"});this.program.push(f,x,A,H,$);let E=s.createPropertyAssignment(this.ids.methodParameter,L(this.ids.methodParameter,P("toUpperCase"))),W=s.createPropertyAssignment(this.ids.headersProperty,Ne(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(O.json))]),this.ids.undefinedValue)),b=s.createPropertyAssignment(this.ids.bodyProperty,Ne(this.ids.hasBodyConst,L(s.createIdentifier("JSON"),P("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),X=s.createVariableStatement(void 0,j(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,Ge)]),s.createObjectLiteralExpression([E,W,b])])))),ke=s.createVariableStatement(void 0,j(this.ids.hasBodyConst,s.createLogicalNot(L(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),P("includes"),[this.ids.methodParameter])))),Ot=s.createVariableStatement(void 0,j(this.ids.searchParamsConst,Ne(this.ids.hasBodyConst,s.createStringLiteral(""),s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier(URLSearchParams.name),void 0,[this.ids.paramsArgument]),Ge)])))),Ve=s.createVariableStatement(void 0,j(this.ids.contentTypeConst,L([this.ids.responseConst,this.ids.headersProperty],P("get"),[s.createStringLiteral("content-type")]))),Le=s.createIfStatement(s.createPrefixUnaryExpression(M.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement(void 0),void 0),Io=s.createVariableStatement(void 0,j(this.ids.isJsonConst,s.createCallChain(s.createPropertyAccessChain(this.ids.contentTypeConst,void 0,P("startsWith")),void 0,void 0,[s.createStringLiteral(O.json)]))),zo=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,Ne(this.ids.isJsonConst,s.createStringLiteral(P("json")),s.createStringLiteral(P("text")))),void 0,[])),Co=s.createVariableStatement(ge,j(this.ids.exampleImplementationConst,So([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([ke,Ot,X,Ve,Le,Io,zo]),!0),s.createTypeReferenceNode(this.ids.implementationType))),Zo=s.createExpressionStatement(L(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),vo=s.createVariableStatement(void 0,j(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(Co,vo,Zo)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Vt(r,t)).join(`
|
|
19
19
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&M.addSyntheticLeadingComment(M.addSyntheticLeadingComment(s.createEmptyStatement(),M.SyntaxKind.SingleLineCommentTrivia," Usage example:"),M.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
20
|
${r}`);return this.program.concat(o||[]).map((n,i)=>Vt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "21.6.
|
|
3
|
+
"version": "21.6.1",
|
|
4
4
|
"description": "A Typescript framework 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": {
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
78
|
"ansis": "^3.2.0",
|
|
79
|
-
"node-mocks-http": "^1.16.
|
|
79
|
+
"node-mocks-http": "^1.16.2",
|
|
80
80
|
"openapi3-ts": "^4.4.0",
|
|
81
81
|
"ramda": "^0.30.1"
|
|
82
82
|
},
|