express-zod-api 22.12.0 → 22.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,13 +2,32 @@
2
2
 
3
3
  ## Version 22
4
4
 
5
+ ### v22.13.0
6
+
7
+ - Ability to configure and disable access logging:
8
+ - New config option: `accessLogger` — the function for producing access logs;
9
+ - The default value is the function writing messages similar to `GET: /v1/path` having `debug` severity;
10
+ - The option can be assigned with `null` to disable writing of access logs;
11
+ - Thanks to the contributions of [@gmorgen1](https://github.com/gmorgen1) and [@crgeary](https://github.com/crgeary);
12
+ - [@danmichaelo](https://github.com/danmichaelo) fixed a broken link in the Security policy;
13
+ - Added JSDoc for several types involved into creating Middlewares and producing Endpoints.
14
+
15
+ ```ts
16
+ import { createConfig } from "express-zod-api";
17
+
18
+ const config = createConfig({
19
+ accessLogger: (request, logger) => logger.info(request.path), // or null to disable
20
+ });
21
+ ```
22
+
5
23
  ### v22.12.0
6
24
 
7
25
  - Featuring HTML forms support (URL Encoded request body):
8
26
  - Introducing the new proprietary schema `ez.form()` accepting an object shape or a custom `z.object()` schema;
9
27
  - Introducing the new config option `formParser` having `express.urlencoded()` as the default value;
10
28
  - Requests to Endpoints having `input` schema assigned with `ez.form()` are parsed using `formParser`;
11
- - Exception: requests to Endpoints having `ez.upload()` within `ez.form()` are still parsed by `express-fileupload`.
29
+ - Exception: requests to Endpoints having `ez.upload()` within `ez.form()` are still parsed by `express-fileupload`;
30
+ - The lack of this feature was reported by [@james10424](https://github.com/james10424).
12
31
 
13
32
  ```ts
14
33
  import { defaultEndpointsFactory, ez } from "express-zod-api";
@@ -1394,7 +1413,7 @@ new Integration({
1394
1413
  - This makes all requests eligible for the assigned parsers and reverts changes made in [v18.5.2](#v1852);
1395
1414
  - Specifying `rawParser` in config is no longer needed to enable the feature.
1396
1415
  - Non-breaking significant changes:
1397
- - Request logging reflects the actual path instead of the configured route, and it's placed in front of parsing:
1416
+ - Access logging reflects the actual path instead of the configured route, and it's placed in front of parsing:
1398
1417
  - The severity of those messaged reduced from `info` to `debug`;
1399
1418
  - The debug messages from uploader are enabled by default when the logger level is set to `debug`;
1400
1419
  - How to migrate confidently:
package/README.md CHANGED
@@ -88,6 +88,10 @@ 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/gmorgen1.png" alt="@gmorgen1" width="50px" />](https://github.com/gmorgen1)
92
+ [<img src="https://github.com/crgeary.png" alt="@crgeary" width="50px" />](https://github.com/crgeary)
93
+ [<img src="https://github.com/danmichaelo.png" alt="@danmichaelo" width="50px" />](https://github.com/danmichaelo)
94
+ [<img src="https://github.com/james10424.png" alt="@james10424" width="50px" />](https://github.com/james10424)
91
95
  [<img src="https://github.com/APTy.png" alt="@APTy" width="50px" />](https://github.com/APTy)
92
96
  [<img src="https://github.com/LufyCZ.png" alt="@LufyCZ" width="50px" />](https://github.com/LufyCZ)
93
97
  [<img src="https://github.com/mlms13.png" alt="@mlms13" width="50px" />](https://github.com/mlms13)
package/SECURITY.md CHANGED
@@ -32,6 +32,6 @@
32
32
  Found a vulnerability or other security issue?
33
33
 
34
34
  Please urgently inform me privately by
35
- [email](https://github.com/RobinTail/express-zod-api/blob/master/package.json#L14).
35
+ [email](https://github.com/RobinTail/express-zod-api/blob/master/express-zod-api/package.json#L14).
36
36
 
37
37
  I will try to fix it as soon as possible.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";var dn=Object.create;var ct=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var ln=Object.getOwnPropertyNames;var un=Object.getPrototypeOf,fn=Object.prototype.hasOwnProperty;var yn=(e,t)=>{for(var r in t)ct(e,r,{get:t[r],enumerable:!0})},Er=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ln(t))!fn.call(e,n)&&n!==r&&ct(e,n,{get:()=>t[n],enumerable:!(o=mn(t,n))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?dn(un(e)):{},Er(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),gn=e=>Er(ct({},"__esModule",{value:!0}),e);var ni={};yn(ni,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>It,DocumentationError:()=>B,EndpointsFactory:()=>ye,EventStreamFactory:()=>Ht,InputValidationError:()=>X,Integration:()=>Dt,Middleware:()=>V,MissingPeerError:()=>ve,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>be,ServeStatic:()=>qe,arrayEndpointsFactory:()=>_r,arrayResultHandler:()=>Pt,attachRouting:()=>Po,createConfig:()=>Ir,createServer:()=>wo,defaultEndpointsFactory:()=>$r,defaultResultHandler:()=>Ue,ensureHttpError:()=>we,ez:()=>cn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>Wo,testMiddleware:()=>Yo});module.exports=gn(ni);var H=S(require("ramda"),1),Te=require("zod");var D=S(require("ramda"),1),$t=require("zod");var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var be=class extends Error{name="RoutingError"},B=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},dt=class extends Error{name="IOSchemaError"},ae=class extends dt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends dt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(ce(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},ve=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var _t=/:([A-Za-z0-9_]+)/g,mt=e=>e.match(_t)?.map(t=>t.slice(1))||[],hn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},Vt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},bn=["body","query","params"],Gt=e=>e.method.toLowerCase(),lt=(e,t={})=>{let r=Gt(e);return r==="options"?{}:(t[r]||Vt[r]||bn).filter(o=>o==="files"?hn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof $t.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ae?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,xn=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return xe(t,(n[g]?.examples||[]).map(D.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[g]?.examples||[];if(!n.length&&o&&e instanceof $t.z.ZodObject&&(n=xn(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},xe=(e,t,r)=>e.length&&t.length?D.xprod(e,t).map(r):e.concat(t),Ge=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=D.chain(o=>o.split(/[^A-Z0-9]/gi),e);return D.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Jt).join("")},ut=D.tryCatch((e,t)=>typeof e.parse(t),D.always(void 0)),Se=e=>typeof e=="object"&&e!==null,Re=D.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ft=S(require("ramda"),1),g=Symbol.for("express-zod-api"),Je=e=>{let t=e.describe(e.description);return t._def[g]=ft.clone(t._def[g])||{examples:[]},t},zr=(e,t)=>{if(!(g in e._def))return t;let r=Je(t);return r._def[g].examples=xe(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?ft.mergeDeepRight({...o},{...n}):n),r};var Sn=function(e){let t=Je(this);return t._def[g].examples.push(e),t},Rn=function(){let e=Je(this);return e._def[g].isDeprecated=!0,e},Tn=function(e){let t=Je(this);return t._def[g].defaultLabel=e,t},On=function(e){return new Te.z.ZodBranded({typeName:Te.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...H.clone(this._def[g]),brand:e}})},Pn=function(e){let t=typeof e=="function"?e:H.pipe(H.toPairs,H.map(([n,s])=>H.pair(e[String(n)]||n,s)),H.fromPairs),r=t(H.clone(this.shape)),o=Te.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Te.z.ZodType.prototype,{example:{get(){return Sn.bind(this)}},deprecated:{get(){return Rn.bind(this)}},brand:{set(){},get(){return On.bind(this)}}}),Object.defineProperty(Te.z.ZodDefault.prototype,"label",{get(){return Tn.bind(this)}}),Object.defineProperty(Te.z.ZodObject.prototype,"remap",{get(){return Pn.bind(this)}}));function Ir(e){return e}var rr=require("zod");var er=require("zod");var L=require("node:assert/strict");var ke=require("zod");var yt=e=>!isNaN(e.getTime());var Oe=Symbol("DateIn"),Zr=()=>ke.z.union([ke.z.string().date(),ke.z.string().datetime(),ke.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ke.z.date().refine(yt)).brand(Oe);var vr=require("zod");var Pe=Symbol("DateOut"),kr=()=>vr.z.date().refine(yt).transform(e=>e.toISOString()).brand(Pe);var We=require("zod"),ee=Symbol("File"),Cr=We.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),wn={buffer:()=>Cr.brand(ee),string:()=>We.z.string().brand(ee),binary:()=>Cr.or(We.z.string()).brand(ee),base64:()=>We.z.string().base64().brand(ee)};function gt(e){return wn[e||"string"]()}var Wt=require("zod"),ht=Symbol("Form"),jr=e=>(e instanceof Wt.z.ZodObject?e:Wt.z.object(e)).brand(ht);var Nr=require("zod");var le=Symbol("Raw"),Lr=(e={})=>Nr.z.object({raw:gt("buffer")}).extend(e).brand(le);var Mr=require("zod"),Ce=Symbol("Upload"),Ur=()=>Mr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ce);var Dr=(e,{next:t})=>e.options.some(t),An=({_def:e},{next:t})=>[e.left,e.right].some(t),bt=(e,{next:t})=>t(e.unwrap()),xt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Dr,ZodDiscriminatedUnion:Dr,ZodIntersection:An,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:bt,ZodNullable:bt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Ye=(e,{condition:t,rules:r=xt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Ye(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Hr=e=>Ye(e,{condition:t=>t._def[g]?.brand===Ce,rules:{...xt,[ht]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),St=e=>Ye(e,{condition:t=>t._def[g]?.brand===le,maxDepth:3}),Kr=e=>Ye(e,{condition:t=>t._def[g]?.brand===ht,maxDepth:3}),Fr=(e,t)=>{let r=new WeakSet;return Ye(e,{maxDepth:300,rules:{...xt,ZodBranded:bt,ZodReadonly:bt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:xt.ZodEffects}[t],ZodNaN:()=>(0,L.fail)("z.nan()"),ZodSymbol:()=>(0,L.fail)("z.symbol()"),ZodFunction:()=>(0,L.fail)("z.function()"),ZodMap:()=>(0,L.fail)("z.map()"),ZodSet:()=>(0,L.fail)("z.set()"),ZodBigInt:()=>(0,L.fail)("z.bigint()"),ZodVoid:()=>(0,L.fail)("z.void()"),ZodPromise:()=>(0,L.fail)("z.promise()"),ZodNever:()=>(0,L.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,L.fail)("z.date()"),[Pe]:()=>t==="in"&&(0,L.fail)("ez.dateOut()"),[Oe]:()=>t==="out"&&(0,L.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,L.fail)("ez.raw()"),[Ce]:()=>t==="out"&&(0,L.fail)("ez.upload()"),[ee]:()=>!1}})};var Rt=S(require("http-errors"),1);var Qe=S(require("http-errors"),1),qr=require("zod");var Yt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof qr.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},Xe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>(0,Qe.isHttpError)(e)?e:(0,Qe.default)(e instanceof X?400:500,ce(e),{cause:e.cause||e}),Ae=e=>Re()&&!e.expose?(0,Qe.default)(e.statusCode).message:e.message;var Tt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ae((0,Rt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:(0,Rt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Qt=require("zod");var Xt=class{},V=class extends Xt{#e;#t;#r;constructor({input:t=Qt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Qt.z.ZodError?new X(o):o}}},je=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ne=class{nest(t){return Object.assign(t,{"":this})}};var et=class extends Ne{},Ot=class e extends et{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Hr(this.#e.inputSchema)?"upload":St(this.#e.inputSchema)?"raw":Kr(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof er.z.ZodError?new ae(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof je))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof er.z.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){Tt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Gt(t),a={},c=null,m=null,p=lt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};var ue=require("zod");var Br=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>zr(s,n),o)},G=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?G(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>G(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?G(e._def.schema):e instanceof ue.z.ZodPipeline?G(e._def.in):G(e._def.left).merge(G(e._def.right));var J=require("zod");var Le={positive:200,negative:400},Me=Object.keys(Le);var tr=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends tr{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Yt(this.#e,{variant:"positive",args:[t],statusCodes:[Le.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[C.json]})}},Ue=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.z.object({status:J.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.z.object({status:J.z.literal("error"),error:J.z.object({message:J.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=we(e);return Xe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.positive).json({status:"success",data:r})}}),Pt=new fe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof J.z.ZodArray?e.shape.items:J.z.array(J.z.any());return t.reduce((o,n)=>Se(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=we(r);return Xe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new je(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=rr.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new Ot({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:h,tags:x,methods:l,getOperationId:b,inputSchema:Br(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:rr.z.object({}),handler:async o=>(await t(o),{})})}},$r=new ye(Ue),_r=new ye(Pt);var Qr=S(require("ansis"),1),Xr=require("node:util"),nr=require("node:perf_hooks");var te=require("ansis"),Vr=S(require("ramda"),1);var or={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},wt={debug:10,info:20,warn:30,error:40},Gr=e=>Se(e)&&Object.keys(wt).some(t=>t in e),Jr=e=>e in wt,Wr=(e,t)=>wt[e]<wt[t],En=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=Vr.memoizeWith((e,t)=>`${e}${t}`,En),Yr=e=>e<1e-6?De("nanosecond",3).format(e/1e-6):e<.001?De("nanosecond").format(e/1e-6):e<1?De("microsecond").format(e/.001):e<1e3?De("millisecond").format(e):e<6e4?De("second",2).format(e/1e3):De("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=Qr.default.isSupported(),level:r=Re()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,Xr.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Wr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?or.ctx(s):s),m.push(c?`${or[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=nr.performance.now();return()=>{let o=nr.performance.now()-r,{message:n,severity:s="debug",formatter:a=Yr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Fe=S(require("ramda"),1);var Ke=class e extends Ne{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Fe.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Fe.reject(Fe.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var eo=S(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,eo.default.static(...this.params))}};var rt=S(require("express"),1),Ro=S(require("node:http"),1),To=S(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ve(e)};var oo=S(require("http-errors"),1);var to=S(require("ramda"),1);var At=class{constructor(t){this.logger=t}#e=to.tryCatch(Fr);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Me){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(C.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=mt(t);if(s.length===0)return;let a=n?.shape||G(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var ro=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new be(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),$e=({routing:e,onEndpoint:t,onStatic:r})=>{let o=ro(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof et){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof qe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new be(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...ro(s,n))}};var zn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,oo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},sr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new At(t()),a=new Map;if($e({routing:o,onEndpoint:(m,p,l,b)=>{Re()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let h=n?.[m.getRequestType()]||[],x=async(y,j)=>{let P=t(y);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:P,defaultHeaders:T}):T;for(let N in v)j.set(N,v[N])}return m.execute({request:y,response:j,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...h,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...h,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,zn(p))};var tt=S(require("http-errors"),1);var co=require("node:timers/promises");var no=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",so=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",io=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ao=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),po=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var mo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(no(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",ao);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(io(p)||so(p))&&a(p);for await(let p of(0,co.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(po))};return{sockets:n,shutdown:()=>o??=m()}};var lo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,tt.isHttpError)(r)?r:(0,tt.default)(400,de(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),uo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,tt.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){Tt({response:o,logger:s,error:new pe(de(a),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Zn=e=>({log:e.debug.bind(e)}),fo=async({getLogger:e,config:t})=>{let r=await Be("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Zn(l)})(c,m,p)}),o&&a.push(In(o)),a},yo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},go=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},ho=e=>t=>t?.res?.locals[g]?.logger||e,bo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
2
+ Original error: ${e.handled.message}.`:""),{expose:(0,Rt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Qt=require("zod");var Xt=class{},V=class extends Xt{#e;#t;#r;constructor({input:t=Qt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Qt.z.ZodError?new X(o):o}}},je=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ne=class{nest(t){return Object.assign(t,{"":this})}};var et=class extends Ne{},Ot=class e extends et{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Hr(this.#e.inputSchema)?"upload":St(this.#e.inputSchema)?"raw":Kr(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof er.z.ZodError?new ae(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof je))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof er.z.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){Tt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Gt(t),a={},c=null,m=null,p=lt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};var ue=require("zod");var Br=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>zr(s,n),o)},G=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?G(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>G(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?G(e._def.schema):e instanceof ue.z.ZodPipeline?G(e._def.in):G(e._def.left).merge(G(e._def.right));var J=require("zod");var Le={positive:200,negative:400},Me=Object.keys(Le);var tr=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends tr{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Yt(this.#e,{variant:"positive",args:[t],statusCodes:[Le.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[C.json]})}},Ue=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.z.object({status:J.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.z.object({status:J.z.literal("error"),error:J.z.object({message:J.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=we(e);return Xe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.positive).json({status:"success",data:r})}}),Pt=new fe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof J.z.ZodArray?e.shape.items:J.z.array(J.z.any());return t.reduce((o,n)=>Se(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=we(r);return Xe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new je(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=rr.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new Ot({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:h,tags:x,methods:l,getOperationId:b,inputSchema:Br(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:rr.z.object({}),handler:async o=>(await t(o),{})})}},$r=new ye(Ue),_r=new ye(Pt);var Qr=S(require("ansis"),1),Xr=require("node:util"),nr=require("node:perf_hooks");var te=require("ansis"),Vr=S(require("ramda"),1);var or={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},wt={debug:10,info:20,warn:30,error:40},Gr=e=>Se(e)&&Object.keys(wt).some(t=>t in e),Jr=e=>e in wt,Wr=(e,t)=>wt[e]<wt[t],En=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=Vr.memoizeWith((e,t)=>`${e}${t}`,En),Yr=e=>e<1e-6?De("nanosecond",3).format(e/1e-6):e<.001?De("nanosecond").format(e/1e-6):e<1?De("microsecond").format(e/.001):e<1e3?De("millisecond").format(e):e<6e4?De("second",2).format(e/1e3):De("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=Qr.default.isSupported(),level:r=Re()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,Xr.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Wr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?or.ctx(s):s),m.push(c?`${or[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=nr.performance.now();return()=>{let o=nr.performance.now()-r,{message:n,severity:s="debug",formatter:a=Yr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Fe=S(require("ramda"),1);var Ke=class e extends Ne{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Fe.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Fe.reject(Fe.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var eo=S(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,eo.default.static(...this.params))}};var rt=S(require("express"),1),Ro=S(require("node:http"),1),To=S(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ve(e)};var oo=S(require("http-errors"),1);var to=S(require("ramda"),1);var At=class{constructor(t){this.logger=t}#e=to.tryCatch(Fr);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Me){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(C.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=mt(t);if(s.length===0)return;let a=n?.shape||G(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var ro=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new be(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),$e=({routing:e,onEndpoint:t,onStatic:r})=>{let o=ro(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof et){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof qe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new be(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...ro(s,n))}};var zn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,oo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},sr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new At(t()),a=new Map;if($e({routing:o,onEndpoint:(m,p,l,b)=>{Re()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let h=n?.[m.getRequestType()]||[],x=async(y,j)=>{let P=t(y);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:P,defaultHeaders:T}):T;for(let N in v)j.set(N,v[N])}return m.execute({request:y,response:j,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...h,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...h,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,zn(p))};var tt=S(require("http-errors"),1);var co=require("node:timers/promises");var no=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",so=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",io=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ao=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),po=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var mo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(no(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",ao);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(io(p)||so(p))&&a(p);for await(let p of(0,co.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(po))};return{sockets:n,shutdown:()=>o??=m()}};var lo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,tt.isHttpError)(r)?r:(0,tt.default)(400,de(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),uo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,tt.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){Tt({response:o,logger:s,error:new pe(de(a),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Zn=e=>({log:e.debug.bind(e)}),fo=async({getLogger:e,config:t})=>{let r=await Be("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Zn(l)})(c,m,p)}),o&&a.push(In(o)),a},yo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},go=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{try{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[g]={logger:a}),s()}catch(a){s(a)}},ho=e=>t=>t?.res?.locals[g]?.logger||e,bo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
3
  `).slice(1))),xo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=mo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var $=require("ansis"),So=e=>{if(e.columns<132)return;let t=(0,$.italic)("Proudly supports transgender community.".padStart(109)),r=(0,$.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,$.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,$.italic)("for Tai".padEnd(20)),s=(0,$.hex)("#F5A9B8"),a=(0,$.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill($.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill($.gray,12,13),m=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
@@ -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 Oo=e=>{e.startupLogo!==!1&&So(process.stdout);let t=e.errorHandler||Ue,r=Gr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.12.0 (CJS)",env:process.env.NODE_ENV||"development"}),bo(r);let o=go({logger:r,config:e}),s={getLogger:ho(r),errorHandler:t},a=uo(s),c=lo(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Po=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Oo(e);return sr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},wo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Oo(e),c=(0,rt.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||rt.default.json()],raw:[e.rawParser||rt.default.raw(),yo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await fo({config:e,getLogger:o}):[]};sr({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=Ro.default.createServer(c);p.push(h),b.push(l(h,e.http.listen))}if(e.https){let h=To.default.createServer(e.https.options,c);p.push(h),b.push(l(h,e.https.listen))}return e.gracefulShutdown&&xo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(h=>h())}};var Vo=require("openapi3-ts/oas31"),Go=S(require("ramda"),1);var O=S(require("ramda"),1);var Ao=e=>Se(e)&&"or"in e,Eo=e=>Se(e)&&"and"in e,ir=e=>!Eo(e)&&!Ao(e),zo=e=>{let t=O.filter(ir,e),r=O.chain(O.prop("and"),O.filter(Eo,e)),[o,n]=O.partition(ir,r),s=O.concat(t,o),a=O.filter(Ao,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>xe(m,O.map(l=>ir(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 Io=["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 Zo=50,ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",kn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Cn=/^\d{4}-\d{2}-\d{2}$/,jn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Nn=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$/,Co=e=>e.replace(_t,t=>`{${t.slice(1)}}`),Ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Mn=({_def:{innerType:e}},{next:t})=>t(e),Un=()=>({format:"any"}),Dn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Fn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),qn=(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")},jo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(qn,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))},Bn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(jo)),d.isEmpty)),$n=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Bn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,jo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),_n=({_def:{left:e,right:t}},{next:r})=>$n([e,t].map(r)),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>t(e.unwrap()),Jn=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Lo(r)),r},No=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},vo=e=>({type:No(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Wn=({value:e})=>({type:No(e),const:e}),Yn=(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=Et(e,r)),s.length&&(a.required=s),a},Qn=()=>({type:"null"}),Xn=({},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:ko}}},es=({},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:ko}}},ts=({},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)},rs=()=>({type:"boolean"}),os=()=>({type:"integer",format:"bigint"}),ns=e=>e.every(t=>t instanceof K.z.ZodLiteral),ss=({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=Et(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Et(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&ns(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Et(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},is=({_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},as=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ps=({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=Cn.source),x&&(z.pattern=jn.source),l&&(z.pattern=Nn(v?.offset).source),T&&(z.pattern=T.regex.source),z},cs=({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},Et=({shape:e},t)=>d.map(t,e),ds=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return kn?.[t]},Lo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ms=(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=ut(e,ds(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},ls=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),us=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ys=(e,{next:t})=>t(e.unwrap().shape.raw),Mo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Uo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Mo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),gs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Mo)({schema:e,variant:"original",validate:!0,pullProps:!0}),hs=(e,t)=>t?.includes(e)||e.startsWith("x-")||Io.includes(e),Do=({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=mt(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)??hs(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,...ar},onEach:pr,onMissing:cr,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:gs(b,v)})},[])},ar={ZodString:ps,ZodNumber:cs,ZodBigInt:os,ZodBoolean:rs,ZodNull:Qn,ZodArray:is,ZodTuple:as,ZodRecord:ss,ZodObject:Yn,ZodLiteral:Wn,ZodIntersection:_n,ZodUnion:Kn,ZodAny:Un,ZodDefault:Ln,ZodEnum:vo,ZodNativeEnum:vo,ZodEffects:ms,ZodOptional:Vn,ZodNullable:Jn,ZodDiscriminatedUnion:Fn,ZodBranded:us,ZodDate:ts,ZodCatch:Mn,ZodPipeline:ls,ZodLazy:fs,ZodReadonly:Gn,[ee]:Hn,[Ce]:Dn,[Pe]:es,[Oe]:Xn,[le]:ys},pr=(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=Lo(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},cr=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Ho=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Ho(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]},Ko=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Fo=({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} ${Jt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let h=Ko(Ee(r,{rules:{...p,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,h,me(b)):h,examples:Uo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},bs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},xs=({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},Ss=({name:e})=>({type:"apiKey",in:"header",name:e}),Rs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ts=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Os=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),qo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?bs(o):o.type==="input"?xs(o,t):o.type==="header"?Ss(o):o.type==="cookie"?Rs(o):o.type==="openid"?Ts(o):Os(o);return e.map(o=>o.map(r))},Bo=(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]=Ho(Ee(r,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),h=Ko(l),x={schema:s==="components"?n(r,h,me(p)):h,examples:Uo(G(r),!1,c)},y={description:p,content:{[o]:x}};return(b||St(r))&&(y.required=!0),y},_o=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)},[]),dr=e=>e.length<=Zo?e:e.slice(0,Zo-1)+"\u2026",zt=e=>e.length?e.slice():void 0;var It=class extends Vo.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?dr(Z):b&&T?dr(T):void 0,N=r.inputSources?.[P]||Vt[P],U=this.ensureUniqOperationId(j,P,y.getOperationId(P)),z=zo(y.getSecurity()),q=Do({...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:qt,schema:at,statusCodes:pt}of he)for(let Bt of pt)k[Bt]=Fo({...Q,variant:ie,schema:at,mimeTypes:qt,statusCode:Bt,hasMultipleStatusCodes:he.length>1||pt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:P,path:j,operationId:U,statusCode:Bt})})}let Kt=N.includes("body")?$o({...Q,paramNames:Go.pluck("name",q),schema:y.getSchema("input"),mimeType:C[y.getRequestType()],description:a?.requestBody?.call(null,{method:P,path:j,operationId:U})}):void 0,it=Bo(qo(z,N),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),Ft={operationId:U,summary:v,description:T,deprecated:y.isDeprecated||void 0,tags:zt(y.getTags()),parameters:zt(q),requestBody:Kt,security:zt(it),responses:k};this.addPath(Co(j),{[P]:Ft})}}),m&&(this.rootDoc.tags=_o(m))}};var Zt=require("node-mocks-http"),Ps=e=>(0,Zt.createRequest)({...e,headers:{"content-type":C.json,...e?.headers}}),ws=e=>(0,Zt.createResponse)(e),As=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)}})},Jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ps(e),s=ws({req:n,...t});s.req=t?.req||n,n.res=s;let a=As(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Wo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Yo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Jo(o),m=lt(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 nn=S(require("ramda"),1),st=S(require("typescript"),1),sn=require("zod");var rn=S(require("ramda"),1),Y=S(require("typescript"),1);var Qo=["get","post","put","delete","patch"];var re=S(require("ramda"),1),u=S(require("typescript"),1),i=u.default.factory,vt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Es=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],ot={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},mr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),lr=(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)},zs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ur=e=>typeof e=="string"&&zs.test(e)?i.createIdentifier(e):E(e),kt=(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)))),Ct=(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])=>Ct(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),fr=(e,t=[])=>i.createConstructorDeclaration(ot.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,yr=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,ur(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?mr(s,a.join(" ")):s},gr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),hr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&vt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),br=(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?vt:void 0,e,n&&Tr(n),t);return o?mr(s,o):s},Xo=(e,t)=>i.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),xr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(ot.public,void 0,e,void 0,o&&Tr(o),t,n,i.createBlock(r)),Sr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(vt,e,r&&Tr(r),void 0,t),Rr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),jt=e=>f(Promise.name,[e]),Nt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?mr(n,o):n},Tr=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?Es:void 0,void 0,Array.isArray(e)?re.map(Ct,e):_e(e),void 0,void 0,t),w=e=>e,nt=(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),Lt=(e,t)=>f("Extract",[e,t]),Or=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),en=e=>i.createUnionTypeNode([f(e),jt(e)]),Pr=(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)),Is=[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],tn=e=>Is.includes(e.kind);var Mt=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=br("Method",Qo);someOfType=oe("SomeOf",W("T",Rr("T")),{params:["T"]});requestType=oe("Request",Rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>br(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Nt(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(ur(t),i.createArrayLiteralExpression(rn.map(E,r))))),{expose:!0});makeImplementationType=()=>oe(this.ids.implementationType,Pr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:yr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},jt(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]:yr},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([Or(this.ids.pathParameter,A(this.ids.pathParameter,w("replace"))(kt(":",[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=()=>xr(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(hr(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:jt(W(this.interfaces.response,"K"))});makeClientClass=t=>Sr(t,[fr([Ct(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:ot.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>kt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,kt("",[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"),nt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(C.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(w("body"),nt(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,nt(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,nt(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=()=>fr(_e({request:"K",params:W(this.interfaces.input,"K")}),[M(hr(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)),Or(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ze(w("event"),t)]);makeOnMethod=()=>xr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Pr({[this.ids.dataParameter.text]:W(Lt("R",gr(this.makeEventNarrow("E"))),F(w("data")))},en(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=>Sr(t,[Xo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:Lt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Lt(W(this.interfaces.positive,"K"),gr(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),Ut=require("zod");var{factory:_}=R.default,Zs={[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},wr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},vs=({value:e})=>F(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&&Ge(a)?a instanceof Ut.z.ZodOptional:a.isOptional();return ze(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return _.createTypeLiteralNode(n)},Cs=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),js=({options:e})=>_.createUnionTypeNode(e.map(F)),on=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(tn(n)?n.kind:n,n)}return _.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=ut(e,Ns(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},Ms=e=>_.createUnionTypeNode(Object.values(e.enum).map(F)),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(R.default.SyntaxKind.UndefinedKeyword)]):o},Ds=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),F(null)]),Hs=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),Ks=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Fs=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(wr.name,...o))return!1;if(I.both(I.eqBy(wr.type),I.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),qs=({_def:{left:e,right:t}},{next:r})=>Fs([e,t].map(r)),Bs=({_def:e},{next:t})=>t(e.innerType),ge=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=()=>F(null),Ws=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ys=e=>{let t=e.unwrap(),r=f(R.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Ut.z.ZodString?r:t instanceof Ut.z.ZodUnion?n:o},Qs=(e,{next:t})=>t(e.unwrap().shape.raw),Xs={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:Js,ZodArray:Cs,ZodTuple:Hs,ZodRecord:Ks,ZodObject:ks,ZodLiteral:vs,ZodIntersection:qs,ZodUnion:on,ZodDefault:Bs,ZodEnum:js,ZodNativeEnum:Ms,ZodEffects:Ls,ZodOptional:Us,ZodNullable:Ds,ZodDiscriminatedUnion:on,ZodBranded:$s,ZodCatch:Vs,ZodPipeline:Gs,ZodLazy:Ws,ZodReadonly:_s,[ee]:Ys,[le]:Qs},Ar=(e,{brandHandling:t,ctx:r})=>Ee(e,{rules:{...t,...Xs},onMissing:()=>f(R.default.SyntaxKind.AnyKeyword),ctx:r});var Dt=class extends Mt{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=sn.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"),Ar(x.getSchema("input"),l),{comment:Z});this.program.push(T);let v=Me.reduce((z,q)=>{let k=x.getResponses(q),Kt=nn.chain(([Ft,{schema:ie,mimeTypes:he,statusCodes:qt}])=>{let at=oe(P(q,"variant",`${Ft+1}`),Ar(he?ie:m,b),{comment:Z});return this.program.push(at),qt.map(pt=>ze(pt,at.name))},Array.from(k.entries())),it=Nt(P(q,"response","variants"),Kt,{comment:Z});return this.program.push(it),Object.assign(z,{[q]:it})},{});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:lr(r,t)).join(`
18
+ `))};var Oo=e=>{e.startupLogo!==!1&&So(process.stdout);let t=e.errorHandler||Ue,r=Gr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.13.0 (CJS)",env:process.env.NODE_ENV||"development"}),bo(r);let o=go({logger:r,config:e}),s={getLogger:ho(r),errorHandler:t},a=uo(s),c=lo(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Po=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Oo(e);return sr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},wo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Oo(e),c=(0,rt.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||rt.default.json()],raw:[e.rawParser||rt.default.raw(),yo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await fo({config:e,getLogger:o}):[]};sr({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=Ro.default.createServer(c);p.push(h),b.push(l(h,e.http.listen))}if(e.https){let h=To.default.createServer(e.https.options,c);p.push(h),b.push(l(h,e.https.listen))}return e.gracefulShutdown&&xo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(h=>h())}};var Vo=require("openapi3-ts/oas31"),Go=S(require("ramda"),1);var O=S(require("ramda"),1);var Ao=e=>Se(e)&&"or"in e,Eo=e=>Se(e)&&"and"in e,ir=e=>!Eo(e)&&!Ao(e),zo=e=>{let t=O.filter(ir,e),r=O.chain(O.prop("and"),O.filter(Eo,e)),[o,n]=O.partition(ir,r),s=O.concat(t,o),a=O.filter(Ao,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>xe(m,O.map(l=>ir(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 Io=["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 Zo=50,ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",kn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Cn=/^\d{4}-\d{2}-\d{2}$/,jn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Nn=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$/,Co=e=>e.replace(_t,t=>`{${t.slice(1)}}`),Ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Mn=({_def:{innerType:e}},{next:t})=>t(e),Un=()=>({format:"any"}),Dn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Fn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),qn=(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")},jo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(qn,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))},Bn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(jo)),d.isEmpty)),$n=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Bn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,jo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),_n=({_def:{left:e,right:t}},{next:r})=>$n([e,t].map(r)),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>t(e.unwrap()),Jn=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Lo(r)),r},No=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},vo=e=>({type:No(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Wn=({value:e})=>({type:No(e),const:e}),Yn=(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=Et(e,r)),s.length&&(a.required=s),a},Qn=()=>({type:"null"}),Xn=({},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:ko}}},es=({},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:ko}}},ts=({},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)},rs=()=>({type:"boolean"}),os=()=>({type:"integer",format:"bigint"}),ns=e=>e.every(t=>t instanceof K.z.ZodLiteral),ss=({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=Et(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Et(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&ns(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Et(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},is=({_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},as=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ps=({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=Cn.source),x&&(z.pattern=jn.source),l&&(z.pattern=Nn(v?.offset).source),T&&(z.pattern=T.regex.source),z},cs=({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},Et=({shape:e},t)=>d.map(t,e),ds=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return kn?.[t]},Lo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ms=(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=ut(e,ds(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},ls=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),us=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ys=(e,{next:t})=>t(e.unwrap().shape.raw),Mo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Uo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Mo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),gs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Mo)({schema:e,variant:"original",validate:!0,pullProps:!0}),hs=(e,t)=>t?.includes(e)||e.startsWith("x-")||Io.includes(e),Do=({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=mt(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)??hs(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,...ar},onEach:pr,onMissing:cr,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:gs(b,v)})},[])},ar={ZodString:ps,ZodNumber:cs,ZodBigInt:os,ZodBoolean:rs,ZodNull:Qn,ZodArray:is,ZodTuple:as,ZodRecord:ss,ZodObject:Yn,ZodLiteral:Wn,ZodIntersection:_n,ZodUnion:Kn,ZodAny:Un,ZodDefault:Ln,ZodEnum:vo,ZodNativeEnum:vo,ZodEffects:ms,ZodOptional:Vn,ZodNullable:Jn,ZodDiscriminatedUnion:Fn,ZodBranded:us,ZodDate:ts,ZodCatch:Mn,ZodPipeline:ls,ZodLazy:fs,ZodReadonly:Gn,[ee]:Hn,[Ce]:Dn,[Pe]:es,[Oe]:Xn,[le]:ys},pr=(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=Lo(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},cr=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Ho=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Ho(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]},Ko=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Fo=({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} ${Jt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let h=Ko(Ee(r,{rules:{...p,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,h,me(b)):h,examples:Uo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},bs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},xs=({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},Ss=({name:e})=>({type:"apiKey",in:"header",name:e}),Rs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ts=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Os=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),qo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?bs(o):o.type==="input"?xs(o,t):o.type==="header"?Ss(o):o.type==="cookie"?Rs(o):o.type==="openid"?Ts(o):Os(o);return e.map(o=>o.map(r))},Bo=(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]=Ho(Ee(r,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),h=Ko(l),x={schema:s==="components"?n(r,h,me(p)):h,examples:Uo(G(r),!1,c)},y={description:p,content:{[o]:x}};return(b||St(r))&&(y.required=!0),y},_o=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)},[]),dr=e=>e.length<=Zo?e:e.slice(0,Zo-1)+"\u2026",zt=e=>e.length?e.slice():void 0;var It=class extends Vo.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?dr(Z):b&&T?dr(T):void 0,N=r.inputSources?.[P]||Vt[P],U=this.ensureUniqOperationId(j,P,y.getOperationId(P)),z=zo(y.getSecurity()),q=Do({...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:qt,schema:at,statusCodes:pt}of he)for(let Bt of pt)k[Bt]=Fo({...Q,variant:ie,schema:at,mimeTypes:qt,statusCode:Bt,hasMultipleStatusCodes:he.length>1||pt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:P,path:j,operationId:U,statusCode:Bt})})}let Kt=N.includes("body")?$o({...Q,paramNames:Go.pluck("name",q),schema:y.getSchema("input"),mimeType:C[y.getRequestType()],description:a?.requestBody?.call(null,{method:P,path:j,operationId:U})}):void 0,it=Bo(qo(z,N),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),Ft={operationId:U,summary:v,description:T,deprecated:y.isDeprecated||void 0,tags:zt(y.getTags()),parameters:zt(q),requestBody:Kt,security:zt(it),responses:k};this.addPath(Co(j),{[P]:Ft})}}),m&&(this.rootDoc.tags=_o(m))}};var Zt=require("node-mocks-http"),Ps=e=>(0,Zt.createRequest)({...e,headers:{"content-type":C.json,...e?.headers}}),ws=e=>(0,Zt.createResponse)(e),As=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)}})},Jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ps(e),s=ws({req:n,...t});s.req=t?.req||n,n.res=s;let a=As(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Wo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Yo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Jo(o),m=lt(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 nn=S(require("ramda"),1),st=S(require("typescript"),1),sn=require("zod");var rn=S(require("ramda"),1),Y=S(require("typescript"),1);var Qo=["get","post","put","delete","patch"];var re=S(require("ramda"),1),u=S(require("typescript"),1),i=u.default.factory,vt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Es=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],ot={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},mr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),lr=(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)},zs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ur=e=>typeof e=="string"&&zs.test(e)?i.createIdentifier(e):E(e),kt=(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)))),Ct=(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])=>Ct(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),fr=(e,t=[])=>i.createConstructorDeclaration(ot.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,yr=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,ur(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?mr(s,a.join(" ")):s},gr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),hr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&vt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),br=(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?vt:void 0,e,n&&Tr(n),t);return o?mr(s,o):s},Xo=(e,t)=>i.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),xr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(ot.public,void 0,e,void 0,o&&Tr(o),t,n,i.createBlock(r)),Sr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(vt,e,r&&Tr(r),void 0,t),Rr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),jt=e=>f(Promise.name,[e]),Nt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?mr(n,o):n},Tr=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?Es:void 0,void 0,Array.isArray(e)?re.map(Ct,e):_e(e),void 0,void 0,t),w=e=>e,nt=(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),Lt=(e,t)=>f("Extract",[e,t]),Or=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),en=e=>i.createUnionTypeNode([f(e),jt(e)]),Pr=(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)),Is=[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],tn=e=>Is.includes(e.kind);var Mt=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=br("Method",Qo);someOfType=oe("SomeOf",W("T",Rr("T")),{params:["T"]});requestType=oe("Request",Rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>br(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Nt(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(ur(t),i.createArrayLiteralExpression(rn.map(E,r))))),{expose:!0});makeImplementationType=()=>oe(this.ids.implementationType,Pr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:yr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},jt(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]:yr},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([Or(this.ids.pathParameter,A(this.ids.pathParameter,w("replace"))(kt(":",[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=()=>xr(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(hr(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:jt(W(this.interfaces.response,"K"))});makeClientClass=t=>Sr(t,[fr([Ct(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:ot.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>kt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,kt("",[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"),nt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(C.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(w("body"),nt(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,nt(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,nt(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=()=>fr(_e({request:"K",params:W(this.interfaces.input,"K")}),[M(hr(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)),Or(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ze(w("event"),t)]);makeOnMethod=()=>xr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Pr({[this.ids.dataParameter.text]:W(Lt("R",gr(this.makeEventNarrow("E"))),F(w("data")))},en(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=>Sr(t,[Xo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:Lt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Lt(W(this.interfaces.positive,"K"),gr(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),Ut=require("zod");var{factory:_}=R.default,Zs={[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},wr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},vs=({value:e})=>F(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&&Ge(a)?a instanceof Ut.z.ZodOptional:a.isOptional();return ze(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return _.createTypeLiteralNode(n)},Cs=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),js=({options:e})=>_.createUnionTypeNode(e.map(F)),on=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(tn(n)?n.kind:n,n)}return _.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=ut(e,Ns(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},Ms=e=>_.createUnionTypeNode(Object.values(e.enum).map(F)),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(R.default.SyntaxKind.UndefinedKeyword)]):o},Ds=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),F(null)]),Hs=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),Ks=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Fs=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(wr.name,...o))return!1;if(I.both(I.eqBy(wr.type),I.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),qs=({_def:{left:e,right:t}},{next:r})=>Fs([e,t].map(r)),Bs=({_def:e},{next:t})=>t(e.innerType),ge=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=()=>F(null),Ws=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ys=e=>{let t=e.unwrap(),r=f(R.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Ut.z.ZodString?r:t instanceof Ut.z.ZodUnion?n:o},Qs=(e,{next:t})=>t(e.unwrap().shape.raw),Xs={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:Js,ZodArray:Cs,ZodTuple:Hs,ZodRecord:Ks,ZodObject:ks,ZodLiteral:vs,ZodIntersection:qs,ZodUnion:on,ZodDefault:Bs,ZodEnum:js,ZodNativeEnum:Ms,ZodEffects:Ls,ZodOptional:Us,ZodNullable:Ds,ZodDiscriminatedUnion:on,ZodBranded:$s,ZodCatch:Vs,ZodPipeline:Gs,ZodLazy:Ws,ZodReadonly:_s,[ee]:Ys,[le]:Qs},Ar=(e,{brandHandling:t,ctx:r})=>Ee(e,{rules:{...t,...Xs},onMissing:()=>f(R.default.SyntaxKind.AnyKeyword),ctx:r});var Dt=class extends Mt{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=sn.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"),Ar(x.getSchema("input"),l),{comment:Z});this.program.push(T);let v=Me.reduce((z,q)=>{let k=x.getResponses(q),Kt=nn.chain(([Ft,{schema:ie,mimeTypes:he,statusCodes:qt}])=>{let at=oe(P(q,"variant",`${Ft+1}`),Ar(he?ie:m,b),{comment:Z});return this.program.push(at),qt.map(pt=>ze(pt,at.name))},Array.from(k.entries())),it=Nt(P(q,"response","variants"),Kt,{comment:Z});return this.program.push(it),Object.assign(z,{[q]:it})},{});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:lr(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.printUsage(t),o=r&&st.default.addSyntheticLeadingComment(st.default.addSyntheticLeadingComment(i.createEmptyStatement(),st.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),st.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.program.concat(o||[]).map((n,s)=>lr(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/dist/index.d.cts CHANGED
@@ -203,10 +203,18 @@ interface OAuth2Security<S extends string> {
203
203
  type Security<K extends string = string, S extends string = string> = BasicSecurity | BearerSecurity | InputSecurity<K> | CustomHeaderSecurity | CookieSecurity | OpenIdSecurity | OAuth2Security<S>;
204
204
 
205
205
  type Handler$2<IN, OPT, OUT> = (params: {
206
+ /** @desc The inputs from the enabled input sources validated against final input schema of the Middleware */
206
207
  input: IN;
208
+ /**
209
+ * @desc The returns of the previously executed Middlewares (typed when chaining Middlewares)
210
+ * @link https://github.com/RobinTail/express-zod-api/discussions/1250
211
+ * */
207
212
  options: OPT;
213
+ /** @link https://expressjs.com/en/5x/api.html#req */
208
214
  request: Request;
215
+ /** @link https://expressjs.com/en/5x/api.html#res */
209
216
  response: Response;
217
+ /** @desc The instance of the configured logger */
210
218
  logger: ActualLogger;
211
219
  }) => Promise<OUT>;
212
220
  declare abstract class AbstractMiddleware {
@@ -223,8 +231,15 @@ declare abstract class AbstractMiddleware {
223
231
  declare class Middleware<OPT extends FlatObject, OUT extends FlatObject, SCO extends string, IN extends IOSchema<"strip"> = EmptySchema> extends AbstractMiddleware {
224
232
  #private;
225
233
  constructor({ input, security, handler, }: {
234
+ /**
235
+ * @desc Input schema of the Middleware, combining properties from all the enabled input sources
236
+ * @default z.object({})
237
+ * @see defaultInputSources
238
+ * */
226
239
  input?: IN;
240
+ /** @desc Declaration of the security schemas implemented within the handler */
227
241
  security?: LogicalContainer<Security<Extract<keyof z.input<IN>, string>, SCO>>;
242
+ /** @desc The handler returning options available to Endpoints */
228
243
  handler: Handler$2<z.output<IN>, OPT, OUT>;
229
244
  });
230
245
  getSecurity(): LogicalContainer<Security<Extract<keyof z.input<IN>, string>, SCO>> | undefined;
@@ -389,8 +404,11 @@ declare abstract class Routable {
389
404
  }
390
405
 
391
406
  type Handler<IN, OUT, OPT> = (params: {
407
+ /** @desc The inputs from the enabled input sources validated against the final input schema (incl. Middlewares) */
392
408
  input: IN;
409
+ /** @desc The returns of the assigned Middlewares */
393
410
  options: OPT;
411
+ /** @desc The instance of the configured logger */
394
412
  logger: ActualLogger;
395
413
  }) => Promise<OUT>;
396
414
  type DescriptionVariant = "short" | "long";
@@ -463,6 +481,7 @@ type ChildLoggerProvider = (params: {
463
481
  request: Request;
464
482
  parent: ActualLogger;
465
483
  }) => ActualLogger | Promise<ActualLogger>;
484
+ type LogAccess = (request: Request, logger: ActualLogger) => void;
466
485
  interface CommonConfig {
467
486
  /**
468
487
  * @desc Enables cross-origin resource sharing.
@@ -495,6 +514,12 @@ interface CommonConfig {
495
514
  * @example ({ parent }) => parent.child({ requestId: uuid() })
496
515
  * */
497
516
  childLoggerProvider?: ChildLoggerProvider;
517
+ /**
518
+ * @desc The function for producing access logs
519
+ * @default ({ method, path }, logger) => logger.debug(`${method}: ${path}`)
520
+ * @example null — disables the feature
521
+ * */
522
+ accessLogger?: null | LogAccess;
498
523
  /**
499
524
  * @desc You can disable the startup logo.
500
525
  * @default true
@@ -522,7 +547,6 @@ type UploadOptions = Pick<express_fileupload__default.Options, "createParentPath
522
547
  limitError?: Error;
523
548
  /**
524
549
  * @desc A handler to execute before uploading — it can be used for restrictions by throwing an error.
525
- * @default undefined
526
550
  * @example ({ request }) => { throw createHttpError(403, "Not authorized"); }
527
551
  * */
528
552
  beforeUpload?: BeforeUpload;
@@ -567,13 +591,11 @@ interface ServerConfig extends CommonConfig {
567
591
  jsonParser?: RequestHandler;
568
592
  /**
569
593
  * @desc Enable or configure uploads handling.
570
- * @default undefined
571
594
  * @requires express-fileupload
572
595
  * */
573
596
  upload?: boolean | UploadOptions;
574
597
  /**
575
598
  * @desc Enable or configure response compression.
576
- * @default undefined
577
599
  * @requires compression
578
600
  */
579
601
  compression?: boolean | CompressionOptions;
@@ -593,13 +615,11 @@ interface ServerConfig extends CommonConfig {
593
615
  * @desc A code to execute before processing the Routing of your API (and before parsing).
594
616
  * @desc This can be a good place for express middlewares establishing their own routes.
595
617
  * @desc It can help to avoid making a DIY solution based on the attachRouting() approach.
596
- * @default undefined
597
618
  * @example ({ app }) => { app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); }
598
619
  * */
599
620
  beforeRouting?: BeforeRouting;
600
621
  /**
601
622
  * @desc Rejects new connections and attempts to finish ongoing ones in the specified time before exit.
602
- * @default undefined
603
623
  * */
604
624
  gracefulShutdown?: boolean | GracefulOptions;
605
625
  }
@@ -695,15 +715,39 @@ declare module "zod" {
695
715
  }
696
716
 
697
717
  interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN extends IOSchema<"strip">, OPT extends FlatObject, SCO extends string> {
718
+ /**
719
+ * @desc Input schema of the Endpoint, combining properties from all the enabled input sources (path params, headers)
720
+ * @default z.object({})
721
+ * @see defaultInputSources
722
+ * */
698
723
  input?: IN;
724
+ /** @desc The schema by which the returns of the Endpoint handler is validated */
699
725
  output: OUT;
726
+ /** @desc The Endpoint handler receiving the validated inputs, returns of added Middlewares (options) and a logger */
700
727
  handler: Handler<z.output<z.ZodIntersection<MIN, IN>>, z.input<OUT>, OPT>;
728
+ /** @desc The operation description for the generated Documentation */
701
729
  description?: string;
730
+ /** @desc The operation summary for the generated Documentation (50 symbols max) */
702
731
  shortDescription?: string;
732
+ /** @desc The operation ID for the generated Documentation (must be unique) */
703
733
  operationId?: string | ((method: Method) => string);
734
+ /**
735
+ * @desc HTTP method(s) this endpoint can handle
736
+ * @default "get" unless the Endpoint is assigned within DependsOnMethod
737
+ * @see DependsOnMethod
738
+ * */
704
739
  method?: Method | [Method, ...Method[]];
740
+ /**
741
+ * @desc Scope(s) from the list of the ones defined by the added Middlewares having "oauth2" security type
742
+ * @see OAuth2Security
743
+ * */
705
744
  scope?: SCO | SCO[];
745
+ /**
746
+ * @desc Tag(s) for generating Documentation. For establishing constraints:
747
+ * @see TagOverrides
748
+ * */
706
749
  tag?: Tag | Tag[];
750
+ /** @desc Marks the operation deprecated in the generated Documentation */
707
751
  deprecated?: boolean;
708
752
  }
709
753
  declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT extends FlatObject = EmptyObject, SCO extends string = string> {
@@ -924,7 +968,10 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
924
968
  middleware: AbstractMiddleware;
925
969
  /** @desc The aggregated output from previously executed middlewares */
926
970
  options?: FlatObject;
927
- /** @desc Enables transforming possible middleware errors into response, so that test Middleware does not throw */
971
+ /**
972
+ * @desc Enables transforming possible middleware errors into response, so that test Middleware does not throw
973
+ * @todo consider utilizing errorHandler from config instead in v23
974
+ * */
928
975
  errorHandler?: (error: Error, response: Response) => void;
929
976
  }) => Promise<{
930
977
  requestMock: node_mocks_http.MockRequest<Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>> & REQ>;
package/dist/index.d.ts CHANGED
@@ -203,10 +203,18 @@ interface OAuth2Security<S extends string> {
203
203
  type Security<K extends string = string, S extends string = string> = BasicSecurity | BearerSecurity | InputSecurity<K> | CustomHeaderSecurity | CookieSecurity | OpenIdSecurity | OAuth2Security<S>;
204
204
 
205
205
  type Handler$2<IN, OPT, OUT> = (params: {
206
+ /** @desc The inputs from the enabled input sources validated against final input schema of the Middleware */
206
207
  input: IN;
208
+ /**
209
+ * @desc The returns of the previously executed Middlewares (typed when chaining Middlewares)
210
+ * @link https://github.com/RobinTail/express-zod-api/discussions/1250
211
+ * */
207
212
  options: OPT;
213
+ /** @link https://expressjs.com/en/5x/api.html#req */
208
214
  request: Request;
215
+ /** @link https://expressjs.com/en/5x/api.html#res */
209
216
  response: Response;
217
+ /** @desc The instance of the configured logger */
210
218
  logger: ActualLogger;
211
219
  }) => Promise<OUT>;
212
220
  declare abstract class AbstractMiddleware {
@@ -223,8 +231,15 @@ declare abstract class AbstractMiddleware {
223
231
  declare class Middleware<OPT extends FlatObject, OUT extends FlatObject, SCO extends string, IN extends IOSchema<"strip"> = EmptySchema> extends AbstractMiddleware {
224
232
  #private;
225
233
  constructor({ input, security, handler, }: {
234
+ /**
235
+ * @desc Input schema of the Middleware, combining properties from all the enabled input sources
236
+ * @default z.object({})
237
+ * @see defaultInputSources
238
+ * */
226
239
  input?: IN;
240
+ /** @desc Declaration of the security schemas implemented within the handler */
227
241
  security?: LogicalContainer<Security<Extract<keyof z.input<IN>, string>, SCO>>;
242
+ /** @desc The handler returning options available to Endpoints */
228
243
  handler: Handler$2<z.output<IN>, OPT, OUT>;
229
244
  });
230
245
  getSecurity(): LogicalContainer<Security<Extract<keyof z.input<IN>, string>, SCO>> | undefined;
@@ -389,8 +404,11 @@ declare abstract class Routable {
389
404
  }
390
405
 
391
406
  type Handler<IN, OUT, OPT> = (params: {
407
+ /** @desc The inputs from the enabled input sources validated against the final input schema (incl. Middlewares) */
392
408
  input: IN;
409
+ /** @desc The returns of the assigned Middlewares */
393
410
  options: OPT;
411
+ /** @desc The instance of the configured logger */
394
412
  logger: ActualLogger;
395
413
  }) => Promise<OUT>;
396
414
  type DescriptionVariant = "short" | "long";
@@ -463,6 +481,7 @@ type ChildLoggerProvider = (params: {
463
481
  request: Request;
464
482
  parent: ActualLogger;
465
483
  }) => ActualLogger | Promise<ActualLogger>;
484
+ type LogAccess = (request: Request, logger: ActualLogger) => void;
466
485
  interface CommonConfig {
467
486
  /**
468
487
  * @desc Enables cross-origin resource sharing.
@@ -495,6 +514,12 @@ interface CommonConfig {
495
514
  * @example ({ parent }) => parent.child({ requestId: uuid() })
496
515
  * */
497
516
  childLoggerProvider?: ChildLoggerProvider;
517
+ /**
518
+ * @desc The function for producing access logs
519
+ * @default ({ method, path }, logger) => logger.debug(`${method}: ${path}`)
520
+ * @example null — disables the feature
521
+ * */
522
+ accessLogger?: null | LogAccess;
498
523
  /**
499
524
  * @desc You can disable the startup logo.
500
525
  * @default true
@@ -522,7 +547,6 @@ type UploadOptions = Pick<express_fileupload__default.Options, "createParentPath
522
547
  limitError?: Error;
523
548
  /**
524
549
  * @desc A handler to execute before uploading — it can be used for restrictions by throwing an error.
525
- * @default undefined
526
550
  * @example ({ request }) => { throw createHttpError(403, "Not authorized"); }
527
551
  * */
528
552
  beforeUpload?: BeforeUpload;
@@ -567,13 +591,11 @@ interface ServerConfig extends CommonConfig {
567
591
  jsonParser?: RequestHandler;
568
592
  /**
569
593
  * @desc Enable or configure uploads handling.
570
- * @default undefined
571
594
  * @requires express-fileupload
572
595
  * */
573
596
  upload?: boolean | UploadOptions;
574
597
  /**
575
598
  * @desc Enable or configure response compression.
576
- * @default undefined
577
599
  * @requires compression
578
600
  */
579
601
  compression?: boolean | CompressionOptions;
@@ -593,13 +615,11 @@ interface ServerConfig extends CommonConfig {
593
615
  * @desc A code to execute before processing the Routing of your API (and before parsing).
594
616
  * @desc This can be a good place for express middlewares establishing their own routes.
595
617
  * @desc It can help to avoid making a DIY solution based on the attachRouting() approach.
596
- * @default undefined
597
618
  * @example ({ app }) => { app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); }
598
619
  * */
599
620
  beforeRouting?: BeforeRouting;
600
621
  /**
601
622
  * @desc Rejects new connections and attempts to finish ongoing ones in the specified time before exit.
602
- * @default undefined
603
623
  * */
604
624
  gracefulShutdown?: boolean | GracefulOptions;
605
625
  }
@@ -695,15 +715,39 @@ declare module "zod" {
695
715
  }
696
716
 
697
717
  interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN extends IOSchema<"strip">, OPT extends FlatObject, SCO extends string> {
718
+ /**
719
+ * @desc Input schema of the Endpoint, combining properties from all the enabled input sources (path params, headers)
720
+ * @default z.object({})
721
+ * @see defaultInputSources
722
+ * */
698
723
  input?: IN;
724
+ /** @desc The schema by which the returns of the Endpoint handler is validated */
699
725
  output: OUT;
726
+ /** @desc The Endpoint handler receiving the validated inputs, returns of added Middlewares (options) and a logger */
700
727
  handler: Handler<z.output<z.ZodIntersection<MIN, IN>>, z.input<OUT>, OPT>;
728
+ /** @desc The operation description for the generated Documentation */
701
729
  description?: string;
730
+ /** @desc The operation summary for the generated Documentation (50 symbols max) */
702
731
  shortDescription?: string;
732
+ /** @desc The operation ID for the generated Documentation (must be unique) */
703
733
  operationId?: string | ((method: Method) => string);
734
+ /**
735
+ * @desc HTTP method(s) this endpoint can handle
736
+ * @default "get" unless the Endpoint is assigned within DependsOnMethod
737
+ * @see DependsOnMethod
738
+ * */
704
739
  method?: Method | [Method, ...Method[]];
740
+ /**
741
+ * @desc Scope(s) from the list of the ones defined by the added Middlewares having "oauth2" security type
742
+ * @see OAuth2Security
743
+ * */
705
744
  scope?: SCO | SCO[];
745
+ /**
746
+ * @desc Tag(s) for generating Documentation. For establishing constraints:
747
+ * @see TagOverrides
748
+ * */
706
749
  tag?: Tag | Tag[];
750
+ /** @desc Marks the operation deprecated in the generated Documentation */
707
751
  deprecated?: boolean;
708
752
  }
709
753
  declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT extends FlatObject = EmptyObject, SCO extends string = string> {
@@ -924,7 +968,10 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
924
968
  middleware: AbstractMiddleware;
925
969
  /** @desc The aggregated output from previously executed middlewares */
926
970
  options?: FlatObject;
927
- /** @desc Enables transforming possible middleware errors into response, so that test Middleware does not throw */
971
+ /**
972
+ * @desc Enables transforming possible middleware errors into response, so that test Middleware does not throw
973
+ * @todo consider utilizing errorHandler from config instead in v23
974
+ * */
928
975
  errorHandler?: (error: Error, response: Response) => void;
929
976
  }) => Promise<{
930
977
  requestMock: node_mocks_http.MockRequest<Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>> & REQ>;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import*as D from"ramda";import{z as Pe}from"zod";import*as U from"ramda";import{z as yr}from"zod";var k={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var Oe=class extends Error{name="RoutingError"},B=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},et=class extends Error{name="IOSchemaError"},ce=class extends et{constructor(r){super(de(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends et{constructor(r){super(de(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(de(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ue=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ct=/:([A-Za-z0-9_]+)/g,tt=e=>e.match(Ct)?.map(t=>t.slice(1))||[],Uo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(k.upload);return"files"in e&&r},jt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Do=["body","query","params"],Nt=e=>e.method.toLowerCase(),rt=(e,t={})=>{let r=Nt(e);return r==="options"?{}:(t[r]||jt[r]||Do).filter(o=>o==="files"?Uo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),de=e=>e instanceof yr.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ce?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Ho=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return me(t,(n[g]?.examples||[]).map(U.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[g]?.examples||[];if(!n.length&&o&&e instanceof yr.ZodObject&&(n=Ho(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},me=(e,t,r)=>e.length&&t.length?U.xprod(e,t).map(r):e.concat(t),De=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Lt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=U.chain(o=>o.split(/[^A-Z0-9]/gi),e);return U.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Lt).join("")},ot=U.tryCatch((e,t)=>typeof e.parse(t),U.always(void 0)),le=e=>typeof e=="object"&&e!==null,ue=U.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as nt from"ramda";var g=Symbol.for("express-zod-api"),He=e=>{let t=e.describe(e.description);return t._def[g]=nt.clone(t._def[g])||{examples:[]},t},gr=(e,t)=>{if(!(g in e._def))return t;let r=He(t);return r._def[g].examples=me(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?nt.mergeDeepRight({...o},{...n}):n),r};var Ko=function(e){let t=He(this);return t._def[g].examples.push(e),t},Fo=function(){let e=He(this);return e._def[g].isDeprecated=!0,e},qo=function(e){let t=He(this);return t._def[g].defaultLabel=e,t},Bo=function(e){return new Pe.ZodBranded({typeName:Pe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...D.clone(this._def[g]),brand:e}})},$o=function(e){let t=typeof e=="function"?e:D.pipe(D.toPairs,D.map(([n,s])=>D.pair(e[String(n)]||n,s)),D.fromPairs),r=t(D.clone(this.shape)),o=Pe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Pe.ZodType.prototype,{example:{get(){return Ko.bind(this)}},deprecated:{get(){return Fo.bind(this)}},brand:{set(){},get(){return Bo.bind(this)}}}),Object.defineProperty(Pe.ZodDefault.prototype,"label",{get(){return qo.bind(this)}}),Object.defineProperty(Pe.ZodObject.prototype,"remap",{get(){return $o.bind(this)}}));function _o(e){return e}import{z as kr}from"zod";import{z as Zr}from"zod";import{fail as L}from"node:assert/strict";import{z as Ke}from"zod";var st=e=>!isNaN(e.getTime());var fe=Symbol("DateIn"),hr=()=>Ke.union([Ke.string().date(),Ke.string().datetime(),Ke.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ke.date().refine(st)).brand(fe);import{z as Vo}from"zod";var ye=Symbol("DateOut"),br=()=>Vo.date().refine(st).transform(e=>e.toISOString()).brand(ye);import{z as it}from"zod";var G=Symbol("File"),xr=it.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Go={buffer:()=>xr.brand(G),string:()=>it.string().brand(G),binary:()=>xr.or(it.string()).brand(G),base64:()=>it.string().base64().brand(G)};function at(e){return Go[e||"string"]()}import{z as Sr}from"zod";var pt=Symbol("Form"),Rr=e=>(e instanceof Sr.ZodObject?e:Sr.object(e)).brand(pt);import{z as Jo}from"zod";var ie=Symbol("Raw"),Tr=(e={})=>Jo.object({raw:at("buffer")}).extend(e).brand(ie);import{z as Wo}from"zod";var we=Symbol("Upload"),Or=()=>Wo.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(we);var Pr=(e,{next:t})=>e.options.some(t),Yo=({_def:e},{next:t})=>[e.left,e.right].some(t),ct=(e,{next:t})=>t(e.unwrap()),dt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Pr,ZodDiscriminatedUnion:Pr,ZodIntersection:Yo,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:ct,ZodNullable:ct,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Fe=(e,{condition:t,rules:r=dt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Fe(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},wr=e=>Fe(e,{condition:t=>t._def[g]?.brand===we,rules:{...dt,[pt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),mt=e=>Fe(e,{condition:t=>t._def[g]?.brand===ie,maxDepth:3}),Ar=e=>Fe(e,{condition:t=>t._def[g]?.brand===pt,maxDepth:3}),Er=(e,t)=>{let r=new WeakSet;return Fe(e,{maxDepth:300,rules:{...dt,ZodBranded:ct,ZodReadonly:ct,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:dt.ZodEffects}[t],ZodNaN:()=>L("z.nan()"),ZodSymbol:()=>L("z.symbol()"),ZodFunction:()=>L("z.function()"),ZodMap:()=>L("z.map()"),ZodSet:()=>L("z.set()"),ZodBigInt:()=>L("z.bigint()"),ZodVoid:()=>L("z.void()"),ZodPromise:()=>L("z.promise()"),ZodNever:()=>L("z.never()"),ZodDate:()=>t==="in"&&L("z.date()"),[ye]:()=>t==="in"&&L("ez.dateOut()"),[fe]:()=>t==="out"&&L("ez.dateIn()"),[ie]:()=>t==="out"&&L("ez.raw()"),[we]:()=>t==="out"&&L("ez.upload()"),[G]:()=>!1}})};import en,{isHttpError as tn}from"http-errors";import zr,{isHttpError as Qo}from"http-errors";import{z as Xo}from"zod";var Mt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Xo.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},qe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ae=e=>Qo(e)?e:zr(e instanceof ee?400:500,de(e),{cause:e.cause||e}),ge=e=>ue()&&!e.expose?zr(e.statusCode).message:e.message;var lt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ge(en(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:tn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ir}from"zod";var Ut=class{},J=class extends Ut{#e;#t;#r;constructor({input:t=Ir.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Ir.ZodError?new ee(o):o}}},Ee=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var ze=class{nest(t){return Object.assign(t,{"":this})}};var Be=class extends ze{},ut=class e extends Be{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return wr(this.#e.inputSchema)?"upload":mt(this.#e.inputSchema)?"raw":Ar(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Zr.ZodError?new ce(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Ee))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Zr.ZodError?new ee(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){lt({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),a={},c=null,m=null,p=rt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import{z as he}from"zod";var vr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>gr(s,n),o)},$=e=>e instanceof he.ZodObject?e:e instanceof he.ZodBranded?$(e.unwrap()):e instanceof he.ZodUnion||e instanceof he.ZodDiscriminatedUnion?e.options.map(t=>$(t)).reduce((t,r)=>t.merge(r.partial()),he.object({})):e instanceof he.ZodEffects?$(e._def.schema):e instanceof he.ZodPipeline?$(e._def.in):$(e._def.left).merge($(e._def.right));import{z as W}from"zod";var Ie={positive:200,negative:400},Ze=Object.keys(Ie);var Dt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Dt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Mt(this.#e,{variant:"positive",args:[t],statusCodes:[Ie.positive],mimeTypes:[k.json]})}getNegativeResponse(){return Mt(this.#t,{variant:"negative",args:[],statusCodes:[Ie.negative],mimeTypes:[k.json]})}},$e=new be({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Ae(e);return qe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ge(a)}})}n.status(Ie.positive).json({status:"success",data:r})}}),Ht=new be({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>le(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ae(r);return qe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ge(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Ie.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var xe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof J?t:new J(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new J({handler:t})),this.resultHandler)}build({input:t=kr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new ut({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:h,tags:x,methods:l,getOperationId:b,inputSchema:vr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:kr.object({}),handler:async o=>(await t(o),{})})}},rn=new xe($e),on=new xe(Ht);import mn from"ansis";import{inspect as ln}from"node:util";import{performance as Ur}from"node:perf_hooks";import{blue as nn,green as sn,hex as an,red as pn,cyanBright as cn}from"ansis";import*as Cr from"ramda";var Kt={debug:nn,info:sn,warn:an("#FFA500"),error:pn,ctx:cn},ft={debug:10,info:20,warn:30,error:40},jr=e=>le(e)&&Object.keys(ft).some(t=>t in e),Nr=e=>e in ft,Lr=(e,t)=>ft[e]<ft[t],dn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),ve=Cr.memoizeWith((e,t)=>`${e}${t}`,dn),Mr=e=>e<1e-6?ve("nanosecond",3).format(e/1e-6):e<.001?ve("nanosecond").format(e/1e-6):e<1?ve("microsecond").format(e/.001):e<1e3?ve("millisecond").format(e):e<6e4?ve("second",2).format(e/1e3):ve("minute",2).format(e/6e4);var _e=class e{config;constructor({color:t=mn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return ln(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Lr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Kt.ctx(s):s),m.push(c?`${Kt[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Ur.now();return()=>{let o=Ur.now()-r,{message:n,severity:s="debug",formatter:a=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as ke from"ramda";var Ve=class e extends ze{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=ke.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,ke.reject(ke.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import un from"express";var Ge=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,un.static(...this.params))}};import ht from"express";import Tn from"node:http";import On from"node:https";var Ce=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ue(e)};import fn from"http-errors";import*as Dr from"ramda";var yt=class{constructor(t){this.logger=t}#e=Dr.tryCatch(Er);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Ze){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(k.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=tt(t);if(s.length===0)return;let a=n?.shape||$(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Hr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new Oe(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Hr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Be){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Ge)r&&s.apply(n,r);else if(s instanceof Ve)for(let[a,c,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new Oe(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...Hr(s,n))}};var yn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=fn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Ft=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new yt(t()),a=new Map;if(je({routing:o,onEndpoint:(m,p,l,b)=>{ue()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let h=n?.[m.getRequestType()]||[],x=async(y,C)=>{let O=t(y);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:O,defaultHeaders:R}):R;for(let j in Z)C.set(j,Z[j])}return m.execute({request:y,response:C,logger:O,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...h,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...h,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,yn(p))};import Vr,{isHttpError as hn}from"http-errors";import{setInterval as gn}from"node:timers/promises";var Kr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Fr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Br=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),$r=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var _r=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Kr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",Br);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(qr(p)||Fr(p))&&a(p);for await(let p of gn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map($r))};return{sockets:n,shutdown:()=>o??=m()}};var Gr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:hn(r)?r:Vr(400,oe(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Jr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Vr(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){lt({response:o,logger:s,error:new re(oe(a),n)})}},bn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},xn=e=>({log:e.debug.bind(e)}),Wr=async({getLogger:e,config:t})=>{let r=await Ce("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:xn(l)})(c,m,p)}),o&&a.push(bn(o)),a},Yr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Qr=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},Xr=e=>t=>t?.res?.locals[g]?.logger||e,eo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
2
+ Original error: ${e.handled.message}.`:""),{expose:tn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ir}from"zod";var Ut=class{},J=class extends Ut{#e;#t;#r;constructor({input:t=Ir.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Ir.ZodError?new ee(o):o}}},Ee=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var ze=class{nest(t){return Object.assign(t,{"":this})}};var Be=class extends ze{},ut=class e extends Be{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return wr(this.#e.inputSchema)?"upload":mt(this.#e.inputSchema)?"raw":Ar(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Zr.ZodError?new ce(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Ee))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Zr.ZodError?new ee(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){lt({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),a={},c=null,m=null,p=rt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import{z as he}from"zod";var vr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>gr(s,n),o)},$=e=>e instanceof he.ZodObject?e:e instanceof he.ZodBranded?$(e.unwrap()):e instanceof he.ZodUnion||e instanceof he.ZodDiscriminatedUnion?e.options.map(t=>$(t)).reduce((t,r)=>t.merge(r.partial()),he.object({})):e instanceof he.ZodEffects?$(e._def.schema):e instanceof he.ZodPipeline?$(e._def.in):$(e._def.left).merge($(e._def.right));import{z as W}from"zod";var Ie={positive:200,negative:400},Ze=Object.keys(Ie);var Dt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Dt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Mt(this.#e,{variant:"positive",args:[t],statusCodes:[Ie.positive],mimeTypes:[k.json]})}getNegativeResponse(){return Mt(this.#t,{variant:"negative",args:[],statusCodes:[Ie.negative],mimeTypes:[k.json]})}},$e=new be({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Ae(e);return qe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ge(a)}})}n.status(Ie.positive).json({status:"success",data:r})}}),Ht=new be({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>le(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ae(r);return qe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ge(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Ie.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var xe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof J?t:new J(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new J({handler:t})),this.resultHandler)}build({input:t=kr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new ut({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:h,tags:x,methods:l,getOperationId:b,inputSchema:vr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:kr.object({}),handler:async o=>(await t(o),{})})}},rn=new xe($e),on=new xe(Ht);import mn from"ansis";import{inspect as ln}from"node:util";import{performance as Ur}from"node:perf_hooks";import{blue as nn,green as sn,hex as an,red as pn,cyanBright as cn}from"ansis";import*as Cr from"ramda";var Kt={debug:nn,info:sn,warn:an("#FFA500"),error:pn,ctx:cn},ft={debug:10,info:20,warn:30,error:40},jr=e=>le(e)&&Object.keys(ft).some(t=>t in e),Nr=e=>e in ft,Lr=(e,t)=>ft[e]<ft[t],dn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),ve=Cr.memoizeWith((e,t)=>`${e}${t}`,dn),Mr=e=>e<1e-6?ve("nanosecond",3).format(e/1e-6):e<.001?ve("nanosecond").format(e/1e-6):e<1?ve("microsecond").format(e/.001):e<1e3?ve("millisecond").format(e):e<6e4?ve("second",2).format(e/1e3):ve("minute",2).format(e/6e4);var _e=class e{config;constructor({color:t=mn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return ln(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Lr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Kt.ctx(s):s),m.push(c?`${Kt[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Ur.now();return()=>{let o=Ur.now()-r,{message:n,severity:s="debug",formatter:a=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as ke from"ramda";var Ve=class e extends ze{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=ke.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,ke.reject(ke.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import un from"express";var Ge=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,un.static(...this.params))}};import ht from"express";import Tn from"node:http";import On from"node:https";var Ce=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ue(e)};import fn from"http-errors";import*as Dr from"ramda";var yt=class{constructor(t){this.logger=t}#e=Dr.tryCatch(Er);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Ze){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(k.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=tt(t);if(s.length===0)return;let a=n?.shape||$(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Hr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new Oe(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Hr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Be){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Ge)r&&s.apply(n,r);else if(s instanceof Ve)for(let[a,c,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new Oe(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...Hr(s,n))}};var yn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=fn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Ft=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new yt(t()),a=new Map;if(je({routing:o,onEndpoint:(m,p,l,b)=>{ue()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let h=n?.[m.getRequestType()]||[],x=async(y,C)=>{let O=t(y);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:O,defaultHeaders:R}):R;for(let j in Z)C.set(j,Z[j])}return m.execute({request:y,response:C,logger:O,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...h,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...h,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,yn(p))};import Vr,{isHttpError as hn}from"http-errors";import{setInterval as gn}from"node:timers/promises";var Kr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Fr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Br=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),$r=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var _r=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Kr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",Br);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(qr(p)||Fr(p))&&a(p);for await(let p of gn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map($r))};return{sockets:n,shutdown:()=>o??=m()}};var Gr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:hn(r)?r:Vr(400,oe(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Jr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Vr(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){lt({response:o,logger:s,error:new re(oe(a),n)})}},bn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},xn=e=>({log:e.debug.bind(e)}),Wr=async({getLogger:e,config:t})=>{let r=await Ce("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:xn(l)})(c,m,p)}),o&&a.push(bn(o)),a},Yr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Qr=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{try{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[g]={logger:a}),s()}catch(a){s(a)}},Xr=e=>t=>t?.res?.locals[g]?.logger||e,eo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
3
  `).slice(1))),to=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=_r(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as Sn,hex as ro,italic as gt,whiteBright as Rn}from"ansis";var oo=e=>{if(e.columns<132)return;let t=gt("Proudly supports transgender community.".padStart(109)),r=gt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=gt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=gt("for Tai".padEnd(20)),s=ro("#F5A9B8"),a=ro("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(Rn,5,7).fill(s,7,9).fill(a,9,12).fill(Sn,12,13),m=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
@@ -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=jr(e.logger)?e.logger:new _e(e.logger);r.debug("Running",{build:"v22.12.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:Nr(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=jr(e.logger)?e.logger:new _e(e.logger);r.debug("Running",{build:"v22.13.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:Nr(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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "22.12.0",
3
+ "version": "22.13.0",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {