npm package diff

Package: express-zod-api

Versions: 22.6.0 - 22.7.0-beta.0

File: package/dist/index.js

Index: package/dist/index.js
===================================================================
--- package/dist/index.js
+++ package/dist/index.js
@@ -14,9 +14,9 @@
 ${n}888${r}
 ${o}
 `;e.write(d.split(`
 `).map((p,m)=>c[m]?c[m](p):p).join(`
-`))};var Wr=e=>{e.startupLogo!==!1&&Jr(process.stdout);let t=e.errorHandler||Ne,r=zr(e.logger)?e.logger:new Le(e.logger);r.debug("Running",{build:"v22.6.0 (ESM)",env:process.env.NODE_ENV||"development"}),_r(r);let o=$r({logger:r,config:e}),s={getLogger:Vr(r),errorHandler:t},a=Fr(s),c=Dr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Wr(e);return vt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},kn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Wr(e),c=Zt().disable("x-powered-by").use(a);if(e.compression){let x=await Ae("compression");c.use(x(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Zt.json()],raw:[e.rawParser||Zt.raw(),Br],upload:e.upload?await qr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),vt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let x=In.createServer(c);p.push(x),f.push(m(x,e.http.listen))}if(e.https){let x=vn.createServer(e.https.options,c);p.push(x),f.push(m(x,e.https.listen))}return e.gracefulShutdown&&Gr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(x=>x())}};import{OpenApiBuilder as Bs}from"openapi3-ts/oas31";import{pluck as $s}from"ramda";import{chain as Cn,isEmpty as jn,map as Qr,partition as Nn,prop as Xr,reject as Ln,filter as kt,concat as Ct}from"ramda";var eo=e=>ie(e)&&"or"in e,to=e=>ie(e)&&"and"in e,jt=e=>!to(e)&&!eo(e),ro=e=>{let t=kt(jt,e),r=Cn(Xr("and"),kt(to,e)),[o,n]=Nn(jt,r),s=Ct(t,o),a=kt(eo,e);return Qr(Xr("or"),Ct(a,n)).reduce((d,p)=>se(d,Qr(m=>jt(m)?[m]:m.and,p),([m,f])=>Ct(m,f)),Ln(jn,[s]))};import{isReferenceObject as Mt,isSchemaObject as it}from"openapi3-ts/oas31";import{concat as Un,chain as Hn,type as io,filter as ao,fromPairs as at,has as Kn,isNil as Dn,map as He,mergeDeepRight as Fn,mergeDeepWith as qn,objOf as Bn,omit as pt,pipe as po,pluck as $n,reject as Vn,times as _n,toLower as Gn,union as Yn,when as Jn,xprod as Nt,zip as Wn}from"ramda";import{z as A}from"zod";var le=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>le(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var oo=["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","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-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,co="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Qn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},mo=/:([A-Za-z0-9_]+)/g,Xn=/^\d{4}-\d{2}-\d{2}$/,es=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,ts=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$/,rs=e=>e.match(mo)?.map(t=>t.slice(1))||[],lo=e=>e.replace(mo,t=>`{${t.slice(1)}}`),os=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),ns=({_def:{innerType:e}},{next:t})=>t(e),ss=()=>({format:"any"}),is=({},e)=>{if(e.isResponse)throw new H("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},as=e=>{let t=e.unwrap();return{type:"string",format:t instanceof A.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ps=({options:e},{next:t})=>({oneOf:e.map(t)}),cs=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ds=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Un(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},ms=e=>{let[t,r]=e.filter(it).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=qn(ds,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Yn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>Fn(n,s))),o},ls=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return ms(o)}catch{}return{allOf:o}},us=(e,{next:t})=>t(e.unwrap()),ys=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t})=>{let r=t(e.unwrap());return it(r)&&(r.type=yo(r)),r},uo=e=>{let t=Gn(io(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},so=e=>({type:uo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),gs=({value:e})=>({type:uo(e),const:e}),hs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ze(c)?c instanceof A.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=st(e,r)),s.length&&(a.required=s),a},xs=()=>({type:"null"}),bs=({},e)=>{if(e.isResponse)throw new H("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:co}}},Ss=({},e)=>{if(!e.isResponse)throw new H("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:co}}},Ts=({},e)=>{throw new H(`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)},Os=()=>({type:"boolean"}),Rs=()=>({type:"integer",format:"bigint"}),Ps=e=>e.every(t=>t instanceof A.ZodLiteral),As=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof A.ZodEnum||e instanceof A.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=st(A.object(at(Nt(o,[t]))),r),n.required=o),n}if(e instanceof A.ZodLiteral)return{type:"object",properties:st(A.object({[e.value]:t}),r),required:[e.value]};if(e instanceof A.ZodUnion&&Ps(e.options)){let o=He(s=>`${s.value}`,e.options),n=at(Nt(o,[t]));return{type:"object",properties:st(A.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ws=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),zs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:x,isTime:y,isBase64:T,isNANOID:S,isBase64url:C,isDuration:j,_def:{checks:b}})=>{let w=b.find(Z=>Z.kind==="regex"),I=b.find(Z=>Z.kind==="datetime"),N=b.some(Z=>Z.kind==="jwt"),v=b.find(Z=>Z.kind==="length"),E={type:"string"},te={"date-time":m,byte:T,base64url:C,date:x,time:y,duration:j,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:S,jwt:N,ip:d,cidr:f,emoji:p};for(let Z in te)if(te[Z]){E.format=Z;break}return v&&([E.minLength,E.maxLength]=[v.value,v.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),x&&(E.pattern=Xn.source),y&&(E.pattern=es.source),m&&(E.pattern=ts(I?.offset).source),w&&(E.pattern=w.regex.source),E},Is=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},st=({shape:e},t)=>He(t,e),vs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Qn?.[t]},yo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Zs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&it(o)){let s=Ve(e,vs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(A.any())}if(!t&&n.type==="preprocess"&&it(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ks=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Cs=(e,{next:t})=>t(e.unwrap()),js=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ns=(e,{next:t})=>t(e.unwrap().shape.raw),fo=e=>e.length?at(Wn(_n(t=>`example${t+1}`,e.length),He(Bn("value"),e))):void 0,go=(e,t,r=[])=>po(J,He(Jn(o=>io(o)==="Object",pt(r))),fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Ls=(e,t)=>po(J,ao(Kn(t)),$n(t),fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),X=e=>e instanceof A.ZodObject?e:e instanceof A.ZodBranded?X(e.unwrap()):e instanceof A.ZodUnion||e instanceof A.ZodDiscriminatedUnion?e.options.map(t=>X(t)).reduce((t,r)=>t.merge(r.partial()),A.object({})):e instanceof A.ZodEffects?X(e._def.schema):e instanceof A.ZodPipeline?X(e._def.in):X(e._def.left).merge(X(e._def.right)),Ms=(e,t)=>t?.includes(e)||e.startsWith("x-")||oo.includes(e),ho=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=X(r),f=rs(e),x=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=b=>y&&f.includes(b),C=Hn(ao(b=>b.type==="header"),d??[]).map(({name:b})=>b),j=b=>T&&(c?.(b,t,e)??Ms(b,C));return Object.entries(m.shape).reduce((b,[w,I])=>{let N=S(w)?"path":j(w)?"header":x?"query":void 0;if(!N)return b;let v=le(I,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),E=s==="components"?n(I,v,W(p,w)):v;return b.concat({name:w,in:N,required:!I.isOptional(),description:v.description||p,schema:E,examples:Ls(m,w)})},[])},Ut={ZodString:zs,ZodNumber:Is,ZodBigInt:Rs,ZodBoolean:Os,ZodNull:xs,ZodArray:ws,ZodTuple:Es,ZodRecord:As,ZodObject:hs,ZodLiteral:gs,ZodIntersection:ls,ZodUnion:ps,ZodAny:ss,ZodDefault:os,ZodEnum:so,ZodNativeEnum:so,ZodEffects:Zs,ZodOptional:us,ZodNullable:fs,ZodDiscriminatedUnion:cs,ZodBranded:Cs,ZodDate:Ts,ZodCatch:ns,ZodPipeline:ks,ZodLazy:js,ZodReadonly:ys,[D]:as,[xe]:is,[pe]:Ss,[ae]:bs,[Q]:Ns},Ht=(e,{isResponse:t,prev:r})=>{if(Mt(r))return{};let{description:o}=e,n=e instanceof A.ZodLazy,s=r.type!==void 0,a=t&&Ze(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=yo(r)),!n){let p=J({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Kt=(e,t)=>{throw new H(`Zod type ${e.constructor.name} is unsupported.`,t)},Lt=(e,t)=>{if(Mt(e))return e;let r={...e};return r.properties&&(r.properties=pt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>pt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Lt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Lt(o,t))),r},xo=e=>Mt(e)?e:pt(["examples"],e),bo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${Ot(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=xo(le(r,{rules:{...p,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x={schema:a==="components"?s(r,f,W(m)):f,examples:go(r,!0)};return{description:m,content:at(Nt(o,[x]))}},Us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Hs=({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},Ks=({name:e})=>({type:"apiKey",in:"header",name:e}),Ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),qs=({flows:e={}})=>({type:"oauth2",flows:He(t=>({...t,scopes:t.scopes||{}}),Vn(Dn,e))}),So=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Us(o):o.type==="input"?Hs(o,t):o.type==="header"?Ks(o):o.type==="cookie"?Ds(o):o.type==="openid"?Fs(o):qs(o);return e.map(o=>o.map(r))},To=(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:[]})},{})),Oo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=xo(Lt(le(r,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,W(d)):p,examples:go(X(r),!1,c)};return{description:d,content:{[o]:m}}},Ro=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)},[]),Dt=e=>e.length<=no?e:e.slice(0,no-1)+"\u2026";var Ft=class extends Bs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||W(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new H(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});we({routing:t,onEndpoint:(y,T,S)=>{let C={path:T,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[j,b]=["short","long"].map(y.getDescription.bind(y)),w=j?Dt(j):m&&b?Dt(b):void 0,I=r.inputSources?.[S]||St[S],N=this.ensureUniqOperationId(T,S,y.getOperationId(S)),v=ro(y.getSecurity()),E=ho({...C,inputSources:I,isHeader:p,security:v,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:T,operationId:N})}),te={};for(let _ of Re){let re=y.getResponses(_);for(let{mimeTypes:xt,schema:Fe,statusCodes:qe}of re)for(let bt of qe)te[bt]=bo({...C,variant:_,schema:Fe,mimeTypes:xt,statusCode:bt,hasMultipleStatusCodes:re.length>1||qe.length>1,description:a?.[`${_}Response`]?.call(null,{method:S,path:T,operationId:N,statusCode:bt})})}let Z=I.includes("body")?Oo({...C,paramNames:$s("name",E),schema:y.getSchema("input"),mimeType:z[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:T,operationId:N})}):void 0,ht=To(So(v,I),y.getScopes(),_=>{let re=this.ensureUniqSecuritySchemaName(_);return this.addSecurityScheme(re,_),re});this.addPath(lo(T),{[S]:{operationId:N,summary:w,description:b,tags:_e(y.getTags()),parameters:_e(E),requestBody:Z,security:_e(ht),responses:te}})}}),d&&(this.rootDoc.tags=Ro(d))}};import{createRequest as Vs,createResponse as _s}from"node-mocks-http";var Gs=e=>Vs({...e,headers:{"content-type":z.json,...e?.headers}}),Ys=e=>_s(e),Js=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Ir(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Po=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Gs(e),s=Ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=Js(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Ws=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Po(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Qs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Po(o),d=$e(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(Y(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Zi}from"ramda";import gt from"typescript";import{z as ki}from"zod";import{map as oi}from"ramda";import $ from"typescript";var Ao=["get","post","put","delete","patch"];import{map as qt,pair as Xs}from"ramda";import l from"typescript";var i=l.factory,ct=[i.createModifier(l.SyntaxKind.ExportKeyword)],ei=[i.createModifier(l.SyntaxKind.AsyncKeyword)],Ke={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Bt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),$t=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},ti=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vt=e=>typeof e=="string"&&ti.test(e)?i.createIdentifier(e):P(e),dt=(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)))),mt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),Ee=e=>Object.entries(e).map(([t,r])=>mt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),_t=(e,t=[])=>i.createConstructorDeclaration(Ke.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&qt(u,t)):e,Gt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),ue=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,Vt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t));return o?Bt(n,o):n},Yt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Jt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),k=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&ct,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),Wt=(e,t)=>B(e,i.createUnionTypeNode(qt(M,t)),{expose:!0}),B=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?ct:void 0,e,n&&tr(n),t);return o?Bt(s,o):s},wo=(e,t)=>i.createPropertyDeclaration(Ke.public,e,void 0,u(t),void 0),Qt=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ke.public,void 0,e,void 0,o&&tr(o),t,n,i.createBlock(r)),Xt=(e,t,{typeParams:r}={})=>i.createClassDeclaration(ct,e,r&&tr(r),void 0,t),er=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),lt=e=>u(Promise.name,[e]),ut=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?ct:void 0,e,void 0,void 0,t);return o?Bt(n,o):n},tr=e=>(Array.isArray(e)?e.map(t=>Xs(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?u(o):void 0,n?u(n):void 0)}),ye=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ei:void 0,void 0,Array.isArray(e)?qt(mt,e):Ee(e),void 0,void 0,t),O=e=>e,De=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),ze=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),yt=(e,t)=>u("Extract",[e,t]),rr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),K=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Eo=e=>i.createUnionTypeNode([u(e),lt(e)]),or=(e,t)=>i.createFunctionTypeNode(void 0,Ee(e),u(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),M=e=>i.createLiteralTypeNode(P(e)),ri=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],zo=e=>ri.includes(e.kind);var ft=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={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=Wt("Method",Ao);someOfType=B("SomeOf",K("T",er("T")),{params:["T"]});requestType=B("Request",er(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>Wt(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>ut(this.interfaces[t],Array.from(this.registry).map(([r,o])=>ue(r,o[t])),{expose:!0}));makeEndpointTags=()=>k("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Vt(t),i.createArrayLiteralExpression(oi(P,r))))),{expose:!0});makeImplementationType=()=>B(this.ids.implementationType,or({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},lt($.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:$.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>k(this.ids.parseRequestFn,ye({[this.ids.requestParameter.text]:$.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>k(this.ids.substituteFn,ye({[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt},i.createBlock([k(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],$.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([rr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(dt(":",[this.ids.keyParameter]),ye([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>Qt(this.ids.provideMethod,Ee({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:K(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[k(Jt(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:lt(K(this.interfaces.response,"K"))});makeClientClass=t=>Xt(t,[_t([mt(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:Ke.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>dt("?",[ze(URLSearchParams.name,t)]);makeFetchURL=()=>ze(URL.name,dt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),De(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(z.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),De(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=k(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=k(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=k(this.ids.searchParamsConst,De(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=k(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression($.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=k(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(z.json))),m=i.createReturnStatement(R(this.ids.responseConst,De(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return k(this.ids.defaultImplementationConst,ye([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>_t(Ee({request:"K",params:K(this.interfaces.input,"K")}),[k(Jt(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),k(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),rr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),ze("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ue(O("event"),t)]);makeOnMethod=()=>Qt(this.ids.onMethod,Ee({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:or({[this.ids.dataParameter.text]:K(yt("R",Yt(this.makeEventNarrow("E"))),M(O("data")))},Eo($.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,ye([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:K("R",M(O("event")))}});makeSubscriptionClass=t=>Xt(t,[wo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:yt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u($.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:yt(K(this.interfaces.positive,"K"),Yt(this.makeEventNarrow($.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[k(this.ids.clientConst,ze(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(ze(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),ye(["time"],i.createBlock([])))]};import{chain as ni,eqBy as nr,path as sr,prop as si,uniqWith as ii}from"ramda";import h from"typescript";import{z as ar}from"zod";var{factory:U}=h,ai={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},ir={name:sr(["name","text"]),type:sr(["type"]),optional:sr(["questionToken"])},pi=({value:e})=>M(e),ci=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&Ze(a)?a instanceof ar.ZodOptional:a.isOptional();return ue(s,r(a),{isOptional:c&&o,comment:a.description})});return U.createTypeLiteralNode(n)},di=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),mi=({options:e})=>U.createUnionTypeNode(e.map(M)),Io=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(zo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},li=e=>ai?.[e.kind],ui=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ve(e,li(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},yi=e=>U.createUnionTypeNode(Object.values(e.enum).map(M)),fi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},gi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),M(null)]),hi=({items:e,_def:{rest:t}},{next:r})=>U.createTupleTypeNode(e.map(r).concat(t===null?[]:U.createRestTypeNode(r(t)))),xi=({keySchema:e,valueSchema:t},{next:r})=>u("Record",[e,t].map(r)),bi=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=ni(si("members"),e),o=ii((...n)=>{if(!nr(ir.name,...n))return!1;if(nr(ir.type,...n)&&nr(ir.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},Si=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return bi(o)}catch{}return U.createIntersectionTypeNode(o)},Ti=({_def:e},{next:t})=>t(e.innerType),ee=e=>()=>u(e),Oi=(e,{next:t})=>t(e.unwrap()),Ri=(e,{next:t})=>t(e.unwrap()),Pi=({_def:e},{next:t})=>t(e.innerType),Ai=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),wi=()=>M(null),Ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),zi=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof ar.ZodString?r:t instanceof ar.ZodUnion?n:o},Ii=(e,{next:t})=>t(e.unwrap().shape.raw),vi={ZodString:ee(h.SyntaxKind.StringKeyword),ZodNumber:ee(h.SyntaxKind.NumberKeyword),ZodBigInt:ee(h.SyntaxKind.BigIntKeyword),ZodBoolean:ee(h.SyntaxKind.BooleanKeyword),ZodAny:ee(h.SyntaxKind.AnyKeyword),ZodUndefined:ee(h.SyntaxKind.UndefinedKeyword),[ae]:ee(h.SyntaxKind.StringKeyword),[pe]:ee(h.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:di,ZodTuple:hi,ZodRecord:xi,ZodObject:ci,ZodLiteral:pi,ZodIntersection:Si,ZodUnion:Io,ZodDefault:Ti,ZodEnum:mi,ZodNativeEnum:yi,ZodEffects:ui,ZodOptional:fi,ZodNullable:gi,ZodDiscriminatedUnion:Io,ZodBranded:Oi,ZodCatch:Pi,ZodPipeline:Ai,ZodLazy:Ei,ZodReadonly:Ri,[D]:zi,[Q]:Ii},pr=(e,{brandHandling:t,ctx:r})=>le(e,{rules:{...t,...vi},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var cr=class extends ft{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=M(null);this.aliases.set(t,B(o,n)),this.aliases.set(t,B(o,r()))}return u(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:d=ki.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},f={brandHandling:r,ctx:{...p,isResponse:!0}};we({routing:t,onEndpoint:(y,T,S)=>{let C=W.bind(null,S,T),j=`${S} ${T}`,b=B(C("input"),pr(y.getSchema("input"),m),{comment:j});this.program.push(b);let w=Re.reduce((N,v)=>{let E=y.getResponses(v),te=Zi(([ht,{schema:_,mimeTypes:re,statusCodes:xt}])=>{let Fe=B(C(v,"variant",`${ht+1}`),pr(re?_:d,f),{comment:j});return this.program.push(Fe),xt.map(qe=>ue(qe,Fe.name))},Array.from(E.entries())),Z=ut(C(v,"response","variants"),te,{comment:j});return this.program.push(Z),Object.assign(N,{[v]:Z})},{});this.paths.add(T);let I=M(j);this.registry.set(j,{input:u(b.name),positive:this.someOf(w.positive),negative:this.someOf(w.negative),response:i.createUnionTypeNode([K(this.interfaces.positive,I),K(this.interfaces.negative,I)]),encoded:i.createIntersectionTypeNode([u(w.positive.name),u(w.negative.name)])}),this.tags.set(j,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:$t(r,t)).join(`
+`))};var Wr=e=>{e.startupLogo!==!1&&Jr(process.stdout);let t=e.errorHandler||Ne,r=zr(e.logger)?e.logger:new Le(e.logger);r.debug("Running",{build:"v22.7.0-beta.0 (ESM)",env:process.env.NODE_ENV||"development"}),_r(r);let o=$r({logger:r,config:e}),s={getLogger:Vr(r),errorHandler:t},a=Fr(s),c=Dr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Wr(e);return vt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},kn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Wr(e),c=Zt().disable("x-powered-by").use(a);if(e.compression){let x=await Ae("compression");c.use(x(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Zt.json()],raw:[e.rawParser||Zt.raw(),Br],upload:e.upload?await qr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),vt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let x=In.createServer(c);p.push(x),f.push(m(x,e.http.listen))}if(e.https){let x=vn.createServer(e.https.options,c);p.push(x),f.push(m(x,e.https.listen))}return e.gracefulShutdown&&Gr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(x=>x())}};import{OpenApiBuilder as Bs}from"openapi3-ts/oas31";import{pluck as $s}from"ramda";import{chain as Cn,isEmpty as jn,map as Qr,partition as Nn,prop as Xr,reject as Ln,filter as kt,concat as Ct}from"ramda";var eo=e=>ie(e)&&"or"in e,to=e=>ie(e)&&"and"in e,jt=e=>!to(e)&&!eo(e),ro=e=>{let t=kt(jt,e),r=Cn(Xr("and"),kt(to,e)),[o,n]=Nn(jt,r),s=Ct(t,o),a=kt(eo,e);return Qr(Xr("or"),Ct(a,n)).reduce((d,p)=>se(d,Qr(m=>jt(m)?[m]:m.and,p),([m,f])=>Ct(m,f)),Ln(jn,[s]))};import{isReferenceObject as Mt,isSchemaObject as it}from"openapi3-ts/oas31";import{concat as Un,chain as Hn,type as io,filter as ao,fromPairs as at,has as Kn,isNil as Dn,map as He,mergeDeepRight as Fn,mergeDeepWith as qn,objOf as Bn,omit as pt,pipe as po,pluck as $n,reject as Vn,times as _n,toLower as Gn,union as Yn,when as Jn,xprod as Nt,zip as Wn}from"ramda";import{z as A}from"zod";var le=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>le(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var oo=["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","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,co="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Qn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},mo=/:([A-Za-z0-9_]+)/g,Xn=/^\d{4}-\d{2}-\d{2}$/,es=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,ts=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$/,rs=e=>e.match(mo)?.map(t=>t.slice(1))||[],lo=e=>e.replace(mo,t=>`{${t.slice(1)}}`),os=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),ns=({_def:{innerType:e}},{next:t})=>t(e),ss=()=>({format:"any"}),is=({},e)=>{if(e.isResponse)throw new H("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},as=e=>{let t=e.unwrap();return{type:"string",format:t instanceof A.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ps=({options:e},{next:t})=>({oneOf:e.map(t)}),cs=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ds=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Un(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},ms=e=>{let[t,r]=e.filter(it).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=qn(ds,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Yn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>Fn(n,s))),o},ls=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return ms(o)}catch{}return{allOf:o}},us=(e,{next:t})=>t(e.unwrap()),ys=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t})=>{let r=t(e.unwrap());return it(r)&&(r.type=yo(r)),r},uo=e=>{let t=Gn(io(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},so=e=>({type:uo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),gs=({value:e})=>({type:uo(e),const:e}),hs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ze(c)?c instanceof A.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=st(e,r)),s.length&&(a.required=s),a},xs=()=>({type:"null"}),bs=({},e)=>{if(e.isResponse)throw new H("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:co}}},Ss=({},e)=>{if(!e.isResponse)throw new H("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:co}}},Ts=({},e)=>{throw new H(`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)},Os=()=>({type:"boolean"}),Rs=()=>({type:"integer",format:"bigint"}),Ps=e=>e.every(t=>t instanceof A.ZodLiteral),As=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof A.ZodEnum||e instanceof A.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=st(A.object(at(Nt(o,[t]))),r),n.required=o),n}if(e instanceof A.ZodLiteral)return{type:"object",properties:st(A.object({[e.value]:t}),r),required:[e.value]};if(e instanceof A.ZodUnion&&Ps(e.options)){let o=He(s=>`${s.value}`,e.options),n=at(Nt(o,[t]));return{type:"object",properties:st(A.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ws=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),zs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:x,isTime:y,isBase64:T,isNANOID:S,isBase64url:C,isDuration:j,_def:{checks:b}})=>{let w=b.find(Z=>Z.kind==="regex"),I=b.find(Z=>Z.kind==="datetime"),N=b.some(Z=>Z.kind==="jwt"),v=b.find(Z=>Z.kind==="length"),E={type:"string"},te={"date-time":m,byte:T,base64url:C,date:x,time:y,duration:j,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:S,jwt:N,ip:d,cidr:f,emoji:p};for(let Z in te)if(te[Z]){E.format=Z;break}return v&&([E.minLength,E.maxLength]=[v.value,v.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),x&&(E.pattern=Xn.source),y&&(E.pattern=es.source),m&&(E.pattern=ts(I?.offset).source),w&&(E.pattern=w.regex.source),E},Is=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},st=({shape:e},t)=>He(t,e),vs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Qn?.[t]},yo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Zs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&it(o)){let s=Ve(e,vs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(A.any())}if(!t&&n.type==="preprocess"&&it(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ks=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Cs=(e,{next:t})=>t(e.unwrap()),js=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ns=(e,{next:t})=>t(e.unwrap().shape.raw),fo=e=>e.length?at(Wn(_n(t=>`example${t+1}`,e.length),He(Bn("value"),e))):void 0,go=(e,t,r=[])=>po(J,He(Jn(o=>io(o)==="Object",pt(r))),fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Ls=(e,t)=>po(J,ao(Kn(t)),$n(t),fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),X=e=>e instanceof A.ZodObject?e:e instanceof A.ZodBranded?X(e.unwrap()):e instanceof A.ZodUnion||e instanceof A.ZodDiscriminatedUnion?e.options.map(t=>X(t)).reduce((t,r)=>t.merge(r.partial()),A.object({})):e instanceof A.ZodEffects?X(e._def.schema):e instanceof A.ZodPipeline?X(e._def.in):X(e._def.left).merge(X(e._def.right)),Ms=(e,t)=>t?.includes(e)||e.startsWith("x-")||oo.includes(e),ho=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=X(r),f=rs(e),x=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=b=>y&&f.includes(b),C=Hn(ao(b=>b.type==="header"),d??[]).map(({name:b})=>b),j=b=>T&&(c?.(b,t,e)??Ms(b,C));return Object.entries(m.shape).reduce((b,[w,I])=>{let N=S(w)?"path":j(w)?"header":x?"query":void 0;if(!N)return b;let v=le(I,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),E=s==="components"?n(I,v,W(p,w)):v;return b.concat({name:w,in:N,required:!I.isOptional(),description:v.description||p,schema:E,examples:Ls(m,w)})},[])},Ut={ZodString:zs,ZodNumber:Is,ZodBigInt:Rs,ZodBoolean:Os,ZodNull:xs,ZodArray:ws,ZodTuple:Es,ZodRecord:As,ZodObject:hs,ZodLiteral:gs,ZodIntersection:ls,ZodUnion:ps,ZodAny:ss,ZodDefault:os,ZodEnum:so,ZodNativeEnum:so,ZodEffects:Zs,ZodOptional:us,ZodNullable:fs,ZodDiscriminatedUnion:cs,ZodBranded:Cs,ZodDate:Ts,ZodCatch:ns,ZodPipeline:ks,ZodLazy:js,ZodReadonly:ys,[D]:as,[xe]:is,[pe]:Ss,[ae]:bs,[Q]:Ns},Ht=(e,{isResponse:t,prev:r})=>{if(Mt(r))return{};let{description:o}=e,n=e instanceof A.ZodLazy,s=r.type!==void 0,a=t&&Ze(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=yo(r)),!n){let p=J({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Kt=(e,t)=>{throw new H(`Zod type ${e.constructor.name} is unsupported.`,t)},Lt=(e,t)=>{if(Mt(e))return e;let r={...e};return r.properties&&(r.properties=pt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>pt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Lt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Lt(o,t))),r},xo=e=>Mt(e)?e:pt(["examples"],e),bo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${Ot(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=xo(le(r,{rules:{...p,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x={schema:a==="components"?s(r,f,W(m)):f,examples:go(r,!0)};return{description:m,content:at(Nt(o,[x]))}},Us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Hs=({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},Ks=({name:e})=>({type:"apiKey",in:"header",name:e}),Ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),qs=({flows:e={}})=>({type:"oauth2",flows:He(t=>({...t,scopes:t.scopes||{}}),Vn(Dn,e))}),So=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Us(o):o.type==="input"?Hs(o,t):o.type==="header"?Ks(o):o.type==="cookie"?Ds(o):o.type==="openid"?Fs(o):qs(o);return e.map(o=>o.map(r))},To=(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:[]})},{})),Oo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=xo(Lt(le(r,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,W(d)):p,examples:go(X(r),!1,c)};return{description:d,content:{[o]:m}}},Ro=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)},[]),Dt=e=>e.length<=no?e:e.slice(0,no-1)+"\u2026";var Ft=class extends Bs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||W(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new H(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});we({routing:t,onEndpoint:(y,T,S)=>{let C={path:T,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[j,b]=["short","long"].map(y.getDescription.bind(y)),w=j?Dt(j):m&&b?Dt(b):void 0,I=r.inputSources?.[S]||St[S],N=this.ensureUniqOperationId(T,S,y.getOperationId(S)),v=ro(y.getSecurity()),E=ho({...C,inputSources:I,isHeader:p,security:v,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:T,operationId:N})}),te={};for(let _ of Re){let re=y.getResponses(_);for(let{mimeTypes:xt,schema:Fe,statusCodes:qe}of re)for(let bt of qe)te[bt]=bo({...C,variant:_,schema:Fe,mimeTypes:xt,statusCode:bt,hasMultipleStatusCodes:re.length>1||qe.length>1,description:a?.[`${_}Response`]?.call(null,{method:S,path:T,operationId:N,statusCode:bt})})}let Z=I.includes("body")?Oo({...C,paramNames:$s("name",E),schema:y.getSchema("input"),mimeType:z[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:T,operationId:N})}):void 0,ht=To(So(v,I),y.getScopes(),_=>{let re=this.ensureUniqSecuritySchemaName(_);return this.addSecurityScheme(re,_),re});this.addPath(lo(T),{[S]:{operationId:N,summary:w,description:b,tags:_e(y.getTags()),parameters:_e(E),requestBody:Z,security:_e(ht),responses:te}})}}),d&&(this.rootDoc.tags=Ro(d))}};import{createRequest as Vs,createResponse as _s}from"node-mocks-http";var Gs=e=>Vs({...e,headers:{"content-type":z.json,...e?.headers}}),Ys=e=>_s(e),Js=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Ir(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Po=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Gs(e),s=Ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=Js(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Ws=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Po(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Qs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Po(o),d=$e(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(Y(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Zi}from"ramda";import gt from"typescript";import{z as ki}from"zod";import{map as oi}from"ramda";import $ from"typescript";var Ao=["get","post","put","delete","patch"];import{map as qt,pair as Xs}from"ramda";import l from"typescript";var i=l.factory,ct=[i.createModifier(l.SyntaxKind.ExportKeyword)],ei=[i.createModifier(l.SyntaxKind.AsyncKeyword)],Ke={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Bt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),$t=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},ti=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vt=e=>typeof e=="string"&&ti.test(e)?i.createIdentifier(e):P(e),dt=(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)))),mt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),Ee=e=>Object.entries(e).map(([t,r])=>mt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),_t=(e,t=[])=>i.createConstructorDeclaration(Ke.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&qt(u,t)):e,Gt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),ue=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,Vt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t));return o?Bt(n,o):n},Yt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Jt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),k=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&ct,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),Wt=(e,t)=>B(e,i.createUnionTypeNode(qt(M,t)),{expose:!0}),B=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?ct:void 0,e,n&&tr(n),t);return o?Bt(s,o):s},wo=(e,t)=>i.createPropertyDeclaration(Ke.public,e,void 0,u(t),void 0),Qt=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ke.public,void 0,e,void 0,o&&tr(o),t,n,i.createBlock(r)),Xt=(e,t,{typeParams:r}={})=>i.createClassDeclaration(ct,e,r&&tr(r),void 0,t),er=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),lt=e=>u(Promise.name,[e]),ut=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?ct:void 0,e,void 0,void 0,t);return o?Bt(n,o):n},tr=e=>(Array.isArray(e)?e.map(t=>Xs(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?u(o):void 0,n?u(n):void 0)}),ye=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ei:void 0,void 0,Array.isArray(e)?qt(mt,e):Ee(e),void 0,void 0,t),O=e=>e,De=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),ze=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),yt=(e,t)=>u("Extract",[e,t]),rr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),K=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Eo=e=>i.createUnionTypeNode([u(e),lt(e)]),or=(e,t)=>i.createFunctionTypeNode(void 0,Ee(e),u(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),M=e=>i.createLiteralTypeNode(P(e)),ri=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],zo=e=>ri.includes(e.kind);var ft=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={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=Wt("Method",Ao);someOfType=B("SomeOf",K("T",er("T")),{params:["T"]});requestType=B("Request",er(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>Wt(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>ut(this.interfaces[t],Array.from(this.registry).map(([r,o])=>ue(r,o[t])),{expose:!0}));makeEndpointTags=()=>k("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Vt(t),i.createArrayLiteralExpression(oi(P,r))))),{expose:!0});makeImplementationType=()=>B(this.ids.implementationType,or({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},lt($.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:$.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>k(this.ids.parseRequestFn,ye({[this.ids.requestParameter.text]:$.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>k(this.ids.substituteFn,ye({[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt},i.createBlock([k(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],$.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([rr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(dt(":",[this.ids.keyParameter]),ye([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>Qt(this.ids.provideMethod,Ee({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:K(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[k(Jt(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:lt(K(this.interfaces.response,"K"))});makeClientClass=t=>Xt(t,[_t([mt(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:Ke.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>dt("?",[ze(URLSearchParams.name,t)]);makeFetchURL=()=>ze(URL.name,dt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),De(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(z.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),De(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=k(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=k(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=k(this.ids.searchParamsConst,De(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=k(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression($.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=k(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(z.json))),m=i.createReturnStatement(R(this.ids.responseConst,De(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return k(this.ids.defaultImplementationConst,ye([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>_t(Ee({request:"K",params:K(this.interfaces.input,"K")}),[k(Jt(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),k(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),rr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),ze("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ue(O("event"),t)]);makeOnMethod=()=>Qt(this.ids.onMethod,Ee({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:or({[this.ids.dataParameter.text]:K(yt("R",Yt(this.makeEventNarrow("E"))),M(O("data")))},Eo($.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,ye([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:K("R",M(O("event")))}});makeSubscriptionClass=t=>Xt(t,[wo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:yt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u($.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:yt(K(this.interfaces.positive,"K"),Yt(this.makeEventNarrow($.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[k(this.ids.clientConst,ze(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(ze(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),ye(["time"],i.createBlock([])))]};import{chain as ni,eqBy as nr,path as sr,prop as si,uniqWith as ii}from"ramda";import h from"typescript";import{z as ar}from"zod";var{factory:U}=h,ai={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},ir={name:sr(["name","text"]),type:sr(["type"]),optional:sr(["questionToken"])},pi=({value:e})=>M(e),ci=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&Ze(a)?a instanceof ar.ZodOptional:a.isOptional();return ue(s,r(a),{isOptional:c&&o,comment:a.description})});return U.createTypeLiteralNode(n)},di=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),mi=({options:e})=>U.createUnionTypeNode(e.map(M)),Io=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(zo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},li=e=>ai?.[e.kind],ui=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ve(e,li(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},yi=e=>U.createUnionTypeNode(Object.values(e.enum).map(M)),fi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},gi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),M(null)]),hi=({items:e,_def:{rest:t}},{next:r})=>U.createTupleTypeNode(e.map(r).concat(t===null?[]:U.createRestTypeNode(r(t)))),xi=({keySchema:e,valueSchema:t},{next:r})=>u("Record",[e,t].map(r)),bi=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=ni(si("members"),e),o=ii((...n)=>{if(!nr(ir.name,...n))return!1;if(nr(ir.type,...n)&&nr(ir.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},Si=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return bi(o)}catch{}return U.createIntersectionTypeNode(o)},Ti=({_def:e},{next:t})=>t(e.innerType),ee=e=>()=>u(e),Oi=(e,{next:t})=>t(e.unwrap()),Ri=(e,{next:t})=>t(e.unwrap()),Pi=({_def:e},{next:t})=>t(e.innerType),Ai=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),wi=()=>M(null),Ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),zi=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof ar.ZodString?r:t instanceof ar.ZodUnion?n:o},Ii=(e,{next:t})=>t(e.unwrap().shape.raw),vi={ZodString:ee(h.SyntaxKind.StringKeyword),ZodNumber:ee(h.SyntaxKind.NumberKeyword),ZodBigInt:ee(h.SyntaxKind.BigIntKeyword),ZodBoolean:ee(h.SyntaxKind.BooleanKeyword),ZodAny:ee(h.SyntaxKind.AnyKeyword),ZodUndefined:ee(h.SyntaxKind.UndefinedKeyword),[ae]:ee(h.SyntaxKind.StringKeyword),[pe]:ee(h.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:di,ZodTuple:hi,ZodRecord:xi,ZodObject:ci,ZodLiteral:pi,ZodIntersection:Si,ZodUnion:Io,ZodDefault:Ti,ZodEnum:mi,ZodNativeEnum:yi,ZodEffects:ui,ZodOptional:fi,ZodNullable:gi,ZodDiscriminatedUnion:Io,ZodBranded:Oi,ZodCatch:Pi,ZodPipeline:Ai,ZodLazy:Ei,ZodReadonly:Ri,[D]:zi,[Q]:Ii},pr=(e,{brandHandling:t,ctx:r})=>le(e,{rules:{...t,...vi},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var cr=class extends ft{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=M(null);this.aliases.set(t,B(o,n)),this.aliases.set(t,B(o,r()))}return u(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:d=ki.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},f={brandHandling:r,ctx:{...p,isResponse:!0}};we({routing:t,onEndpoint:(y,T,S)=>{let C=W.bind(null,S,T),j=`${S} ${T}`,b=B(C("input"),pr(y.getSchema("input"),m),{comment:j});this.program.push(b);let w=Re.reduce((N,v)=>{let E=y.getResponses(v),te=Zi(([ht,{schema:_,mimeTypes:re,statusCodes:xt}])=>{let Fe=B(C(v,"variant",`${ht+1}`),pr(re?_:d,f),{comment:j});return this.program.push(Fe),xt.map(qe=>ue(qe,Fe.name))},Array.from(E.entries())),Z=ut(C(v,"response","variants"),te,{comment:j});return this.program.push(Z),Object.assign(N,{[v]:Z})},{});this.paths.add(T);let I=M(j);this.registry.set(j,{input:u(b.name),positive:this.someOf(w.positive),negative:this.someOf(w.negative),response:i.createUnionTypeNode([K(this.interfaces.positive,I),K(this.interfaces.negative,I)]),encoded:i.createIntersectionTypeNode([u(w.positive.name),u(w.negative.name)])}),this.tags.set(j,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:$t(r,t)).join(`
 `):void 0}print(t){let r=this.printUsage(t),o=r&&gt.addSyntheticLeadingComment(gt.addSyntheticLeadingComment(i.createEmptyStatement(),gt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),gt.SyntaxKind.MultiLineCommentTrivia,`
 ${r}`);return this.program.concat(o||[]).map((n,s)=>$t(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
 
 `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Ae("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};import{z as Ie}from"zod";var Zo=(e,t)=>Ie.object({data:t,event:Ie.literal(e),id:Ie.string().optional(),retry:Ie.number().int().positive().optional()}),Ci=(e,t,r)=>Zo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`