express-zod-api 25.0.0-beta.2 → 25.0.0-beta.3

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
@@ -13,6 +13,15 @@
13
13
 
14
14
  ## Version 24
15
15
 
16
+ ### v24.6.1
17
+
18
+ - Compatibility fix for recently changed type of Express native middleware:
19
+ - Fixes error `TS2345` when passing over an Express middleware to:
20
+ - `EndpointsFactory::use()`;
21
+ - `EndpointsFactory::addExpressMiddleware()`;
22
+ - The issue caused by `@types/express-serve-static-core` v5.0.7;
23
+ - The issue reported by [@zoton2](https://github.com/zoton2).
24
+
16
25
  ### v24.6.0
17
26
 
18
27
  - Supporting `zod` versions `^3.25.35 || ^4.0.0`:
package/README.md CHANGED
@@ -84,6 +84,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
84
84
 
85
85
  These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
86
86
 
87
+ [<img src="https://github.com/zoton2.png" alt="@zoton2" width="50px" />](https://github.com/zoton2)
87
88
  [<img src="https://github.com/ThomasKientz.png" alt="@ThomasKientz" width="50px" />](https://github.com/ThomasKientz)
88
89
  [<img src="https://github.com/james10424.png" alt="@james10424" width="50px" />](https://github.com/james10424)
89
90
  [<img src="https://github.com/HeikoOsigus.png" alt="@HeikoOsigus" width="50px" />](https://github.com/HeikoOsigus)
package/SECURITY.md CHANGED
@@ -9,7 +9,7 @@
9
9
  | 23.x.x | Sonia | 04.2025 | :white_check_mark: |
10
10
  | 22.x.x | Tai | 01.2025 | :white_check_mark: |
11
11
  | 21.x.x | Kesaria | 11.2024 | :white_check_mark: |
12
- | 20.x.x | Zoey | 06.2024 | :white_check_mark: |
12
+ | 20.x.x | Zoey | 06.2024 | :x: |
13
13
  | 19.x.x | Dime | 05.2024 | :x: |
14
14
  | 18.x.x | Victoria | 04.2024 | :x: |
15
15
  | 17.x.x | Tonya | 02.2024 | :x: |
package/dist/index.d.ts CHANGED
@@ -295,7 +295,7 @@ declare class Middleware<OPT extends FlatObject, OUT extends FlatObject, SCO ext
295
295
  }): Promise<OUT>;
296
296
  }
297
297
  declare class ExpressMiddleware<R extends Request, S extends Response, OUT extends FlatObject> extends Middleware<FlatObject, OUT, string> {
298
- constructor(nativeMw: (request: R, response: S, next: NextFunction) => void | Promise<void>, { provider, transformer, }?: {
298
+ constructor(nativeMw: (request: R, response: S, next: NextFunction) => any, { provider, transformer, }?: {
299
299
  provider?: (request: R, response: S) => OUT | Promise<OUT>;
300
300
  transformer?: (err: Error) => Error;
301
301
  });
@@ -650,7 +650,7 @@ declare class EndpointsFactory<IN extends IOSchema | undefined = undefined, OUT
650
650
  protected middlewares: AbstractMiddleware[];
651
651
  constructor(resultHandler: AbstractResultHandler);
652
652
  addMiddleware<AOUT extends FlatObject, ASCO extends string, AIN extends IOSchema | undefined = undefined>(subject: Middleware<OUT, AOUT, ASCO, AIN> | ConstructorParameters<typeof Middleware<OUT, AOUT, ASCO, AIN>>[0]): EndpointsFactory<Extension<IN, AIN>, OUT & AOUT, SCO & ASCO>;
653
- use: <R extends Request, S extends Response, AOUT extends FlatObject = Record<string, never>>(nativeMw: (request: R, response: S, next: express.NextFunction) => void | Promise<void>, params_1?: {
653
+ use: <R extends Request, S extends Response, AOUT extends FlatObject = Record<string, never>>(nativeMw: (request: R, response: S, next: express.NextFunction) => any, params_1?: {
654
654
  provider?: ((request: R, response: S) => AOUT | Promise<AOUT>) | undefined;
655
655
  transformer?: (err: Error) => Error;
656
656
  } | undefined) => EndpointsFactory<Extension<IN, undefined>, OUT & AOUT, SCO>;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import*as D from"ramda";import{z as Y}from"zod";import{globalRegistry as Mo}from"zod";var we=Symbol.for("express-zod-api"),W=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},Z=e=>{let{examples:t,example:r}=Mo.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Zo=Y.core.$constructor("$EZBrandCheck",(e,t)=>{Y.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),Bo=function(e){let t=Z(this).slice();return t.push(e),this.meta({examples:t})},Ko=function(){return this.meta({deprecated:!0})},Ho=function(e){return this.meta({default:e})},qo=function(e){return this.check(new Zo({brand:e,check:"$EZBrandCheck"}))},Fo=function(e){let t=typeof e=="function"?e:D.renameKeys(D.reject(D.isNil,e)),r=t(D.map(D.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof Y.ZodUnknown?Y.looseObject:Y.object)(r);return this.transform(t).pipe(n)};if(!(we in globalThis)){globalThis[we]=!0;for(let e of Object.keys(Y)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=Y[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:Bo,writable:!1},deprecated:{value:Ko,writable:!1},brand:{set(){},get(){return qo.bind(this)}}})}Object.defineProperty(Y.ZodDefault.prototype,"label",{value:Ho,writable:!1}),Object.defineProperty(Y.ZodObject.prototype,"remap",{value:Fo,writable:!1})}function Do(e){return e}import*as L from"ramda";import{z as Ee}from"zod";var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var Be=Ee.object({}),At=/:([A-Za-z0-9_]+)/g,st=e=>e.match(At)?.map(t=>t.slice(1))||[],Uo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},Ct={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},_o=["body","query","params"],Nt=e=>e.method.toLowerCase(),it=(e,t={})=>{let r=Nt(e);return r==="options"?{}:(t[r]||Ct[r]||_o).filter(o=>o==="files"?Uo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},re=e=>e instanceof Error?e:e instanceof Ee.ZodError?new Ee.ZodRealError(e.issues):new Error(String(e)),me=e=>e instanceof Ee.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Ee.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,oe=(e,t)=>E(e)&&"_zod"in e&&(t?L.path(["_zod","def","type"],e)===t:!0),le=(e,t,r)=>e.length&&t.length?L.xprod(e,t).map(r):e.concat(t),jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ne=(...e)=>{let t=L.chain(o=>o.split(/[^A-Z0-9]/gi),e);return L.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(jt).join("")},at=L.tryCatch((e,t)=>typeof Ee.parse(e,t),L.always(void 0)),E=e=>typeof e=="object"&&e!==null,ue=L.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as pe from"ramda";import{z as Ir,globalRegistry as sn}from"zod";import*as ae from"ramda";import{z as Or}from"zod";import{z as Jo}from"zod";var fe=Symbol("Buffer"),pt=()=>Jo.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(fe);import{z as Ke}from"zod";var ye=Symbol("DateIn"),yr=({examples:e,...t}={})=>Ke.union([Ke.iso.date(),Ke.iso.datetime(),Ke.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ke.date()).brand(ye).meta(t);import{z as Vo}from"zod";var ge=Symbol("DateOut"),gr=(e={})=>Vo.date().transform(t=>t.toISOString()).brand(ge).meta(e);import{z as Go}from"zod";var he=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},Q=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.`}},He=class extends Error{name="IOSchemaError"},ct=class extends He{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},qe=class extends He{constructor(r){let o=new Go.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(me(o),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends He{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},se=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Fe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as hr}from"zod";var De=Symbol("Form"),xr=e=>(e instanceof hr.ZodObject?e:hr.object(e)).brand(De);import{z as Wo}from"zod";var ie=Symbol("Upload"),br=()=>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",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ie);import{z as Yo}from"zod";var B=Symbol("Raw"),Sr=Yo.object({raw:pt()}),Qo=e=>Sr.extend(e).brand(B);function Rr(e){return e?Qo(e):Sr.brand(B)}var Tr=(e,{io:t,condition:r})=>ae.tryCatch(()=>{Or.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ct(o)}})},o=>o.cause)(),Pr=(e,{io:t})=>{let o=[Or.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(ae.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ae.values(n))}ae.is(Array,n)&&o.push(...ae.values(n))}return!1},wr=e=>Tr(e,{condition:t=>{let r=W(t);return typeof r=="symbol"&&[ie,B,De].includes(r)},io:"input"}),Xo=["nan","symbol","map","set","bigint","void","promise","never"],zt=(e,t)=>Tr(e,{io:t,condition:r=>{let o=W(r),{type:n}=r._zod.def;return!!(Xo.includes(n)||o===fe||t==="input"&&(n==="date"||o===ge)||t==="output"&&(o===ye||o===B||o===ie))}});import rn,{isHttpError as on}from"http-errors";import Er,{isHttpError as en}from"http-errors";import*as kr from"ramda";import{z as tn}from"zod";var Lt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof tn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new se(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Ue=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),ke=e=>en(e)?e:Er(e instanceof X?400:500,me(e),{cause:e.cause||e}),xe=e=>ue()&&!e.expose?Er(e.statusCode).message:e.message,vr=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>le(t,Z(o).map(kr.objOf(r)),([n,s])=>({...n,...s})),[]);var dt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=xe(rn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:on(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as nn}from"zod";var $t=class{},U=class extends $t{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await(this.#e||Be).parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof nn.ZodError?new X(o):o}}},ve=class extends U{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends Ie{},mt=class e extends _e{#e;#t=pe.once(()=>{if(Z(this.#e.outputSchema).length||!oe(this.#e.outputSchema,"object"))return;let t=vr(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();sn.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=wr(this.#e.inputSchema);if(t){let r=W(t);if(r===ie)return"upload";if(r===B)return"raw";if(r===De)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=pe.pluck("security",this.#e.middlewares||[]);return pe.reject(pe.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Ir.ZodError?new qe(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof ve))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Ir.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){dt({...t,error:new se(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),i={},p={output:{},error:null},d=it(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Ar=(e,t)=>e&&t?e.and(t):e||t,Cr=(e,t)=>e?e.and(t):t;import{globalRegistry as Nr,z as K}from"zod";var Ae={positive:200,negative:400},Ce=Object.keys(Ae);var Mt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Mt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Lt(this.#e,{variant:"positive",args:[t],statusCodes:[Ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return Lt(this.#t,{variant:"negative",args:[],statusCodes:[Ae.negative],mimeTypes:[w.json]})}},Se=new be({positive:e=>{let t=K.object({status:K.literal("success"),data:e}),r=Z(e);return r.length&&Nr.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:K.object({status:K.literal("error"),error:K.object({message:K.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 i=ke(e);return Ue(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:xe(i)}})}n.status(Ae.positive).json({status:"success",data:r})}}),Zt=new be({positive:e=>{let t=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());if(Z(t).length)return t;let r=Z(e).filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();Nr.remove(t).add(t,{...o,examples:r})}return t},negative:K.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=ke(r);return Ue(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(xe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ae.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}schema=void 0;middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r.schema=Ar(this.schema,t.schema),r}addMiddleware(t){return this.#e(t instanceof U?t:new U(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new ve(...t))}addOptions(t){return this.#e(new U({handler:t}))}build({input:t=Be,output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,g=typeof o=="function"?o:()=>o,x=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new mt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:x,tags:y,methods:m,getOperationId:g,inputSchema:Cr(this.schema,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Be,handler:async o=>(await t(o),{})})}},an=new Re(Se),pn=new Re(Zt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as Zr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as jr from"ramda";var Bt={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},lt={debug:10,info:20,warn:30,error:40},zr=e=>E(e)&&Object.keys(lt).some(t=>t in e),Lr=e=>e in lt,$r=(e,t)=>lt[e]<lt[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ne=jr.memoizeWith((e,t)=>`${e}${t}`,fn),Mr=e=>e<1e-6?Ne("nanosecond",3).format(e/1e-6):e<.001?Ne("nanosecond").format(e/1e-6):e<1?Ne("microsecond").format(e/.001):e<1e3?Ne("millisecond").format(e):e<6e4?Ne("second",2).format(e/1e3):Ne("minute",2).format(e/6e4);var Je=class e{config;constructor({color:t=yn.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 gn(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,...i},color:p}=this.config;if(n==="silent"||$r(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Bt.ctx(s):s),d.push(p?`${Bt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),console.log(d.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=Zr.now();return()=>{let o=Zr.now()-r,{message:n,severity:s="debug",formatter:i=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Br from"ramda";var Ve=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=Br.filter(r=>!!r[1],Object.entries(this.#e));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 hn from"express";var Ge=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import yt from"express";import zn from"node:http";import Ln from"node:https";var je=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Fe(e)};import wn from"http-errors";import{z as Hr}from"zod";import*as b from"ramda";var xn=e=>e.type==="object",bn=b.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return b.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),Sn=b.pipe(Object.keys,b.without(["type","properties","required","examples","description","additionalProperties"]),b.isEmpty),Kr=b.pair(!0),ze=(e,t="coerce")=>{let r=[b.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&Sn(p)))throw new Error("Can not merge");return b.pair(s,p)})),i.anyOf&&r.push(...b.map(Kr,i.anyOf)),i.oneOf&&r.push(...b.map(Kr,i.oneOf)),i.examples?.length&&(s?o.examples=b.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>b.mergeDeepRight(p,d))),!!xn(i)&&(r.push([s,{examples:Rn(i)}]),i.properties&&(o.properties=(t==="throw"?bn:b.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Rn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return le(t,n.map(b.objOf(r)),([s,i])=>({...s,...i}))},[]);var ut=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Hr.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=zt(t.inputSchema,"input");o&&this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ce)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(w.json))continue;let i=zt(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=st(t);if(s.length===0)return;let i=n?.flat||ze(Hr.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var Kt=["get","post","put","delete","patch"],qr=e=>Kt.includes(e);var On=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&qr(t)?[r,t]:[e]},Tn=e=>e.trim().split("/").filter(Boolean).join("/"),Fr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=On(r);return[[t||""].concat(Tn(n)||[]).join("/"),o,s]}),Pn=(e,t)=>{throw new he("Route with explicit method can only be assigned with Endpoint",e,t)},Dr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new he(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ht=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new he("Route has a duplicate",e,t);r.add(o)},Le=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Fr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof _e)if(p)Ht(p,s,n),Dr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)Ht(c,s,n),t(i,s,c)}else if(p&&Pn(p,s),i instanceof Ge)r&&i.apply(s,r);else if(i instanceof Ve)for(let[d,c]of i.entries){let{methods:m}=c;Ht(d,s,n),Dr(d,s,m),t(c,s,d)}else o.unshift(...Fr(i,s))}};import*as Ur from"ramda";var _r=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),En=e=>({method:t},r,o)=>{let n=_r(e);r.set({Allow:n});let s=wn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":_r(e),"Access-Control-Allow-Headers":"content-type"}),qt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new ut(t()),i=new Map;Le({routing:o,onEndpoint:(c,m,g)=>{ue()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let x=n?.[c.requestType]||[],y=Ur.pair(x,c);i.has(m)||i.set(m,new Map(r.cors?[["options",y]]:[])),i.get(m)?.set(g,y)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let g=Array.from(m.keys());for(let[x,[y,I]]of m){let k=y.slice().concat(async(z,S)=>{let A=t(z);return I.execute({request:z,response:S,logger:A,config:r})});r.cors&&k.unshift(async(z,S,A)=>{let C=t(z),M=kn(g),N=typeof r.cors=="function"?await r.cors({request:z,endpoint:I,logger:C,defaultHeaders:M}):M;S.set(N),A()}),e[x](c,...k)}r.wrongMethodBehavior!==404&&d.set(c,En(g))}for(let[c,m]of d)e.all(c,m)};import In from"http-errors";import{setInterval as vn}from"node:timers/promises";var Jr=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",Vr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Wr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Yr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Qr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Jr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Wr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Gr(c)||Vr(c))&&i(c);for await(let c of vn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(Yr))};return{sockets:n,shutdown:()=>o??=d()}};var Xr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:re(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),eo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=In(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(i){dt({response:o,logger:s,error:new se(re(i),n)})}},An=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Cn=e=>({log:e.debug.bind(e)}),to=async({getLogger:e,config:t})=>{let r=await je("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Cn(m)})(p,d,c)}),o&&i.push(An(o)),i},ro=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},oo=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[we]={logger:i}),s()},no=e=>t=>t?.res?.locals[we]?.logger||e,so=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
1
+ import*as D from"ramda";import{z as Y}from"zod";import{globalRegistry as Mo}from"zod";var we=Symbol.for("express-zod-api"),W=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},Z=e=>{let{examples:t,example:r}=Mo.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Zo=Y.core.$constructor("$EZBrandCheck",(e,t)=>{Y.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),Bo=function(e){let t=Z(this).slice();return t.push(e),this.meta({examples:t})},Ko=function(){return this.meta({deprecated:!0})},Ho=function(e){return this.meta({default:e})},qo=function(e){return this.check(new Zo({brand:e,check:"$EZBrandCheck"}))},Fo=function(e){let t=typeof e=="function"?e:D.renameKeys(D.reject(D.isNil,e)),r=t(D.map(D.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof Y.ZodUnknown?Y.looseObject:Y.object)(r);return this.transform(t).pipe(n)};if(!(we in globalThis)){globalThis[we]=!0;for(let e of Object.keys(Y)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=Y[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:Bo,writable:!1},deprecated:{value:Ko,writable:!1},brand:{set(){},get(){return qo.bind(this)}}})}Object.defineProperty(Y.ZodDefault.prototype,"label",{value:Ho,writable:!1}),Object.defineProperty(Y.ZodObject.prototype,"remap",{value:Fo,writable:!1})}function Do(e){return e}import*as L from"ramda";import{z as Ee}from"zod";var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var Be=Ee.object({}),At=/:([A-Za-z0-9_]+)/g,st=e=>e.match(At)?.map(t=>t.slice(1))||[],Uo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},Ct={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},_o=["body","query","params"],Nt=e=>e.method.toLowerCase(),it=(e,t={})=>{let r=Nt(e);return r==="options"?{}:(t[r]||Ct[r]||_o).filter(o=>o==="files"?Uo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},re=e=>e instanceof Error?e:e instanceof Ee.ZodError?new Ee.ZodRealError(e.issues):new Error(String(e)),me=e=>e instanceof Ee.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Ee.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,oe=(e,t)=>E(e)&&"_zod"in e&&(t?L.path(["_zod","def","type"],e)===t:!0),le=(e,t,r)=>e.length&&t.length?L.xprod(e,t).map(r):e.concat(t),jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ne=(...e)=>{let t=L.chain(o=>o.split(/[^A-Z0-9]/gi),e);return L.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(jt).join("")},at=L.tryCatch((e,t)=>typeof Ee.parse(e,t),L.always(void 0)),E=e=>typeof e=="object"&&e!==null,ue=L.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as pe from"ramda";import{z as vr,globalRegistry as sn}from"zod";import*as ae from"ramda";import{z as Or}from"zod";import{z as Jo}from"zod";var fe=Symbol("Buffer"),pt=()=>Jo.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(fe);import{z as Ke}from"zod";var ye=Symbol("DateIn"),yr=({examples:e,...t}={})=>Ke.union([Ke.iso.date(),Ke.iso.datetime(),Ke.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ke.date()).brand(ye).meta(t);import{z as Vo}from"zod";var ge=Symbol("DateOut"),gr=(e={})=>Vo.date().transform(t=>t.toISOString()).brand(ge).meta(e);import{z as Go}from"zod";var he=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},Q=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.`}},He=class extends Error{name="IOSchemaError"},ct=class extends He{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},qe=class extends He{constructor(r){let o=new Go.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(me(o),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends He{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},se=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Fe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as hr}from"zod";var De=Symbol("Form"),xr=e=>(e instanceof hr.ZodObject?e:hr.object(e)).brand(De);import{z as Wo}from"zod";var ie=Symbol("Upload"),br=()=>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",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ie);import{z as Yo}from"zod";var B=Symbol("Raw"),Sr=Yo.object({raw:pt()}),Qo=e=>Sr.extend(e).brand(B);function Rr(e){return e?Qo(e):Sr.brand(B)}var Tr=(e,{io:t,condition:r})=>ae.tryCatch(()=>{Or.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ct(o)}})},o=>o.cause)(),Pr=(e,{io:t})=>{let o=[Or.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(ae.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ae.values(n))}ae.is(Array,n)&&o.push(...ae.values(n))}return!1},wr=e=>Tr(e,{condition:t=>{let r=W(t);return typeof r=="symbol"&&[ie,B,De].includes(r)},io:"input"}),Xo=["nan","symbol","map","set","bigint","void","promise","never"],zt=(e,t)=>Tr(e,{io:t,condition:r=>{let o=W(r),{type:n}=r._zod.def;return!!(Xo.includes(n)||o===fe||t==="input"&&(n==="date"||o===ge)||t==="output"&&(o===ye||o===B||o===ie))}});import rn,{isHttpError as on}from"http-errors";import Er,{isHttpError as en}from"http-errors";import*as kr from"ramda";import{z as tn}from"zod";var Lt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof tn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new se(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Ue=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),ke=e=>en(e)?e:Er(e instanceof X?400:500,me(e),{cause:e.cause||e}),xe=e=>ue()&&!e.expose?Er(e.statusCode).message:e.message,Ir=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>le(t,Z(o).map(kr.objOf(r)),([n,s])=>({...n,...s})),[]);var dt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=xe(rn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:on(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as nn}from"zod";var $t=class{},U=class extends $t{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await(this.#e||Be).parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof nn.ZodError?new X(o):o}}},Ie=class extends U{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var ve=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends ve{},mt=class e extends _e{#e;#t=pe.once(()=>{if(Z(this.#e.outputSchema).length||!oe(this.#e.outputSchema,"object"))return;let t=Ir(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();sn.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=wr(this.#e.inputSchema);if(t){let r=W(t);if(r===ie)return"upload";if(r===B)return"raw";if(r===De)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=pe.pluck("security",this.#e.middlewares||[]);return pe.reject(pe.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof vr.ZodError?new qe(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ie))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof vr.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){dt({...t,error:new se(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),i={},p={output:{},error:null},d=it(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Ar=(e,t)=>e&&t?e.and(t):e||t,Cr=(e,t)=>e?e.and(t):t;import{globalRegistry as Nr,z as K}from"zod";var Ae={positive:200,negative:400},Ce=Object.keys(Ae);var Mt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Mt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Lt(this.#e,{variant:"positive",args:[t],statusCodes:[Ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return Lt(this.#t,{variant:"negative",args:[],statusCodes:[Ae.negative],mimeTypes:[w.json]})}},Se=new be({positive:e=>{let t=K.object({status:K.literal("success"),data:e}),r=Z(e);return r.length&&Nr.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:K.object({status:K.literal("error"),error:K.object({message:K.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 i=ke(e);return Ue(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:xe(i)}})}n.status(Ae.positive).json({status:"success",data:r})}}),Zt=new be({positive:e=>{let t=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());if(Z(t).length)return t;let r=Z(e).filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();Nr.remove(t).add(t,{...o,examples:r})}return t},negative:K.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=ke(r);return Ue(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(xe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ae.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}schema=void 0;middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r.schema=Ar(this.schema,t.schema),r}addMiddleware(t){return this.#e(t instanceof U?t:new U(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new Ie(...t))}addOptions(t){return this.#e(new U({handler:t}))}build({input:t=Be,output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,g=typeof o=="function"?o:()=>o,x=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new mt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:x,tags:y,methods:m,getOperationId:g,inputSchema:Cr(this.schema,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Be,handler:async o=>(await t(o),{})})}},an=new Re(Se),pn=new Re(Zt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as Zr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as jr from"ramda";var Bt={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},lt={debug:10,info:20,warn:30,error:40},zr=e=>E(e)&&Object.keys(lt).some(t=>t in e),Lr=e=>e in lt,$r=(e,t)=>lt[e]<lt[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ne=jr.memoizeWith((e,t)=>`${e}${t}`,fn),Mr=e=>e<1e-6?Ne("nanosecond",3).format(e/1e-6):e<.001?Ne("nanosecond").format(e/1e-6):e<1?Ne("microsecond").format(e/.001):e<1e3?Ne("millisecond").format(e):e<6e4?Ne("second",2).format(e/1e3):Ne("minute",2).format(e/6e4);var Je=class e{config;constructor({color:t=yn.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 gn(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,...i},color:p}=this.config;if(n==="silent"||$r(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Bt.ctx(s):s),d.push(p?`${Bt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),console.log(d.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=Zr.now();return()=>{let o=Zr.now()-r,{message:n,severity:s="debug",formatter:i=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Br from"ramda";var Ve=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Br.filter(r=>!!r[1],Object.entries(this.#e));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 hn from"express";var Ge=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import yt from"express";import zn from"node:http";import Ln from"node:https";var je=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Fe(e)};import wn from"http-errors";import{z as Hr}from"zod";import*as b from"ramda";var xn=e=>e.type==="object",bn=b.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return b.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),Sn=b.pipe(Object.keys,b.without(["type","properties","required","examples","description","additionalProperties"]),b.isEmpty),Kr=b.pair(!0),ze=(e,t="coerce")=>{let r=[b.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&Sn(p)))throw new Error("Can not merge");return b.pair(s,p)})),i.anyOf&&r.push(...b.map(Kr,i.anyOf)),i.oneOf&&r.push(...b.map(Kr,i.oneOf)),i.examples?.length&&(s?o.examples=b.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>b.mergeDeepRight(p,d))),!!xn(i)&&(r.push([s,{examples:Rn(i)}]),i.properties&&(o.properties=(t==="throw"?bn:b.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Rn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return le(t,n.map(b.objOf(r)),([s,i])=>({...s,...i}))},[]);var ut=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Hr.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=zt(t.inputSchema,"input");o&&this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ce)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(w.json))continue;let i=zt(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=st(t);if(s.length===0)return;let i=n?.flat||ze(Hr.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var Kt=["get","post","put","delete","patch"],qr=e=>Kt.includes(e);var On=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&qr(t)?[r,t]:[e]},Tn=e=>e.trim().split("/").filter(Boolean).join("/"),Fr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=On(r);return[[t||""].concat(Tn(n)||[]).join("/"),o,s]}),Pn=(e,t)=>{throw new he("Route with explicit method can only be assigned with Endpoint",e,t)},Dr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new he(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ht=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new he("Route has a duplicate",e,t);r.add(o)},Le=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Fr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof _e)if(p)Ht(p,s,n),Dr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)Ht(c,s,n),t(i,s,c)}else if(p&&Pn(p,s),i instanceof Ge)r&&i.apply(s,r);else if(i instanceof Ve)for(let[d,c]of i.entries){let{methods:m}=c;Ht(d,s,n),Dr(d,s,m),t(c,s,d)}else o.unshift(...Fr(i,s))}};import*as Ur from"ramda";var _r=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),En=e=>({method:t},r,o)=>{let n=_r(e);r.set({Allow:n});let s=wn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":_r(e),"Access-Control-Allow-Headers":"content-type"}),qt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new ut(t()),i=new Map;Le({routing:o,onEndpoint:(c,m,g)=>{ue()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let x=n?.[c.requestType]||[],y=Ur.pair(x,c);i.has(m)||i.set(m,new Map(r.cors?[["options",y]]:[])),i.get(m)?.set(g,y)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let g=Array.from(m.keys());for(let[x,[y,v]]of m){let k=y.slice().concat(async(z,S)=>{let A=t(z);return v.execute({request:z,response:S,logger:A,config:r})});r.cors&&k.unshift(async(z,S,A)=>{let C=t(z),M=kn(g),N=typeof r.cors=="function"?await r.cors({request:z,endpoint:v,logger:C,defaultHeaders:M}):M;S.set(N),A()}),e[x](c,...k)}r.wrongMethodBehavior!==404&&d.set(c,En(g))}for(let[c,m]of d)e.all(c,m)};import vn from"http-errors";import{setInterval as In}from"node:timers/promises";var Jr=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",Vr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Wr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Yr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Qr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Jr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Wr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Gr(c)||Vr(c))&&i(c);for await(let c of In(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(Yr))};return{sockets:n,shutdown:()=>o??=d()}};var Xr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:re(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),eo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=vn(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(i){dt({response:o,logger:s,error:new se(re(i),n)})}},An=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Cn=e=>({log:e.debug.bind(e)}),to=async({getLogger:e,config:t})=>{let r=await je("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Cn(m)})(p,d,c)}),o&&i.push(An(o)),i},ro=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},oo=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[we]={logger:i}),s()},no=e=>t=>t?.res?.locals[we]?.logger||e,so=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
3
  `).slice(1))),io=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=Qr(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};import{gray as Nn,hex as ao,italic as ft,whiteBright as jn}from"ansis";var po=e=>{if(e.columns<132)return;let t=ft("Proudly supports transgender community.".padStart(109)),r=ft("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=ft("Thank you for choosing Express Zod API for your project.".padStart(132)),n=ft("for Sara".padEnd(20)),s=ao("#F5A9B8"),i=ao("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(jn,5,7).fill(s,7,9).fill(i,9,12).fill(Nn,12,13),d=`
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(d.split(`
17
17
  `).map((c,m)=>p[m]?p[m](c):c).join(`
18
- `))};var co=e=>{e.startupLogo!==!1&&po(process.stdout);let t=e.errorHandler||Se,r=zr(e.logger)?e.logger:new Je(e.logger);r.debug("Running",{build:"v25.0.0-beta.2",env:process.env.NODE_ENV||"development"}),so(r);let o=oo({logger:r,config:e}),s={getLogger:no(r),errorHandler:t},i=eo(s),p=Xr(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},$n=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=co(e);return qt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Mn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=co(e),p=yt().disable("x-powered-by").use(i);if(e.compression){let x=await je("compression");p.use(x(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||yt.json()],raw:[e.rawParser||yt.raw(),ro],form:[e.formParser||yt.urlencoded()],upload:e.upload?await to({config:e,getLogger:o}):[]};qt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let x=zn.createServer(p);c.push(x),g.push(m(x,e.http.listen))}if(e.https){let x=Ln.createServer(e.https.options,p);c.push(x),g.push(m(x,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&io({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(x=>x())}};import{OpenApiBuilder as as}from"openapi3-ts/oas31";import*as vo from"ramda";import*as R from"ramda";var mo=e=>E(e)&&"or"in e,lo=e=>E(e)&&"and"in e,Ft=e=>!lo(e)&&!mo(e),uo=e=>{let t=R.filter(Ft,e),r=R.chain(R.prop("and"),R.filter(lo,e)),[o,n]=R.partition(Ft,r),s=R.concat(t,o),i=R.filter(mo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>le(d,R.map(m=>Ft(m)?[m]:m.and,c),([m,g])=>R.concat(m,g)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as ho,isSchemaObject as gt}from"openapi3-ts/oas31";import*as l from"ramda";import{z as yo}from"zod";var fo=["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 go=50,xo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Bn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},bo=e=>e.replace(At,t=>`{${t.slice(1)}}`),Kn=({},e)=>{if(e.isResponse)throw new Q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),qn=({zodSchema:e,jsonSchema:t})=>{if(!oe(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Fn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return ze(e,"throw")},(e,{jsonSchema:t})=>t),Dn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Wn(t.type)})},We=e=>e,Un=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Q("Please use ez.dateOut() for output.",r);let o={description:t||"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:xo}};return e?.length&&(o.examples=e),o},_n=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Q("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:xo}};return e?.length&&(o.examples=e),o},Jn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Vn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Gn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Bn?.[t]},Wn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],Yn=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!oe(o,"transform"))return t;let s=We(_t(n,{ctx:r}));if(gt(s))if(r.isResponse){let i=at(o,Gn(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},Qn=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},Dt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,Xn=(e,t)=>t?.includes(e)||e.startsWith("x-")||fo.includes(e),So=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=ze(r),m=st(e),g=o.includes("query"),x=o.includes("params"),y=o.includes("headers"),I=S=>x&&m.includes(S),k=l.chain(l.filter(S=>S.type==="header"),p??[]).map(({name:S})=>S),z=S=>y&&(i?.(S,t,e)??Xn(S,k));return Object.entries(c.properties).reduce((S,[A,C])=>{if(!E(C))return S;let M=I(A)?"path":z(A)?"header":g?"query":void 0;if(!M)return S;let N=We(C),ee=s==="components"?n(C.id||JSON.stringify(C),N,ne(d,A)):N;return S.concat({name:A,in:M,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:ee,examples:Dt(gt(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(E,l.has(A)))||[]))})},[])},Ut={nullable:Dn,union:qn,bigint:Jn,intersection:Fn,tuple:Vn,pipe:Yn,[ye]:Un,[ge]:_n,[ie]:Kn,[B]:Qn,[fe]:Hn},es=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(ho(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,We(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},_t=(e,{ctx:t,rules:r=Ut})=>{let{$defs:o={},properties:n={}}=yo.toJSONSchema(yo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=W(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return es(E(n.subject)?n.subject:{},o,t)},Ro=(e,t)=>{if(ho(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Ro(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},Oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${jt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=We(_t(r,{rules:{...c,...Ut},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x=[];gt(g)&&g.examples&&(x.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,ne(m)):g,examples:Dt(x)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},ts=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},rs=({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},os=({name:e})=>({type:"apiKey",in:"header",name:e}),ns=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ss=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),is=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),To=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ts(o):o.type==="input"?rs(o,t):o.type==="header"?os(o):o.type==="cookie"?ns(o):o.type==="openid"?ss(o):is(o);return e.map(o=>o.map(r))},Po=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),wo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>_t(e,{rules:{...t,...Ut},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Eo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=Ro(We(o),p),g=[];gt(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let x={schema:i==="components"?s(r,c,ne(d)):c,examples:Dt(g.length?g:ze(o).examples?.filter(I=>E(I)&&!Array.isArray(I)).map(l.omit(p))||[])},y={description:d,content:{[n]:x}};return(m||n===w.raw)&&(y.required=!0),y},ko=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)},[]),Jt=e=>e.length<=go?e:e.slice(0,go-1)+"\u2026",ht=e=>e.length?e.slice():void 0;var Vt=class extends as{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||ne(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});Le({routing:t,onEndpoint:(y,I,k)=>{let z={path:I,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:S,shortDescription:A,scopes:C,inputSchema:M}=y,N=A?Jt(A):m&&S?Jt(S):void 0,ee=r.inputSources?.[k]||Ct[k],Pe=this.#n(I,k,y.getOperationId(k)),et=wo({...z,schema:M}),ce=uo(y.security),tt=So({...z,inputSources:ee,isHeader:c,security:ce,request:et,description:i?.requestParameter?.call(null,{method:k,path:I,operationId:Pe})}),rt={};for(let te of Ce){let de=y.getResponses(te);for(let{mimeTypes:nt,schema:vt,statusCodes:fr}of de)for(let It of fr)rt[It]=Oo({...z,variant:te,schema:vt,mimeTypes:nt,statusCode:It,hasMultipleStatusCodes:de.length>1||fr.length>1,description:i?.[`${te}Response`]?.call(null,{method:k,path:I,operationId:Pe,statusCode:It})})}let ot=ee.includes("body")?Eo({...z,request:et,paramNames:vo.pluck("name",tt),schema:M,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:I,operationId:Pe})}):void 0,Et=Po(To(ce,ee),C,te=>{let de=this.#s(te);return this.addSecurityScheme(de,te),de}),kt={operationId:Pe,summary:N,description:S,deprecated:y.isDeprecated||void 0,tags:ht(y.tags),parameters:ht(tt),requestBody:ot,security:ht(Et),responses:rt};this.addPath(bo(I),{[k]:kt})}}),d&&(this.rootDoc.tags=ko(d))}};import{createRequest as ps,createResponse as cs}from"node-mocks-http";var ds=e=>ps({...e,headers:{"content-type":w.json,...e?.headers}}),ms=e=>cs(e),ls=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Lr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Io=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ds(e),s=ms({req:n,...t});s.req=t?.req||n,n.res=s;let i=ls(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},us=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Io(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},fs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=Se}}=Io(r),d=it(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:re(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as zo from"ramda";import wt from"typescript";import{z as Bs}from"zod";import*as No from"ramda";import G from"typescript";import*as _ from"ramda";import u from"typescript";var a=u.factory,xt=[a.createModifier(u.SyntaxKind.ExportKeyword)],ys=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Gt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Wt=(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)},gs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yt=e=>typeof e=="string"&&gs.test(e)?a.createIdentifier(e):P(e),bt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),St=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),$e=e=>Object.entries(e).map(([t,r])=>St(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Qt=(e,t=[])=>a.createConstructorDeclaration(Ye.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&_.map(f,t)):e,Xt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),J=e=>{let t=new Map;for(let r of e)t.set(xs(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Yt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?J([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=_.reject(_.isNil,[o?"@deprecated":void 0,n]);return p.length?Gt(i,p.join(" ")):i},er=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),tr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&xt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),rr=(e,t)=>V(e,J(_.map($,t)),{expose:!0}),V=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?xt:void 0,e,n&&ir(n),t);return o?Gt(s,o):s},Ao=(e,t)=>a.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),or=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&ir(o),t,n,a.createBlock(r)),nr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(xt,e,r&&ir(r),void 0,t),sr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Rt=e=>f(Promise.name,[e]),Ot=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?xt:void 0,e,void 0,void 0,t);return o?Gt(n,o):n},ir=e=>(Array.isArray(e)?e.map(t=>_.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Te=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?ys:void 0,void 0,Array.isArray(e)?_.map(St,e):$e(e),void 0,void 0,t),O=e=>e,Qe=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),T=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Me=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Tt=(e,t)=>f("Extract",[e,t]),ar=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),H=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Co=e=>J([f(e),Rt(e)]),pr=(e,t)=>a.createFunctionTypeNode(void 0,$e(e),f(t)),P=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),$=e=>a.createLiteralTypeNode(P(e)),hs=[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],xs=e=>hs.includes(e.kind);var Pt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=rr("Method",Kt);someOfType=V("SomeOf",H("T",sr("T")),{params:["T"]});requestType=V("Request",sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>rr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ot(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Yt(t),a.createArrayLiteralExpression(No.map(P,r))))),{expose:!0});makeImplementationType=()=>V(this.#e.implementationType,pr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Rt(G.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:G.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Te({[this.#e.requestParameter.text]:G.SyntaxKind.StringKeyword},a.createAsExpression(T(this.#e.requestParameter,O("split"))(a.createRegularExpressionLiteral("/ (.+)/"),P(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,Te({[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt},a.createBlock([j(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],G.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([ar(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(bt(":",[this.#e.keyParameter]),Te([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>or(this.#e.provideMethod,$e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:H(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(tr(this.#e.methodParameter,this.#e.pathParameter),T(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(T(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(T(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Rt(H(this.interfaces.response,"K"))});makeClientClass=t=>nr(t,[Qt([St(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>bt("?",[Me(URLSearchParams.name,t)]);#o=()=>Me(URL.name,bt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(O("method"),T(this.#e.methodParameter,O("toUpperCase"))()),r=a.createPropertyAssignment(O("headers"),Qe(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Qe(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=j(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=j(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(G.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=j(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,Qe(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return j(this.#e.defaultImplementationConst,Te([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>Qt($e({request:"K",params:H(this.interfaces.input,"K")}),[j(tr(this.#e.pathParameter,this.#e.restConst),T(this.#e.substituteFn)(a.createElementAccessExpression(T(this.#e.parseRequestFn)(this.#e.requestParameter),P(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),ar(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Oe(O("event"),t)]);#i=()=>or(this.#e.onMethod,$e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:pr({[this.#e.dataParameter.text]:H(Tt("R",er(this.#s("E"))),$(O("data")))},Co(G.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Te([this.#e.msgParameter],T(this.#e.handlerParameter)(T(JSON[Symbol.toStringTag],O("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),O("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:H("R",$(O("event")))}});makeSubscriptionClass=t=>nr(t,[Ao(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Tt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(G.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Tt(H(this.interfaces.positive,"K"),er(this.#s(G.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Me(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Me(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Te(["time"],a.createBlock([])))]};import*as v from"ramda";import h from"typescript";import{globalRegistry as bs}from"zod";var cr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=W(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>cr(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:F}=h,Ss={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},dr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Rs=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(h.SyntaxKind.UndefinedKeyword):$(r));return t.length===1?t[0]:J(t)},Os=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(oe(p)){r.unshift(p);break}i+=p??""}return i},n=F.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?F.createTemplateMiddle:F.createTemplateTail;s.push(F.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?F.createTemplateLiteralType(n,s):$(n.text)},Ts=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=bs.get(p)||{};return Oe(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return F.createTypeLiteralNode(s)};return Pr(e,{io:t?"output":"input"})?o(e,n):n()},Ps=({_zod:{def:e}},{next:t})=>F.createArrayTypeNode(t(e.element)),ws=({_zod:{def:e}})=>J(Object.values(e.entries).map($)),Es=({_zod:{def:e}},{next:t})=>J(e.options.map(t)),ks=e=>Ss?.[e.kind],vs=({_zod:{def:e}},{next:t})=>J([t(e.innerType),$(null)]),Is=({_zod:{def:e}},{next:t})=>F.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:F.createRestTypeNode(t(e.rest)))),As=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Cs=v.tryCatch(e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(dr.name,...o))return!1;if(v.both(v.eqBy(dr.type),v.eqBy(dr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Ns=({_zod:{def:e}},{next:t})=>Cs([e.left,e.right].map(t)),q=e=>()=>f(e),Xe=({_zod:{def:e}},{next:t})=>t(e.innerType),jo=e=>f(e?h.SyntaxKind.UnknownKeyword:h.SyntaxKind.AnyKeyword),js=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!oe(o,"transform"))return t(o);let s=t(n),i=at(o,ks(s)),p={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return f(i&&p[i]||jo(r))},zs=()=>$(null),Ls=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),$s=()=>f("Buffer"),Ms=(e,{next:t})=>t(e._zod.def.shape.raw),Zs={string:q(h.SyntaxKind.StringKeyword),number:q(h.SyntaxKind.NumberKeyword),bigint:q(h.SyntaxKind.BigIntKeyword),boolean:q(h.SyntaxKind.BooleanKeyword),any:q(h.SyntaxKind.AnyKeyword),undefined:q(h.SyntaxKind.UndefinedKeyword),[ye]:q(h.SyntaxKind.StringKeyword),[ge]:q(h.SyntaxKind.StringKeyword),never:q(h.SyntaxKind.NeverKeyword),void:q(h.SyntaxKind.UndefinedKeyword),unknown:q(h.SyntaxKind.UnknownKeyword),null:zs,array:Ps,tuple:Is,record:As,object:Ts,literal:Rs,template_literal:Os,intersection:Ns,union:Es,default:Xe,enum:ws,optional:Xe,nonoptional:Xe,nullable:vs,catch:Xe,pipe:js,lazy:Ls,readonly:Xe,[fe]:$s,[B]:Ms},mr=(e,{brandHandling:t,ctx:r})=>cr(e,{rules:{...t,...Zs},onMissing:({},{isResponse:o})=>jo(o),ctx:r});var lr=class extends Pt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=$(null);this.#t.set(t,V(o,n)),this.#t.set(t,V(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=Bs.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};Le({routing:t,onEndpoint:(x,y,I)=>{let k=ne.bind(null,I,y),{isDeprecated:z,inputSchema:S,tags:A}=x,C=`${I} ${y}`,M=V(k("input"),mr(S,c),{comment:C});this.#e.push(M);let N=Ce.reduce((et,ce)=>{let tt=x.getResponses(ce),rt=zo.chain(([Et,{schema:kt,mimeTypes:te,statusCodes:de}])=>{let nt=V(k(ce,"variant",`${Et+1}`),mr(te?kt:p,m),{comment:C});return this.#e.push(nt),de.map(vt=>Oe(vt,nt.name))},Array.from(tt.entries())),ot=Ot(k(ce,"response","variants"),rt,{comment:C});return this.#e.push(ot),Object.assign(et,{[ce]:ot})},{});this.paths.add(y);let ee=$(C),Pe={input:f(M.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:J([H(this.interfaces.positive,ee),H(this.interfaces.negative,ee)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:z,store:Pe}),this.tags.set(C,A)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Wt(r,t)).join(`
18
+ `))};var co=e=>{e.startupLogo!==!1&&po(process.stdout);let t=e.errorHandler||Se,r=zr(e.logger)?e.logger:new Je(e.logger);r.debug("Running",{build:"v25.0.0-beta.3",env:process.env.NODE_ENV||"development"}),so(r);let o=oo({logger:r,config:e}),s={getLogger:no(r),errorHandler:t},i=eo(s),p=Xr(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},$n=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=co(e);return qt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Mn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=co(e),p=yt().disable("x-powered-by").use(i);if(e.compression){let x=await je("compression");p.use(x(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||yt.json()],raw:[e.rawParser||yt.raw(),ro],form:[e.formParser||yt.urlencoded()],upload:e.upload?await to({config:e,getLogger:o}):[]};qt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let x=zn.createServer(p);c.push(x),g.push(m(x,e.http.listen))}if(e.https){let x=Ln.createServer(e.https.options,p);c.push(x),g.push(m(x,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&io({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(x=>x())}};import{OpenApiBuilder as as}from"openapi3-ts/oas31";import*as Io from"ramda";import*as R from"ramda";var mo=e=>E(e)&&"or"in e,lo=e=>E(e)&&"and"in e,Ft=e=>!lo(e)&&!mo(e),uo=e=>{let t=R.filter(Ft,e),r=R.chain(R.prop("and"),R.filter(lo,e)),[o,n]=R.partition(Ft,r),s=R.concat(t,o),i=R.filter(mo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>le(d,R.map(m=>Ft(m)?[m]:m.and,c),([m,g])=>R.concat(m,g)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as ho,isSchemaObject as gt}from"openapi3-ts/oas31";import*as l from"ramda";import{z as yo}from"zod";var fo=["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 go=50,xo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Bn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},bo=e=>e.replace(At,t=>`{${t.slice(1)}}`),Kn=({},e)=>{if(e.isResponse)throw new Q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),qn=({zodSchema:e,jsonSchema:t})=>{if(!oe(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Fn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return ze(e,"throw")},(e,{jsonSchema:t})=>t),Dn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Wn(t.type)})},We=e=>e,Un=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Q("Please use ez.dateOut() for output.",r);let o={description:t||"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:xo}};return e?.length&&(o.examples=e),o},_n=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Q("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:xo}};return e?.length&&(o.examples=e),o},Jn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Vn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Gn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Bn?.[t]},Wn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],Yn=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!oe(o,"transform"))return t;let s=We(_t(n,{ctx:r}));if(gt(s))if(r.isResponse){let i=at(o,Gn(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},Qn=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},Dt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,Xn=(e,t)=>t?.includes(e)||e.startsWith("x-")||fo.includes(e),So=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=ze(r),m=st(e),g=o.includes("query"),x=o.includes("params"),y=o.includes("headers"),v=S=>x&&m.includes(S),k=l.chain(l.filter(S=>S.type==="header"),p??[]).map(({name:S})=>S),z=S=>y&&(i?.(S,t,e)??Xn(S,k));return Object.entries(c.properties).reduce((S,[A,C])=>{if(!E(C))return S;let M=v(A)?"path":z(A)?"header":g?"query":void 0;if(!M)return S;let N=We(C),ee=s==="components"?n(C.id||JSON.stringify(C),N,ne(d,A)):N;return S.concat({name:A,in:M,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:ee,examples:Dt(gt(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(E,l.has(A)))||[]))})},[])},Ut={nullable:Dn,union:qn,bigint:Jn,intersection:Fn,tuple:Vn,pipe:Yn,[ye]:Un,[ge]:_n,[ie]:Kn,[B]:Qn,[fe]:Hn},es=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(ho(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,We(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},_t=(e,{ctx:t,rules:r=Ut})=>{let{$defs:o={},properties:n={}}=yo.toJSONSchema(yo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=W(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return es(E(n.subject)?n.subject:{},o,t)},Ro=(e,t)=>{if(ho(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Ro(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},Oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${jt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=We(_t(r,{rules:{...c,...Ut},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x=[];gt(g)&&g.examples&&(x.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,ne(m)):g,examples:Dt(x)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},ts=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},rs=({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},os=({name:e})=>({type:"apiKey",in:"header",name:e}),ns=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ss=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),is=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),To=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ts(o):o.type==="input"?rs(o,t):o.type==="header"?os(o):o.type==="cookie"?ns(o):o.type==="openid"?ss(o):is(o);return e.map(o=>o.map(r))},Po=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),wo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>_t(e,{rules:{...t,...Ut},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Eo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=Ro(We(o),p),g=[];gt(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let x={schema:i==="components"?s(r,c,ne(d)):c,examples:Dt(g.length?g:ze(o).examples?.filter(v=>E(v)&&!Array.isArray(v)).map(l.omit(p))||[])},y={description:d,content:{[n]:x}};return(m||n===w.raw)&&(y.required=!0),y},ko=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)},[]),Jt=e=>e.length<=go?e:e.slice(0,go-1)+"\u2026",ht=e=>e.length?e.slice():void 0;var Vt=class extends as{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||ne(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});Le({routing:t,onEndpoint:(y,v,k)=>{let z={path:v,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:S,shortDescription:A,scopes:C,inputSchema:M}=y,N=A?Jt(A):m&&S?Jt(S):void 0,ee=r.inputSources?.[k]||Ct[k],Pe=this.#n(v,k,y.getOperationId(k)),et=wo({...z,schema:M}),ce=uo(y.security),tt=So({...z,inputSources:ee,isHeader:c,security:ce,request:et,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Pe})}),rt={};for(let te of Ce){let de=y.getResponses(te);for(let{mimeTypes:nt,schema:It,statusCodes:fr}of de)for(let vt of fr)rt[vt]=Oo({...z,variant:te,schema:It,mimeTypes:nt,statusCode:vt,hasMultipleStatusCodes:de.length>1||fr.length>1,description:i?.[`${te}Response`]?.call(null,{method:k,path:v,operationId:Pe,statusCode:vt})})}let ot=ee.includes("body")?Eo({...z,request:et,paramNames:Io.pluck("name",tt),schema:M,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Pe})}):void 0,Et=Po(To(ce,ee),C,te=>{let de=this.#s(te);return this.addSecurityScheme(de,te),de}),kt={operationId:Pe,summary:N,description:S,deprecated:y.isDeprecated||void 0,tags:ht(y.tags),parameters:ht(tt),requestBody:ot,security:ht(Et),responses:rt};this.addPath(bo(v),{[k]:kt})}}),d&&(this.rootDoc.tags=ko(d))}};import{createRequest as ps,createResponse as cs}from"node-mocks-http";var ds=e=>ps({...e,headers:{"content-type":w.json,...e?.headers}}),ms=e=>cs(e),ls=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Lr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},vo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ds(e),s=ms({req:n,...t});s.req=t?.req||n,n.res=s;let i=ls(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},us=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=vo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},fs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=Se}}=vo(r),d=it(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:re(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as zo from"ramda";import wt from"typescript";import{z as Bs}from"zod";import*as No from"ramda";import G from"typescript";import*as _ from"ramda";import u from"typescript";var a=u.factory,xt=[a.createModifier(u.SyntaxKind.ExportKeyword)],ys=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Gt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Wt=(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)},gs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yt=e=>typeof e=="string"&&gs.test(e)?a.createIdentifier(e):P(e),bt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),St=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),$e=e=>Object.entries(e).map(([t,r])=>St(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Qt=(e,t=[])=>a.createConstructorDeclaration(Ye.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&_.map(f,t)):e,Xt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),J=e=>{let t=new Map;for(let r of e)t.set(xs(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Yt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?J([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=_.reject(_.isNil,[o?"@deprecated":void 0,n]);return p.length?Gt(i,p.join(" ")):i},er=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),tr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&xt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),rr=(e,t)=>V(e,J(_.map($,t)),{expose:!0}),V=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?xt:void 0,e,n&&ir(n),t);return o?Gt(s,o):s},Ao=(e,t)=>a.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),or=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&ir(o),t,n,a.createBlock(r)),nr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(xt,e,r&&ir(r),void 0,t),sr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Rt=e=>f(Promise.name,[e]),Ot=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?xt:void 0,e,void 0,void 0,t);return o?Gt(n,o):n},ir=e=>(Array.isArray(e)?e.map(t=>_.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Te=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?ys:void 0,void 0,Array.isArray(e)?_.map(St,e):$e(e),void 0,void 0,t),O=e=>e,Qe=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),T=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Me=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Tt=(e,t)=>f("Extract",[e,t]),ar=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),H=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Co=e=>J([f(e),Rt(e)]),pr=(e,t)=>a.createFunctionTypeNode(void 0,$e(e),f(t)),P=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),$=e=>a.createLiteralTypeNode(P(e)),hs=[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],xs=e=>hs.includes(e.kind);var Pt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=rr("Method",Kt);someOfType=V("SomeOf",H("T",sr("T")),{params:["T"]});requestType=V("Request",sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>rr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ot(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Yt(t),a.createArrayLiteralExpression(No.map(P,r))))),{expose:!0});makeImplementationType=()=>V(this.#e.implementationType,pr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Rt(G.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:G.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Te({[this.#e.requestParameter.text]:G.SyntaxKind.StringKeyword},a.createAsExpression(T(this.#e.requestParameter,O("split"))(a.createRegularExpressionLiteral("/ (.+)/"),P(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,Te({[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt},a.createBlock([j(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],G.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([ar(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(bt(":",[this.#e.keyParameter]),Te([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>or(this.#e.provideMethod,$e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:H(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(tr(this.#e.methodParameter,this.#e.pathParameter),T(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(T(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(T(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Rt(H(this.interfaces.response,"K"))});makeClientClass=t=>nr(t,[Qt([St(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>bt("?",[Me(URLSearchParams.name,t)]);#o=()=>Me(URL.name,bt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(O("method"),T(this.#e.methodParameter,O("toUpperCase"))()),r=a.createPropertyAssignment(O("headers"),Qe(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Qe(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=j(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=j(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(G.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=j(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,Qe(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return j(this.#e.defaultImplementationConst,Te([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>Qt($e({request:"K",params:H(this.interfaces.input,"K")}),[j(tr(this.#e.pathParameter,this.#e.restConst),T(this.#e.substituteFn)(a.createElementAccessExpression(T(this.#e.parseRequestFn)(this.#e.requestParameter),P(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),ar(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Oe(O("event"),t)]);#i=()=>or(this.#e.onMethod,$e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:pr({[this.#e.dataParameter.text]:H(Tt("R",er(this.#s("E"))),$(O("data")))},Co(G.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Te([this.#e.msgParameter],T(this.#e.handlerParameter)(T(JSON[Symbol.toStringTag],O("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),O("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:H("R",$(O("event")))}});makeSubscriptionClass=t=>nr(t,[Ao(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Tt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(G.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Tt(H(this.interfaces.positive,"K"),er(this.#s(G.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Me(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Me(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Te(["time"],a.createBlock([])))]};import*as I from"ramda";import h from"typescript";import{globalRegistry as bs}from"zod";var cr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=W(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>cr(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:F}=h,Ss={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},dr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Rs=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(h.SyntaxKind.UndefinedKeyword):$(r));return t.length===1?t[0]:J(t)},Os=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(oe(p)){r.unshift(p);break}i+=p??""}return i},n=F.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?F.createTemplateMiddle:F.createTemplateTail;s.push(F.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?F.createTemplateLiteralType(n,s):$(n.text)},Ts=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=bs.get(p)||{};return Oe(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return F.createTypeLiteralNode(s)};return Pr(e,{io:t?"output":"input"})?o(e,n):n()},Ps=({_zod:{def:e}},{next:t})=>F.createArrayTypeNode(t(e.element)),ws=({_zod:{def:e}})=>J(Object.values(e.entries).map($)),Es=({_zod:{def:e}},{next:t})=>J(e.options.map(t)),ks=e=>Ss?.[e.kind],Is=({_zod:{def:e}},{next:t})=>J([t(e.innerType),$(null)]),vs=({_zod:{def:e}},{next:t})=>F.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:F.createRestTypeNode(t(e.rest)))),As=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Cs=I.tryCatch(e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(dr.name,...o))return!1;if(I.both(I.eqBy(dr.type),I.eqBy(dr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Ns=({_zod:{def:e}},{next:t})=>Cs([e.left,e.right].map(t)),q=e=>()=>f(e),Xe=({_zod:{def:e}},{next:t})=>t(e.innerType),jo=e=>f(e?h.SyntaxKind.UnknownKeyword:h.SyntaxKind.AnyKeyword),js=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!oe(o,"transform"))return t(o);let s=t(n),i=at(o,ks(s)),p={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return f(i&&p[i]||jo(r))},zs=()=>$(null),Ls=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),$s=()=>f("Buffer"),Ms=(e,{next:t})=>t(e._zod.def.shape.raw),Zs={string:q(h.SyntaxKind.StringKeyword),number:q(h.SyntaxKind.NumberKeyword),bigint:q(h.SyntaxKind.BigIntKeyword),boolean:q(h.SyntaxKind.BooleanKeyword),any:q(h.SyntaxKind.AnyKeyword),undefined:q(h.SyntaxKind.UndefinedKeyword),[ye]:q(h.SyntaxKind.StringKeyword),[ge]:q(h.SyntaxKind.StringKeyword),never:q(h.SyntaxKind.NeverKeyword),void:q(h.SyntaxKind.UndefinedKeyword),unknown:q(h.SyntaxKind.UnknownKeyword),null:zs,array:Ps,tuple:vs,record:As,object:Ts,literal:Rs,template_literal:Os,intersection:Ns,union:Es,default:Xe,enum:ws,optional:Xe,nonoptional:Xe,nullable:Is,catch:Xe,pipe:js,lazy:Ls,readonly:Xe,[fe]:$s,[B]:Ms},mr=(e,{brandHandling:t,ctx:r})=>cr(e,{rules:{...t,...Zs},onMissing:({},{isResponse:o})=>jo(o),ctx:r});var lr=class extends Pt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=$(null);this.#t.set(t,V(o,n)),this.#t.set(t,V(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=Bs.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};Le({routing:t,onEndpoint:(x,y,v)=>{let k=ne.bind(null,v,y),{isDeprecated:z,inputSchema:S,tags:A}=x,C=`${v} ${y}`,M=V(k("input"),mr(S,c),{comment:C});this.#e.push(M);let N=Ce.reduce((et,ce)=>{let tt=x.getResponses(ce),rt=zo.chain(([Et,{schema:kt,mimeTypes:te,statusCodes:de}])=>{let nt=V(k(ce,"variant",`${Et+1}`),mr(te?kt:p,m),{comment:C});return this.#e.push(nt),de.map(It=>Oe(It,nt.name))},Array.from(tt.entries())),ot=Ot(k(ce,"response","variants"),rt,{comment:C});return this.#e.push(ot),Object.assign(et,{[ce]:ot})},{});this.paths.add(y);let ee=$(C),Pe={input:f(M.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:J([H(this.interfaces.positive,ee),H(this.interfaces.negative,ee)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:z,store:Pe}),this.tags.set(C,A)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Wt(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&wt.addSyntheticLeadingComment(wt.addSyntheticLeadingComment(a.createEmptyStatement(),wt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),wt.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>Wt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "25.0.0-beta.2",
3
+ "version": "25.0.0-beta.3",
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": {