express-zod-api 23.0.0-beta.1 → 23.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -171,7 +171,7 @@ Install the framework, its peer dependencies and type assistance packages using
171
171
 
172
172
  ```shell
173
173
  # example for yarn:
174
- yarn add express-zod-api express zod typescript http-errors
174
+ yarn add express-zod-api express zod@3 typescript http-errors
175
175
  yarn add -D @types/express @types/node @types/http-errors
176
176
  ```
177
177
 
package/dist/index.cjs CHANGED
@@ -15,7 +15,7 @@ ${n}888${r}
15
15
  ${o}
16
16
  `;e.write(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var zo=e=>{e.startupLogo!==!1&&wo(process.stdout);let t=e.errorHandler||ye,r=Qr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.0.0-beta.1 (CJS)",env:process.env.NODE_ENV||"development"}),Oo(r);let o=Ro({logger:r,config:e}),s={getLogger:To(r),errorHandler:t},a=bo(s),c=ho(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return ar({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Io=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=zo(e),c=(0,ot.default)().disable("x-powered-by").use(a);if(e.compression){let g=await _e("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ot.default.json()],raw:[e.rawParser||ot.default.raw(),So],form:[e.formParser||ot.default.urlencoded()],upload:e.upload?await xo({config:e,getLogger:o}):[]};ar({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,R)=>()=>g.listen(R,()=>r.info("Listening",R)),S=[];if(e.http){let g=Ao.default.createServer(c);p.push(g),S.push(l(g,e.http.listen))}if(e.https){let g=Eo.default.createServer(e.https.options,c);p.push(g),S.push(l(g,e.https.listen))}return e.gracefulShutdown&&Po({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:S.map(g=>g())}};var Qo=require("openapi3-ts/oas31"),Xo=h(require("ramda"),1);var O=h(require("ramda"),1);var vo=e=>Te(e)&&"or"in e,ko=e=>Te(e)&&"and"in e,pr=e=>!ko(e)&&!vo(e),Co=e=>{let t=O.filter(pr,e),r=O.chain(O.prop("and"),O.filter(ko,e)),[o,n]=O.partition(pr,r),s=O.concat(t,o),a=O.filter(vo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>Re(m,O.map(l=>pr(l)?[l]:l.and,p),([l,S])=>O.concat(l,S)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=h(require("ramda"),1),K=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var jo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var No=50,Mo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Mn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Un=/^\d{4}-\d{2}-\d{2}$/,Hn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Dn=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$/,Uo=e=>e.replace(Gt,t=>`{${t.slice(1)}}`),Kn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Fn=({_def:{innerType:e}},{next:t})=>t(e),qn=()=>({format:"any"}),Bn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},$n=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},_n=({options:e},{next:t})=>({oneOf:e.map(t)}),Vn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Gn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Ho={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Gn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},Jn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Ho)),d.isEmpty)),Wn=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Jn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Ho);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Yn=({_def:{left:e,right:t}},{next:r})=>Wn([e,t].map(r)),Qn=(e,{next:t})=>t(e.unwrap()),Xn=(e,{next:t})=>t(e.unwrap()),es=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Ko(r)),r},Do=e=>{let t=d.toLower(d.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:Do(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ts=({value:e})=>({type:Do(e),const:e}),rs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&We(c)?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Zt(e,r)),s.length&&(a.required=s),a},os=()=>({type:"null"}),ns=({},e)=>{if(e.isResponse)throw new q("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:Mo}}},ss=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mo}}},is=({},e)=>{throw new q(`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)},as=()=>({type:"boolean"}),ps=()=>({type:"integer",format:"bigint"}),cs=e=>e.every(t=>t instanceof K.z.ZodLiteral),ds=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Zt(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Zt(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&cs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Zt(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ms=({_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},ls=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),us=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:S,isDate:g,isTime:R,isBase64:b,isNANOID:C,isBase64url:w,isDuration:Q,_def:{checks:M}})=>{let T=M.find(v=>v.kind==="regex"),Z=M.find(v=>v.kind==="datetime"),j=M.some(v=>v.kind==="jwt"),U=M.find(v=>v.kind==="length"),P={type:"string"},_={"date-time":l,byte:b,base64url:w,date:g,time:R,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:j,ip:m,cidr:S,emoji:p};for(let v in _)if(_[v]){P.format=v;break}return U&&([P.minLength,P.maxLength]=[U.value,U.value]),r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),g&&(P.pattern=Un.source),R&&(P.pattern=Hn.source),l&&(P.pattern=Dn(Z?.offset).source),T&&(P.pattern=T.regex.source),P},fs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(b=>b.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(b=>b.kind==="max"),S=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,R={type:e?"integer":"number",format:e?"int64":"double"};return p?R.minimum=m:R.exclusiveMinimum=m,g?R.maximum=S:R.exclusiveMaximum=S,R},Zt=({shape:e},t)=>d.map(t,e),ys=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Mn?.[t]},Ko=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",gs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=yt(e,ys(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},hs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ss=(e,{next:t})=>t(e.unwrap().shape.raw),Fo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,qo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Rs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ts=(e,t)=>t?.includes(e)||e.startsWith("x-")||jo.includes(e),Bo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let S=G(r),g=ut(e),R=o.includes("query"),b=o.includes("params"),C=o.includes("headers"),w=T=>b&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),M=T=>C&&(c?.(T,t,e)??Ts(T,Q));return Object.entries(S.shape).reduce((T,[Z,j])=>{let U=w(Z)?"path":M(Z)?"header":R?"query":void 0;if(!U)return T;let P=Ze(j,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),_=s==="components"?n(j,P,me(l,Z)):P,{_def:v}=j;return T.concat({name:Z,in:U,deprecated:v[y]?.isDeprecated,required:!j.isOptional(),description:P.description||l,schema:_,examples:Rs(S,Z)})},[])},cr={ZodString:us,ZodNumber:fs,ZodBigInt:ps,ZodBoolean:as,ZodNull:os,ZodArray:ms,ZodTuple:ls,ZodRecord:ds,ZodObject:rs,ZodLiteral:ts,ZodIntersection:Yn,ZodUnion:_n,ZodAny:qn,ZodDefault:Kn,ZodEnum:Lo,ZodNativeEnum:Lo,ZodEffects:gs,ZodOptional:Qn,ZodNullable:es,ZodDiscriminatedUnion:Vn,ZodBranded:bs,ZodDate:is,ZodCatch:Fn,ZodPipeline:hs,ZodLazy:xs,ZodReadonly:Xn,[ee]:$n,[Ne]:Bn,[Ae]:ss,[we]:ns,[le]:Ss},dr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=t&&We(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=Ko(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},mr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},$o=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=$o(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},_o=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Vo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:S=`${e.toUpperCase()} ${t} ${Yt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:S};let g=_o(Ze(r,{rules:{...p,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,g,me(S)):g,examples:qo(r,!0)};return{description:S,content:d.fromPairs(d.xprod(o,[R]))}},Os=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ps=({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},ws=({name:e})=>({type:"apiKey",in:"header",name:e}),As=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Es=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),zs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Go=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Os(o):o.type==="input"?Ps(o,t):o.type==="header"?ws(o):o.type==="cookie"?As(o):o.type==="openid"?Es(o):zs(o);return e.map(o=>o.map(r))},Jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Wo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,S]=$o(Ze(r,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=_o(l),R={schema:s==="components"?n(r,g,me(p)):g,examples:qo(G(r),!1,c)},b={description:p,content:{[o]:R}};return(S||Tt(r))&&(b.required=!0),b},Yo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),lr=e=>e.length<=No?e:e.slice(0,No-1)+"\u2026",It=e=>e.length?e.slice():void 0;var vt=class extends Qo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||me(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:S=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let b of typeof s=="string"?[s]:s)this.addServer({url:b});Ve({routing:t,onEndpoint:(b,C,w)=>{let Q={path:C,method:w,endpoint:b,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:M,shortDescription:T,scopes:Z,inputSchema:j}=b,U=T?lr(T):S&&M?lr(M):void 0,P=r.inputSources?.[w]||Jt[w],_=this.#n(C,w,b.getOperationId(w)),v=Co(b.security),be=Bo({...Q,inputSources:P,isHeader:p,security:v,schema:j,description:a?.requestParameter?.call(null,{method:w,path:C,operationId:_})}),at={};for(let ie of De){let xe=b.getResponses(ie);for(let{mimeTypes:$t,schema:ct,statusCodes:dt}of xe)for(let _t of dt)at[_t]=Vo({...Q,variant:ie,schema:ct,mimeTypes:$t,statusCode:_t,hasMultipleStatusCodes:xe.length>1||dt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:w,path:C,operationId:_,statusCode:_t})})}let qt=P.includes("body")?Wo({...Q,paramNames:Xo.pluck("name",be),schema:j,mimeType:k[b.requestType],description:a?.requestBody?.call(null,{method:w,path:C,operationId:_})}):void 0,pt=Jo(Go(v,P),Z,ie=>{let xe=this.#s(ie);return this.addSecurityScheme(xe,ie),xe}),Bt={operationId:_,summary:U,description:M,deprecated:b.isDeprecated||void 0,tags:It(b.tags),parameters:It(be),requestBody:qt,security:It(pt),responses:at};this.addPath(Uo(C),{[w]:Bt})}}),m&&(this.rootDoc.tags=Yo(m))}};var kt=require("node-mocks-http");var Zs=e=>(0,kt.createRequest)({...e,headers:{"content-type":k.json,...e?.headers}}),Is=e=>(0,kt.createResponse)(e),vs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},en=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Zs(e),s=Is({req:n,...t});s.req=t?.req||n,n.res=s;let a=vs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},tn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=en(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},rn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ye}}=en(r),m=ft(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:de(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=h(require("ramda"),1),it=h(require("typescript"),1),mn=require("zod");var pn=h(require("ramda"),1),Y=h(require("typescript"),1);var on=["get","post","put","delete","patch"];var re=h(require("ramda"),1),u=h(require("typescript"),1),i=u.default.factory,Ct=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],ks=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],nt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ur=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),fr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Cs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yr=e=>typeof e=="string"&&Cs.test(e)?i.createIdentifier(e):z(e),jt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Nt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ge=e=>Object.entries(e).map(([t,r])=>Nt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),gr=(e,t=[])=>i.createConstructorDeclaration(nt.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,hr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,yr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?ur(s,a.join(" ")):s},br=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),xr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Ct,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),Sr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Ct:void 0,e,n&&Pr(n),t);return o?ur(s,o):s},nn=(e,t)=>i.createPropertyDeclaration(nt.public,e,void 0,f(t),void 0),Rr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(nt.public,void 0,e,void 0,o&&Pr(o),t,n,i.createBlock(r)),Tr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Ct,e,r&&Pr(r),void 0,t),Or=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Lt=e=>f(Promise.name,[e]),Mt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Ct:void 0,e,void 0,void 0,t);return o?ur(n,o):n},Pr=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ks:void 0,void 0,Array.isArray(e)?re.map(Nt,e):Ge(e),void 0,void 0,t),A=e=>e,st=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Je=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Ut=(e,t)=>f("Extract",[e,t]),wr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>i.createUnionTypeNode([f(e),Lt(e)]),Ar=(e,t)=>i.createFunctionTypeNode(void 0,Ge(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(z(e)),js=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>js.includes(e.kind);var Ht=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Sr("Method",on);someOfType=oe("SomeOf",W("T",Or("T")),{params:["T"]});requestType=oe("Request",Or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Mt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>L("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(yr(t),i.createArrayLiteralExpression(pn.map(z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,Ar({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Lt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>L(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr},i.createBlock([L(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Y.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([wr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(jt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>Rr(this.#e.provideMethod,Ge({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:W(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[L(xr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Lt(W(this.interfaces.response,"K"))});makeClientClass=t=>Tr(t,[gr([Nt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:nt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>jt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,jt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),st(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(k.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),st(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=L(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=L(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=L(this.#e.searchParamsConst,st(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=L(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=L(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(k.json))),l=i.createReturnStatement(E(this.#e.responseConst,st(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return L(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>gr(Ge({request:"K",params:W(this.interfaces.input,"K")}),[L(xr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),L(this.#e.searchParamsConst,this.#r(this.#e.restConst)),wr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(A("event"),t)]);#i=()=>Rr(this.#e.onMethod,Ge({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Ar({[this.#e.dataParameter.text]:W(Ut("R",br(this.#s("E"))),F(A("data")))},sn(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(A("event")))}});makeSubscriptionClass=t=>Tr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ut(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ut(W(this.interfaces.positive,"K"),br(this.#s(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.#e.clientConst,Je(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Je(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),ve(["time"],i.createBlock([])))]};var I=h(require("ramda"),1),x=h(require("typescript"),1),Dt=require("zod");var{factory:$}=x.default,Ns={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Er={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Ls=({value:e})=>F(e),Ms=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&We(a)?a instanceof Dt.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return $.createTypeLiteralNode(n)},Us=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Hs=({options:e})=>$.createUnionTypeNode(e.map(F)),cn=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(an(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},Ds=e=>Ns?.[e.kind],Ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=yt(e,Ds(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Fs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},Bs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),$s=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),_s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Vs=I.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(Er.name,...o))return!1;if(I.both(I.eqBy(Er.type),I.eqBy(Er.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Gs=({_def:{left:e,right:t}},{next:r})=>Vs([e,t].map(r)),Js=({_def:e},{next:t})=>t(e.innerType),he=e=>()=>f(e),Ws=(e,{next:t})=>t(e.unwrap()),Ys=(e,{next:t})=>t(e.unwrap()),Qs=({_def:e},{next:t})=>t(e.innerType),Xs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ei=()=>F(null),ti=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ri=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Dt.z.ZodString?r:t instanceof Dt.z.ZodUnion?n:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:he(x.default.SyntaxKind.StringKeyword),ZodNumber:he(x.default.SyntaxKind.NumberKeyword),ZodBigInt:he(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:he(x.default.SyntaxKind.BooleanKeyword),ZodAny:he(x.default.SyntaxKind.AnyKeyword),ZodUndefined:he(x.default.SyntaxKind.UndefinedKeyword),[we]:he(x.default.SyntaxKind.StringKeyword),[Ae]:he(x.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Us,ZodTuple:$s,ZodRecord:_s,ZodObject:Ms,ZodLiteral:Ls,ZodIntersection:Gs,ZodUnion:cn,ZodDefault:Js,ZodEnum:Hs,ZodNativeEnum:Fs,ZodEffects:Ks,ZodOptional:qs,ZodNullable:Bs,ZodDiscriminatedUnion:cn,ZodBranded:Ws,ZodCatch:Qs,ZodPipeline:Xs,ZodLazy:ti,ZodReadonly:Ys,[ee]:ri,[le]:oi},zr=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...ni},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Kt=class extends Ht{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=F(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=mn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},S={brandHandling:r,ctx:{...p,isResponse:!0}};Ve({routing:t,onEndpoint:(R,b,C)=>{let w=me.bind(null,C,b),{isDeprecated:Q,inputSchema:M,tags:T}=R,Z=`${C} ${b}`,j=oe(w("input"),zr(M,l),{comment:Z});this.#e.push(j);let U=De.reduce((v,be)=>{let at=R.getResponses(be),qt=dn.chain(([Bt,{schema:ie,mimeTypes:xe,statusCodes:$t}])=>{let ct=oe(w(be,"variant",`${Bt+1}`),zr(xe?ie:m,S),{comment:Z});return this.#e.push(ct),$t.map(dt=>Ie(dt,ct.name))},Array.from(at.entries())),pt=Mt(w(be,"response","variants"),qt,{comment:Z});return this.#e.push(pt),Object.assign(v,{[be]:pt})},{});this.paths.add(b);let P=F(Z),_={input:f(j.name),positive:this.someOf(U.positive),negative:this.someOf(U.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,P),W(this.interfaces.negative,P)]),encoded:i.createIntersectionTypeNode([f(U.positive.name),f(U.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:_}),this.tags.set(Z,T)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:fr(r,t)).join(`
18
+ `))};var zo=e=>{e.startupLogo!==!1&&wo(process.stdout);let t=e.errorHandler||ye,r=Qr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.0.0 (CJS)",env:process.env.NODE_ENV||"development"}),Oo(r);let o=Ro({logger:r,config:e}),s={getLogger:To(r),errorHandler:t},a=bo(s),c=ho(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return ar({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Io=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=zo(e),c=(0,ot.default)().disable("x-powered-by").use(a);if(e.compression){let g=await _e("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ot.default.json()],raw:[e.rawParser||ot.default.raw(),So],form:[e.formParser||ot.default.urlencoded()],upload:e.upload?await xo({config:e,getLogger:o}):[]};ar({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,R)=>()=>g.listen(R,()=>r.info("Listening",R)),S=[];if(e.http){let g=Ao.default.createServer(c);p.push(g),S.push(l(g,e.http.listen))}if(e.https){let g=Eo.default.createServer(e.https.options,c);p.push(g),S.push(l(g,e.https.listen))}return e.gracefulShutdown&&Po({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:S.map(g=>g())}};var Qo=require("openapi3-ts/oas31"),Xo=h(require("ramda"),1);var O=h(require("ramda"),1);var vo=e=>Te(e)&&"or"in e,ko=e=>Te(e)&&"and"in e,pr=e=>!ko(e)&&!vo(e),Co=e=>{let t=O.filter(pr,e),r=O.chain(O.prop("and"),O.filter(ko,e)),[o,n]=O.partition(pr,r),s=O.concat(t,o),a=O.filter(vo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>Re(m,O.map(l=>pr(l)?[l]:l.and,p),([l,S])=>O.concat(l,S)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=h(require("ramda"),1),K=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var jo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var No=50,Mo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Mn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Un=/^\d{4}-\d{2}-\d{2}$/,Hn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Dn=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$/,Uo=e=>e.replace(Gt,t=>`{${t.slice(1)}}`),Kn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Fn=({_def:{innerType:e}},{next:t})=>t(e),qn=()=>({format:"any"}),Bn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},$n=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},_n=({options:e},{next:t})=>({oneOf:e.map(t)}),Vn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Gn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Ho={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Gn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},Jn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Ho)),d.isEmpty)),Wn=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Jn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Ho);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Yn=({_def:{left:e,right:t}},{next:r})=>Wn([e,t].map(r)),Qn=(e,{next:t})=>t(e.unwrap()),Xn=(e,{next:t})=>t(e.unwrap()),es=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Ko(r)),r},Do=e=>{let t=d.toLower(d.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:Do(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ts=({value:e})=>({type:Do(e),const:e}),rs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&We(c)?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Zt(e,r)),s.length&&(a.required=s),a},os=()=>({type:"null"}),ns=({},e)=>{if(e.isResponse)throw new q("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:Mo}}},ss=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mo}}},is=({},e)=>{throw new q(`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)},as=()=>({type:"boolean"}),ps=()=>({type:"integer",format:"bigint"}),cs=e=>e.every(t=>t instanceof K.z.ZodLiteral),ds=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Zt(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Zt(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&cs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Zt(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ms=({_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},ls=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),us=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:S,isDate:g,isTime:R,isBase64:b,isNANOID:C,isBase64url:w,isDuration:Q,_def:{checks:M}})=>{let T=M.find(v=>v.kind==="regex"),Z=M.find(v=>v.kind==="datetime"),j=M.some(v=>v.kind==="jwt"),U=M.find(v=>v.kind==="length"),P={type:"string"},_={"date-time":l,byte:b,base64url:w,date:g,time:R,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:j,ip:m,cidr:S,emoji:p};for(let v in _)if(_[v]){P.format=v;break}return U&&([P.minLength,P.maxLength]=[U.value,U.value]),r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),g&&(P.pattern=Un.source),R&&(P.pattern=Hn.source),l&&(P.pattern=Dn(Z?.offset).source),T&&(P.pattern=T.regex.source),P},fs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(b=>b.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(b=>b.kind==="max"),S=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,R={type:e?"integer":"number",format:e?"int64":"double"};return p?R.minimum=m:R.exclusiveMinimum=m,g?R.maximum=S:R.exclusiveMaximum=S,R},Zt=({shape:e},t)=>d.map(t,e),ys=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Mn?.[t]},Ko=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",gs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=yt(e,ys(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},hs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ss=(e,{next:t})=>t(e.unwrap().shape.raw),Fo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,qo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Rs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ts=(e,t)=>t?.includes(e)||e.startsWith("x-")||jo.includes(e),Bo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let S=G(r),g=ut(e),R=o.includes("query"),b=o.includes("params"),C=o.includes("headers"),w=T=>b&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),M=T=>C&&(c?.(T,t,e)??Ts(T,Q));return Object.entries(S.shape).reduce((T,[Z,j])=>{let U=w(Z)?"path":M(Z)?"header":R?"query":void 0;if(!U)return T;let P=Ze(j,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),_=s==="components"?n(j,P,me(l,Z)):P,{_def:v}=j;return T.concat({name:Z,in:U,deprecated:v[y]?.isDeprecated,required:!j.isOptional(),description:P.description||l,schema:_,examples:Rs(S,Z)})},[])},cr={ZodString:us,ZodNumber:fs,ZodBigInt:ps,ZodBoolean:as,ZodNull:os,ZodArray:ms,ZodTuple:ls,ZodRecord:ds,ZodObject:rs,ZodLiteral:ts,ZodIntersection:Yn,ZodUnion:_n,ZodAny:qn,ZodDefault:Kn,ZodEnum:Lo,ZodNativeEnum:Lo,ZodEffects:gs,ZodOptional:Qn,ZodNullable:es,ZodDiscriminatedUnion:Vn,ZodBranded:bs,ZodDate:is,ZodCatch:Fn,ZodPipeline:hs,ZodLazy:xs,ZodReadonly:Xn,[ee]:$n,[Ne]:Bn,[Ae]:ss,[we]:ns,[le]:Ss},dr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=t&&We(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=Ko(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},mr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},$o=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=$o(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},_o=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Vo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:S=`${e.toUpperCase()} ${t} ${Yt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:S};let g=_o(Ze(r,{rules:{...p,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,g,me(S)):g,examples:qo(r,!0)};return{description:S,content:d.fromPairs(d.xprod(o,[R]))}},Os=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ps=({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},ws=({name:e})=>({type:"apiKey",in:"header",name:e}),As=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Es=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),zs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Go=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Os(o):o.type==="input"?Ps(o,t):o.type==="header"?ws(o):o.type==="cookie"?As(o):o.type==="openid"?Es(o):zs(o);return e.map(o=>o.map(r))},Jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Wo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,S]=$o(Ze(r,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=_o(l),R={schema:s==="components"?n(r,g,me(p)):g,examples:qo(G(r),!1,c)},b={description:p,content:{[o]:R}};return(S||Tt(r))&&(b.required=!0),b},Yo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),lr=e=>e.length<=No?e:e.slice(0,No-1)+"\u2026",It=e=>e.length?e.slice():void 0;var vt=class extends Qo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||me(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:S=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let b of typeof s=="string"?[s]:s)this.addServer({url:b});Ve({routing:t,onEndpoint:(b,C,w)=>{let Q={path:C,method:w,endpoint:b,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:M,shortDescription:T,scopes:Z,inputSchema:j}=b,U=T?lr(T):S&&M?lr(M):void 0,P=r.inputSources?.[w]||Jt[w],_=this.#n(C,w,b.getOperationId(w)),v=Co(b.security),be=Bo({...Q,inputSources:P,isHeader:p,security:v,schema:j,description:a?.requestParameter?.call(null,{method:w,path:C,operationId:_})}),at={};for(let ie of De){let xe=b.getResponses(ie);for(let{mimeTypes:$t,schema:ct,statusCodes:dt}of xe)for(let _t of dt)at[_t]=Vo({...Q,variant:ie,schema:ct,mimeTypes:$t,statusCode:_t,hasMultipleStatusCodes:xe.length>1||dt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:w,path:C,operationId:_,statusCode:_t})})}let qt=P.includes("body")?Wo({...Q,paramNames:Xo.pluck("name",be),schema:j,mimeType:k[b.requestType],description:a?.requestBody?.call(null,{method:w,path:C,operationId:_})}):void 0,pt=Jo(Go(v,P),Z,ie=>{let xe=this.#s(ie);return this.addSecurityScheme(xe,ie),xe}),Bt={operationId:_,summary:U,description:M,deprecated:b.isDeprecated||void 0,tags:It(b.tags),parameters:It(be),requestBody:qt,security:It(pt),responses:at};this.addPath(Uo(C),{[w]:Bt})}}),m&&(this.rootDoc.tags=Yo(m))}};var kt=require("node-mocks-http");var Zs=e=>(0,kt.createRequest)({...e,headers:{"content-type":k.json,...e?.headers}}),Is=e=>(0,kt.createResponse)(e),vs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},en=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Zs(e),s=Is({req:n,...t});s.req=t?.req||n,n.res=s;let a=vs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},tn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=en(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},rn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ye}}=en(r),m=ft(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:de(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=h(require("ramda"),1),it=h(require("typescript"),1),mn=require("zod");var pn=h(require("ramda"),1),Y=h(require("typescript"),1);var on=["get","post","put","delete","patch"];var re=h(require("ramda"),1),u=h(require("typescript"),1),i=u.default.factory,Ct=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],ks=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],nt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ur=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),fr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Cs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yr=e=>typeof e=="string"&&Cs.test(e)?i.createIdentifier(e):z(e),jt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Nt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ge=e=>Object.entries(e).map(([t,r])=>Nt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),gr=(e,t=[])=>i.createConstructorDeclaration(nt.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,hr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,yr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?ur(s,a.join(" ")):s},br=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),xr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Ct,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),Sr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Ct:void 0,e,n&&Pr(n),t);return o?ur(s,o):s},nn=(e,t)=>i.createPropertyDeclaration(nt.public,e,void 0,f(t),void 0),Rr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(nt.public,void 0,e,void 0,o&&Pr(o),t,n,i.createBlock(r)),Tr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Ct,e,r&&Pr(r),void 0,t),Or=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Lt=e=>f(Promise.name,[e]),Mt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Ct:void 0,e,void 0,void 0,t);return o?ur(n,o):n},Pr=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ks:void 0,void 0,Array.isArray(e)?re.map(Nt,e):Ge(e),void 0,void 0,t),A=e=>e,st=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Je=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Ut=(e,t)=>f("Extract",[e,t]),wr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>i.createUnionTypeNode([f(e),Lt(e)]),Ar=(e,t)=>i.createFunctionTypeNode(void 0,Ge(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(z(e)),js=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>js.includes(e.kind);var Ht=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Sr("Method",on);someOfType=oe("SomeOf",W("T",Or("T")),{params:["T"]});requestType=oe("Request",Or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Mt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>L("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(yr(t),i.createArrayLiteralExpression(pn.map(z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,Ar({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Lt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>L(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr},i.createBlock([L(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Y.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([wr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(jt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>Rr(this.#e.provideMethod,Ge({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:W(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[L(xr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Lt(W(this.interfaces.response,"K"))});makeClientClass=t=>Tr(t,[gr([Nt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:nt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>jt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,jt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),st(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(k.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),st(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=L(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=L(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=L(this.#e.searchParamsConst,st(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=L(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=L(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(k.json))),l=i.createReturnStatement(E(this.#e.responseConst,st(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return L(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>gr(Ge({request:"K",params:W(this.interfaces.input,"K")}),[L(xr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),L(this.#e.searchParamsConst,this.#r(this.#e.restConst)),wr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(A("event"),t)]);#i=()=>Rr(this.#e.onMethod,Ge({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Ar({[this.#e.dataParameter.text]:W(Ut("R",br(this.#s("E"))),F(A("data")))},sn(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(A("event")))}});makeSubscriptionClass=t=>Tr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ut(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ut(W(this.interfaces.positive,"K"),br(this.#s(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.#e.clientConst,Je(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Je(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),ve(["time"],i.createBlock([])))]};var I=h(require("ramda"),1),x=h(require("typescript"),1),Dt=require("zod");var{factory:$}=x.default,Ns={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Er={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Ls=({value:e})=>F(e),Ms=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&We(a)?a instanceof Dt.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return $.createTypeLiteralNode(n)},Us=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Hs=({options:e})=>$.createUnionTypeNode(e.map(F)),cn=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(an(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},Ds=e=>Ns?.[e.kind],Ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=yt(e,Ds(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Fs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},Bs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),$s=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),_s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Vs=I.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(Er.name,...o))return!1;if(I.both(I.eqBy(Er.type),I.eqBy(Er.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Gs=({_def:{left:e,right:t}},{next:r})=>Vs([e,t].map(r)),Js=({_def:e},{next:t})=>t(e.innerType),he=e=>()=>f(e),Ws=(e,{next:t})=>t(e.unwrap()),Ys=(e,{next:t})=>t(e.unwrap()),Qs=({_def:e},{next:t})=>t(e.innerType),Xs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ei=()=>F(null),ti=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ri=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Dt.z.ZodString?r:t instanceof Dt.z.ZodUnion?n:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:he(x.default.SyntaxKind.StringKeyword),ZodNumber:he(x.default.SyntaxKind.NumberKeyword),ZodBigInt:he(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:he(x.default.SyntaxKind.BooleanKeyword),ZodAny:he(x.default.SyntaxKind.AnyKeyword),ZodUndefined:he(x.default.SyntaxKind.UndefinedKeyword),[we]:he(x.default.SyntaxKind.StringKeyword),[Ae]:he(x.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Us,ZodTuple:$s,ZodRecord:_s,ZodObject:Ms,ZodLiteral:Ls,ZodIntersection:Gs,ZodUnion:cn,ZodDefault:Js,ZodEnum:Hs,ZodNativeEnum:Fs,ZodEffects:Ks,ZodOptional:qs,ZodNullable:Bs,ZodDiscriminatedUnion:cn,ZodBranded:Ws,ZodCatch:Qs,ZodPipeline:Xs,ZodLazy:ti,ZodReadonly:Ys,[ee]:ri,[le]:oi},zr=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...ni},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Kt=class extends Ht{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=F(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=mn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},S={brandHandling:r,ctx:{...p,isResponse:!0}};Ve({routing:t,onEndpoint:(R,b,C)=>{let w=me.bind(null,C,b),{isDeprecated:Q,inputSchema:M,tags:T}=R,Z=`${C} ${b}`,j=oe(w("input"),zr(M,l),{comment:Z});this.#e.push(j);let U=De.reduce((v,be)=>{let at=R.getResponses(be),qt=dn.chain(([Bt,{schema:ie,mimeTypes:xe,statusCodes:$t}])=>{let ct=oe(w(be,"variant",`${Bt+1}`),zr(xe?ie:m,S),{comment:Z});return this.#e.push(ct),$t.map(dt=>Ie(dt,ct.name))},Array.from(at.entries())),pt=Mt(w(be,"response","variants"),qt,{comment:Z});return this.#e.push(pt),Object.assign(v,{[be]:pt})},{});this.paths.add(b);let P=F(Z),_={input:f(j.name),positive:this.someOf(U.positive),negative:this.someOf(U.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,P),W(this.interfaces.negative,P)]),encoded:i.createIntersectionTypeNode([f(U.positive.name),f(U.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:_}),this.tags.set(Z,T)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:fr(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&it.default.addSyntheticLeadingComment(it.default.addSyntheticLeadingComment(i.createEmptyStatement(),it.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),it.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>fr(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ ${n}888${r}
15
15
  ${o}
16
16
  `;e.write(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var po=e=>{e.startupLogo!==!1&&ao(process.stdout);let t=e.errorHandler||Se,r=Hr(e.logger)?e.logger:new Ge(e.logger);r.debug("Running",{build:"v23.0.0-beta.1 (ESM)",env:process.env.NODE_ENV||"development"}),no(r);let o=ro({logger:r,config:e}),s={getLogger:oo(r),errorHandler:t},a=Xr(s),c=Qr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=po(e);return $t({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=po(e),c=St().disable("x-powered-by").use(a);if(e.compression){let g=await Le("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||St.json()],raw:[e.rawParser||St.raw(),to],form:[e.formParser||St.urlencoded()],upload:e.upload?await eo({config:e,getLogger:o}):[]};$t({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,S)=>()=>g.listen(S,()=>r.info("Listening",S)),b=[];if(e.http){let g=An.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=En.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&so({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};import{OpenApiBuilder as Os}from"openapi3-ts/oas31";import*as vo from"ramda";import*as T from"ramda";var co=e=>ue(e)&&"or"in e,mo=e=>ue(e)&&"and"in e,_t=e=>!mo(e)&&!co(e),lo=e=>{let t=T.filter(_t,e),r=T.chain(T.prop("and"),T.filter(mo,e)),[o,n]=T.partition(_t,r),s=T.concat(t,o),a=T.filter(co,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>le(m,T.map(l=>_t(l)?[l]:l.and,p),([l,b])=>T.concat(l,b)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as Vt,isSchemaObject as Tt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as K}from"zod";var Te=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Te(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var uo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var fo=50,go="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",vn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},kn=/^\d{4}-\d{2}-\d{2}$/,Cn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,jn=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$/,ho=e=>e.replace(Lt,t=>`{${t.slice(1)}}`),Nn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Ln=({_def:{innerType:e}},{next:t})=>t(e),Mn=()=>({format:"any"}),Un=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Dn=({options:e},{next:t})=>({oneOf:e.map(t)}),Kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Fn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},bo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Fn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>le(e,t,([r,o])=>d.mergeDeepRight(r,o))},qn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(bo)),d.isEmpty)),Bn=d.tryCatch(e=>{let[t,r]=e.filter(Tt).filter(qn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,bo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),$n=({_def:{left:e,right:t}},{next:r})=>Bn([e,t].map(r)),_n=(e,{next:t})=>t(e.unwrap()),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>{let r=t(e.unwrap());return Tt(r)&&(r.type=So(r)),r},xo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},yo=e=>({type:xo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jn=({value:e})=>({type:xo(e),const:e}),Wn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Fe(c)?c instanceof K.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Rt(e,r)),s.length&&(a.required=s),a},Yn=()=>({type:"null"}),Qn=({},e)=>{if(e.isResponse)throw new B("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:go}}},Xn=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:go}}},es=({},e)=>{throw new B(`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)},ts=()=>({type:"boolean"}),rs=()=>({type:"integer",format:"bigint"}),os=e=>e.every(t=>t instanceof K.ZodLiteral),ns=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.ZodEnum||e instanceof K.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Rt(K.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.ZodLiteral)return{type:"object",properties:Rt(K.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.ZodUnion&&os(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Rt(K.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ss=({_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},is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),as=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:S,isBase64:h,isNANOID:k,isBase64url:P,isDuration:V,_def:{checks:L}})=>{let R=L.find(I=>I.kind==="regex"),z=L.find(I=>I.kind==="datetime"),C=L.some(I=>I.kind==="jwt"),M=L.find(I=>I.kind==="length"),O={type:"string"},q={"date-time":l,byte:h,base64url:P,date:g,time:S,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:k,jwt:C,ip:m,cidr:b,emoji:p};for(let I in q)if(q[I]){O.format=I;break}return M&&([O.minLength,O.maxLength]=[M.value,M.value]),r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),g&&(O.pattern=kn.source),S&&(O.pattern=Cn.source),l&&(O.pattern=jn(z?.offset).source),R&&(O.pattern=R.regex.source),O},ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(h=>h.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(h=>h.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,S={type:e?"integer":"number",format:e?"int64":"double"};return p?S.minimum=m:S.exclusiveMinimum=m,g?S.maximum=b:S.exclusiveMaximum=b,S},Rt=({shape:e},t)=>d.map(t,e),cs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return vn?.[t]},So=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ds=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&Tt(o)){let s=it(e,cs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.any())}if(!t&&n.type==="preprocess"&&Tt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ms=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ls=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),fs=(e,{next:t})=>t(e.unwrap().shape.raw),Ro=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,To=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Ro)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ys=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Ro)({schema:e,variant:"original",validate:!0,pullProps:!0}),gs=(e,t)=>t?.includes(e)||e.startsWith("x-")||uo.includes(e),Oo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=$(r),g=nt(e),S=o.includes("query"),h=o.includes("params"),k=o.includes("headers"),P=R=>h&&g.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),L=R=>k&&(c?.(R,t,e)??gs(R,V));return Object.entries(b.shape).reduce((R,[z,C])=>{let M=P(z)?"path":L(z)?"header":S?"query":void 0;if(!M)return R;let O=Te(C,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(C,O,se(l,z)):O,{_def:I}=C;return R.concat({name:z,in:M,deprecated:I[y]?.isDeprecated,required:!C.isOptional(),description:O.description||l,schema:q,examples:ys(b,z)})},[])},Gt={ZodString:as,ZodNumber:ps,ZodBigInt:rs,ZodBoolean:ts,ZodNull:Yn,ZodArray:ss,ZodTuple:is,ZodRecord:ns,ZodObject:Wn,ZodLiteral:Jn,ZodIntersection:$n,ZodUnion:Dn,ZodAny:Mn,ZodDefault:Nn,ZodEnum:yo,ZodNativeEnum:yo,ZodEffects:ds,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:Kn,ZodBranded:ls,ZodDate:es,ZodCatch:Ln,ZodPipeline:ms,ZodLazy:us,ZodReadonly:Vn,[G]:Hn,[Ee]:Un,[ge]:Xn,[ye]:Qn,[ie]:fs},Jt=(e,{isResponse:t,prev:r})=>{if(Vt(r))return{};let{description:o,_def:n}=e,s=e instanceof K.ZodLazy,a=r.type!==void 0,c=t&&Fe(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=So(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},Wt=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Po=(e,t)=>{if(Vt(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Po(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},wo=e=>Vt(e)?e:d.omit(["examples"],e),Ao=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Ht(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=wo(Te(r,{rules:{...p,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),S={schema:a==="components"?s(r,g,se(b)):g,examples:To(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[S]))}},hs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},bs=({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},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),Ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ts=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Eo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?hs(o):o.type==="input"?bs(o,t):o.type==="header"?xs(o):o.type==="cookie"?Ss(o):o.type==="openid"?Rs(o):Ts(o);return e.map(o=>o.map(r))},zo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Zo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Po(Te(r,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=wo(l),S={schema:s==="components"?n(r,g,se(p)):g,examples:To($(r),!1,c)},h={description:p,content:{[o]:S}};return(b||ft(r))&&(h.required=!0),h},Io=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Yt=e=>e.length<=fo?e:e.slice(0,fo-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Qt=class extends Os{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});Me({routing:t,onEndpoint:(h,k,P)=>{let V={path:k,method:P,endpoint:h,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:L,shortDescription:R,scopes:z,inputSchema:C}=h,M=R?Yt(R):b&&L?Yt(L):void 0,O=r.inputSources?.[P]||Mt[P],q=this.#n(k,P,h.getOperationId(P)),I=lo(h.security),pe=Oo({...V,inputSources:O,isHeader:p,security:I,schema:C,description:a?.requestParameter?.call(null,{method:P,path:k,operationId:q})}),Xe={};for(let te of Ce){let ce=h.getResponses(te);for(let{mimeTypes:jt,schema:tt,statusCodes:rt}of ce)for(let Nt of rt)Xe[Nt]=Ao({...V,variant:te,schema:tt,mimeTypes:jt,statusCode:Nt,hasMultipleStatusCodes:ce.length>1||rt.length>1,description:a?.[`${te}Response`]?.call(null,{method:P,path:k,operationId:q,statusCode:Nt})})}let kt=O.includes("body")?Zo({...V,paramNames:vo.pluck("name",pe),schema:C,mimeType:v[h.requestType],description:a?.requestBody?.call(null,{method:P,path:k,operationId:q})}):void 0,et=zo(Eo(I,O),z,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),Ct={operationId:q,summary:M,description:L,deprecated:h.isDeprecated||void 0,tags:Ot(h.tags),parameters:Ot(pe),requestBody:kt,security:Ot(et),responses:Xe};this.addPath(ho(k),{[P]:Ct})}}),m&&(this.rootDoc.tags=Io(m))}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var As=e=>Ps({...e,headers:{"content-type":v.json,...e?.headers}}),Es=e=>ws(e),zs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},ko=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),s=Es({req:n,...t});s.req=t?.req||n,n.res=s;let a=zs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=ko(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Is=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Se}}=ko(r),m=st(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import vt from"typescript";import{z as ni}from"zod";import*as Mo from"ramda";import X from"typescript";var Co=["get","post","put","delete","patch"];import*as Y from"ramda";import u from"typescript";var i=u.factory,Pt=[i.createModifier(u.SyntaxKind.ExportKeyword)],vs=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Xt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),er=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},ks=/^[A-Za-z_$][A-Za-z0-9_$]*$/,tr=e=>typeof e=="string"&&ks.test(e)?i.createIdentifier(e):E(e),wt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),At=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ue=e=>Object.entries(e).map(([t,r])=>At(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),rr=(e,t=[])=>i.createConstructorDeclaration(Ye.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,or=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,tr(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Xt(s,a.join(" ")):s},nr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),sr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Pt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),ir=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(D,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Pt:void 0,e,n&&dr(n),t);return o?Xt(s,o):s},jo=(e,t)=>i.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),ar=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&dr(o),t,n,i.createBlock(r)),pr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Pt,e,r&&dr(r),void 0,t),cr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Et=e=>f(Promise.name,[e]),zt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Pt:void 0,e,void 0,void 0,t);return o?Xt(n,o):n},dr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Pe=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?vs:void 0,void 0,Array.isArray(e)?Y.map(At,e):Ue(e),void 0,void 0,t),w=e=>e,Qe=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),He=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Zt=(e,t)=>f("Extract",[e,t]),mr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),No=e=>i.createUnionTypeNode([f(e),Et(e)]),lr=(e,t)=>i.createFunctionTypeNode(void 0,Ue(e),f(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),D=e=>i.createLiteralTypeNode(E(e)),Cs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Lo=e=>Cs.includes(e.kind);var It=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=ir("Method",Co);someOfType=Q("SomeOf",_("T",cr("T")),{params:["T"]});requestType=Q("Request",cr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>ir(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>zt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(tr(t),i.createArrayLiteralExpression(Mo.map(E,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,lr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Et(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Pe({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(A(this.#e.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,Pe({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([mr(this.#e.pathParameter,A(this.#e.pathParameter,w("replace"))(wt(":",[this.#e.keyParameter]),Pe([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ar(this.#e.provideMethod,Ue({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(sr(this.#e.methodParameter,this.#e.pathParameter),A(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(A(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(A(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Et(_(this.interfaces.response,"K"))});makeClientClass=t=>pr(t,[rr([At(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>wt("?",[He(URLSearchParams.name,t)]);#o=()=>He(URL.name,wt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.#e.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),Qe(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(v.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(w("body"),Qe(this.#e.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(A(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,E(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,A(this.#e.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,A(this.#e.contentTypeConst,w("startsWith"))(E(v.json))),l=i.createReturnStatement(A(this.#e.responseConst,Qe(this.#e.isJsonConst,E(w("json")),E(w("text"))))());return j(this.#e.defaultImplementationConst,Pe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>rr(Ue({request:"K",params:_(this.interfaces.input,"K")}),[j(sr(this.#e.pathParameter,this.#e.restConst),A(this.#e.substituteFn)(i.createElementAccessExpression(A(this.#e.parseRequestFn)(this.#e.requestParameter),E(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),mr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),He("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Oe(w("event"),t)]);#i=()=>ar(this.#e.onMethod,Ue({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:lr({[this.#e.dataParameter.text]:_(Zt("R",nr(this.#s("E"))),D(w("data")))},No(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,Pe([this.#e.msgParameter],A(this.#e.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",D(w("event")))}});makeSubscriptionClass=t=>pr(t,[jo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Zt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Zt(_(this.interfaces.positive,"K"),nr(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,He(t)),A(this.#e.clientConst,this.#e.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(He(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(E("time"),Pe(["time"],i.createBlock([])))]};import*as Z from"ramda";import x from"typescript";import{z as fr}from"zod";var{factory:F}=x,js={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},ur={name:Z.path(["name","text"]),type:Z.path(["type"]),optional:Z.path(["questionToken"])},Ns=({value:e})=>D(e),Ls=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&Fe(a)?a instanceof fr.ZodOptional:a.isOptional();return Oe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return F.createTypeLiteralNode(n)},Ms=({element:e},{next:t})=>F.createArrayTypeNode(t(e)),Us=({options:e})=>F.createUnionTypeNode(e.map(D)),Uo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Lo(n)?n.kind:n,n)}return F.createUnionTypeNode(Array.from(r.values()))},Hs=e=>js?.[e.kind],Ds=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=it(e,Hs(o)),s={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.SyntaxKind.AnyKeyword)}return o},Ks=e=>F.createUnionTypeNode(Object.values(e.enum).map(D)),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?F.createUnionTypeNode([o,f(x.SyntaxKind.UndefinedKeyword)]):o},qs=(e,{next:t})=>F.createUnionTypeNode([t(e.unwrap()),D(null)]),Bs=({items:e,_def:{rest:t}},{next:r})=>F.createTupleTypeNode(e.map(r).concat(t===null?[]:F.createRestTypeNode(r(t)))),$s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),_s=Z.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=Z.chain(Z.prop("members"),e),r=Z.uniqWith((...o)=>{if(!Z.eqBy(ur.name,...o))return!1;if(Z.both(Z.eqBy(ur.type),Z.eqBy(ur.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Vs=({_def:{left:e,right:t}},{next:r})=>_s([e,t].map(r)),Gs=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),Js=(e,{next:t})=>t(e.unwrap()),Ws=(e,{next:t})=>t(e.unwrap()),Ys=({_def:e},{next:t})=>t(e.innerType),Qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Xs=()=>D(null),ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ti=e=>{let t=e.unwrap(),r=f(x.SyntaxKind.StringKeyword),o=f("Buffer"),n=F.createUnionTypeNode([r,o]);return t instanceof fr.ZodString?r:t instanceof fr.ZodUnion?n:o},ri=(e,{next:t})=>t(e.unwrap().shape.raw),oi={ZodString:ae(x.SyntaxKind.StringKeyword),ZodNumber:ae(x.SyntaxKind.NumberKeyword),ZodBigInt:ae(x.SyntaxKind.BigIntKeyword),ZodBoolean:ae(x.SyntaxKind.BooleanKeyword),ZodAny:ae(x.SyntaxKind.AnyKeyword),ZodUndefined:ae(x.SyntaxKind.UndefinedKeyword),[ye]:ae(x.SyntaxKind.StringKeyword),[ge]:ae(x.SyntaxKind.StringKeyword),ZodNull:Xs,ZodArray:Ms,ZodTuple:Bs,ZodRecord:$s,ZodObject:Ls,ZodLiteral:Ns,ZodIntersection:Vs,ZodUnion:Uo,ZodDefault:Gs,ZodEnum:Us,ZodNativeEnum:Ks,ZodEffects:Ds,ZodOptional:Fs,ZodNullable:qs,ZodDiscriminatedUnion:Uo,ZodBranded:Js,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:ei,ZodReadonly:Ws,[G]:ti,[ie]:ri},yr=(e,{brandHandling:t,ctx:r})=>Te(e,{rules:{...t,...oi},onMissing:()=>f(x.SyntaxKind.AnyKeyword),ctx:r});var gr=class extends It{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=D(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=ni.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(S,h,k)=>{let P=se.bind(null,k,h),{isDeprecated:V,inputSchema:L,tags:R}=S,z=`${k} ${h}`,C=Q(P("input"),yr(L,l),{comment:z});this.#e.push(C);let M=Ce.reduce((I,pe)=>{let Xe=S.getResponses(pe),kt=Ho.chain(([Ct,{schema:te,mimeTypes:ce,statusCodes:jt}])=>{let tt=Q(P(pe,"variant",`${Ct+1}`),yr(ce?te:m,b),{comment:z});return this.#e.push(tt),jt.map(rt=>Oe(rt,tt.name))},Array.from(Xe.entries())),et=zt(P(pe,"response","variants"),kt,{comment:z});return this.#e.push(et),Object.assign(I,{[pe]:et})},{});this.paths.add(h);let O=D(z),q={input:f(C.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,O),_(this.interfaces.negative,O)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(z,{isDeprecated:V,store:q}),this.tags.set(z,R)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:er(r,t)).join(`
18
+ `))};var po=e=>{e.startupLogo!==!1&&ao(process.stdout);let t=e.errorHandler||Se,r=Hr(e.logger)?e.logger:new Ge(e.logger);r.debug("Running",{build:"v23.0.0 (ESM)",env:process.env.NODE_ENV||"development"}),no(r);let o=ro({logger:r,config:e}),s={getLogger:oo(r),errorHandler:t},a=Xr(s),c=Qr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=po(e);return $t({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=po(e),c=St().disable("x-powered-by").use(a);if(e.compression){let g=await Le("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||St.json()],raw:[e.rawParser||St.raw(),to],form:[e.formParser||St.urlencoded()],upload:e.upload?await eo({config:e,getLogger:o}):[]};$t({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,S)=>()=>g.listen(S,()=>r.info("Listening",S)),b=[];if(e.http){let g=An.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=En.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&so({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};import{OpenApiBuilder as Os}from"openapi3-ts/oas31";import*as vo from"ramda";import*as T from"ramda";var co=e=>ue(e)&&"or"in e,mo=e=>ue(e)&&"and"in e,_t=e=>!mo(e)&&!co(e),lo=e=>{let t=T.filter(_t,e),r=T.chain(T.prop("and"),T.filter(mo,e)),[o,n]=T.partition(_t,r),s=T.concat(t,o),a=T.filter(co,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>le(m,T.map(l=>_t(l)?[l]:l.and,p),([l,b])=>T.concat(l,b)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as Vt,isSchemaObject as Tt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as K}from"zod";var Te=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Te(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var uo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var fo=50,go="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",vn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},kn=/^\d{4}-\d{2}-\d{2}$/,Cn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,jn=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$/,ho=e=>e.replace(Lt,t=>`{${t.slice(1)}}`),Nn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Ln=({_def:{innerType:e}},{next:t})=>t(e),Mn=()=>({format:"any"}),Un=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Dn=({options:e},{next:t})=>({oneOf:e.map(t)}),Kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Fn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},bo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Fn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>le(e,t,([r,o])=>d.mergeDeepRight(r,o))},qn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(bo)),d.isEmpty)),Bn=d.tryCatch(e=>{let[t,r]=e.filter(Tt).filter(qn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,bo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),$n=({_def:{left:e,right:t}},{next:r})=>Bn([e,t].map(r)),_n=(e,{next:t})=>t(e.unwrap()),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>{let r=t(e.unwrap());return Tt(r)&&(r.type=So(r)),r},xo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},yo=e=>({type:xo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jn=({value:e})=>({type:xo(e),const:e}),Wn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Fe(c)?c instanceof K.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Rt(e,r)),s.length&&(a.required=s),a},Yn=()=>({type:"null"}),Qn=({},e)=>{if(e.isResponse)throw new B("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:go}}},Xn=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:go}}},es=({},e)=>{throw new B(`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)},ts=()=>({type:"boolean"}),rs=()=>({type:"integer",format:"bigint"}),os=e=>e.every(t=>t instanceof K.ZodLiteral),ns=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.ZodEnum||e instanceof K.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Rt(K.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.ZodLiteral)return{type:"object",properties:Rt(K.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.ZodUnion&&os(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Rt(K.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ss=({_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},is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),as=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:S,isBase64:h,isNANOID:k,isBase64url:P,isDuration:V,_def:{checks:L}})=>{let R=L.find(I=>I.kind==="regex"),z=L.find(I=>I.kind==="datetime"),C=L.some(I=>I.kind==="jwt"),M=L.find(I=>I.kind==="length"),O={type:"string"},q={"date-time":l,byte:h,base64url:P,date:g,time:S,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:k,jwt:C,ip:m,cidr:b,emoji:p};for(let I in q)if(q[I]){O.format=I;break}return M&&([O.minLength,O.maxLength]=[M.value,M.value]),r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),g&&(O.pattern=kn.source),S&&(O.pattern=Cn.source),l&&(O.pattern=jn(z?.offset).source),R&&(O.pattern=R.regex.source),O},ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(h=>h.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(h=>h.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,S={type:e?"integer":"number",format:e?"int64":"double"};return p?S.minimum=m:S.exclusiveMinimum=m,g?S.maximum=b:S.exclusiveMaximum=b,S},Rt=({shape:e},t)=>d.map(t,e),cs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return vn?.[t]},So=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ds=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&Tt(o)){let s=it(e,cs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.any())}if(!t&&n.type==="preprocess"&&Tt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ms=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ls=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),fs=(e,{next:t})=>t(e.unwrap().shape.raw),Ro=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,To=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Ro)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ys=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Ro)({schema:e,variant:"original",validate:!0,pullProps:!0}),gs=(e,t)=>t?.includes(e)||e.startsWith("x-")||uo.includes(e),Oo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=$(r),g=nt(e),S=o.includes("query"),h=o.includes("params"),k=o.includes("headers"),P=R=>h&&g.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),L=R=>k&&(c?.(R,t,e)??gs(R,V));return Object.entries(b.shape).reduce((R,[z,C])=>{let M=P(z)?"path":L(z)?"header":S?"query":void 0;if(!M)return R;let O=Te(C,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(C,O,se(l,z)):O,{_def:I}=C;return R.concat({name:z,in:M,deprecated:I[y]?.isDeprecated,required:!C.isOptional(),description:O.description||l,schema:q,examples:ys(b,z)})},[])},Gt={ZodString:as,ZodNumber:ps,ZodBigInt:rs,ZodBoolean:ts,ZodNull:Yn,ZodArray:ss,ZodTuple:is,ZodRecord:ns,ZodObject:Wn,ZodLiteral:Jn,ZodIntersection:$n,ZodUnion:Dn,ZodAny:Mn,ZodDefault:Nn,ZodEnum:yo,ZodNativeEnum:yo,ZodEffects:ds,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:Kn,ZodBranded:ls,ZodDate:es,ZodCatch:Ln,ZodPipeline:ms,ZodLazy:us,ZodReadonly:Vn,[G]:Hn,[Ee]:Un,[ge]:Xn,[ye]:Qn,[ie]:fs},Jt=(e,{isResponse:t,prev:r})=>{if(Vt(r))return{};let{description:o,_def:n}=e,s=e instanceof K.ZodLazy,a=r.type!==void 0,c=t&&Fe(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=So(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},Wt=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Po=(e,t)=>{if(Vt(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Po(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},wo=e=>Vt(e)?e:d.omit(["examples"],e),Ao=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Ht(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=wo(Te(r,{rules:{...p,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),S={schema:a==="components"?s(r,g,se(b)):g,examples:To(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[S]))}},hs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},bs=({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},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),Ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ts=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Eo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?hs(o):o.type==="input"?bs(o,t):o.type==="header"?xs(o):o.type==="cookie"?Ss(o):o.type==="openid"?Rs(o):Ts(o);return e.map(o=>o.map(r))},zo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Zo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Po(Te(r,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=wo(l),S={schema:s==="components"?n(r,g,se(p)):g,examples:To($(r),!1,c)},h={description:p,content:{[o]:S}};return(b||ft(r))&&(h.required=!0),h},Io=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Yt=e=>e.length<=fo?e:e.slice(0,fo-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Qt=class extends Os{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});Me({routing:t,onEndpoint:(h,k,P)=>{let V={path:k,method:P,endpoint:h,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:L,shortDescription:R,scopes:z,inputSchema:C}=h,M=R?Yt(R):b&&L?Yt(L):void 0,O=r.inputSources?.[P]||Mt[P],q=this.#n(k,P,h.getOperationId(P)),I=lo(h.security),pe=Oo({...V,inputSources:O,isHeader:p,security:I,schema:C,description:a?.requestParameter?.call(null,{method:P,path:k,operationId:q})}),Xe={};for(let te of Ce){let ce=h.getResponses(te);for(let{mimeTypes:jt,schema:tt,statusCodes:rt}of ce)for(let Nt of rt)Xe[Nt]=Ao({...V,variant:te,schema:tt,mimeTypes:jt,statusCode:Nt,hasMultipleStatusCodes:ce.length>1||rt.length>1,description:a?.[`${te}Response`]?.call(null,{method:P,path:k,operationId:q,statusCode:Nt})})}let kt=O.includes("body")?Zo({...V,paramNames:vo.pluck("name",pe),schema:C,mimeType:v[h.requestType],description:a?.requestBody?.call(null,{method:P,path:k,operationId:q})}):void 0,et=zo(Eo(I,O),z,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),Ct={operationId:q,summary:M,description:L,deprecated:h.isDeprecated||void 0,tags:Ot(h.tags),parameters:Ot(pe),requestBody:kt,security:Ot(et),responses:Xe};this.addPath(ho(k),{[P]:Ct})}}),m&&(this.rootDoc.tags=Io(m))}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var As=e=>Ps({...e,headers:{"content-type":v.json,...e?.headers}}),Es=e=>ws(e),zs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},ko=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),s=Es({req:n,...t});s.req=t?.req||n,n.res=s;let a=zs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=ko(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Is=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Se}}=ko(r),m=st(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import vt from"typescript";import{z as ni}from"zod";import*as Mo from"ramda";import X from"typescript";var Co=["get","post","put","delete","patch"];import*as Y from"ramda";import u from"typescript";var i=u.factory,Pt=[i.createModifier(u.SyntaxKind.ExportKeyword)],vs=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Xt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),er=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},ks=/^[A-Za-z_$][A-Za-z0-9_$]*$/,tr=e=>typeof e=="string"&&ks.test(e)?i.createIdentifier(e):E(e),wt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),At=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ue=e=>Object.entries(e).map(([t,r])=>At(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),rr=(e,t=[])=>i.createConstructorDeclaration(Ye.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,or=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,tr(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Xt(s,a.join(" ")):s},nr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),sr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Pt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),ir=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(D,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Pt:void 0,e,n&&dr(n),t);return o?Xt(s,o):s},jo=(e,t)=>i.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),ar=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&dr(o),t,n,i.createBlock(r)),pr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Pt,e,r&&dr(r),void 0,t),cr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Et=e=>f(Promise.name,[e]),zt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Pt:void 0,e,void 0,void 0,t);return o?Xt(n,o):n},dr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Pe=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?vs:void 0,void 0,Array.isArray(e)?Y.map(At,e):Ue(e),void 0,void 0,t),w=e=>e,Qe=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),He=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Zt=(e,t)=>f("Extract",[e,t]),mr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),No=e=>i.createUnionTypeNode([f(e),Et(e)]),lr=(e,t)=>i.createFunctionTypeNode(void 0,Ue(e),f(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),D=e=>i.createLiteralTypeNode(E(e)),Cs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Lo=e=>Cs.includes(e.kind);var It=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=ir("Method",Co);someOfType=Q("SomeOf",_("T",cr("T")),{params:["T"]});requestType=Q("Request",cr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>ir(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>zt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(tr(t),i.createArrayLiteralExpression(Mo.map(E,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,lr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Et(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Pe({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(A(this.#e.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,Pe({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([mr(this.#e.pathParameter,A(this.#e.pathParameter,w("replace"))(wt(":",[this.#e.keyParameter]),Pe([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ar(this.#e.provideMethod,Ue({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(sr(this.#e.methodParameter,this.#e.pathParameter),A(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(A(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(A(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Et(_(this.interfaces.response,"K"))});makeClientClass=t=>pr(t,[rr([At(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>wt("?",[He(URLSearchParams.name,t)]);#o=()=>He(URL.name,wt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.#e.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),Qe(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(v.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(w("body"),Qe(this.#e.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(A(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,E(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,A(this.#e.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,A(this.#e.contentTypeConst,w("startsWith"))(E(v.json))),l=i.createReturnStatement(A(this.#e.responseConst,Qe(this.#e.isJsonConst,E(w("json")),E(w("text"))))());return j(this.#e.defaultImplementationConst,Pe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>rr(Ue({request:"K",params:_(this.interfaces.input,"K")}),[j(sr(this.#e.pathParameter,this.#e.restConst),A(this.#e.substituteFn)(i.createElementAccessExpression(A(this.#e.parseRequestFn)(this.#e.requestParameter),E(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),mr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),He("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Oe(w("event"),t)]);#i=()=>ar(this.#e.onMethod,Ue({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:lr({[this.#e.dataParameter.text]:_(Zt("R",nr(this.#s("E"))),D(w("data")))},No(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,Pe([this.#e.msgParameter],A(this.#e.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",D(w("event")))}});makeSubscriptionClass=t=>pr(t,[jo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Zt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Zt(_(this.interfaces.positive,"K"),nr(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,He(t)),A(this.#e.clientConst,this.#e.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(He(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(E("time"),Pe(["time"],i.createBlock([])))]};import*as Z from"ramda";import x from"typescript";import{z as fr}from"zod";var{factory:F}=x,js={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},ur={name:Z.path(["name","text"]),type:Z.path(["type"]),optional:Z.path(["questionToken"])},Ns=({value:e})=>D(e),Ls=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&Fe(a)?a instanceof fr.ZodOptional:a.isOptional();return Oe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return F.createTypeLiteralNode(n)},Ms=({element:e},{next:t})=>F.createArrayTypeNode(t(e)),Us=({options:e})=>F.createUnionTypeNode(e.map(D)),Uo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Lo(n)?n.kind:n,n)}return F.createUnionTypeNode(Array.from(r.values()))},Hs=e=>js?.[e.kind],Ds=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=it(e,Hs(o)),s={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.SyntaxKind.AnyKeyword)}return o},Ks=e=>F.createUnionTypeNode(Object.values(e.enum).map(D)),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?F.createUnionTypeNode([o,f(x.SyntaxKind.UndefinedKeyword)]):o},qs=(e,{next:t})=>F.createUnionTypeNode([t(e.unwrap()),D(null)]),Bs=({items:e,_def:{rest:t}},{next:r})=>F.createTupleTypeNode(e.map(r).concat(t===null?[]:F.createRestTypeNode(r(t)))),$s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),_s=Z.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=Z.chain(Z.prop("members"),e),r=Z.uniqWith((...o)=>{if(!Z.eqBy(ur.name,...o))return!1;if(Z.both(Z.eqBy(ur.type),Z.eqBy(ur.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Vs=({_def:{left:e,right:t}},{next:r})=>_s([e,t].map(r)),Gs=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),Js=(e,{next:t})=>t(e.unwrap()),Ws=(e,{next:t})=>t(e.unwrap()),Ys=({_def:e},{next:t})=>t(e.innerType),Qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Xs=()=>D(null),ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ti=e=>{let t=e.unwrap(),r=f(x.SyntaxKind.StringKeyword),o=f("Buffer"),n=F.createUnionTypeNode([r,o]);return t instanceof fr.ZodString?r:t instanceof fr.ZodUnion?n:o},ri=(e,{next:t})=>t(e.unwrap().shape.raw),oi={ZodString:ae(x.SyntaxKind.StringKeyword),ZodNumber:ae(x.SyntaxKind.NumberKeyword),ZodBigInt:ae(x.SyntaxKind.BigIntKeyword),ZodBoolean:ae(x.SyntaxKind.BooleanKeyword),ZodAny:ae(x.SyntaxKind.AnyKeyword),ZodUndefined:ae(x.SyntaxKind.UndefinedKeyword),[ye]:ae(x.SyntaxKind.StringKeyword),[ge]:ae(x.SyntaxKind.StringKeyword),ZodNull:Xs,ZodArray:Ms,ZodTuple:Bs,ZodRecord:$s,ZodObject:Ls,ZodLiteral:Ns,ZodIntersection:Vs,ZodUnion:Uo,ZodDefault:Gs,ZodEnum:Us,ZodNativeEnum:Ks,ZodEffects:Ds,ZodOptional:Fs,ZodNullable:qs,ZodDiscriminatedUnion:Uo,ZodBranded:Js,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:ei,ZodReadonly:Ws,[G]:ti,[ie]:ri},yr=(e,{brandHandling:t,ctx:r})=>Te(e,{rules:{...t,...oi},onMissing:()=>f(x.SyntaxKind.AnyKeyword),ctx:r});var gr=class extends It{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=D(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=ni.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(S,h,k)=>{let P=se.bind(null,k,h),{isDeprecated:V,inputSchema:L,tags:R}=S,z=`${k} ${h}`,C=Q(P("input"),yr(L,l),{comment:z});this.#e.push(C);let M=Ce.reduce((I,pe)=>{let Xe=S.getResponses(pe),kt=Ho.chain(([Ct,{schema:te,mimeTypes:ce,statusCodes:jt}])=>{let tt=Q(P(pe,"variant",`${Ct+1}`),yr(ce?te:m,b),{comment:z});return this.#e.push(tt),jt.map(rt=>Oe(rt,tt.name))},Array.from(Xe.entries())),et=zt(P(pe,"response","variants"),kt,{comment:z});return this.#e.push(et),Object.assign(I,{[pe]:et})},{});this.paths.add(h);let O=D(z),q={input:f(C.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,O),_(this.interfaces.negative,O)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(z,{isDeprecated:V,store:q}),this.tags.set(z,R)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:er(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&vt.addSyntheticLeadingComment(vt.addSyntheticLeadingComment(i.createEmptyStatement(),vt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),vt.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>er(n,s<this.#e.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": "23.0.0-beta.1",
3
+ "version": "23.0.0",
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": {