express-zod-api 22.0.0-beta.5 → 22.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,9 +5,9 @@
5
5
  ### v22.0.0
6
6
 
7
7
  - Minimum supported Node versions: 20.9.0 and 22.0.0:
8
- - Node 18 is no longer supported, its end of life is April 30, 2025.
8
+ - Node 18 is no longer supported; its end of life is April 30, 2025.
9
9
  - `BuiltinLogger::profile()` behavior changed for picoseconds: expressing them through nanoseconds;
10
- - Feature: handling all headers as input source (when enabled):
10
+ - Feature: handling all (not just `x-` prefixed) headers as an input source (when enabled):
11
11
  - Behavior changed for `headers` inside `inputSources` config option: all headers are addressed to the `input` object;
12
12
  - This change is motivated by the deprecation of `x-` prefixed headers;
13
13
  - Since the order inside `inputSources` matters, consider moving `headers` to the first place to avoid overwrites;
@@ -19,7 +19,7 @@
19
19
  - The overload of the `Client::provide()` having 3 arguments and the `Provider` type are removed;
20
20
  - The public `jsonEndpoints` const is removed — use the `content-type` header of an actual response instead;
21
21
  - The public type `MethodPath` is removed — use the `Request` type instead.
22
- - The approach on tagging endpoints changed:
22
+ - The approach to tagging endpoints changed:
23
23
  - The `tags` property moved from the argument of `createConfig()` to `Documentation::constructor()`;
24
24
  - The overload of `EndpointsFactory::constructor()` accepting `config` property is removed;
25
25
  - The argument of `EventStreamFactory::constructor()` is now the events map (formerly assigned to `events` property);
package/SECURITY.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Version | Release | Supported |
6
6
  | ------: | :------ | :----------------: |
7
- | 22.x.x | 02.2025 | :white_check_mark: |
7
+ | 22.x.x | 01.2025 | :white_check_mark: |
8
8
  | 21.x.x | 11.2024 | :white_check_mark: |
9
9
  | 20.x.x | 06.2024 | :white_check_mark: |
10
10
  | 19.x.x | 05.2024 | :white_check_mark: |
package/dist/index.cjs CHANGED
@@ -15,7 +15,7 @@ ${n}888${r}
15
15
  ${o}
16
16
  `;e.write(d.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var ro=e=>{e.startupLogo!==!1&&Xr(process.stdout);let t=e.errorHandler||Ze,r=Zr(e.logger)?e.logger:new ve(e.logger);r.debug("Running",{build:"v22.0.0-beta.5 (CJS)",env:process.env.NODE_ENV||"development"}),Jr(r);let o=Yr({logger:r,config:e}),i={getLogger:Wr(r),errorHandler:t},a=Vr(i),c=$r(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},oo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=ro(e);return _t({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},no=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=ro(e),c=(0,yt.default)().disable("x-powered-by").use(a);if(e.compression){let h=await Le("compression");c.use(h(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||yt.default.json()],raw:[e.rawParser||yt.default.raw(),Gr],upload:e.upload?await _r({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),_t({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],l=(h,f)=>()=>h.listen(f,()=>r.info("Listening",f)),g=[];if(e.http){let h=eo.default.createServer(c);p.push(h),g.push(l(h,e.http.listen))}if(e.https){let h=to.default.createServer(e.https.options,c);p.push(h),g.push(l(h,e.https.listen))}return e.gracefulShutdown&&Qr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:g.map(h=>h())}};var Ro=require("openapi3-ts/oas31"),Po=require("ramda");var so=require("ramda");var he=e=>me(e)&&"or"in e,He=e=>me(e)&&"and"in e,Gt=e=>({and:(0,so.chain)(t=>He(t)?t.and:[t],e)}),ft=(e,t)=>He(e)?{and:e.and.map(r=>he(r)?{or:r.or.map(t)}:t(r))}:he(e)?{or:e.or.map(r=>He(r)?{and:r.and.map(t)}:t(r))}:t(e),Yt=e=>e.and.reduce((t,r)=>({or:de(t.or,he(r)?r.or:[r],Gt)}),{or:[]}),Me=(e,t)=>He(e)?he(t)?Me(Yt(e),t):Gt([e,t]):he(e)?He(t)?Me(t,e):he(t)?{or:de(e.or,t.or,Gt)}:Me(e,{and:[t]}):He(t)||he(t)?Me(t,e):{and:[e,t]};var W=require("openapi3-ts/oas31"),m=require("ramda"),R=require("zod");var xe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[b]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>xe(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 io=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-patch","accept-post","accept-ranges","accept-signature","access-control","access-control-allow-credentials","access-control-allow-headers","access-control-allow-methods","access-control-allow-origin","access-control-expose-headers","access-control-max-age","access-control-request-headers","access-control-request-method","age","allow","alpn","alt-svc","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","cache-status","cal-managed-id","caldav-timezones","capsule-protocol","cdn-cache-control","cdn-loop","cert-not-after","cert-not-before","clear-site-data","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-base","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-security-policy","content-security-policy-report-only","content-style-type","content-type","content-version","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","etag","expect","expect-ct","expires","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","last-modified","link","link-template","location","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","optional-www-authenticate","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-authenticate","proxy-authentication-info","proxy-authorization","proxy-features","proxy-instruction","proxy-status","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","refresh","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","retry-after","safe","schedule-reply","schedule-tag","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","server","server-timing","set-cookie","set-cookie2","setprofile","signature","signature-input","slug","soapaction","status-uri","strict-transport-security","sunset","surrogate-capability","surrogate-control","tcn","te","timeout","timing-allow-origin","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","vary","via","want-content-digest","want-digest","want-repr-digest","warning","www-authenticate","x-content-type-options","x-frame-options"];var ao=50,co="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",an={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},mo=/:([A-Za-z0-9_]+)/g,pn=/^\d{4}-\d{2}-\d{2}$/,cn=/^\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$/,mn=e=>e.match(mo)?.map(t=>t.slice(1))||[],lo=e=>e.replace(mo,t=>`{${t.slice(1)}}`),ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[b]?.defaultLabel||e.defaultValue()}),un=({_def:{innerType:e}},{next:t})=>t(e),yn=()=>({format:"any"}),fn=({},e)=>{if(e.isResponse)throw new U("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},gn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof R.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},hn=({options:e},{next:t})=>({oneOf:e.map(t)}),xn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),bn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Sn=e=>{let[t,r]=e.filter(W.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(bn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=de(t.examples||[],r.examples||[],([n,i])=>(0,m.mergeDeepRight)(n,i))),o},On=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Sn(o)}catch{}return{allOf:o}},Tn=(e,{next:t})=>t(e.unwrap()),Rn=(e,{next:t})=>t(e.unwrap()),Pn=(e,{next:t})=>{let r=t(e.unwrap());return(0,W.isSchemaObject)(r)&&(r.type=yo(r)),r},uo=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},po=e=>({type:uo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),wn=({value:e})=>({type:uo(e),const:e}),An=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Fe(c)?c instanceof R.z.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=gt(e,r)),i.length&&(a.required=i),a},zn=()=>({type:"null"}),In=({},e)=>{if(e.isResponse)throw new U("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}}},En=({},e)=>{if(!e.isResponse)throw new U("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:co}}},Zn=({},e)=>{throw new U(`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)},Cn=()=>({type:"boolean"}),vn=()=>({type:"integer",format:"bigint"}),kn=e=>e.every(t=>t instanceof R.z.ZodLiteral),Nn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof R.z.ZodEnum||e instanceof R.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=gt(R.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof R.z.ZodLiteral)return{type:"object",properties:gt(R.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof R.z.ZodUnion&&kn(e.options)){let o=(0,m.map)(i=>`${i.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:gt(R.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},jn=({_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},Ln=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Un=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:g,isDate:h,isTime:f,isBase64:T,isNANOID:O,isBase64url:P,isDuration:w,_def:{checks:I}})=>{let N=I.find(C=>C.kind==="regex"),Z=I.find(C=>C.kind==="datetime"),D=I.some(C=>C.kind==="jwt"),F=I.find(C=>C.kind==="length"),A={type:"string"},ae={"date-time":l,byte:T,base64url:P,date:h,time:f,duration:w,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:O,jwt:D,ip:d,cidr:g,emoji:p};for(let C in ae)if(ae[C]){A.format=C;break}return F&&([A.minLength,A.maxLength]=[F.value,F.value]),r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),h&&(A.pattern=pn.source),f&&(A.pattern=cn.source),l&&(A.pattern=dn(Z?.offset).source),N&&(A.pattern=N.regex.source),A},Mn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(g=>g.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(g=>g.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,p?l.maximum=d:l.exclusiveMaximum=d,l},gt=({shape:e},t)=>(0,m.map)(t,e),Hn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return an?.[t]},yo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Kn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,W.isSchemaObject)(o)){let i=tt(e,Hn(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(R.z.any())}if(!t&&n.type==="preprocess"&&(0,W.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Dn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Fn=(e,{next:t})=>t(e.unwrap()),qn=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Bn=(e,{next:t})=>t(e.unwrap().shape.raw),fo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,go=(e,t,r=[])=>(0,m.pipe)(Y,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),fo)({schema:e,variant:t?"parsed":"original",validate:!0}),$n=(e,t)=>(0,m.pipe)(Y,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),fo)({schema:e,variant:"original",validate:!0}),be=e=>e instanceof R.z.ZodObject?e:e instanceof R.z.ZodBranded?be(e.unwrap()):e instanceof R.z.ZodUnion||e instanceof R.z.ZodDiscriminatedUnion?e.options.map(t=>be(t)).reduce((t,r)=>t.merge(r.partial()),R.z.object({})):e instanceof R.z.ZodEffects?be(e._def.schema):e instanceof R.z.ZodPipeline?be(e._def.in):be(e._def.left).merge(be(e._def.right)),Vn=e=>e.startsWith("x-")||io.includes(e),ho=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,isHeader:c,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:p}=be(r),l=mn(e),g=o.includes("query"),h=o.includes("params"),f=o.includes("headers"),T=P=>h&&l.includes(P),O=P=>f&&(c?.(P,t,e)??Vn(P));return Object.keys(p).reduce((P,w)=>{let I=T(w)?"path":O(w)?"header":g?"query":void 0;if(!I)return P;let N=xe(p[w],{rules:{...a,...Jt},onEach:Qt,onMissing:Xt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),Z=i==="components"?n(p[w],N,re(d,w)):N;return P.concat({name:w,in:I,required:!p[w].isOptional(),description:N.description||d,schema:Z,examples:$n(r,w)})},[])},Jt={ZodString:Un,ZodNumber:Mn,ZodBigInt:vn,ZodBoolean:Cn,ZodNull:zn,ZodArray:jn,ZodTuple:Ln,ZodRecord:Nn,ZodObject:An,ZodLiteral:wn,ZodIntersection:On,ZodUnion:hn,ZodAny:yn,ZodDefault:ln,ZodEnum:po,ZodNativeEnum:po,ZodEffects:Kn,ZodOptional:Tn,ZodNullable:Pn,ZodDiscriminatedUnion:xn,ZodBranded:Fn,ZodDate:Zn,ZodCatch:un,ZodPipeline:Dn,ZodLazy:qn,ZodReadonly:Rn,[B]:gn,[we]:fn,[ye]:En,[ue]:In,[oe]:Bn},Qt=(e,{isResponse:t,prev:r})=>{if((0,W.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof R.z.ZodLazy,i=r.type!==void 0,a=t&&Fe(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=yo(r)),!n){let p=Y({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Xt=(e,t)=>{throw new U(`Zod type ${e.constructor.name} is unsupported.`,t)},Wt=(e,t)=>{if((0,W.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Wt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Wt(o,t))),r},xo=e=>(0,W.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),bo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${Lt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let g=xo(xe(r,{rules:{...p,...Jt},onEach:Qt,onMissing:Xt,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),h={schema:a==="components"?i(r,g,re(l)):g,examples:go(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[h]))}},_n=()=>({type:"http",scheme:"basic"}),Gn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Yn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Wn=({name:e})=>({type:"apiKey",in:"header",name:e}),Jn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Qn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Xn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),So=(e,t)=>{let r={basic:_n,bearer:Gn,input:Yn,header:Wn,cookie:Jn,openid:Qn,oauth2:Xn};return ft(e,o=>r[o.type](o,t))},ht=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?ht(Yt(e)):ht({or:[e]}),Oo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=xo(Wt(xe(r,{rules:{...a,...Jt},onEach:Qt,onMissing:Xt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:i==="components"?n(r,p,re(d)):p,examples:go(r,!1,c)};return{description:d,content:{[o]:l}}},To=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)},[]),er=e=>e.length<=ao?e:e.slice(0,ao-1)+"\u2026";var xt=class extends Ro.OpenApiBuilder{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||re(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new U(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof i=="string"?[i]:i)this.addServer({url:f});Ue({routing:t,onEndpoint:(f,T,O)=>{let P={path:T,method:O,endpoint:f,composition:g,brandHandling:c,makeRef:this.makeRef.bind(this)},[w,I]=["short","long"].map(f.getDescription.bind(f)),N=w?er(w):l&&I?er(I):void 0,Z=f.getTags(),D=r.inputSources?.[O]||Nt[O],F=this.ensureUniqOperationId(T,O,f.getOperationId(O)),A=ho({...P,inputSources:D,isHeader:p,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:T,operationId:F})}),ae={};for(let G of Ee){let J=f.getResponses(G);for(let{mimeTypes:De,schema:Ko,statusCodes:cr}of J)for(let kt of cr)ae[kt]=bo({...P,variant:G,schema:Ko,mimeTypes:De,statusCode:kt,hasMultipleStatusCodes:J.length>1||cr.length>1,description:a?.[`${G}Response`]?.call(null,{method:O,path:T,operationId:F,statusCode:kt})})}let C=D.includes("body")?Oo({...P,paramNames:(0,Po.pluck)("name",A),schema:f.getSchema("input"),mimeType:z[f.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:T,operationId:F})}):void 0,Je=ht(ft(So(f.getSecurity().reduce(Me,{and:[]}),D),G=>{let J=this.ensureUniqSecuritySchemaName(G),De=["oauth2","openIdConnect"].includes(G.type)?f.getScopes().slice():[];return this.addSecurityScheme(J,G),{name:J,scopes:De}}));this.addPath(lo(T),{[O]:{operationId:F,summary:N,description:I,tags:Z.length>0?Z:void 0,parameters:A.length>0?A:void 0,requestBody:C,security:Je.length>0?Je:void 0,responses:ae}})}}),d&&(this.rootDoc.tags=To(d))}};var bt=require("node-mocks-http"),es=e=>(0,bt.createRequest)({...e,headers:{"content-type":z.json,...e?.headers}}),ts=e=>(0,bt.createResponse)(e),rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Cr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},wo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=es(e),i=ts({req:n,...t});i.req=t?.req||n,n.res=i;let a=rs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Ao=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=wo(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},zo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=wo(o),d=et(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(te(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};var jo=require("ramda"),We=v(require("typescript"),1),Lo=require("zod");var Se=v(require("typescript"),1);var Io=["get","post","put","delete","patch"];var u=v(require("typescript"),1),s=u.default.factory,St=[s.createModifier(u.default.SyntaxKind.ExportKeyword)],os=[s.createModifier(u.default.SyntaxKind.AsyncKeyword)],Ot={public:[s.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[s.createModifier(u.default.SyntaxKind.ProtectedKeyword),s.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},Tt=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),tr=(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)},ns=/^[A-Za-z_$][A-Za-z0-9_$]*$/,rr=e=>typeof e=="number"?s.createNumericLiteral(e):ns.test(e)?s.createIdentifier(e):s.createStringLiteral(e),Rt=(e,...t)=>s.createTemplateExpression(s.createTemplateHead(e),t.map(([r,o=""],n)=>s.createTemplateSpan(r,n===t.length-1?s.createTemplateTail(o):s.createTemplateMiddle(o)))),or=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(u.default.SyntaxKind.StringKeyword),s.createKeywordTypeNode(u.default.SyntaxKind.AnyKeyword)]),Pt=(e,{type:t,mod:r}={})=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),wt=e=>Object.entries(e).map(([t,r])=>Pt(s.createIdentifier(t),{type:r})),Eo=e=>s.createConstructorDeclaration(Ot.public,e,s.createBlock([])),S=e=>typeof e=="string"||u.default.isIdentifier(e)?s.createTypeReferenceNode(e):e,Ke=(e,t,{isOptional:r}={})=>s.createPropertySignature(void 0,rr(e),r?s.createToken(u.default.SyntaxKind.QuestionToken):void 0,S(t)),Zo=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>s.createVariableStatement(o&&St,s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],u.default.NodeFlags.Const)),nr=(e,t)=>V(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{expose:!0}),V=(e,t,{expose:r,comment:o,params:n}={})=>{let i=s.createTypeAliasDeclaration(r?St:void 0,e,n&&ar(n),t);return o?Tt(i,o):i},Co=(e,t,r,{typeParams:o,returns:n}={})=>s.createMethodDeclaration(Ot.public,void 0,e,void 0,o&&ar(o),t,n,r),vo=(e,t)=>s.createClassDeclaration(St,e,void 0,void 0,t),sr=e=>s.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,S(e)),ir=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(u.default.SyntaxKind.AnyKeyword):e]),At=(e,t,{expose:r,comment:o}={})=>{let n=s.createInterfaceDeclaration(r?St:void 0,e,void 0,void 0,t);return o?Tt(n,o):n},ar=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,r&&S(r))),Ge=(e,t,{isAsync:r,typeParams:o}={})=>s.createArrowFunction(r?os:void 0,o&&ar(o),Array.isArray(e)?e.map(n=>Pt(n)):wt(e),void 0,void 0,t),k=e=>e,Ye=(e,t,r)=>s.createConditionalExpression(e,s.createToken(u.default.SyntaxKind.QuestionToken),t,s.createToken(u.default.SyntaxKind.ColonToken),r),_=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),zt=(e,...t)=>s.createNewExpression(e,void 0,t),ss=[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],ko=e=>ss.includes(e.kind);var It=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:s.createIdentifier("Path"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("Client"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),parseRequestFn:s.createIdentifier("parseRequest"),substituteFn:s.createIdentifier("substitute"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),responseConst:s.createIdentifier("response"),restConst:s.createIdentifier("rest"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces={input:s.createIdentifier("Input"),positive:s.createIdentifier("PositiveResponse"),negative:s.createIdentifier("NegativeResponse"),encoded:s.createIdentifier("EncodedResponse"),response:s.createIdentifier("Response")};methodType=nr("Method",Io);someOfType=V("SomeOf",s.createIndexedAccessTypeNode(S("T"),sr("T")),{params:{T:void 0}});requestType=V("Request",sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>s.createTypeReferenceNode(this.someOfType.name,[S(t)]);makePathType=()=>nr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>At(this.interfaces[t],Array.from(this.registry).map(([r,o])=>Ke(r,o[t])),{expose:!0}));makeEndpointTags=()=>L("endpointTags",s.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>s.createPropertyAssignment(rr(t),s.createArrayLiteralExpression(r.map(o=>s.createStringLiteral(o)))))),{expose:!0});makeImplementationType=()=>V(this.ids.implementationType,s.createFunctionTypeNode(void 0,wt({[this.ids.methodParameter.text]:S(this.methodType.name),[this.ids.pathParameter.text]:s.createKeywordTypeNode(Se.default.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:or}),ir("any")),{expose:!0});makeParseRequestFn=()=>L(this.ids.parseRequestFn,Ge({[this.ids.requestParameter.text]:s.createKeywordTypeNode(Se.default.SyntaxKind.StringKeyword)},s.createAsExpression(_(this.ids.requestParameter,k("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)]),s.createTupleTypeNode([S(this.methodType.name),S(this.ids.pathType)]))));makeSubstituteFn=()=>L(this.ids.substituteFn,Ge({[this.ids.pathParameter.text]:s.createKeywordTypeNode(Se.default.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:or},s.createBlock([L(this.ids.restConst,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.paramsArgument)])),s.createForInStatement(s.createVariableDeclarationList([s.createVariableDeclaration(this.ids.keyParameter)],Se.default.NodeFlags.Const),this.ids.paramsArgument,s.createBlock([s.createExpressionStatement(s.createBinaryExpression(this.ids.pathParameter,s.createToken(Se.default.SyntaxKind.EqualsToken),_(this.ids.pathParameter,k("replace"),[Rt(":",[this.ids.keyParameter]),Ge([],s.createBlock([s.createExpressionStatement(s.createDeleteExpression(s.createElementAccessExpression(s.createIdentifier("rest"),this.ids.keyParameter))),s.createReturnStatement(s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))])))])),s.createReturnStatement(s.createAsExpression(s.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),S("const")))])));makeProvider=()=>Co(this.ids.provideMethod,wt({[this.ids.requestParameter.text]:S("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(S(this.interfaces.input),S("K"))}),s.createBlock([L(Zo(this.ids.methodParameter,this.ids.pathParameter),s.createCallExpression(this.ids.parseRequestFn,void 0,[this.ids.requestParameter])),s.createReturnStatement(_(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,s.createSpreadElement(s.createCallExpression(this.ids.substituteFn,void 0,[this.ids.pathParameter,this.ids.paramsArgument]))]))]),{typeParams:{K:this.requestType.name},returns:ir(s.createIndexedAccessTypeNode(S(this.interfaces.response),S("K")))});makeClientClass=()=>vo(this.ids.clientClass,[Eo([Pt(this.ids.implementationArgument,{type:S(this.ids.implementationType),mod:Ot.protectedReadonly})]),this.makeProvider()]);makeExampleImplementation=()=>{let t=s.createPropertyAssignment(k("method"),_(this.ids.methodParameter,k("toUpperCase"))),r=s.createPropertyAssignment(k("headers"),Ye(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(z.json))]),this.ids.undefinedValue)),o=s.createPropertyAssignment(k("body"),Ye(this.ids.hasBodyConst,_(s.createIdentifier(JSON[Symbol.toStringTag]),k("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),n=L(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[zt(s.createIdentifier(URL.name),Rt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),s.createStringLiteral(this.serverUrl)),s.createObjectLiteralExpression([t,r,o])]))),i=L(this.ids.hasBodyConst,s.createLogicalNot(_(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),k("includes"),[this.ids.methodParameter]))),a=L(this.ids.searchParamsConst,Ye(this.ids.hasBodyConst,s.createStringLiteral(""),Rt("?",[zt(s.createIdentifier(URLSearchParams.name),this.ids.paramsArgument)]))),c=L(this.ids.contentTypeConst,_([this.ids.responseConst,k("headers")],k("get"),[s.createStringLiteral("content-type")])),d=s.createIfStatement(s.createPrefixUnaryExpression(Se.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement()),p=L(this.ids.isJsonConst,_(this.ids.contentTypeConst,k("startsWith"),[s.createStringLiteral(z.json)])),l=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,Ye(this.ids.isJsonConst,s.createStringLiteral(k("json")),s.createStringLiteral(k("text")))),void 0,[]));return L(this.ids.exampleImplementationConst,Ge([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([i,a,n,c,d,p,l]),{isAsync:!0}),{expose:!0,type:S(this.ids.implementationType)})};makeUsageStatements=()=>[L(this.ids.clientConst,zt(this.ids.clientClass,this.ids.exampleImplementationConst)),_(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])]};var Zt=require("ramda"),x=v(require("typescript"),1),Et=require("zod");var{factory:y}=x.default,is={[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},as=({value:e})=>y.createLiteralTypeNode(typeof e=="number"?y.createNumericLiteral(e):typeof e=="boolean"?e?y.createTrue():y.createFalse():y.createStringLiteral(e)),ps=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&Fe(a)?a instanceof Et.z.ZodOptional:a.isOptional(),d=Ke(i,r(a),{isOptional:c&&o});return a.description?Tt(d,a.description):d});return y.createTypeLiteralNode(n)},cs=({element:e},{next:t})=>y.createArrayTypeNode(t(e)),ds=({options:e})=>y.createUnionTypeNode(e.map(t=>y.createLiteralTypeNode(y.createStringLiteral(t)))),No=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(ko(n)?n.kind:n,n)}return y.createUnionTypeNode(Array.from(r.values()))},ms=e=>is?.[e.kind],ls=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=tt(e,ms(o)),i={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 y.createKeywordTypeNode(n&&i[n]||x.default.SyntaxKind.AnyKeyword)}return o},us=e=>y.createUnionTypeNode(Object.values(e.enum).map(t=>y.createLiteralTypeNode(typeof t=="number"?y.createNumericLiteral(t):y.createStringLiteral(t)))),ys=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?y.createUnionTypeNode([o,y.createKeywordTypeNode(x.default.SyntaxKind.UndefinedKeyword)]):o},fs=(e,{next:t})=>y.createUnionTypeNode([t(e.unwrap()),y.createLiteralTypeNode(y.createNull())]),gs=({items:e,_def:{rest:t}},{next:r})=>y.createTupleTypeNode(e.map(r).concat(t===null?[]:y.createRestTypeNode(r(t)))),hs=({keySchema:e,valueSchema:t},{next:r})=>y.createExpressionWithTypeArguments(y.createIdentifier("Record"),[e,t].map(r)),xs=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(x.default.isTypeLiteralNode)?y.createTypeLiteralNode((0,Zt.chain)((0,Zt.prop)("members"),o)):y.createIntersectionTypeNode(o)},bs=({_def:e},{next:t})=>t(e.innerType),ie=e=>()=>y.createKeywordTypeNode(e),Ss=(e,{next:t})=>t(e.unwrap()),Os=(e,{next:t})=>t(e.unwrap()),Ts=({_def:e},{next:t})=>t(e.innerType),Rs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ps=()=>y.createLiteralTypeNode(y.createNull()),ws=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),As=e=>{let t=e.unwrap(),r=y.createKeywordTypeNode(x.default.SyntaxKind.StringKeyword),o=S("Buffer"),n=y.createUnionTypeNode([r,o]);return t instanceof Et.z.ZodString?r:t instanceof Et.z.ZodUnion?n:o},zs=(e,{next:t})=>t(e.unwrap().shape.raw),Is={ZodString:ie(x.default.SyntaxKind.StringKeyword),ZodNumber:ie(x.default.SyntaxKind.NumberKeyword),ZodBigInt:ie(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:ie(x.default.SyntaxKind.BooleanKeyword),ZodAny:ie(x.default.SyntaxKind.AnyKeyword),ZodUndefined:ie(x.default.SyntaxKind.UndefinedKeyword),[ue]:ie(x.default.SyntaxKind.StringKeyword),[ye]:ie(x.default.SyntaxKind.StringKeyword),ZodNull:Ps,ZodArray:cs,ZodTuple:gs,ZodRecord:hs,ZodObject:ps,ZodLiteral:as,ZodIntersection:xs,ZodUnion:No,ZodDefault:bs,ZodEnum:ds,ZodNativeEnum:us,ZodEffects:ls,ZodOptional:ys,ZodNullable:fs,ZodDiscriminatedUnion:No,ZodBranded:Ss,ZodCatch:Ts,ZodPipeline:Rs,ZodLazy:ws,ZodReadonly:Os,[B]:As,[oe]:zs},pr=(e,{brandHandling:t,ctx:r})=>xe(e,{rules:{...t,...Is},onMissing:()=>y.createKeywordTypeNode(x.default.SyntaxKind.AnyKeyword),ctx:r});var Ct=class extends It{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=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,V(o,n)),this.aliases.set(t,V(o,r()))}return S(o)}constructor({routing:t,brandHandling:r,variant:o="client",serverUrl:n="https://example.com",optionalPropStyle:i={withQuestionMark:!0,withUndefined:!0},noContent:a=Lo.z.undefined()}){super(n);let c={makeAlias:this.makeAlias.bind(this),optionalPropStyle:i},d={brandHandling:r,ctx:{...c,isResponse:!1}},p={brandHandling:r,ctx:{...c,isResponse:!0}};Ue({routing:t,onEndpoint:(g,h,f)=>{let T=re.bind(null,f,h),O=`${f} ${h}`,P=V(T("input"),pr(g.getSchema("input"),d),{comment:O});this.program.push(P);let w=Ee.reduce((N,Z)=>{let D=g.getResponses(Z),F=(0,jo.chain)(([ae,{schema:C,mimeTypes:Je,statusCodes:G}])=>{let J=V(T(Z,"variant",`${ae+1}`),pr(Je?C:a,p),{comment:O});return this.program.push(J),G.map(De=>Ke(De,J.name))},Array.from(D.entries())),A=At(T(Z,"response","variants"),F,{comment:O});return this.program.push(A),Object.assign(N,{[Z]:A})},{});this.paths.add(h);let I=s.createLiteralTypeNode(s.createStringLiteral(O));this.registry.set(O,{input:S(P.name),positive:this.someOf(w.positive),negative:this.someOf(w.negative),response:s.createUnionTypeNode([s.createIndexedAccessTypeNode(S(this.interfaces.positive),I),s.createIndexedAccessTypeNode(S(this.interfaces.negative),I)]),encoded:s.createIntersectionTypeNode([S(w.positive.name),S(w.negative.name)])}),this.tags.set(O,g.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.makeClientClass()),this.usage.push(this.makeExampleImplementation(),...this.makeUsageStatements()))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:tr(r,t)).join(`
18
+ `))};var ro=e=>{e.startupLogo!==!1&&Xr(process.stdout);let t=e.errorHandler||Ze,r=Zr(e.logger)?e.logger:new ve(e.logger);r.debug("Running",{build:"v22.0.0 (CJS)",env:process.env.NODE_ENV||"development"}),Jr(r);let o=Yr({logger:r,config:e}),i={getLogger:Wr(r),errorHandler:t},a=Vr(i),c=$r(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},oo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=ro(e);return _t({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},no=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=ro(e),c=(0,yt.default)().disable("x-powered-by").use(a);if(e.compression){let h=await Le("compression");c.use(h(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||yt.default.json()],raw:[e.rawParser||yt.default.raw(),Gr],upload:e.upload?await _r({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),_t({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],l=(h,f)=>()=>h.listen(f,()=>r.info("Listening",f)),g=[];if(e.http){let h=eo.default.createServer(c);p.push(h),g.push(l(h,e.http.listen))}if(e.https){let h=to.default.createServer(e.https.options,c);p.push(h),g.push(l(h,e.https.listen))}return e.gracefulShutdown&&Qr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:g.map(h=>h())}};var Ro=require("openapi3-ts/oas31"),Po=require("ramda");var so=require("ramda");var he=e=>me(e)&&"or"in e,He=e=>me(e)&&"and"in e,Gt=e=>({and:(0,so.chain)(t=>He(t)?t.and:[t],e)}),ft=(e,t)=>He(e)?{and:e.and.map(r=>he(r)?{or:r.or.map(t)}:t(r))}:he(e)?{or:e.or.map(r=>He(r)?{and:r.and.map(t)}:t(r))}:t(e),Yt=e=>e.and.reduce((t,r)=>({or:de(t.or,he(r)?r.or:[r],Gt)}),{or:[]}),Me=(e,t)=>He(e)?he(t)?Me(Yt(e),t):Gt([e,t]):he(e)?He(t)?Me(t,e):he(t)?{or:de(e.or,t.or,Gt)}:Me(e,{and:[t]}):He(t)||he(t)?Me(t,e):{and:[e,t]};var W=require("openapi3-ts/oas31"),m=require("ramda"),R=require("zod");var xe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[b]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>xe(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 io=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-patch","accept-post","accept-ranges","accept-signature","access-control","access-control-allow-credentials","access-control-allow-headers","access-control-allow-methods","access-control-allow-origin","access-control-expose-headers","access-control-max-age","access-control-request-headers","access-control-request-method","age","allow","alpn","alt-svc","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","cache-status","cal-managed-id","caldav-timezones","capsule-protocol","cdn-cache-control","cdn-loop","cert-not-after","cert-not-before","clear-site-data","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-base","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-security-policy","content-security-policy-report-only","content-style-type","content-type","content-version","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","etag","expect","expect-ct","expires","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","last-modified","link","link-template","location","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","optional-www-authenticate","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-authenticate","proxy-authentication-info","proxy-authorization","proxy-features","proxy-instruction","proxy-status","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","refresh","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","retry-after","safe","schedule-reply","schedule-tag","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","server","server-timing","set-cookie","set-cookie2","setprofile","signature","signature-input","slug","soapaction","status-uri","strict-transport-security","sunset","surrogate-capability","surrogate-control","tcn","te","timeout","timing-allow-origin","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","vary","via","want-content-digest","want-digest","want-repr-digest","warning","www-authenticate","x-content-type-options","x-frame-options"];var ao=50,co="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",an={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},mo=/:([A-Za-z0-9_]+)/g,pn=/^\d{4}-\d{2}-\d{2}$/,cn=/^\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$/,mn=e=>e.match(mo)?.map(t=>t.slice(1))||[],lo=e=>e.replace(mo,t=>`{${t.slice(1)}}`),ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[b]?.defaultLabel||e.defaultValue()}),un=({_def:{innerType:e}},{next:t})=>t(e),yn=()=>({format:"any"}),fn=({},e)=>{if(e.isResponse)throw new U("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},gn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof R.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},hn=({options:e},{next:t})=>({oneOf:e.map(t)}),xn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),bn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Sn=e=>{let[t,r]=e.filter(W.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(bn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=de(t.examples||[],r.examples||[],([n,i])=>(0,m.mergeDeepRight)(n,i))),o},On=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Sn(o)}catch{}return{allOf:o}},Tn=(e,{next:t})=>t(e.unwrap()),Rn=(e,{next:t})=>t(e.unwrap()),Pn=(e,{next:t})=>{let r=t(e.unwrap());return(0,W.isSchemaObject)(r)&&(r.type=yo(r)),r},uo=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},po=e=>({type:uo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),wn=({value:e})=>({type:uo(e),const:e}),An=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Fe(c)?c instanceof R.z.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=gt(e,r)),i.length&&(a.required=i),a},zn=()=>({type:"null"}),In=({},e)=>{if(e.isResponse)throw new U("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}}},En=({},e)=>{if(!e.isResponse)throw new U("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:co}}},Zn=({},e)=>{throw new U(`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)},Cn=()=>({type:"boolean"}),vn=()=>({type:"integer",format:"bigint"}),kn=e=>e.every(t=>t instanceof R.z.ZodLiteral),Nn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof R.z.ZodEnum||e instanceof R.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=gt(R.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof R.z.ZodLiteral)return{type:"object",properties:gt(R.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof R.z.ZodUnion&&kn(e.options)){let o=(0,m.map)(i=>`${i.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:gt(R.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},jn=({_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},Ln=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Un=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:g,isDate:h,isTime:f,isBase64:T,isNANOID:O,isBase64url:P,isDuration:w,_def:{checks:I}})=>{let N=I.find(C=>C.kind==="regex"),Z=I.find(C=>C.kind==="datetime"),D=I.some(C=>C.kind==="jwt"),F=I.find(C=>C.kind==="length"),A={type:"string"},ae={"date-time":l,byte:T,base64url:P,date:h,time:f,duration:w,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:O,jwt:D,ip:d,cidr:g,emoji:p};for(let C in ae)if(ae[C]){A.format=C;break}return F&&([A.minLength,A.maxLength]=[F.value,F.value]),r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),h&&(A.pattern=pn.source),f&&(A.pattern=cn.source),l&&(A.pattern=dn(Z?.offset).source),N&&(A.pattern=N.regex.source),A},Mn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(g=>g.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(g=>g.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,p?l.maximum=d:l.exclusiveMaximum=d,l},gt=({shape:e},t)=>(0,m.map)(t,e),Hn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return an?.[t]},yo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Kn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,W.isSchemaObject)(o)){let i=tt(e,Hn(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(R.z.any())}if(!t&&n.type==="preprocess"&&(0,W.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Dn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Fn=(e,{next:t})=>t(e.unwrap()),qn=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Bn=(e,{next:t})=>t(e.unwrap().shape.raw),fo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,go=(e,t,r=[])=>(0,m.pipe)(Y,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),fo)({schema:e,variant:t?"parsed":"original",validate:!0}),$n=(e,t)=>(0,m.pipe)(Y,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),fo)({schema:e,variant:"original",validate:!0}),be=e=>e instanceof R.z.ZodObject?e:e instanceof R.z.ZodBranded?be(e.unwrap()):e instanceof R.z.ZodUnion||e instanceof R.z.ZodDiscriminatedUnion?e.options.map(t=>be(t)).reduce((t,r)=>t.merge(r.partial()),R.z.object({})):e instanceof R.z.ZodEffects?be(e._def.schema):e instanceof R.z.ZodPipeline?be(e._def.in):be(e._def.left).merge(be(e._def.right)),Vn=e=>e.startsWith("x-")||io.includes(e),ho=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,isHeader:c,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:p}=be(r),l=mn(e),g=o.includes("query"),h=o.includes("params"),f=o.includes("headers"),T=P=>h&&l.includes(P),O=P=>f&&(c?.(P,t,e)??Vn(P));return Object.keys(p).reduce((P,w)=>{let I=T(w)?"path":O(w)?"header":g?"query":void 0;if(!I)return P;let N=xe(p[w],{rules:{...a,...Jt},onEach:Qt,onMissing:Xt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),Z=i==="components"?n(p[w],N,re(d,w)):N;return P.concat({name:w,in:I,required:!p[w].isOptional(),description:N.description||d,schema:Z,examples:$n(r,w)})},[])},Jt={ZodString:Un,ZodNumber:Mn,ZodBigInt:vn,ZodBoolean:Cn,ZodNull:zn,ZodArray:jn,ZodTuple:Ln,ZodRecord:Nn,ZodObject:An,ZodLiteral:wn,ZodIntersection:On,ZodUnion:hn,ZodAny:yn,ZodDefault:ln,ZodEnum:po,ZodNativeEnum:po,ZodEffects:Kn,ZodOptional:Tn,ZodNullable:Pn,ZodDiscriminatedUnion:xn,ZodBranded:Fn,ZodDate:Zn,ZodCatch:un,ZodPipeline:Dn,ZodLazy:qn,ZodReadonly:Rn,[B]:gn,[we]:fn,[ye]:En,[ue]:In,[oe]:Bn},Qt=(e,{isResponse:t,prev:r})=>{if((0,W.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof R.z.ZodLazy,i=r.type!==void 0,a=t&&Fe(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=yo(r)),!n){let p=Y({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Xt=(e,t)=>{throw new U(`Zod type ${e.constructor.name} is unsupported.`,t)},Wt=(e,t)=>{if((0,W.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Wt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Wt(o,t))),r},xo=e=>(0,W.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),bo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${Lt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let g=xo(xe(r,{rules:{...p,...Jt},onEach:Qt,onMissing:Xt,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),h={schema:a==="components"?i(r,g,re(l)):g,examples:go(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[h]))}},_n=()=>({type:"http",scheme:"basic"}),Gn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Yn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Wn=({name:e})=>({type:"apiKey",in:"header",name:e}),Jn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Qn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Xn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),So=(e,t)=>{let r={basic:_n,bearer:Gn,input:Yn,header:Wn,cookie:Jn,openid:Qn,oauth2:Xn};return ft(e,o=>r[o.type](o,t))},ht=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?ht(Yt(e)):ht({or:[e]}),Oo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=xo(Wt(xe(r,{rules:{...a,...Jt},onEach:Qt,onMissing:Xt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:i==="components"?n(r,p,re(d)):p,examples:go(r,!1,c)};return{description:d,content:{[o]:l}}},To=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)},[]),er=e=>e.length<=ao?e:e.slice(0,ao-1)+"\u2026";var xt=class extends Ro.OpenApiBuilder{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||re(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new U(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof i=="string"?[i]:i)this.addServer({url:f});Ue({routing:t,onEndpoint:(f,T,O)=>{let P={path:T,method:O,endpoint:f,composition:g,brandHandling:c,makeRef:this.makeRef.bind(this)},[w,I]=["short","long"].map(f.getDescription.bind(f)),N=w?er(w):l&&I?er(I):void 0,Z=f.getTags(),D=r.inputSources?.[O]||Nt[O],F=this.ensureUniqOperationId(T,O,f.getOperationId(O)),A=ho({...P,inputSources:D,isHeader:p,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:T,operationId:F})}),ae={};for(let G of Ee){let J=f.getResponses(G);for(let{mimeTypes:De,schema:Ko,statusCodes:cr}of J)for(let kt of cr)ae[kt]=bo({...P,variant:G,schema:Ko,mimeTypes:De,statusCode:kt,hasMultipleStatusCodes:J.length>1||cr.length>1,description:a?.[`${G}Response`]?.call(null,{method:O,path:T,operationId:F,statusCode:kt})})}let C=D.includes("body")?Oo({...P,paramNames:(0,Po.pluck)("name",A),schema:f.getSchema("input"),mimeType:z[f.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:T,operationId:F})}):void 0,Je=ht(ft(So(f.getSecurity().reduce(Me,{and:[]}),D),G=>{let J=this.ensureUniqSecuritySchemaName(G),De=["oauth2","openIdConnect"].includes(G.type)?f.getScopes().slice():[];return this.addSecurityScheme(J,G),{name:J,scopes:De}}));this.addPath(lo(T),{[O]:{operationId:F,summary:N,description:I,tags:Z.length>0?Z:void 0,parameters:A.length>0?A:void 0,requestBody:C,security:Je.length>0?Je:void 0,responses:ae}})}}),d&&(this.rootDoc.tags=To(d))}};var bt=require("node-mocks-http"),es=e=>(0,bt.createRequest)({...e,headers:{"content-type":z.json,...e?.headers}}),ts=e=>(0,bt.createResponse)(e),rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Cr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},wo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=es(e),i=ts({req:n,...t});i.req=t?.req||n,n.res=i;let a=rs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Ao=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=wo(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},zo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=wo(o),d=et(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(te(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};var jo=require("ramda"),We=v(require("typescript"),1),Lo=require("zod");var Se=v(require("typescript"),1);var Io=["get","post","put","delete","patch"];var u=v(require("typescript"),1),s=u.default.factory,St=[s.createModifier(u.default.SyntaxKind.ExportKeyword)],os=[s.createModifier(u.default.SyntaxKind.AsyncKeyword)],Ot={public:[s.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[s.createModifier(u.default.SyntaxKind.ProtectedKeyword),s.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},Tt=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),tr=(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)},ns=/^[A-Za-z_$][A-Za-z0-9_$]*$/,rr=e=>typeof e=="number"?s.createNumericLiteral(e):ns.test(e)?s.createIdentifier(e):s.createStringLiteral(e),Rt=(e,...t)=>s.createTemplateExpression(s.createTemplateHead(e),t.map(([r,o=""],n)=>s.createTemplateSpan(r,n===t.length-1?s.createTemplateTail(o):s.createTemplateMiddle(o)))),or=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(u.default.SyntaxKind.StringKeyword),s.createKeywordTypeNode(u.default.SyntaxKind.AnyKeyword)]),Pt=(e,{type:t,mod:r}={})=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),wt=e=>Object.entries(e).map(([t,r])=>Pt(s.createIdentifier(t),{type:r})),Eo=e=>s.createConstructorDeclaration(Ot.public,e,s.createBlock([])),S=e=>typeof e=="string"||u.default.isIdentifier(e)?s.createTypeReferenceNode(e):e,Ke=(e,t,{isOptional:r}={})=>s.createPropertySignature(void 0,rr(e),r?s.createToken(u.default.SyntaxKind.QuestionToken):void 0,S(t)),Zo=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>s.createVariableStatement(o&&St,s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],u.default.NodeFlags.Const)),nr=(e,t)=>V(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{expose:!0}),V=(e,t,{expose:r,comment:o,params:n}={})=>{let i=s.createTypeAliasDeclaration(r?St:void 0,e,n&&ar(n),t);return o?Tt(i,o):i},Co=(e,t,r,{typeParams:o,returns:n}={})=>s.createMethodDeclaration(Ot.public,void 0,e,void 0,o&&ar(o),t,n,r),vo=(e,t)=>s.createClassDeclaration(St,e,void 0,void 0,t),sr=e=>s.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,S(e)),ir=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(u.default.SyntaxKind.AnyKeyword):e]),At=(e,t,{expose:r,comment:o}={})=>{let n=s.createInterfaceDeclaration(r?St:void 0,e,void 0,void 0,t);return o?Tt(n,o):n},ar=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,r&&S(r))),Ge=(e,t,{isAsync:r,typeParams:o}={})=>s.createArrowFunction(r?os:void 0,o&&ar(o),Array.isArray(e)?e.map(n=>Pt(n)):wt(e),void 0,void 0,t),k=e=>e,Ye=(e,t,r)=>s.createConditionalExpression(e,s.createToken(u.default.SyntaxKind.QuestionToken),t,s.createToken(u.default.SyntaxKind.ColonToken),r),_=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),zt=(e,...t)=>s.createNewExpression(e,void 0,t),ss=[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],ko=e=>ss.includes(e.kind);var It=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:s.createIdentifier("Path"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("Client"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),parseRequestFn:s.createIdentifier("parseRequest"),substituteFn:s.createIdentifier("substitute"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),responseConst:s.createIdentifier("response"),restConst:s.createIdentifier("rest"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces={input:s.createIdentifier("Input"),positive:s.createIdentifier("PositiveResponse"),negative:s.createIdentifier("NegativeResponse"),encoded:s.createIdentifier("EncodedResponse"),response:s.createIdentifier("Response")};methodType=nr("Method",Io);someOfType=V("SomeOf",s.createIndexedAccessTypeNode(S("T"),sr("T")),{params:{T:void 0}});requestType=V("Request",sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>s.createTypeReferenceNode(this.someOfType.name,[S(t)]);makePathType=()=>nr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>At(this.interfaces[t],Array.from(this.registry).map(([r,o])=>Ke(r,o[t])),{expose:!0}));makeEndpointTags=()=>L("endpointTags",s.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>s.createPropertyAssignment(rr(t),s.createArrayLiteralExpression(r.map(o=>s.createStringLiteral(o)))))),{expose:!0});makeImplementationType=()=>V(this.ids.implementationType,s.createFunctionTypeNode(void 0,wt({[this.ids.methodParameter.text]:S(this.methodType.name),[this.ids.pathParameter.text]:s.createKeywordTypeNode(Se.default.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:or}),ir("any")),{expose:!0});makeParseRequestFn=()=>L(this.ids.parseRequestFn,Ge({[this.ids.requestParameter.text]:s.createKeywordTypeNode(Se.default.SyntaxKind.StringKeyword)},s.createAsExpression(_(this.ids.requestParameter,k("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)]),s.createTupleTypeNode([S(this.methodType.name),S(this.ids.pathType)]))));makeSubstituteFn=()=>L(this.ids.substituteFn,Ge({[this.ids.pathParameter.text]:s.createKeywordTypeNode(Se.default.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:or},s.createBlock([L(this.ids.restConst,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.paramsArgument)])),s.createForInStatement(s.createVariableDeclarationList([s.createVariableDeclaration(this.ids.keyParameter)],Se.default.NodeFlags.Const),this.ids.paramsArgument,s.createBlock([s.createExpressionStatement(s.createBinaryExpression(this.ids.pathParameter,s.createToken(Se.default.SyntaxKind.EqualsToken),_(this.ids.pathParameter,k("replace"),[Rt(":",[this.ids.keyParameter]),Ge([],s.createBlock([s.createExpressionStatement(s.createDeleteExpression(s.createElementAccessExpression(s.createIdentifier("rest"),this.ids.keyParameter))),s.createReturnStatement(s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))])))])),s.createReturnStatement(s.createAsExpression(s.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),S("const")))])));makeProvider=()=>Co(this.ids.provideMethod,wt({[this.ids.requestParameter.text]:S("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(S(this.interfaces.input),S("K"))}),s.createBlock([L(Zo(this.ids.methodParameter,this.ids.pathParameter),s.createCallExpression(this.ids.parseRequestFn,void 0,[this.ids.requestParameter])),s.createReturnStatement(_(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,s.createSpreadElement(s.createCallExpression(this.ids.substituteFn,void 0,[this.ids.pathParameter,this.ids.paramsArgument]))]))]),{typeParams:{K:this.requestType.name},returns:ir(s.createIndexedAccessTypeNode(S(this.interfaces.response),S("K")))});makeClientClass=()=>vo(this.ids.clientClass,[Eo([Pt(this.ids.implementationArgument,{type:S(this.ids.implementationType),mod:Ot.protectedReadonly})]),this.makeProvider()]);makeExampleImplementation=()=>{let t=s.createPropertyAssignment(k("method"),_(this.ids.methodParameter,k("toUpperCase"))),r=s.createPropertyAssignment(k("headers"),Ye(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(z.json))]),this.ids.undefinedValue)),o=s.createPropertyAssignment(k("body"),Ye(this.ids.hasBodyConst,_(s.createIdentifier(JSON[Symbol.toStringTag]),k("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),n=L(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[zt(s.createIdentifier(URL.name),Rt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),s.createStringLiteral(this.serverUrl)),s.createObjectLiteralExpression([t,r,o])]))),i=L(this.ids.hasBodyConst,s.createLogicalNot(_(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),k("includes"),[this.ids.methodParameter]))),a=L(this.ids.searchParamsConst,Ye(this.ids.hasBodyConst,s.createStringLiteral(""),Rt("?",[zt(s.createIdentifier(URLSearchParams.name),this.ids.paramsArgument)]))),c=L(this.ids.contentTypeConst,_([this.ids.responseConst,k("headers")],k("get"),[s.createStringLiteral("content-type")])),d=s.createIfStatement(s.createPrefixUnaryExpression(Se.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement()),p=L(this.ids.isJsonConst,_(this.ids.contentTypeConst,k("startsWith"),[s.createStringLiteral(z.json)])),l=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,Ye(this.ids.isJsonConst,s.createStringLiteral(k("json")),s.createStringLiteral(k("text")))),void 0,[]));return L(this.ids.exampleImplementationConst,Ge([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([i,a,n,c,d,p,l]),{isAsync:!0}),{expose:!0,type:S(this.ids.implementationType)})};makeUsageStatements=()=>[L(this.ids.clientConst,zt(this.ids.clientClass,this.ids.exampleImplementationConst)),_(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])]};var Zt=require("ramda"),x=v(require("typescript"),1),Et=require("zod");var{factory:y}=x.default,is={[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},as=({value:e})=>y.createLiteralTypeNode(typeof e=="number"?y.createNumericLiteral(e):typeof e=="boolean"?e?y.createTrue():y.createFalse():y.createStringLiteral(e)),ps=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&Fe(a)?a instanceof Et.z.ZodOptional:a.isOptional(),d=Ke(i,r(a),{isOptional:c&&o});return a.description?Tt(d,a.description):d});return y.createTypeLiteralNode(n)},cs=({element:e},{next:t})=>y.createArrayTypeNode(t(e)),ds=({options:e})=>y.createUnionTypeNode(e.map(t=>y.createLiteralTypeNode(y.createStringLiteral(t)))),No=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(ko(n)?n.kind:n,n)}return y.createUnionTypeNode(Array.from(r.values()))},ms=e=>is?.[e.kind],ls=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=tt(e,ms(o)),i={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 y.createKeywordTypeNode(n&&i[n]||x.default.SyntaxKind.AnyKeyword)}return o},us=e=>y.createUnionTypeNode(Object.values(e.enum).map(t=>y.createLiteralTypeNode(typeof t=="number"?y.createNumericLiteral(t):y.createStringLiteral(t)))),ys=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?y.createUnionTypeNode([o,y.createKeywordTypeNode(x.default.SyntaxKind.UndefinedKeyword)]):o},fs=(e,{next:t})=>y.createUnionTypeNode([t(e.unwrap()),y.createLiteralTypeNode(y.createNull())]),gs=({items:e,_def:{rest:t}},{next:r})=>y.createTupleTypeNode(e.map(r).concat(t===null?[]:y.createRestTypeNode(r(t)))),hs=({keySchema:e,valueSchema:t},{next:r})=>y.createExpressionWithTypeArguments(y.createIdentifier("Record"),[e,t].map(r)),xs=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(x.default.isTypeLiteralNode)?y.createTypeLiteralNode((0,Zt.chain)((0,Zt.prop)("members"),o)):y.createIntersectionTypeNode(o)},bs=({_def:e},{next:t})=>t(e.innerType),ie=e=>()=>y.createKeywordTypeNode(e),Ss=(e,{next:t})=>t(e.unwrap()),Os=(e,{next:t})=>t(e.unwrap()),Ts=({_def:e},{next:t})=>t(e.innerType),Rs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ps=()=>y.createLiteralTypeNode(y.createNull()),ws=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),As=e=>{let t=e.unwrap(),r=y.createKeywordTypeNode(x.default.SyntaxKind.StringKeyword),o=S("Buffer"),n=y.createUnionTypeNode([r,o]);return t instanceof Et.z.ZodString?r:t instanceof Et.z.ZodUnion?n:o},zs=(e,{next:t})=>t(e.unwrap().shape.raw),Is={ZodString:ie(x.default.SyntaxKind.StringKeyword),ZodNumber:ie(x.default.SyntaxKind.NumberKeyword),ZodBigInt:ie(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:ie(x.default.SyntaxKind.BooleanKeyword),ZodAny:ie(x.default.SyntaxKind.AnyKeyword),ZodUndefined:ie(x.default.SyntaxKind.UndefinedKeyword),[ue]:ie(x.default.SyntaxKind.StringKeyword),[ye]:ie(x.default.SyntaxKind.StringKeyword),ZodNull:Ps,ZodArray:cs,ZodTuple:gs,ZodRecord:hs,ZodObject:ps,ZodLiteral:as,ZodIntersection:xs,ZodUnion:No,ZodDefault:bs,ZodEnum:ds,ZodNativeEnum:us,ZodEffects:ls,ZodOptional:ys,ZodNullable:fs,ZodDiscriminatedUnion:No,ZodBranded:Ss,ZodCatch:Ts,ZodPipeline:Rs,ZodLazy:ws,ZodReadonly:Os,[B]:As,[oe]:zs},pr=(e,{brandHandling:t,ctx:r})=>xe(e,{rules:{...t,...Is},onMissing:()=>y.createKeywordTypeNode(x.default.SyntaxKind.AnyKeyword),ctx:r});var Ct=class extends It{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=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,V(o,n)),this.aliases.set(t,V(o,r()))}return S(o)}constructor({routing:t,brandHandling:r,variant:o="client",serverUrl:n="https://example.com",optionalPropStyle:i={withQuestionMark:!0,withUndefined:!0},noContent:a=Lo.z.undefined()}){super(n);let c={makeAlias:this.makeAlias.bind(this),optionalPropStyle:i},d={brandHandling:r,ctx:{...c,isResponse:!1}},p={brandHandling:r,ctx:{...c,isResponse:!0}};Ue({routing:t,onEndpoint:(g,h,f)=>{let T=re.bind(null,f,h),O=`${f} ${h}`,P=V(T("input"),pr(g.getSchema("input"),d),{comment:O});this.program.push(P);let w=Ee.reduce((N,Z)=>{let D=g.getResponses(Z),F=(0,jo.chain)(([ae,{schema:C,mimeTypes:Je,statusCodes:G}])=>{let J=V(T(Z,"variant",`${ae+1}`),pr(Je?C:a,p),{comment:O});return this.program.push(J),G.map(De=>Ke(De,J.name))},Array.from(D.entries())),A=At(T(Z,"response","variants"),F,{comment:O});return this.program.push(A),Object.assign(N,{[Z]:A})},{});this.paths.add(h);let I=s.createLiteralTypeNode(s.createStringLiteral(O));this.registry.set(O,{input:S(P.name),positive:this.someOf(w.positive),negative:this.someOf(w.negative),response:s.createUnionTypeNode([s.createIndexedAccessTypeNode(S(this.interfaces.positive),I),s.createIndexedAccessTypeNode(S(this.interfaces.negative),I)]),encoded:s.createIntersectionTypeNode([S(w.positive.name),S(w.negative.name)])}),this.tags.set(O,g.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.makeClientClass()),this.usage.push(this.makeExampleImplementation(),...this.makeUsageStatements()))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:tr(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.printUsage(t),o=r&&We.default.addSyntheticLeadingComment(We.default.addSyntheticLeadingComment(s.createEmptyStatement(),We.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),We.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.program.concat(o||[]).map((n,i)=>tr(n,i<this.program.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(d.split(`
17
17
  `).map((p,m)=>c[m]?c[m](p):p).join(`
18
- `))};var Ur=e=>{e.startupLogo!==!1&&Lr(process.stdout);let t=e.errorHandler||Ne,r=yr(e.logger)?e.logger:new je(e.logger);r.debug("Running",{build:"v22.0.0-beta.5 (ESM)",env:process.env.NODE_ENV||"development"}),kr(r);let o=Cr({logger:r,config:e}),i={getLogger:vr(r),errorHandler:t},a=Ir(i),c=zr(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},mn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=Ur(e);return It({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},ln=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Ur(e),c=Et().disable("x-powered-by").use(a);if(e.compression){let g=await Se("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Et.json()],raw:[e.rawParser||Et.raw(),Zr],upload:e.upload?await Er({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),It({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],m=(g,y)=>()=>g.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let g=cn.createServer(c);p.push(g),f.push(m(g,e.http.listen))}if(e.https){let g=dn.createServer(e.https.options,c);p.push(g),f.push(m(g,e.https.listen))}return e.gracefulShutdown&&Nr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(g=>g())}};import{OpenApiBuilder as Ts}from"openapi3-ts/oas31";import{pluck as Rs}from"ramda";import{chain as un}from"ramda";var ae=e=>te(e)&&"or"in e,Re=e=>te(e)&&"and"in e,Zt=e=>({and:un(t=>Re(t)?t.and:[t],e)}),tt=(e,t)=>Re(e)?{and:e.and.map(r=>ae(r)?{or:r.or.map(t)}:t(r))}:ae(e)?{or:e.or.map(r=>Re(r)?{and:r.and.map(t)}:t(r))}:t(e),Ct=e=>e.and.reduce((t,r)=>({or:ee(t.or,ae(r)?r.or:[r],Zt)}),{or:[]}),Te=(e,t)=>Re(e)?ae(t)?Te(Ct(e),t):Zt([e,t]):ae(e)?Re(t)?Te(t,e):ae(t)?{or:ee(e.or,t.or,Zt)}:Te(e,{and:[t]}):Re(t)||ae(t)?Te(t,e):{and:[e,t]};import{isReferenceObject as Nt,isSchemaObject as ot}from"openapi3-ts/oas31";import{concat as fn,type as Dr,filter as gn,fromPairs as nt,has as hn,isNil as xn,map as Pe,mergeAll as bn,mergeDeepRight as Sn,mergeDeepWith as On,objOf as Fr,omit as st,pipe as qr,pluck as Tn,reject as Rn,times as Pn,toLower as wn,union as An,when as zn,xprod as vt,zip as In}from"ramda";import{z as P}from"zod";var pe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[x]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>pe(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 Mr=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-patch","accept-post","accept-ranges","accept-signature","access-control","access-control-allow-credentials","access-control-allow-headers","access-control-allow-methods","access-control-allow-origin","access-control-expose-headers","access-control-max-age","access-control-request-headers","access-control-request-method","age","allow","alpn","alt-svc","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","cache-status","cal-managed-id","caldav-timezones","capsule-protocol","cdn-cache-control","cdn-loop","cert-not-after","cert-not-before","clear-site-data","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-base","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-security-policy","content-security-policy-report-only","content-style-type","content-type","content-version","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","etag","expect","expect-ct","expires","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","last-modified","link","link-template","location","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","optional-www-authenticate","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-authenticate","proxy-authentication-info","proxy-authorization","proxy-features","proxy-instruction","proxy-status","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","refresh","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","retry-after","safe","schedule-reply","schedule-tag","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","server","server-timing","set-cookie","set-cookie2","setprofile","signature","signature-input","slug","soapaction","status-uri","strict-transport-security","sunset","surrogate-capability","surrogate-control","tcn","te","timeout","timing-allow-origin","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","vary","via","want-content-digest","want-digest","want-repr-digest","warning","www-authenticate","x-content-type-options","x-frame-options"];var Hr=50,Br="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",En={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},$r=/:([A-Za-z0-9_]+)/g,Zn=/^\d{4}-\d{2}-\d{2}$/,Cn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,vn=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$/,kn=e=>e.match($r)?.map(t=>t.slice(1))||[],Vr=e=>e.replace($r,t=>`{${t.slice(1)}}`),Nn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),jn=({_def:{innerType:e}},{next:t})=>t(e),Ln=()=>({format:"any"}),Un=({},e)=>{if(e.isResponse)throw new N("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Mn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof P.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Hn=({options:e},{next:t})=>({oneOf:e.map(t)}),Kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Dn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return fn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Fn=e=>{let[t,r]=e.filter(ot).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=On(Dn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=An(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([n,i])=>Sn(n,i))),o},qn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Fn(o)}catch{}return{allOf:o}},Bn=(e,{next:t})=>t(e.unwrap()),$n=(e,{next:t})=>t(e.unwrap()),Vn=(e,{next:t})=>{let r=t(e.unwrap());return ot(r)&&(r.type=Gr(r)),r},_r=e=>{let t=wn(Dr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Kr=e=>({type:_r(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),_n=({value:e})=>({type:_r(e),const:e}),Gn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ze(c)?c instanceof P.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=rt(e,r)),i.length&&(a.required=i),a},Yn=()=>({type:"null"}),Wn=({},e)=>{if(e.isResponse)throw new N("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Br}}},Jn=({},e)=>{if(!e.isResponse)throw new N("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Br}}},Qn=({},e)=>{throw new N(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Xn=()=>({type:"boolean"}),es=()=>({type:"integer",format:"bigint"}),ts=e=>e.every(t=>t instanceof P.ZodLiteral),rs=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof P.ZodEnum||e instanceof P.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=rt(P.object(nt(vt(o,[t]))),r),n.required=o),n}if(e instanceof P.ZodLiteral)return{type:"object",properties:rt(P.object({[e.value]:t}),r),required:[e.value]};if(e instanceof P.ZodUnion&&ts(e.options)){let o=Pe(i=>`${i.value}`,e.options),n=nt(vt(o,[t]));return{type:"object",properties:rt(P.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},os=({_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},ns=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ss=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:g,isTime:y,isBase64:O,isNANOID:S,isBase64url:T,isDuration:R,_def:{checks:z}})=>{let v=z.find(E=>E.kind==="regex"),I=z.find(E=>E.kind==="datetime"),j=z.some(E=>E.kind==="jwt"),L=z.find(E=>E.kind==="length"),w={type:"string"},J={"date-time":m,byte:O,base64url:T,date:g,time:y,duration:R,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:S,jwt:j,ip:d,cidr:f,emoji:p};for(let E in J)if(J[E]){w.format=E;break}return L&&([w.minLength,w.maxLength]=[L.value,L.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),g&&(w.pattern=Zn.source),y&&(w.pattern=Cn.source),m&&(w.pattern=vn(I?.offset).source),v&&(w.pattern=v.regex.source),w},is=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=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=i:m.exclusiveMinimum=i,p?m.maximum=d:m.exclusiveMaximum=d,m},rt=({shape:e},t)=>Pe(t,e),as=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return En?.[t]},Gr=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ps=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&ot(o)){let i=qe(e,as(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(P.any())}if(!t&&n.type==="preprocess"&&ot(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},cs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ds=(e,{next:t})=>t(e.unwrap()),ms=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ls=(e,{next:t})=>t(e.unwrap().shape.raw),Yr=e=>e.length?nt(In(Pn(t=>`example${t+1}`,e.length),Pe(Fr("value"),e))):void 0,Wr=(e,t,r=[])=>qr(_,Pe(zn(o=>Dr(o)==="Object",st(r))),Yr)({schema:e,variant:t?"parsed":"original",validate:!0}),us=(e,t)=>qr(_,gn(hn(t)),Tn(t),Yr)({schema:e,variant:"original",validate:!0}),ce=e=>e instanceof P.ZodObject?e:e instanceof P.ZodBranded?ce(e.unwrap()):e instanceof P.ZodUnion||e instanceof P.ZodDiscriminatedUnion?e.options.map(t=>ce(t)).reduce((t,r)=>t.merge(r.partial()),P.object({})):e instanceof P.ZodEffects?ce(e._def.schema):e instanceof P.ZodPipeline?ce(e._def.in):ce(e._def.left).merge(ce(e._def.right)),ys=e=>e.startsWith("x-")||Mr.includes(e),Jr=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,isHeader:c,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:p}=ce(r),m=kn(e),f=o.includes("query"),g=o.includes("params"),y=o.includes("headers"),O=T=>g&&m.includes(T),S=T=>y&&(c?.(T,t,e)??ys(T));return Object.keys(p).reduce((T,R)=>{let z=O(R)?"path":S(R)?"header":f?"query":void 0;if(!z)return T;let v=pe(p[R],{rules:{...a,...jt},onEach:Lt,onMissing:Ut,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),I=i==="components"?n(p[R],v,G(d,R)):v;return T.concat({name:R,in:z,required:!p[R].isOptional(),description:v.description||d,schema:I,examples:us(r,R)})},[])},jt={ZodString:ss,ZodNumber:is,ZodBigInt:es,ZodBoolean:Xn,ZodNull:Yn,ZodArray:os,ZodTuple:ns,ZodRecord:rs,ZodObject:Gn,ZodLiteral:_n,ZodIntersection:qn,ZodUnion:Hn,ZodAny:Ln,ZodDefault:Nn,ZodEnum:Kr,ZodNativeEnum:Kr,ZodEffects:ps,ZodOptional:Bn,ZodNullable:Vn,ZodDiscriminatedUnion:Kn,ZodBranded:ds,ZodDate:Qn,ZodCatch:jn,ZodPipeline:cs,ZodLazy:ms,ZodReadonly:$n,[U]:Mn,[ue]:Un,[oe]:Jn,[re]:Wn,[Y]:ls},Lt=(e,{isResponse:t,prev:r})=>{if(Nt(r))return{};let{description:o}=e,n=e instanceof P.ZodLazy,i=r.type!==void 0,a=t&&Ze(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=Gr(r)),!n){let p=_({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Ut=(e,t)=>{throw new N(`Zod type ${e.constructor.name} is unsupported.`,t)},kt=(e,t)=>{if(Nt(e))return e;let r={...e};return r.properties&&(r.properties=st(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>st(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>kt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>kt(o,t))),r},Qr=e=>Nt(e)?e:st(["examples"],e),Xr=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${St(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=Qr(pe(r,{rules:{...p,...jt},onEach:Lt,onMissing:Ut,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),g={schema:a==="components"?i(r,f,G(m)):f,examples:Wr(r,!0)};return{description:m,content:nt(vt(o,[g]))}},fs=()=>({type:"http",scheme:"basic"}),gs=({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},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),bs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ss=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Os=({flows:e={}})=>({type:"oauth2",flows:Pe(t=>({...t,scopes:t.scopes||{}}),Rn(xn,e))}),eo=(e,t)=>{let r={basic:fs,bearer:gs,input:hs,header:xs,cookie:bs,openid:Ss,oauth2:Os};return tt(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?bn(Pe(({name:r,scopes:o})=>Fr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(Ct(e)):it({or:[e]}),to=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=Qr(kt(pe(r,{rules:{...a,...jt},onEach:Lt,onMissing:Ut,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:i==="components"?n(r,p,G(d)):p,examples:Wr(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)},[]),Mt=e=>e.length<=Hr?e:e.slice(0,Hr-1)+"\u2026";var Ht=class extends Ts{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||G(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new N(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof i=="string"?[i]:i)this.addServer({url:y});Oe({routing:t,onEndpoint:(y,O,S)=>{let T={path:O,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[R,z]=["short","long"].map(y.getDescription.bind(y)),v=R?Mt(R):m&&z?Mt(z):void 0,I=y.getTags(),j=r.inputSources?.[S]||xt[S],L=this.ensureUniqOperationId(O,S,y.getOperationId(S)),w=Jr({...T,inputSources:j,isHeader:p,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:O,operationId:L})}),J={};for(let F of xe){let B=y.getResponses(F);for(let{mimeTypes:Ie,schema:yo,statusCodes:Jt}of B)for(let ht of Jt)J[ht]=Xr({...T,variant:F,schema:yo,mimeTypes:Ie,statusCode:ht,hasMultipleStatusCodes:B.length>1||Jt.length>1,description:a?.[`${F}Response`]?.call(null,{method:S,path:O,operationId:L,statusCode:ht})})}let E=j.includes("body")?to({...T,paramNames:Rs("name",w),schema:y.getSchema("input"),mimeType:A[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:O,operationId:L})}):void 0,Ke=it(tt(eo(y.getSecurity().reduce(Te,{and:[]}),j),F=>{let B=this.ensureUniqSecuritySchemaName(F),Ie=["oauth2","openIdConnect"].includes(F.type)?y.getScopes().slice():[];return this.addSecurityScheme(B,F),{name:B,scopes:Ie}}));this.addPath(Vr(O),{[S]:{operationId:L,summary:v,description:z,tags:I.length>0?I:void 0,parameters:w.length>0?w:void 0,requestBody:E,security:Ke.length>0?Ke:void 0,responses:J}})}}),d&&(this.rootDoc.tags=ro(d))}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var As=e=>Ps({...e,headers:{"content-type":A.json,...e?.headers}}),zs=e=>ws(e),Is=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:fr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},oo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),i=zs({req:n,...t});i.req=t?.req||n,n.res=i;let a=Is(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Es=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=oo(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Zs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=oo(o),d=Fe(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(V(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};import{chain as si}from"ramda";import gt from"typescript";import{z as ii}from"zod";import Ae from"typescript";var no=["get","post","put","delete","patch"];import l from"typescript";var s=l.factory,at=[s.createModifier(l.SyntaxKind.ExportKeyword)],Cs=[s.createModifier(l.SyntaxKind.AsyncKeyword)],pt={public:[s.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[s.createModifier(l.SyntaxKind.ProtectedKeyword),s.createModifier(l.SyntaxKind.ReadonlyKeyword)]},ct=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Kt=(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)},vs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Dt=e=>typeof e=="number"?s.createNumericLiteral(e):vs.test(e)?s.createIdentifier(e):s.createStringLiteral(e),dt=(e,...t)=>s.createTemplateExpression(s.createTemplateHead(e),t.map(([r,o=""],n)=>s.createTemplateSpan(r,n===t.length-1?s.createTemplateTail(o):s.createTemplateMiddle(o)))),Ft=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(l.SyntaxKind.StringKeyword),s.createKeywordTypeNode(l.SyntaxKind.AnyKeyword)]),mt=(e,{type:t,mod:r}={})=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),lt=e=>Object.entries(e).map(([t,r])=>mt(s.createIdentifier(t),{type:r})),so=e=>s.createConstructorDeclaration(pt.public,e,s.createBlock([])),b=e=>typeof e=="string"||l.isIdentifier(e)?s.createTypeReferenceNode(e):e,we=(e,t,{isOptional:r}={})=>s.createPropertySignature(void 0,Dt(e),r?s.createToken(l.SyntaxKind.QuestionToken):void 0,b(t)),io=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),k=(e,t,{type:r,expose:o}={})=>s.createVariableStatement(o&&at,s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],l.NodeFlags.Const)),qt=(e,t)=>K(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{expose:!0}),K=(e,t,{expose:r,comment:o,params:n}={})=>{let i=s.createTypeAliasDeclaration(r?at:void 0,e,n&&Vt(n),t);return o?ct(i,o):i},ao=(e,t,r,{typeParams:o,returns:n}={})=>s.createMethodDeclaration(pt.public,void 0,e,void 0,o&&Vt(o),t,n,r),po=(e,t)=>s.createClassDeclaration(at,e,void 0,void 0,t),Bt=e=>s.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,b(e)),$t=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(l.SyntaxKind.AnyKeyword):e]),ut=(e,t,{expose:r,comment:o}={})=>{let n=s.createInterfaceDeclaration(r?at:void 0,e,void 0,void 0,t);return o?ct(n,o):n},Vt=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,r&&b(r))),Me=(e,t,{isAsync:r,typeParams:o}={})=>s.createArrowFunction(r?Cs:void 0,o&&Vt(o),Array.isArray(e)?e.map(n=>mt(n)):lt(e),void 0,void 0,t),C=e=>e,He=(e,t,r)=>s.createConditionalExpression(e,s.createToken(l.SyntaxKind.QuestionToken),t,s.createToken(l.SyntaxKind.ColonToken),r),D=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),yt=(e,...t)=>s.createNewExpression(e,void 0,t),ks=[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],co=e=>ks.includes(e.kind);var ft=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:s.createIdentifier("Path"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("Client"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),parseRequestFn:s.createIdentifier("parseRequest"),substituteFn:s.createIdentifier("substitute"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),responseConst:s.createIdentifier("response"),restConst:s.createIdentifier("rest"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces={input:s.createIdentifier("Input"),positive:s.createIdentifier("PositiveResponse"),negative:s.createIdentifier("NegativeResponse"),encoded:s.createIdentifier("EncodedResponse"),response:s.createIdentifier("Response")};methodType=qt("Method",no);someOfType=K("SomeOf",s.createIndexedAccessTypeNode(b("T"),Bt("T")),{params:{T:void 0}});requestType=K("Request",Bt(this.interfaces.input),{expose:!0});someOf=({name:t})=>s.createTypeReferenceNode(this.someOfType.name,[b(t)]);makePathType=()=>qt(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])=>we(r,o[t])),{expose:!0}));makeEndpointTags=()=>k("endpointTags",s.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>s.createPropertyAssignment(Dt(t),s.createArrayLiteralExpression(r.map(o=>s.createStringLiteral(o)))))),{expose:!0});makeImplementationType=()=>K(this.ids.implementationType,s.createFunctionTypeNode(void 0,lt({[this.ids.methodParameter.text]:b(this.methodType.name),[this.ids.pathParameter.text]:s.createKeywordTypeNode(Ae.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:Ft}),$t("any")),{expose:!0});makeParseRequestFn=()=>k(this.ids.parseRequestFn,Me({[this.ids.requestParameter.text]:s.createKeywordTypeNode(Ae.SyntaxKind.StringKeyword)},s.createAsExpression(D(this.ids.requestParameter,C("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)]),s.createTupleTypeNode([b(this.methodType.name),b(this.ids.pathType)]))));makeSubstituteFn=()=>k(this.ids.substituteFn,Me({[this.ids.pathParameter.text]:s.createKeywordTypeNode(Ae.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:Ft},s.createBlock([k(this.ids.restConst,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.paramsArgument)])),s.createForInStatement(s.createVariableDeclarationList([s.createVariableDeclaration(this.ids.keyParameter)],Ae.NodeFlags.Const),this.ids.paramsArgument,s.createBlock([s.createExpressionStatement(s.createBinaryExpression(this.ids.pathParameter,s.createToken(Ae.SyntaxKind.EqualsToken),D(this.ids.pathParameter,C("replace"),[dt(":",[this.ids.keyParameter]),Me([],s.createBlock([s.createExpressionStatement(s.createDeleteExpression(s.createElementAccessExpression(s.createIdentifier("rest"),this.ids.keyParameter))),s.createReturnStatement(s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))])))])),s.createReturnStatement(s.createAsExpression(s.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),b("const")))])));makeProvider=()=>ao(this.ids.provideMethod,lt({[this.ids.requestParameter.text]:b("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(b(this.interfaces.input),b("K"))}),s.createBlock([k(io(this.ids.methodParameter,this.ids.pathParameter),s.createCallExpression(this.ids.parseRequestFn,void 0,[this.ids.requestParameter])),s.createReturnStatement(D(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,s.createSpreadElement(s.createCallExpression(this.ids.substituteFn,void 0,[this.ids.pathParameter,this.ids.paramsArgument]))]))]),{typeParams:{K:this.requestType.name},returns:$t(s.createIndexedAccessTypeNode(b(this.interfaces.response),b("K")))});makeClientClass=()=>po(this.ids.clientClass,[so([mt(this.ids.implementationArgument,{type:b(this.ids.implementationType),mod:pt.protectedReadonly})]),this.makeProvider()]);makeExampleImplementation=()=>{let t=s.createPropertyAssignment(C("method"),D(this.ids.methodParameter,C("toUpperCase"))),r=s.createPropertyAssignment(C("headers"),He(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(A.json))]),this.ids.undefinedValue)),o=s.createPropertyAssignment(C("body"),He(this.ids.hasBodyConst,D(s.createIdentifier(JSON[Symbol.toStringTag]),C("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),n=k(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[yt(s.createIdentifier(URL.name),dt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),s.createStringLiteral(this.serverUrl)),s.createObjectLiteralExpression([t,r,o])]))),i=k(this.ids.hasBodyConst,s.createLogicalNot(D(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),C("includes"),[this.ids.methodParameter]))),a=k(this.ids.searchParamsConst,He(this.ids.hasBodyConst,s.createStringLiteral(""),dt("?",[yt(s.createIdentifier(URLSearchParams.name),this.ids.paramsArgument)]))),c=k(this.ids.contentTypeConst,D([this.ids.responseConst,C("headers")],C("get"),[s.createStringLiteral("content-type")])),d=s.createIfStatement(s.createPrefixUnaryExpression(Ae.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement()),p=k(this.ids.isJsonConst,D(this.ids.contentTypeConst,C("startsWith"),[s.createStringLiteral(A.json)])),m=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,He(this.ids.isJsonConst,s.createStringLiteral(C("json")),s.createStringLiteral(C("text")))),void 0,[]));return k(this.ids.exampleImplementationConst,Me([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([i,a,n,c,d,p,m]),{isAsync:!0}),{expose:!0,type:b(this.ids.implementationType)})};makeUsageStatements=()=>[k(this.ids.clientConst,yt(this.ids.clientClass,this.ids.exampleImplementationConst)),D(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])]};import{chain as Ns,prop as js}from"ramda";import h from"typescript";import{z as _t}from"zod";var{factory:u}=h,Ls={[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},Us=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Ms=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&Ze(a)?a instanceof _t.ZodOptional:a.isOptional(),d=we(i,r(a),{isOptional:c&&o});return a.description?ct(d,a.description):d});return u.createTypeLiteralNode(n)},Hs=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ks=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),mo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(co(n)?n.kind:n,n)}return u.createUnionTypeNode(Array.from(r.values()))},Ds=e=>Ls?.[e.kind],Fs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=qe(e,Ds(o)),i={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.createKeywordTypeNode(n&&i[n]||h.SyntaxKind.AnyKeyword)}return o},qs=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Bs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(h.SyntaxKind.UndefinedKeyword)]):o},$s=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Vs=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),_s=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Gs=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(h.isTypeLiteralNode)?u.createTypeLiteralNode(Ns(js("members"),o)):u.createIntersectionTypeNode(o)},Ys=({_def:e},{next:t})=>t(e.innerType),W=e=>()=>u.createKeywordTypeNode(e),Ws=(e,{next:t})=>t(e.unwrap()),Js=(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=()=>u.createLiteralTypeNode(u.createNull()),ti=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ri=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(h.SyntaxKind.StringKeyword),o=b("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof _t.ZodString?r:t instanceof _t.ZodUnion?n:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:W(h.SyntaxKind.StringKeyword),ZodNumber:W(h.SyntaxKind.NumberKeyword),ZodBigInt:W(h.SyntaxKind.BigIntKeyword),ZodBoolean:W(h.SyntaxKind.BooleanKeyword),ZodAny:W(h.SyntaxKind.AnyKeyword),ZodUndefined:W(h.SyntaxKind.UndefinedKeyword),[re]:W(h.SyntaxKind.StringKeyword),[oe]:W(h.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Hs,ZodTuple:Vs,ZodRecord:_s,ZodObject:Ms,ZodLiteral:Us,ZodIntersection:Gs,ZodUnion:mo,ZodDefault:Ys,ZodEnum:Ks,ZodNativeEnum:qs,ZodEffects:Fs,ZodOptional:Bs,ZodNullable:$s,ZodDiscriminatedUnion:mo,ZodBranded:Ws,ZodCatch:Qs,ZodPipeline:Xs,ZodLazy:ti,ZodReadonly:Js,[U]:ri,[Y]:oi},Gt=(e,{brandHandling:t,ctx:r})=>pe(e,{rules:{...t,...ni},onMissing:()=>u.createKeywordTypeNode(h.SyntaxKind.AnyKeyword),ctx:r});var Yt=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=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,K(o,n)),this.aliases.set(t,K(o,r()))}return b(o)}constructor({routing:t,brandHandling:r,variant:o="client",serverUrl:n="https://example.com",optionalPropStyle:i={withQuestionMark:!0,withUndefined:!0},noContent:a=ii.undefined()}){super(n);let c={makeAlias:this.makeAlias.bind(this),optionalPropStyle:i},d={brandHandling:r,ctx:{...c,isResponse:!1}},p={brandHandling:r,ctx:{...c,isResponse:!0}};Oe({routing:t,onEndpoint:(f,g,y)=>{let O=G.bind(null,y,g),S=`${y} ${g}`,T=K(O("input"),Gt(f.getSchema("input"),d),{comment:S});this.program.push(T);let R=xe.reduce((v,I)=>{let j=f.getResponses(I),L=si(([J,{schema:E,mimeTypes:Ke,statusCodes:F}])=>{let B=K(O(I,"variant",`${J+1}`),Gt(Ke?E:a,p),{comment:S});return this.program.push(B),F.map(Ie=>we(Ie,B.name))},Array.from(j.entries())),w=ut(O(I,"response","variants"),L,{comment:S});return this.program.push(w),Object.assign(v,{[I]:w})},{});this.paths.add(g);let z=s.createLiteralTypeNode(s.createStringLiteral(S));this.registry.set(S,{input:b(T.name),positive:this.someOf(R.positive),negative:this.someOf(R.negative),response:s.createUnionTypeNode([s.createIndexedAccessTypeNode(b(this.interfaces.positive),z),s.createIndexedAccessTypeNode(b(this.interfaces.negative),z)]),encoded:s.createIntersectionTypeNode([b(R.positive.name),b(R.negative.name)])}),this.tags.set(S,f.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.makeClientClass()),this.usage.push(this.makeExampleImplementation(),...this.makeUsageStatements()))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Kt(r,t)).join(`
18
+ `))};var Ur=e=>{e.startupLogo!==!1&&Lr(process.stdout);let t=e.errorHandler||Ne,r=yr(e.logger)?e.logger:new je(e.logger);r.debug("Running",{build:"v22.0.0 (ESM)",env:process.env.NODE_ENV||"development"}),kr(r);let o=Cr({logger:r,config:e}),i={getLogger:vr(r),errorHandler:t},a=Ir(i),c=zr(i);return{...i,logger:r,notFoundHandler:a,parserFailureHandler:c,loggingMiddleware:o}},mn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:i}=Ur(e);return It({app:e.app.use(i),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},ln=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Ur(e),c=Et().disable("x-powered-by").use(a);if(e.compression){let g=await Se("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Et.json()],raw:[e.rawParser||Et.raw(),Zr],upload:e.upload?await Er({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),It({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(i,n);let p=[],m=(g,y)=>()=>g.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let g=cn.createServer(c);p.push(g),f.push(m(g,e.http.listen))}if(e.https){let g=dn.createServer(e.https.options,c);p.push(g),f.push(m(g,e.https.listen))}return e.gracefulShutdown&&Nr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(g=>g())}};import{OpenApiBuilder as Ts}from"openapi3-ts/oas31";import{pluck as Rs}from"ramda";import{chain as un}from"ramda";var ae=e=>te(e)&&"or"in e,Re=e=>te(e)&&"and"in e,Zt=e=>({and:un(t=>Re(t)?t.and:[t],e)}),tt=(e,t)=>Re(e)?{and:e.and.map(r=>ae(r)?{or:r.or.map(t)}:t(r))}:ae(e)?{or:e.or.map(r=>Re(r)?{and:r.and.map(t)}:t(r))}:t(e),Ct=e=>e.and.reduce((t,r)=>({or:ee(t.or,ae(r)?r.or:[r],Zt)}),{or:[]}),Te=(e,t)=>Re(e)?ae(t)?Te(Ct(e),t):Zt([e,t]):ae(e)?Re(t)?Te(t,e):ae(t)?{or:ee(e.or,t.or,Zt)}:Te(e,{and:[t]}):Re(t)||ae(t)?Te(t,e):{and:[e,t]};import{isReferenceObject as Nt,isSchemaObject as ot}from"openapi3-ts/oas31";import{concat as fn,type as Dr,filter as gn,fromPairs as nt,has as hn,isNil as xn,map as Pe,mergeAll as bn,mergeDeepRight as Sn,mergeDeepWith as On,objOf as Fr,omit as st,pipe as qr,pluck as Tn,reject as Rn,times as Pn,toLower as wn,union as An,when as zn,xprod as vt,zip as In}from"ramda";import{z as P}from"zod";var pe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[x]?.brand]||r[e._def.typeName],c=i?i(e,{...n,next:p=>pe(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 Mr=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-patch","accept-post","accept-ranges","accept-signature","access-control","access-control-allow-credentials","access-control-allow-headers","access-control-allow-methods","access-control-allow-origin","access-control-expose-headers","access-control-max-age","access-control-request-headers","access-control-request-method","age","allow","alpn","alt-svc","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","cache-status","cal-managed-id","caldav-timezones","capsule-protocol","cdn-cache-control","cdn-loop","cert-not-after","cert-not-before","clear-site-data","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-base","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-security-policy","content-security-policy-report-only","content-style-type","content-type","content-version","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","etag","expect","expect-ct","expires","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","last-modified","link","link-template","location","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","optional-www-authenticate","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-authenticate","proxy-authentication-info","proxy-authorization","proxy-features","proxy-instruction","proxy-status","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","refresh","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","retry-after","safe","schedule-reply","schedule-tag","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","server","server-timing","set-cookie","set-cookie2","setprofile","signature","signature-input","slug","soapaction","status-uri","strict-transport-security","sunset","surrogate-capability","surrogate-control","tcn","te","timeout","timing-allow-origin","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","vary","via","want-content-digest","want-digest","want-repr-digest","warning","www-authenticate","x-content-type-options","x-frame-options"];var Hr=50,Br="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",En={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},$r=/:([A-Za-z0-9_]+)/g,Zn=/^\d{4}-\d{2}-\d{2}$/,Cn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,vn=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$/,kn=e=>e.match($r)?.map(t=>t.slice(1))||[],Vr=e=>e.replace($r,t=>`{${t.slice(1)}}`),Nn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),jn=({_def:{innerType:e}},{next:t})=>t(e),Ln=()=>({format:"any"}),Un=({},e)=>{if(e.isResponse)throw new N("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Mn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof P.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Hn=({options:e},{next:t})=>({oneOf:e.map(t)}),Kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Dn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return fn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Fn=e=>{let[t,r]=e.filter(ot).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=On(Dn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=An(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([n,i])=>Sn(n,i))),o},qn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Fn(o)}catch{}return{allOf:o}},Bn=(e,{next:t})=>t(e.unwrap()),$n=(e,{next:t})=>t(e.unwrap()),Vn=(e,{next:t})=>{let r=t(e.unwrap());return ot(r)&&(r.type=Gr(r)),r},_r=e=>{let t=wn(Dr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Kr=e=>({type:_r(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),_n=({value:e})=>({type:_r(e),const:e}),Gn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ze(c)?c instanceof P.ZodOptional:c.isOptional(),i=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=rt(e,r)),i.length&&(a.required=i),a},Yn=()=>({type:"null"}),Wn=({},e)=>{if(e.isResponse)throw new N("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Br}}},Jn=({},e)=>{if(!e.isResponse)throw new N("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Br}}},Qn=({},e)=>{throw new N(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Xn=()=>({type:"boolean"}),es=()=>({type:"integer",format:"bigint"}),ts=e=>e.every(t=>t instanceof P.ZodLiteral),rs=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof P.ZodEnum||e instanceof P.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=rt(P.object(nt(vt(o,[t]))),r),n.required=o),n}if(e instanceof P.ZodLiteral)return{type:"object",properties:rt(P.object({[e.value]:t}),r),required:[e.value]};if(e instanceof P.ZodUnion&&ts(e.options)){let o=Pe(i=>`${i.value}`,e.options),n=nt(vt(o,[t]));return{type:"object",properties:rt(P.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},os=({_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},ns=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ss=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:g,isTime:y,isBase64:O,isNANOID:S,isBase64url:T,isDuration:R,_def:{checks:z}})=>{let v=z.find(E=>E.kind==="regex"),I=z.find(E=>E.kind==="datetime"),j=z.some(E=>E.kind==="jwt"),L=z.find(E=>E.kind==="length"),w={type:"string"},J={"date-time":m,byte:O,base64url:T,date:g,time:y,duration:R,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:c,nanoid:S,jwt:j,ip:d,cidr:f,emoji:p};for(let E in J)if(J[E]){w.format=E;break}return L&&([w.minLength,w.maxLength]=[L.value,L.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),g&&(w.pattern=Zn.source),y&&(w.pattern=Cn.source),m&&(w.pattern=vn(I?.offset).source),v&&(w.pattern=v.regex.source),w},is=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=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=i:m.exclusiveMinimum=i,p?m.maximum=d:m.exclusiveMaximum=d,m},rt=({shape:e},t)=>Pe(t,e),as=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return En?.[t]},Gr=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ps=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&ot(o)){let i=qe(e,as(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(P.any())}if(!t&&n.type==="preprocess"&&ot(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},cs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ds=(e,{next:t})=>t(e.unwrap()),ms=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ls=(e,{next:t})=>t(e.unwrap().shape.raw),Yr=e=>e.length?nt(In(Pn(t=>`example${t+1}`,e.length),Pe(Fr("value"),e))):void 0,Wr=(e,t,r=[])=>qr(_,Pe(zn(o=>Dr(o)==="Object",st(r))),Yr)({schema:e,variant:t?"parsed":"original",validate:!0}),us=(e,t)=>qr(_,gn(hn(t)),Tn(t),Yr)({schema:e,variant:"original",validate:!0}),ce=e=>e instanceof P.ZodObject?e:e instanceof P.ZodBranded?ce(e.unwrap()):e instanceof P.ZodUnion||e instanceof P.ZodDiscriminatedUnion?e.options.map(t=>ce(t)).reduce((t,r)=>t.merge(r.partial()),P.object({})):e instanceof P.ZodEffects?ce(e._def.schema):e instanceof P.ZodPipeline?ce(e._def.in):ce(e._def.left).merge(ce(e._def.right)),ys=e=>e.startsWith("x-")||Mr.includes(e),Jr=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,isHeader:c,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:p}=ce(r),m=kn(e),f=o.includes("query"),g=o.includes("params"),y=o.includes("headers"),O=T=>g&&m.includes(T),S=T=>y&&(c?.(T,t,e)??ys(T));return Object.keys(p).reduce((T,R)=>{let z=O(R)?"path":S(R)?"header":f?"query":void 0;if(!z)return T;let v=pe(p[R],{rules:{...a,...jt},onEach:Lt,onMissing:Ut,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),I=i==="components"?n(p[R],v,G(d,R)):v;return T.concat({name:R,in:z,required:!p[R].isOptional(),description:v.description||d,schema:I,examples:us(r,R)})},[])},jt={ZodString:ss,ZodNumber:is,ZodBigInt:es,ZodBoolean:Xn,ZodNull:Yn,ZodArray:os,ZodTuple:ns,ZodRecord:rs,ZodObject:Gn,ZodLiteral:_n,ZodIntersection:qn,ZodUnion:Hn,ZodAny:Ln,ZodDefault:Nn,ZodEnum:Kr,ZodNativeEnum:Kr,ZodEffects:ps,ZodOptional:Bn,ZodNullable:Vn,ZodDiscriminatedUnion:Kn,ZodBranded:ds,ZodDate:Qn,ZodCatch:jn,ZodPipeline:cs,ZodLazy:ms,ZodReadonly:$n,[U]:Mn,[ue]:Un,[oe]:Jn,[re]:Wn,[Y]:ls},Lt=(e,{isResponse:t,prev:r})=>{if(Nt(r))return{};let{description:o}=e,n=e instanceof P.ZodLazy,i=r.type!==void 0,a=t&&Ze(e),c=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=Gr(r)),!n){let p=_({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Ut=(e,t)=>{throw new N(`Zod type ${e.constructor.name} is unsupported.`,t)},kt=(e,t)=>{if(Nt(e))return e;let r={...e};return r.properties&&(r.properties=st(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>st(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>kt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>kt(o,t))),r},Qr=e=>Nt(e)?e:st(["examples"],e),Xr=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${St(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=Qr(pe(r,{rules:{...p,...jt},onEach:Lt,onMissing:Ut,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),g={schema:a==="components"?i(r,f,G(m)):f,examples:Wr(r,!0)};return{description:m,content:nt(vt(o,[g]))}},fs=()=>({type:"http",scheme:"basic"}),gs=({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},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),bs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ss=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Os=({flows:e={}})=>({type:"oauth2",flows:Pe(t=>({...t,scopes:t.scopes||{}}),Rn(xn,e))}),eo=(e,t)=>{let r={basic:fs,bearer:gs,input:hs,header:xs,cookie:bs,openid:Ss,oauth2:Os};return tt(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?bn(Pe(({name:r,scopes:o})=>Fr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(Ct(e)):it({or:[e]}),to=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:i,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=Qr(kt(pe(r,{rules:{...a,...jt},onEach:Lt,onMissing:Ut,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:i==="components"?n(r,p,G(d)):p,examples:Wr(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)},[]),Mt=e=>e.length<=Hr?e:e.slice(0,Hr-1)+"\u2026";var Ht=class extends Ts{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||G(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new N(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof i=="string"?[i]:i)this.addServer({url:y});Oe({routing:t,onEndpoint:(y,O,S)=>{let T={path:O,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[R,z]=["short","long"].map(y.getDescription.bind(y)),v=R?Mt(R):m&&z?Mt(z):void 0,I=y.getTags(),j=r.inputSources?.[S]||xt[S],L=this.ensureUniqOperationId(O,S,y.getOperationId(S)),w=Jr({...T,inputSources:j,isHeader:p,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:O,operationId:L})}),J={};for(let F of xe){let B=y.getResponses(F);for(let{mimeTypes:Ie,schema:yo,statusCodes:Jt}of B)for(let ht of Jt)J[ht]=Xr({...T,variant:F,schema:yo,mimeTypes:Ie,statusCode:ht,hasMultipleStatusCodes:B.length>1||Jt.length>1,description:a?.[`${F}Response`]?.call(null,{method:S,path:O,operationId:L,statusCode:ht})})}let E=j.includes("body")?to({...T,paramNames:Rs("name",w),schema:y.getSchema("input"),mimeType:A[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:O,operationId:L})}):void 0,Ke=it(tt(eo(y.getSecurity().reduce(Te,{and:[]}),j),F=>{let B=this.ensureUniqSecuritySchemaName(F),Ie=["oauth2","openIdConnect"].includes(F.type)?y.getScopes().slice():[];return this.addSecurityScheme(B,F),{name:B,scopes:Ie}}));this.addPath(Vr(O),{[S]:{operationId:L,summary:v,description:z,tags:I.length>0?I:void 0,parameters:w.length>0?w:void 0,requestBody:E,security:Ke.length>0?Ke:void 0,responses:J}})}}),d&&(this.rootDoc.tags=ro(d))}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var As=e=>Ps({...e,headers:{"content-type":A.json,...e?.headers}}),zs=e=>ws(e),Is=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:fr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},oo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),i=zs({req:n,...t});i.req=t?.req||n,n.res=i;let a=Is(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:c}},Es=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=oo(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Zs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:c}=oo(o),d=Fe(n,c.inputSources);try{let p=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(V(p),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};import{chain as si}from"ramda";import gt from"typescript";import{z as ii}from"zod";import Ae from"typescript";var no=["get","post","put","delete","patch"];import l from"typescript";var s=l.factory,at=[s.createModifier(l.SyntaxKind.ExportKeyword)],Cs=[s.createModifier(l.SyntaxKind.AsyncKeyword)],pt={public:[s.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[s.createModifier(l.SyntaxKind.ProtectedKeyword),s.createModifier(l.SyntaxKind.ReadonlyKeyword)]},ct=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Kt=(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)},vs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Dt=e=>typeof e=="number"?s.createNumericLiteral(e):vs.test(e)?s.createIdentifier(e):s.createStringLiteral(e),dt=(e,...t)=>s.createTemplateExpression(s.createTemplateHead(e),t.map(([r,o=""],n)=>s.createTemplateSpan(r,n===t.length-1?s.createTemplateTail(o):s.createTemplateMiddle(o)))),Ft=s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[s.createKeywordTypeNode(l.SyntaxKind.StringKeyword),s.createKeywordTypeNode(l.SyntaxKind.AnyKeyword)]),mt=(e,{type:t,mod:r}={})=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),lt=e=>Object.entries(e).map(([t,r])=>mt(s.createIdentifier(t),{type:r})),so=e=>s.createConstructorDeclaration(pt.public,e,s.createBlock([])),b=e=>typeof e=="string"||l.isIdentifier(e)?s.createTypeReferenceNode(e):e,we=(e,t,{isOptional:r}={})=>s.createPropertySignature(void 0,Dt(e),r?s.createToken(l.SyntaxKind.QuestionToken):void 0,b(t)),io=(...e)=>s.createArrayBindingPattern(e.map(t=>s.createBindingElement(void 0,void 0,t))),k=(e,t,{type:r,expose:o}={})=>s.createVariableStatement(o&&at,s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],l.NodeFlags.Const)),qt=(e,t)=>K(e,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r)))),{expose:!0}),K=(e,t,{expose:r,comment:o,params:n}={})=>{let i=s.createTypeAliasDeclaration(r?at:void 0,e,n&&Vt(n),t);return o?ct(i,o):i},ao=(e,t,r,{typeParams:o,returns:n}={})=>s.createMethodDeclaration(pt.public,void 0,e,void 0,o&&Vt(o),t,n,r),po=(e,t)=>s.createClassDeclaration(at,e,void 0,void 0,t),Bt=e=>s.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,b(e)),$t=e=>s.createTypeReferenceNode(Promise.name,[e==="any"?s.createKeywordTypeNode(l.SyntaxKind.AnyKeyword):e]),ut=(e,t,{expose:r,comment:o}={})=>{let n=s.createInterfaceDeclaration(r?at:void 0,e,void 0,void 0,t);return o?ct(n,o):n},Vt=e=>Object.entries(e).map(([t,r])=>s.createTypeParameterDeclaration([],t,r&&b(r))),Me=(e,t,{isAsync:r,typeParams:o}={})=>s.createArrowFunction(r?Cs:void 0,o&&Vt(o),Array.isArray(e)?e.map(n=>mt(n)):lt(e),void 0,void 0,t),C=e=>e,He=(e,t,r)=>s.createConditionalExpression(e,s.createToken(l.SyntaxKind.QuestionToken),t,s.createToken(l.SyntaxKind.ColonToken),r),D=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(Array.isArray(e)?s.createPropertyAccessExpression(...e):e,t),void 0,r),yt=(e,...t)=>s.createNewExpression(e,void 0,t),ks=[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],co=e=>ks.includes(e.kind);var ft=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:s.createIdentifier("Path"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("Client"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),requestParameter:s.createIdentifier("request"),parseRequestFn:s.createIdentifier("parseRequest"),substituteFn:s.createIdentifier("substitute"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),responseConst:s.createIdentifier("response"),restConst:s.createIdentifier("rest"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),contentTypeConst:s.createIdentifier("contentType"),isJsonConst:s.createIdentifier("isJSON")};interfaces={input:s.createIdentifier("Input"),positive:s.createIdentifier("PositiveResponse"),negative:s.createIdentifier("NegativeResponse"),encoded:s.createIdentifier("EncodedResponse"),response:s.createIdentifier("Response")};methodType=qt("Method",no);someOfType=K("SomeOf",s.createIndexedAccessTypeNode(b("T"),Bt("T")),{params:{T:void 0}});requestType=K("Request",Bt(this.interfaces.input),{expose:!0});someOf=({name:t})=>s.createTypeReferenceNode(this.someOfType.name,[b(t)]);makePathType=()=>qt(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])=>we(r,o[t])),{expose:!0}));makeEndpointTags=()=>k("endpointTags",s.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>s.createPropertyAssignment(Dt(t),s.createArrayLiteralExpression(r.map(o=>s.createStringLiteral(o)))))),{expose:!0});makeImplementationType=()=>K(this.ids.implementationType,s.createFunctionTypeNode(void 0,lt({[this.ids.methodParameter.text]:b(this.methodType.name),[this.ids.pathParameter.text]:s.createKeywordTypeNode(Ae.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:Ft}),$t("any")),{expose:!0});makeParseRequestFn=()=>k(this.ids.parseRequestFn,Me({[this.ids.requestParameter.text]:s.createKeywordTypeNode(Ae.SyntaxKind.StringKeyword)},s.createAsExpression(D(this.ids.requestParameter,C("split"),[s.createRegularExpressionLiteral("/ (.+)/"),s.createNumericLiteral(2)]),s.createTupleTypeNode([b(this.methodType.name),b(this.ids.pathType)]))));makeSubstituteFn=()=>k(this.ids.substituteFn,Me({[this.ids.pathParameter.text]:s.createKeywordTypeNode(Ae.SyntaxKind.StringKeyword),[this.ids.paramsArgument.text]:Ft},s.createBlock([k(this.ids.restConst,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.paramsArgument)])),s.createForInStatement(s.createVariableDeclarationList([s.createVariableDeclaration(this.ids.keyParameter)],Ae.NodeFlags.Const),this.ids.paramsArgument,s.createBlock([s.createExpressionStatement(s.createBinaryExpression(this.ids.pathParameter,s.createToken(Ae.SyntaxKind.EqualsToken),D(this.ids.pathParameter,C("replace"),[dt(":",[this.ids.keyParameter]),Me([],s.createBlock([s.createExpressionStatement(s.createDeleteExpression(s.createElementAccessExpression(s.createIdentifier("rest"),this.ids.keyParameter))),s.createReturnStatement(s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))])))])),s.createReturnStatement(s.createAsExpression(s.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),b("const")))])));makeProvider=()=>ao(this.ids.provideMethod,lt({[this.ids.requestParameter.text]:b("K"),[this.ids.paramsArgument.text]:s.createIndexedAccessTypeNode(b(this.interfaces.input),b("K"))}),s.createBlock([k(io(this.ids.methodParameter,this.ids.pathParameter),s.createCallExpression(this.ids.parseRequestFn,void 0,[this.ids.requestParameter])),s.createReturnStatement(D(s.createThis(),this.ids.implementationArgument,[this.ids.methodParameter,s.createSpreadElement(s.createCallExpression(this.ids.substituteFn,void 0,[this.ids.pathParameter,this.ids.paramsArgument]))]))]),{typeParams:{K:this.requestType.name},returns:$t(s.createIndexedAccessTypeNode(b(this.interfaces.response),b("K")))});makeClientClass=()=>po(this.ids.clientClass,[so([mt(this.ids.implementationArgument,{type:b(this.ids.implementationType),mod:pt.protectedReadonly})]),this.makeProvider()]);makeExampleImplementation=()=>{let t=s.createPropertyAssignment(C("method"),D(this.ids.methodParameter,C("toUpperCase"))),r=s.createPropertyAssignment(C("headers"),He(this.ids.hasBodyConst,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(A.json))]),this.ids.undefinedValue)),o=s.createPropertyAssignment(C("body"),He(this.ids.hasBodyConst,D(s.createIdentifier(JSON[Symbol.toStringTag]),C("stringify"),[this.ids.paramsArgument]),this.ids.undefinedValue)),n=k(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier(fetch.name),void 0,[yt(s.createIdentifier(URL.name),dt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),s.createStringLiteral(this.serverUrl)),s.createObjectLiteralExpression([t,r,o])]))),i=k(this.ids.hasBodyConst,s.createLogicalNot(D(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),C("includes"),[this.ids.methodParameter]))),a=k(this.ids.searchParamsConst,He(this.ids.hasBodyConst,s.createStringLiteral(""),dt("?",[yt(s.createIdentifier(URLSearchParams.name),this.ids.paramsArgument)]))),c=k(this.ids.contentTypeConst,D([this.ids.responseConst,C("headers")],C("get"),[s.createStringLiteral("content-type")])),d=s.createIfStatement(s.createPrefixUnaryExpression(Ae.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),s.createReturnStatement()),p=k(this.ids.isJsonConst,D(this.ids.contentTypeConst,C("startsWith"),[s.createStringLiteral(A.json)])),m=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,He(this.ids.isJsonConst,s.createStringLiteral(C("json")),s.createStringLiteral(C("text")))),void 0,[]));return k(this.ids.exampleImplementationConst,Me([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([i,a,n,c,d,p,m]),{isAsync:!0}),{expose:!0,type:b(this.ids.implementationType)})};makeUsageStatements=()=>[k(this.ids.clientConst,yt(this.ids.clientClass,this.ids.exampleImplementationConst)),D(this.ids.clientConst,this.ids.provideMethod,[s.createStringLiteral("get /v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])]};import{chain as Ns,prop as js}from"ramda";import h from"typescript";import{z as _t}from"zod";var{factory:u}=h,Ls={[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},Us=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Ms=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&Ze(a)?a instanceof _t.ZodOptional:a.isOptional(),d=we(i,r(a),{isOptional:c&&o});return a.description?ct(d,a.description):d});return u.createTypeLiteralNode(n)},Hs=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ks=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),mo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(co(n)?n.kind:n,n)}return u.createUnionTypeNode(Array.from(r.values()))},Ds=e=>Ls?.[e.kind],Fs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=qe(e,Ds(o)),i={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.createKeywordTypeNode(n&&i[n]||h.SyntaxKind.AnyKeyword)}return o},qs=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Bs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(h.SyntaxKind.UndefinedKeyword)]):o},$s=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Vs=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),_s=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Gs=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(h.isTypeLiteralNode)?u.createTypeLiteralNode(Ns(js("members"),o)):u.createIntersectionTypeNode(o)},Ys=({_def:e},{next:t})=>t(e.innerType),W=e=>()=>u.createKeywordTypeNode(e),Ws=(e,{next:t})=>t(e.unwrap()),Js=(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=()=>u.createLiteralTypeNode(u.createNull()),ti=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ri=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(h.SyntaxKind.StringKeyword),o=b("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof _t.ZodString?r:t instanceof _t.ZodUnion?n:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:W(h.SyntaxKind.StringKeyword),ZodNumber:W(h.SyntaxKind.NumberKeyword),ZodBigInt:W(h.SyntaxKind.BigIntKeyword),ZodBoolean:W(h.SyntaxKind.BooleanKeyword),ZodAny:W(h.SyntaxKind.AnyKeyword),ZodUndefined:W(h.SyntaxKind.UndefinedKeyword),[re]:W(h.SyntaxKind.StringKeyword),[oe]:W(h.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Hs,ZodTuple:Vs,ZodRecord:_s,ZodObject:Ms,ZodLiteral:Us,ZodIntersection:Gs,ZodUnion:mo,ZodDefault:Ys,ZodEnum:Ks,ZodNativeEnum:qs,ZodEffects:Fs,ZodOptional:Bs,ZodNullable:$s,ZodDiscriminatedUnion:mo,ZodBranded:Ws,ZodCatch:Qs,ZodPipeline:Xs,ZodLazy:ti,ZodReadonly:Js,[U]:ri,[Y]:oi},Gt=(e,{brandHandling:t,ctx:r})=>pe(e,{rules:{...t,...ni},onMissing:()=>u.createKeywordTypeNode(h.SyntaxKind.AnyKeyword),ctx:r});var Yt=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=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,K(o,n)),this.aliases.set(t,K(o,r()))}return b(o)}constructor({routing:t,brandHandling:r,variant:o="client",serverUrl:n="https://example.com",optionalPropStyle:i={withQuestionMark:!0,withUndefined:!0},noContent:a=ii.undefined()}){super(n);let c={makeAlias:this.makeAlias.bind(this),optionalPropStyle:i},d={brandHandling:r,ctx:{...c,isResponse:!1}},p={brandHandling:r,ctx:{...c,isResponse:!0}};Oe({routing:t,onEndpoint:(f,g,y)=>{let O=G.bind(null,y,g),S=`${y} ${g}`,T=K(O("input"),Gt(f.getSchema("input"),d),{comment:S});this.program.push(T);let R=xe.reduce((v,I)=>{let j=f.getResponses(I),L=si(([J,{schema:E,mimeTypes:Ke,statusCodes:F}])=>{let B=K(O(I,"variant",`${J+1}`),Gt(Ke?E:a,p),{comment:S});return this.program.push(B),F.map(Ie=>we(Ie,B.name))},Array.from(j.entries())),w=ut(O(I,"response","variants"),L,{comment:S});return this.program.push(w),Object.assign(v,{[I]:w})},{});this.paths.add(g);let z=s.createLiteralTypeNode(s.createStringLiteral(S));this.registry.set(S,{input:b(T.name),positive:this.someOf(R.positive),negative:this.someOf(R.negative),response:s.createUnionTypeNode([s.createIndexedAccessTypeNode(b(this.interfaces.positive),z),s.createIndexedAccessTypeNode(b(this.interfaces.negative),z)]),encoded:s.createIntersectionTypeNode([b(R.positive.name),b(R.negative.name)])}),this.tags.set(S,f.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.makeClientClass()),this.usage.push(this.makeExampleImplementation(),...this.makeUsageStatements()))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Kt(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.printUsage(t),o=r&&gt.addSyntheticLeadingComment(gt.addSyntheticLeadingComment(s.createEmptyStatement(),gt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),gt.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.program.concat(o||[]).map((n,i)=>Kt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
@@ -1,4 +1,4 @@
1
- "use strict";var o=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var u=(r,e)=>{for(var t in e)o(r,t,{get:e[t],enumerable:!0})},y=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of d(e))!m.call(r,n)&&n!==t&&o(r,n,{get:()=>e[n],enumerable:!(i=c(e,n))||i.enumerable});return r};var g=r=>y(o({},"__esModule",{value:!0}),r);var b={};u(b,{default:()=>T});module.exports=g(b);var s=require("@typescript-eslint/utils");var a=["get","post","put","delete","patch"];var p="express-zod-api";var f={provide:`${s.AST_NODE_TYPES.CallExpression}[callee.property.name='provide'][arguments.length=3]:has(${s.AST_NODE_TYPES.Literal}[value=/^${a.join("|")}$/] + ${s.AST_NODE_TYPES.Literal} + ${s.AST_NODE_TYPES.ObjectExpression})`,splitResponse:`${s.AST_NODE_TYPES.NewExpression}[callee.name='Integration'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='splitResponse']`,methodPath:`${s.AST_NODE_TYPES.ImportDeclaration} > ${s.AST_NODE_TYPES.ImportSpecifier}[imported.name='MethodPath']`,createConfig:`${s.AST_NODE_TYPES.CallExpression}[callee.name='createConfig'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='tags'][value.type='ObjectExpression']`,newDocs:`${s.AST_NODE_TYPES.NewExpression}[callee.name='Documentation'] > ${s.AST_NODE_TYPES.ObjectExpression}[properties.length>0]:not(:has(>Property[key.name='tags']))`,newFactory:`${s.AST_NODE_TYPES.NewExpression}[callee.name='EndpointsFactory'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='resultHandler']`,newSSE:`${s.AST_NODE_TYPES.NewExpression}[callee.name='EventStreamFactory'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='events']`,newClient:`${s.AST_NODE_TYPES.NewExpression}[callee.name='ExpressZodAPIClient']`},h=r=>Object.keys(r).reduce((e,t)=>Object.assign(e,{[f[t]]:r[t]}),{}),S=s.ESLintUtils.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{add:"Add {{subject}} to {{to}}",change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:r=>h({provide:e=>{let{arguments:[t,i]}=e,n=`"${t.value} ${i.value}"`;r.report({messageId:"change",node:e,data:{subject:"arguments",from:`"${t.value}", "${i.value}"`,to:n},fix:l=>l.replaceTextRange([t.range[0],i.range[1]],n)})},splitResponse:e=>r.report({messageId:"remove",node:e,data:{subject:"property",name:e.key.name},fix:t=>t.remove(e)}),methodPath:e=>{let t="Request";r.report({messageId:"change",node:e.imported,data:{subject:"type",from:e.imported.name,to:t},fix:i=>i.replaceText(e.imported,t)})},createConfig:e=>{let t=e.value.properties.filter(i=>"key"in i&&"name"in i.key).map(i=>` "${i.key.name}": unknown,
1
+ "use strict";var o=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var u=(r,e)=>{for(var t in e)o(r,t,{get:e[t],enumerable:!0})},y=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of d(e))!m.call(r,n)&&n!==t&&o(r,n,{get:()=>e[n],enumerable:!(i=c(e,n))||i.enumerable});return r};var g=r=>y(o({},"__esModule",{value:!0}),r);var E={};u(E,{default:()=>T});module.exports=g(E);var s=require("@typescript-eslint/utils");var a=["get","post","put","delete","patch"];var p="express-zod-api";var f={provide:`${s.AST_NODE_TYPES.CallExpression}[callee.property.name='provide'][arguments.length=3]:has(${s.AST_NODE_TYPES.Literal}[value=/^${a.join("|")}$/] + ${s.AST_NODE_TYPES.Literal} + ${s.AST_NODE_TYPES.ObjectExpression})`,splitResponse:`${s.AST_NODE_TYPES.NewExpression}[callee.name='Integration'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='splitResponse']`,methodPath:`${s.AST_NODE_TYPES.ImportDeclaration} > ${s.AST_NODE_TYPES.ImportSpecifier}[imported.name='MethodPath']`,createConfig:`${s.AST_NODE_TYPES.CallExpression}[callee.name='createConfig'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='tags'][value.type='ObjectExpression']`,newDocs:`${s.AST_NODE_TYPES.NewExpression}[callee.name='Documentation'] > ${s.AST_NODE_TYPES.ObjectExpression}[properties.length>0]:not(:has(>Property[key.name='tags']))`,newFactory:`${s.AST_NODE_TYPES.NewExpression}[callee.name='EndpointsFactory'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='resultHandler']`,newSSE:`${s.AST_NODE_TYPES.NewExpression}[callee.name='EventStreamFactory'] > ${s.AST_NODE_TYPES.ObjectExpression} > ${s.AST_NODE_TYPES.Property}[key.name='events']`,newClient:`${s.AST_NODE_TYPES.NewExpression}[callee.name='ExpressZodAPIClient']`},h=r=>Object.keys(r).reduce((e,t)=>Object.assign(e,{[f[t]]:r[t]}),{}),S=s.ESLintUtils.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{add:"Add {{subject}} to {{to}}",change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:r=>h({provide:e=>{let{arguments:[t,i]}=e,n=`"${t.value} ${i.value}"`;r.report({messageId:"change",node:e,data:{subject:"arguments",from:`"${t.value}", "${i.value}"`,to:n},fix:l=>l.replaceTextRange([t.range[0],i.range[1]],n)})},splitResponse:e=>r.report({messageId:"remove",node:e,data:{subject:"property",name:e.key.name},fix:t=>t.remove(e)}),methodPath:e=>{let t="Request";r.report({messageId:"change",node:e.imported,data:{subject:"type",from:e.imported.name,to:t},fix:i=>i.replaceText(e.imported,t)})},createConfig:e=>{let t=e.value.properties.filter(i=>"key"in i&&"name"in i.key).map(i=>` "${i.key.name}": unknown,
2
2
  `);r.report({messageId:"remove",node:e,data:{subject:"property",name:e.key.name},fix:i=>[i.remove(e),i.insertTextAfter(r.sourceCode.ast,`
3
3
  // Declaring tag constraints
4
4
  declare module "${p}" {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "22.0.0-beta.5",
3
+ "version": "22.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": {