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