express-zod-api 24.0.0-beta.1 → 24.0.0-beta.2

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,9 +13,13 @@
13
13
  - the temporary nature of this transition;
14
14
  - the advantages of Zod 4 that provide opportunities to simplifications and corrections of known issues.
15
15
  - `IOSchema` type had to be simplified down to a schema resulting to an `object`, but not an `array`;
16
- - Despite supporting examples by the new Zod method `.meta()`, users should still use `.example()` to set them;
17
16
  - Refer to [Migration guide on Zod 4](https://v4.zod.dev/v4/changelog) for adjusting your schemas;
18
- - Generating Documentation is partially delegated to Zod 4 `z.toJSONSchema()`:
17
+ - Changes to `ZodType::example()` (Zod plugin method):
18
+ - Now acts as an alias for `ZodType::meta({ examples })`;
19
+ - The argument has to be the output type of the schema (used to be the opposite):
20
+ - This change is only breaking for transforming schemas;
21
+ - In order to specify an input example for a transforming schema the `.example()` method must be called before it;
22
+ - Generating Documentation is mostly delegated to Zod 4 `z.toJSONSchema()`:
19
23
  - The basic depiction of each schema is now natively performed by Zod 4;
20
24
  - Express Zod API implements some overrides and improvements to fit it into OpenAPI 3.1 that extends JSON Schema;
21
25
  - The `numericRange` option removed from `Documentation` class constructor argument;
@@ -26,6 +30,7 @@
26
30
  - Use `.or(z.undefined())` to add `undefined` to the type of the object property;
27
31
  - Reasoning: https://x.com/colinhacks/status/1919292504861491252;
28
32
  - `z.any()` and `z.unknown()` are not optional, details: https://v4.zod.dev/v4/changelog#changes-zunknown-optionality.
33
+ - The `getExamples()` public helper removed — use `.meta()?.examples` instead;
29
34
  - Consider the automated migration using the built-in ESLint rule.
30
35
 
31
36
  ```js
@@ -44,6 +49,14 @@ export default [
44
49
  + import { z } from "zod/v4";
45
50
  ```
46
51
 
52
+ ```diff
53
+ z.string()
54
+ + .example("123")
55
+ .transform(Number)
56
+ - .example("123")
57
+ + .example(123)
58
+ ```
59
+
47
60
  ## Version 23
48
61
 
49
62
  ### v23.5.0
package/README.md CHANGED
@@ -1271,7 +1271,11 @@ const exampleEndpoint = defaultEndpointsFactory.build({
1271
1271
  shortDescription: "Retrieves the user.", // <—— this becomes the summary line
1272
1272
  description: "The detailed explanaition on what this endpoint does.",
1273
1273
  input: z.object({
1274
- id: z.number().describe("the ID of the user").example(123),
1274
+ id: z
1275
+ .string()
1276
+ .example("123") // input examples should be set before transformations
1277
+ .transform(Number)
1278
+ .describe("the ID of the user"),
1275
1279
  }),
1276
1280
  // ..., similarly for output and middlewares
1277
1281
  });
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var yn=Object.create;var mt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Sn=(e,t)=>{for(var r in t)mt(e,r,{get:t[r],enumerable:!0})},Ar=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hn(t))!xn.call(e,n)&&n!==r&&mt(e,n,{get:()=>t[n],enumerable:!(o=gn(t,n))||o.enumerable});return e};var y=(e,t,r)=>(r=e!=null?yn(bn(e)):{},Ar(t||!e||!e.__esModule?mt(r,"default",{value:e,enumerable:!0}):r,e)),Rn=e=>Ar(mt({},"__esModule",{value:!0}),e);var _s={};Sn(_s,{BuiltinLogger:()=>qe,DependsOnMethod:()=>Be,Documentation:()=>wt,DocumentationError:()=>J,EndpointsFactory:()=>ge,EventStreamFactory:()=>Mt,InputValidationError:()=>G,Integration:()=>jt,Middleware:()=>F,MissingPeerError:()=>ze,OutputValidationError:()=>se,ResultHandler:()=>fe,RoutingError:()=>ne,ServeStatic:()=>Fe,arrayEndpointsFactory:()=>Wr,arrayResultHandler:()=>Rt,attachRouting:()=>jo,createConfig:()=>Nr,createServer:()=>Mo,defaultEndpointsFactory:()=>Gr,defaultResultHandler:()=>ye,ensureHttpError:()=>Ee,ez:()=>fn,getExamples:()=>Re,getMessageFromError:()=>ee,testEndpoint:()=>rn,testMiddleware:()=>on});module.exports=Rn(_s);var Z=y(require("ramda"),1),W=require("zod/v4");var M=y(require("ramda"),1),ae=require("zod/v4");var v={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var ne=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},J=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.`}},Ge=class extends Error{name="IOSchemaError"},lt=class extends Ge{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},se=class extends Ge{constructor(r){super(ee(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Ge{constructor(r){super(ee(r),{cause:r});this.cause=r}name="InputValidationError"},ie=class extends Error{constructor(r,o){super(ee(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},ze=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Kt=/:([A-Za-z0-9_]+)/g,ut=e=>e.match(Kt)?.map(t=>t.slice(1))||[],On=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(v.upload);return"files"in e&&r},qt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Tn=["body","query","params"],Bt=e=>e.method.toLowerCase(),ft=(e,t={})=>{let r=Bt(e);return r==="options"?{}:(t[r]||qt[r]||Tn).filter(o=>o==="files"?On(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},pe=e=>e instanceof Error?e:e instanceof ae.z.ZodError?new Error(ee(e),{cause:e}):new Error(String(e)),ee=e=>e instanceof ae.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof se?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,ce=(e,t)=>e._zod.def.type===t,Pn=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=ae.globalRegistry.get(o)?.[T]||{};return Oe(t,n.map(M.objOf(r)),([s,i])=>({...s,...i}))},[]),Re=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=ae.globalRegistry.get(e)?.[T]?.examples||[];if(!n.length&&o&&ce(e,"object")&&(n=Pn(e)),!r&&t==="original")return n;let s=[];for(let i of n){let p=ae.z.safeParse(e,i);p.success&&s.push(t==="parsed"?p.data:i)}return s},Oe=(e,t,r)=>e.length&&t.length?M.xprod(e,t).map(r):e.concat(t),Ft=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),de=(...e)=>{let t=M.chain(o=>o.split(/[^A-Z0-9]/gi),e);return M.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Ft).join("")},yt=M.tryCatch((e,t)=>typeof ae.z.parse(e,t),M.always(void 0)),gt=({_zod:{optin:e,optout:t}},{isResponse:r})=>(r?t:e)==="optional",L=e=>typeof e=="object"&&e!==null,Te=M.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var Cr=y(require("ramda"),1),T=Symbol.for("express-zod-api"),Ir=(e,t)=>{let r=e.meta(),o=t.meta();if(!r?.[T])return t;let n=Oe(o?.[T]?.examples||[],r[T].examples||[],([s,i])=>typeof s=="object"&&typeof i=="object"&&s&&i?Cr.mergeDeepRight(s,i):i);return t.meta({...o,[T]:{...o?.[T],examples:n}})},te=e=>{let{brand:t}=e._zod.bag;if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var wn=W.z.core.$constructor("$EZBrandCheck",(e,t)=>{W.z.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),En=function(e){let{[T]:t,...r}=this.meta()||{},o=t?.examples.slice()||[];return o.push(e),this.meta({...r,[T]:{...t,examples:o}})},vn=function(){return this.meta({...this.meta(),deprecated:!0})},kn=function(e){let{[T]:t={examples:[]},...r}=this.meta()||{};return this.meta({...r,[T]:{...t,defaultLabel:e}})},An=function(e){return this.check(new wn({brand:e,check:"$EZBrandCheck"}))},Cn=function(e){let t=typeof e=="function"?e:Z.pipe(Z.toPairs,Z.map(([s,i])=>Z.pair(e[String(s)]||s,i)),Z.fromPairs),r=t(Z.map(Z.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof W.z.ZodUnknown?W.z.looseObject:W.z.object)(r);return this.transform(t).pipe(n)};if(!(T in globalThis)){globalThis[T]=!0;for(let e of Object.keys(W.z)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=W.z[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return En.bind(this)}},deprecated:{get(){return vn.bind(this)}},brand:{set(){},get(){return An.bind(this)}}})}Object.defineProperty(W.z.ZodDefault.prototype,"label",{get(){return kn.bind(this)}}),Object.defineProperty(W.z.ZodObject.prototype,"remap",{get(){return Cn.bind(this)}})}function Nr(e){return e}var Qt=require("zod/v4");var Ze=y(require("ramda"),1),Wt=require("zod/v4");var ue=y(require("ramda"),1),Ut=require("zod/v4");var je=require("zod/v4"),Pe=Symbol("DateIn"),zr=()=>je.z.union([je.z.iso.date(),je.z.iso.datetime(),je.z.iso.datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.z.date()).brand(Pe);var jr=require("zod/v4"),we=Symbol("DateOut"),Mr=()=>jr.z.date().transform(e=>e.toISOString()).brand(we);var Dt=require("zod/v4"),We=Symbol("Form"),Lr=e=>(e instanceof Dt.z.ZodObject?e:Dt.z.object(e)).brand(We);var Zr=require("zod/v4"),me=Symbol("Upload"),$r=()=>Zr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(me);var Kr=require("zod/v4");var Ye=require("zod/v4"),le=Symbol("File"),Hr=Ye.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),In={buffer:()=>Hr.brand(le),string:()=>Ye.z.string().brand(le),binary:()=>Hr.or(Ye.z.string()).brand(le),base64:()=>Ye.z.base64().brand(le)};function ht(e){return In[e||"string"]()}var B=Symbol("Raw"),qr=Kr.z.object({raw:ht("buffer")}),Nn=e=>qr.extend(e).brand(B);function Br(e){return e?Nn(e):qr.brand(B)}var Fr=(e,{io:t,condition:r})=>ue.tryCatch(()=>{Ut.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new lt(o)}})},o=>o.cause)(),Dr=(e,{io:t})=>{let o=[Ut.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(ue.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ue.values(n))}ue.is(Array,n)&&o.push(...ue.values(n))}return!1},Ur=e=>Fr(e,{condition:t=>{let r=te(t);return typeof r=="symbol"&&[me,B,We].includes(r)},io:"input"}),zn=["nan","symbol","map","set","bigint","void","promise","never"],Vt=(e,t)=>Fr(e,{io:t,condition:r=>{let o=te(r),{type:n}=r._zod.def;return!!(zn.includes(n)||t==="input"&&(n==="date"||o===we)||t==="output"&&(o===Pe||o===B||o===me))}});var bt=y(require("http-errors"),1);var Qe=y(require("http-errors"),1),Vr=require("zod/v4");var _t=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Vr.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ie(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}))},Xe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>(0,Qe.isHttpError)(e)?e:(0,Qe.default)(e instanceof G?400:500,ee(e),{cause:e.cause||e}),ve=e=>Te()&&!e.expose?(0,Qe.default)(e.statusCode).message:e.message;var xt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ve((0,bt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:(0,bt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Jt=require("zod/v4");var Gt=class{},F=class extends Gt{#e;#t;#r;constructor({input:t=Jt.z.object({}),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.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Jt.z.ZodError?new G(o):o}}},Me=class extends F{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 Le=class{nest(t){return Object.assign(t,{"":this})}};var et=class extends Le{},St=class e extends et{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}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.#e.outputSchema}get requestType(){let t=Ur(this.#e.inputSchema);if(t){let r=te(t);if(r===me)return"upload";if(r===B)return"raw";if(r===We)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=Ze.pluck("security",this.#e.middlewares||[]);return Ze.reject(Ze.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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Wt.z.ZodError?new se(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Me))&&(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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Wt.z.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){xt({...t,error:new ie(pe(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Bt(t),i={},p={output:{},error:null},d=ft(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:pe(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};var _r=y(require("ramda"),1);var Jr=(e,t)=>{let r=_r.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ir(s,n),o)};var H=require("zod/v4");var $e={positive:200,negative:400},He=Object.keys($e);var Yt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends Yt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return _t(this.#e,{variant:"positive",args:[t],statusCodes:[$e.positive],mimeTypes:[v.json]})}getNegativeResponse(){return _t(this.#t,{variant:"negative",args:[],statusCodes:[$e.negative],mimeTypes:[v.json]})}},ye=new fe({positive:e=>{let t=Re({schema:e,pullProps:!0}),r=H.z.object({status:H.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:H.z.object({status:H.z.literal("error"),error:H.z.object({message:H.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Ee(e);return Xe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ve(i)}})}n.status($e.positive).json({status:"success",data:r})}}),Rt=new fe({positive:e=>{let t=Re({schema:e}),r=e instanceof H.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof H.z.ZodArray?e.shape.items:H.z.array(H.z.any());return t.reduce((o,n)=>L(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:H.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);return Xe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ve(i))}if("items"in t&&Array.isArray(t.items))return void e.status($e.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ge=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Me(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Qt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,h=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new St({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:g,methods:m,getOperationId:h,inputSchema:Jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Qt.z.object({}),handler:async o=>(await t(o),{})})}},Gr=new ge(ye),Wr=new ge(Rt);var ro=y(require("ansis"),1),oo=require("node:util"),er=require("node:perf_hooks");var Y=require("ansis"),Yr=y(require("ramda"),1);var Xt={debug:Y.blue,info:Y.green,warn:(0,Y.hex)("#FFA500"),error:Y.red,ctx:Y.cyanBright},Ot={debug:10,info:20,warn:30,error:40},Qr=e=>L(e)&&Object.keys(Ot).some(t=>t in e),Xr=e=>e in Ot,eo=(e,t)=>Ot[e]<Ot[t],jn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ke=Yr.memoizeWith((e,t)=>`${e}${t}`,jn),to=e=>e<1e-6?Ke("nanosecond",3).format(e/1e-6):e<.001?Ke("nanosecond").format(e/1e-6):e<1?Ke("microsecond").format(e/.001):e<1e3?Ke("millisecond").format(e):e<6e4?Ke("second",2).format(e/1e3):Ke("minute",2).format(e/6e4);var qe=class e{config;constructor({color:t=ro.default.isSupported(),level:r=Te()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,oo.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||eo(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Xt.ctx(s):s),d.push(p?`${Xt[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=er.performance.now();return()=>{let o=er.performance.now()-r,{message:n,severity:s="debug",formatter:i=to}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var no=y(require("ramda"),1);var Be=class e extends Le{#e;constructor(t){super(),this.#e=t}get entries(){let t=no.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)}};var so=y(require("express"),1),Fe=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,so.default.static(...this.#e))}};var tt=y(require("express"),1),Io=y(require("node:http"),1),No=y(require("node:https"),1);var De=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new ze(e)};var mo=y(require("http-errors"),1);var tr=require("zod/v4");var R=y(require("ramda"),1);var Mn=e=>e.type==="object",Ln=R.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return R.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),Zn=R.pipe(Object.keys,R.without(["type","properties","required","examples","description"]),R.isEmpty),io=R.pair(!0),Ue=(e,t="coerce")=>{let r=[R.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"&&Zn(p)))throw new Error("Can not merge");return R.pair(s,p)})),i.anyOf&&r.push(...R.map(io,i.anyOf)),i.oneOf&&r.push(...R.map(io,i.oneOf)),!!Mn(i)&&(i.properties&&(o.properties=(t==="throw"?Ln:R.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),i.examples?.length&&(s?o.examples=R.concat(o.examples||[],i.examples):o.examples=Oe(o.examples?.filter(L)||[],i.examples.filter(L),([p,d])=>R.mergeDeepRight(p,d))),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};var Tt=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=[tr.z.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=Vt(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 He)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(v.json))continue;let i=Vt(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=ut(t);if(s.length===0)return;let i=n?.flat||Ue(tr.z.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 rr=["get","post","put","delete","patch"],ao=e=>rr.includes(e);var $n=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&ao(t)?[r,t]:[e]},Hn=e=>e.trim().split("/").filter(Boolean).join("/"),po=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=$n(r);return[[t||""].concat(Hn(n)||[]).join("/"),o,s]}),Kn=(e,t)=>{throw new ne("Route with explicit method can only be assigned with Endpoint",e,t)},co=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ne(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},or=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ne("Route has a duplicate",e,t);r.add(o)},Ve=({routing:e,onEndpoint:t,onStatic:r})=>{let o=po(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof et)if(p)or(p,s,n),co(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)or(c,s,n),t(i,s,c)}else if(p&&Kn(p,s),i instanceof Fe)r&&i.apply(s,r);else if(i instanceof Be)for(let[d,c]of i.entries){let{methods:m}=c;or(d,s,n),co(d,s,m),t(c,s,d)}else o.unshift(...po(i,s))}};var lo=y(require("ramda"),1),uo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),qn=e=>({method:t},r,o)=>{let n=uo(e);r.set({Allow:n});let s=(0,mo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Bn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":uo(e),"Access-Control-Allow-Headers":"content-type"}),nr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Te()?void 0:new Tt(t()),i=new Map;Ve({routing:o,onEndpoint:(c,m,h)=>{Te()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let b=n?.[c.requestType]||[],g=lo.pair(b,c);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(h,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let h=Array.from(m.keys());for(let[b,[g,A]]of m){let C=async($,O)=>{let I=t($);if(r.cors){let N=Bn(h),_=typeof r.cors=="function"?await r.cors({request:$,endpoint:A,logger:I,defaultHeaders:N}):N;O.set(_)}return A.execute({request:$,response:O,logger:I,config:r})};e[b](c,...g,C)}r.wrongMethodBehavior!==404&&d.set(c,qn(h))}for(let[c,m]of d)e.all(c,m)};var Ro=y(require("http-errors"),1);var xo=require("node:timers/promises");var fo=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",yo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",go=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ho=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),bo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var So=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(fo(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",ho);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(go(c)||yo(c))&&i(c);for await(let c of(0,xo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(bo))};return{sockets:n,shutdown:()=>o??=d()}};var Oo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:pe(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),To=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Ro.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){xt({response:o,logger:s,error:new ie(pe(i),n)})}},Fn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Dn=e=>({log:e.debug.bind(e)}),Po=async({getLogger:e,config:t})=>{let r=await De("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:Dn(m)})(p,d,c)}),o&&i.push(Fn(o)),i},wo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Eo=({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[T]={logger:i}),s()},vo=e=>t=>t?.res?.locals[T]?.logger||e,ko=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),Ao=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=So(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let i of o)process.on(i,s)};var K=require("ansis"),Co=e=>{if(e.columns<132)return;let t=(0,K.italic)("Proudly supports transgender community.".padStart(109)),r=(0,K.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,K.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,K.italic)("for Ashley".padEnd(20)),s=(0,K.hex)("#F5A9B8"),i=(0,K.hex)("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(K.whiteBright,5,7).fill(s,7,9).fill(i,9,12).fill(K.gray,12,13),d=`
1
+ "use strict";var yn=Object.create;var dt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Sn=(e,t)=>{for(var r in t)dt(e,r,{get:t[r],enumerable:!0})},Ar=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hn(t))!xn.call(e,n)&&n!==r&&dt(e,n,{get:()=>t[n],enumerable:!(o=gn(t,n))||o.enumerable});return e};var y=(e,t,r)=>(r=e!=null?yn(bn(e)):{},Ar(t||!e||!e.__esModule?dt(r,"default",{value:e,enumerable:!0}):r,e)),Rn=e=>Ar(dt({},"__esModule",{value:!0}),e);var Us={};Sn(Us,{BuiltinLogger:()=>Ke,DependsOnMethod:()=>qe,Documentation:()=>wt,DocumentationError:()=>J,EndpointsFactory:()=>fe,EventStreamFactory:()=>Lt,InputValidationError:()=>G,Integration:()=>jt,Middleware:()=>F,MissingPeerError:()=>Ce,OutputValidationError:()=>se,ResultHandler:()=>le,RoutingError:()=>ne,ServeStatic:()=>Be,arrayEndpointsFactory:()=>Wr,arrayResultHandler:()=>Rt,attachRouting:()=>jo,createConfig:()=>Nr,createServer:()=>Lo,defaultEndpointsFactory:()=>Gr,defaultResultHandler:()=>ue,ensureHttpError:()=>Te,ez:()=>fn,getMessageFromError:()=>ee,testEndpoint:()=>rn,testMiddleware:()=>on});module.exports=Rn(Us);var Z=y(require("ramda"),1),W=require("zod/v4");var L=y(require("ramda"),1),Ie=require("zod/v4");var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var ne=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},J=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.`}},Je=class extends Error{name="IOSchemaError"},mt=class extends Je{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},se=class extends Je{constructor(r){super(ee(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Je{constructor(r){super(ee(r),{cause:r});this.cause=r}name="InputValidationError"},ie=class extends Error{constructor(r,o){super(ee(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ce=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Kt=/:([A-Za-z0-9_]+)/g,lt=e=>e.match(Kt)?.map(t=>t.slice(1))||[],On=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},qt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Tn=["body","query","params"],Bt=e=>e.method.toLowerCase(),ut=(e,t={})=>{let r=Bt(e);return r==="options"?{}:(t[r]||qt[r]||Tn).filter(o=>o==="files"?On(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},ae=e=>e instanceof Error?e:e instanceof Ie.z.ZodError?new Error(ee(e),{cause:e}):new Error(String(e)),ee=e=>e instanceof Ie.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof se?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,q=(e,t)=>e._zod.def.type===t,ft=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=Ie.globalRegistry.get(o)||{};return xe(t,n.map(L.objOf(r)),([s,i])=>({...s,...i}))},[]),xe=(e,t,r)=>e.length&&t.length?L.xprod(e,t).map(r):e.concat(t),Ft=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),pe=(...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(Ft).join("")},yt=L.tryCatch((e,t)=>typeof Ie.z.parse(e,t),L.always(void 0)),gt=({_zod:{optin:e,optout:t}},{isResponse:r})=>(r?t:e)==="optional",M=e=>typeof e=="object"&&e!==null,Se=L.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var Cr=y(require("ramda"),1),Ne=Symbol.for("express-zod-api"),Ir=(e,t)=>{let{examples:r=q(e,"object")?ft(e):void 0}=e.meta()||{};if(!r?.length)return t;let{examples:o=[]}=t.meta()||{},n=xe(o,r,([s,i])=>typeof s=="object"&&typeof i=="object"&&s&&i?Cr.mergeDeepRight(s,i):i);return t.meta({examples:n})},te=e=>{let{brand:t}=e._zod.bag;if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Pn=W.z.core.$constructor("$EZBrandCheck",(e,t)=>{W.z.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),wn=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},En=function(){return this.meta({deprecated:!0})},vn=function(e){return this.meta({default:e})},kn=function(e){return this.check(new Pn({brand:e,check:"$EZBrandCheck"}))},An=function(e){let t=typeof e=="function"?e:Z.pipe(Z.toPairs,Z.map(([s,i])=>Z.pair(e[String(s)]||s,i)),Z.fromPairs),r=t(Z.map(Z.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof W.z.ZodUnknown?W.z.looseObject:W.z.object)(r);return this.transform(t).pipe(n)};if(!(Ne in globalThis)){globalThis[Ne]=!0;for(let e of Object.keys(W.z)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=W.z[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return wn.bind(this)}},deprecated:{get(){return En.bind(this)}},brand:{set(){},get(){return kn.bind(this)}}})}Object.defineProperty(W.z.ZodDefault.prototype,"label",{get(){return vn.bind(this)}}),Object.defineProperty(W.z.ZodObject.prototype,"remap",{get(){return An.bind(this)}})}function Nr(e){return e}var Qt=require("zod/v4");var Me=y(require("ramda"),1),Wt=require("zod/v4");var me=y(require("ramda"),1),Dt=require("zod/v4");var ze=require("zod/v4"),Re=Symbol("DateIn"),zr=()=>ze.z.union([ze.z.iso.date(),ze.z.iso.datetime(),ze.z.iso.datetime({local:!0})]).transform(t=>new Date(t)).pipe(ze.z.date()).brand(Re);var jr=require("zod/v4"),Oe=Symbol("DateOut"),Lr=()=>jr.z.date().transform(e=>e.toISOString()).brand(Oe);var Ut=require("zod/v4"),Ge=Symbol("Form"),Mr=e=>(e instanceof Ut.z.ZodObject?e:Ut.z.object(e)).brand(Ge);var Zr=require("zod/v4"),ce=Symbol("Upload"),$r=()=>Zr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ce);var Kr=require("zod/v4");var We=require("zod/v4"),de=Symbol("File"),Hr=We.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Cn={buffer:()=>Hr.brand(de),string:()=>We.z.string().brand(de),binary:()=>Hr.or(We.z.string()).brand(de),base64:()=>We.z.base64().brand(de)};function ht(e){return Cn[e||"string"]()}var B=Symbol("Raw"),qr=Kr.z.object({raw:ht("buffer")}),In=e=>qr.extend(e).brand(B);function Br(e){return e?In(e):qr.brand(B)}var Fr=(e,{io:t,condition:r})=>me.tryCatch(()=>{Dt.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new mt(o)}})},o=>o.cause)(),Ur=(e,{io:t})=>{let o=[Dt.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(me.is(Object,n)){if(n.$ref==="#")return!0;o.push(...me.values(n))}me.is(Array,n)&&o.push(...me.values(n))}return!1},Dr=e=>Fr(e,{condition:t=>{let r=te(t);return typeof r=="symbol"&&[ce,B,Ge].includes(r)},io:"input"}),Nn=["nan","symbol","map","set","bigint","void","promise","never"],_t=(e,t)=>Fr(e,{io:t,condition:r=>{let o=te(r),{type:n}=r._zod.def;return!!(Nn.includes(n)||t==="input"&&(n==="date"||o===Oe)||t==="output"&&(o===Re||o===B||o===ce))}});var bt=y(require("http-errors"),1);var Ye=y(require("http-errors"),1),_r=require("zod/v4");var Vt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof _r.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ie(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}))},Qe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Te=e=>(0,Ye.isHttpError)(e)?e:(0,Ye.default)(e instanceof G?400:500,ee(e),{cause:e.cause||e}),Pe=e=>Se()&&!e.expose?(0,Ye.default)(e.statusCode).message:e.message;var xt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Pe((0,bt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:(0,bt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Jt=require("zod/v4");var Gt=class{},F=class extends Gt{#e;#t;#r;constructor({input:t=Jt.z.object({}),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.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Jt.z.ZodError?new G(o):o}}},je=class extends F{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 Le=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends Le{},St=class e extends Xe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}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.#e.outputSchema}get requestType(){let t=Dr(this.#e.inputSchema);if(t){let r=te(t);if(r===ce)return"upload";if(r===B)return"raw";if(r===Ge)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=Me.pluck("security",this.#e.middlewares||[]);return Me.reject(Me.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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Wt.z.ZodError?new se(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof je))&&(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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Wt.z.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){xt({...t,error:new ie(ae(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Bt(t),i={},p={output:{},error:null},d=ut(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:ae(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};var Vr=y(require("ramda"),1);var Jr=(e,t)=>{let r=Vr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ir(s,n),o)};var C=require("zod/v4");var Ze={positive:200,negative:400},$e=Object.keys(Ze);var Yt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},le=class extends Yt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Vt(this.#e,{variant:"positive",args:[t],statusCodes:[Ze.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Vt(this.#t,{variant:"negative",args:[],statusCodes:[Ze.negative],mimeTypes:[E.json]})}},ue=new le({positive:e=>{let{examples:t=[]}=C.globalRegistry.get(e)||{};!t.length&&q(e,"object")&&t.push(...ft(e)),t.length&&!C.globalRegistry.has(e)&&C.globalRegistry.add(e,{examples:t});let r=C.z.object({status:C.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:C.z.object({status:C.z.literal("error"),error:C.z.object({message:C.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Te(e);return Qe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Pe(i)}})}n.status(Ze.positive).json({status:"success",data:r})}}),Rt=new le({positive:e=>{let{examples:t=[]}=C.globalRegistry.get(e)||{},r=e instanceof C.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof C.z.ZodArray?e.shape.items:C.z.array(C.z.any());return t.reduce((o,n)=>M(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:C.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Te(r);return Qe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Pe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ze.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var fe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new je(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Qt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,h=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new St({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:g,methods:m,getOperationId:h,inputSchema:Jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Qt.z.object({}),handler:async o=>(await t(o),{})})}},Gr=new fe(ue),Wr=new fe(Rt);var ro=y(require("ansis"),1),oo=require("node:util"),er=require("node:perf_hooks");var Y=require("ansis"),Yr=y(require("ramda"),1);var Xt={debug:Y.blue,info:Y.green,warn:(0,Y.hex)("#FFA500"),error:Y.red,ctx:Y.cyanBright},Ot={debug:10,info:20,warn:30,error:40},Qr=e=>M(e)&&Object.keys(Ot).some(t=>t in e),Xr=e=>e in Ot,eo=(e,t)=>Ot[e]<Ot[t],zn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),He=Yr.memoizeWith((e,t)=>`${e}${t}`,zn),to=e=>e<1e-6?He("nanosecond",3).format(e/1e-6):e<.001?He("nanosecond").format(e/1e-6):e<1?He("microsecond").format(e/.001):e<1e3?He("millisecond").format(e):e<6e4?He("second",2).format(e/1e3):He("minute",2).format(e/6e4);var Ke=class e{config;constructor({color:t=ro.default.isSupported(),level:r=Se()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,oo.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||eo(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Xt.ctx(s):s),d.push(p?`${Xt[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=er.performance.now();return()=>{let o=er.performance.now()-r,{message:n,severity:s="debug",formatter:i=to}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var no=y(require("ramda"),1);var qe=class e extends Le{#e;constructor(t){super(),this.#e=t}get entries(){let t=no.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)}};var so=y(require("express"),1),Be=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,so.default.static(...this.#e))}};var et=y(require("express"),1),Io=y(require("node:http"),1),No=y(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new Ce(e)};var mo=y(require("http-errors"),1);var tr=require("zod/v4");var R=y(require("ramda"),1);var jn=e=>e.type==="object",Ln=R.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return R.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),Mn=R.pipe(Object.keys,R.without(["type","properties","required","examples","description"]),R.isEmpty),io=R.pair(!0),Ue=(e,t="coerce")=>{let r=[R.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"&&Mn(p)))throw new Error("Can not merge");return R.pair(s,p)})),i.anyOf&&r.push(...R.map(io,i.anyOf)),i.oneOf&&r.push(...R.map(io,i.oneOf)),i.examples?.length&&(s?o.examples=R.concat(o.examples||[],i.examples):o.examples=xe(o.examples?.filter(M)||[],i.examples.filter(M),([p,d])=>R.mergeDeepRight(p,d))),!!jn(i)&&(i.properties&&(o.properties=(t==="throw"?Ln:R.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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};var Tt=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=[tr.z.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=_t(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 $e)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=_t(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=lt(t);if(s.length===0)return;let i=n?.flat||Ue(tr.z.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 rr=["get","post","put","delete","patch"],ao=e=>rr.includes(e);var Zn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&ao(t)?[r,t]:[e]},$n=e=>e.trim().split("/").filter(Boolean).join("/"),po=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Zn(r);return[[t||""].concat($n(n)||[]).join("/"),o,s]}),Hn=(e,t)=>{throw new ne("Route with explicit method can only be assigned with Endpoint",e,t)},co=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ne(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},or=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ne("Route has a duplicate",e,t);r.add(o)},De=({routing:e,onEndpoint:t,onStatic:r})=>{let o=po(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Xe)if(p)or(p,s,n),co(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)or(c,s,n),t(i,s,c)}else if(p&&Hn(p,s),i instanceof Be)r&&i.apply(s,r);else if(i instanceof qe)for(let[d,c]of i.entries){let{methods:m}=c;or(d,s,n),co(d,s,m),t(c,s,d)}else o.unshift(...po(i,s))}};var lo=y(require("ramda"),1),uo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),Kn=e=>({method:t},r,o)=>{let n=uo(e);r.set({Allow:n});let s=(0,mo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},qn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":uo(e),"Access-Control-Allow-Headers":"content-type"}),nr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Se()?void 0:new Tt(t()),i=new Map;De({routing:o,onEndpoint:(c,m,h)=>{Se()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let b=n?.[c.requestType]||[],g=lo.pair(b,c);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(h,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let h=Array.from(m.keys());for(let[b,[g,k]]of m){let A=async($,O)=>{let I=t($);if(r.cors){let N=qn(h),V=typeof r.cors=="function"?await r.cors({request:$,endpoint:k,logger:I,defaultHeaders:N}):N;O.set(V)}return k.execute({request:$,response:O,logger:I,config:r})};e[b](c,...g,A)}r.wrongMethodBehavior!==404&&d.set(c,Kn(h))}for(let[c,m]of d)e.all(c,m)};var Ro=y(require("http-errors"),1);var xo=require("node:timers/promises");var fo=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",yo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",go=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ho=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),bo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var So=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(fo(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",ho);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(go(c)||yo(c))&&i(c);for await(let c of(0,xo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(bo))};return{sockets:n,shutdown:()=>o??=d()}};var Oo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:ae(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),To=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Ro.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){xt({response:o,logger:s,error:new ie(ae(i),n)})}},Bn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Fn=e=>({log:e.debug.bind(e)}),Po=async({getLogger:e,config:t})=>{let r=await Fe("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:Fn(m)})(p,d,c)}),o&&i.push(Bn(o)),i},wo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Eo=({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[Ne]={logger:i}),s()},vo=e=>t=>t?.res?.locals[Ne]?.logger||e,ko=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),Ao=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=So(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let i of o)process.on(i,s)};var H=require("ansis"),Co=e=>{if(e.columns<132)return;let t=(0,H.italic)("Proudly supports transgender community.".padStart(109)),r=(0,H.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,H.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,H.italic)("for Ashley".padEnd(20)),s=(0,H.hex)("#F5A9B8"),i=(0,H.hex)("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(H.whiteBright,5,7).fill(s,7,9).fill(i,9,12).fill(H.gray,12,13),d=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
6
6
  888 d88P 888 d88P888 888 888 888
@@ -15,9 +15,9 @@ ${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 zo=e=>{e.startupLogo!==!1&&Co(process.stdout);let t=e.errorHandler||ye,r=Qr(e.logger)?e.logger:new qe(e.logger);r.debug("Running",{build:"v24.0.0-beta.1 (CJS)",env:process.env.NODE_ENV||"development"}),ko(r);let o=Eo({logger:r,config:e}),s={getLogger:vo(r),errorHandler:t},i=To(s),p=Oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},jo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return nr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Mo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=zo(e),p=(0,tt.default)().disable("x-powered-by").use(i);if(e.compression){let b=await De("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||tt.default.json()],raw:[e.rawParser||tt.default.raw(),wo],form:[e.formParser||tt.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};nr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,g)=>()=>b.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let b=Io.default.createServer(p);c.push(b),h.push(m(b,e.http.listen))}if(e.https){let b=No.default.createServer(e.https.options,p);c.push(b),h.push(m(b,e.https.listen))}return e.gracefulShutdown&&Ao({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(b=>b())}};var Xo=require("openapi3-ts/oas31"),en=y(require("ramda"),1);var S=y(require("ramda"),1);var Lo=e=>L(e)&&"or"in e,Zo=e=>L(e)&&"and"in e,sr=e=>!Zo(e)&&!Lo(e),$o=e=>{let t=S.filter(sr,e),r=S.chain(S.prop("and"),S.filter(Zo,e)),[o,n]=S.partition(sr,r),s=S.concat(t,o),i=S.filter(Lo,e);return S.map(S.prop("or"),S.concat(i,n)).reduce((d,c)=>Oe(d,S.map(m=>sr(m)?[m]:m.and,c),([m,h])=>S.concat(m,h)),S.reject(S.isEmpty,[s]))};var he=require("openapi3-ts/oas31"),l=y(require("ramda"),1),rt=require("zod/v4");var Ho=["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 Ko=50,Bo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Fo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Do=e=>e.replace(Kt,t=>`{${t.slice(1)}}`),Vn=({zodSchema:e,jsonSchema:t})=>{let r=rt.globalRegistry.get(e)?.[T]?.defaultLabel??t.default;return{...t,default:typeof r=="bigint"?String(r):r}},_n=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Jn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),Gn=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Wn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ue(e,"throw")},(e,{jsonSchema:t})=>t),Yn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:is(t.type)})},qo=e=>e in Fo,Qn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Xn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),es=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{if(r||!ce(e,"object"))return t;let{required:o=[]}=t,n=[];for(let s of o){let i=e._zod.def.shape[s];i&&!gt(i,{isResponse:r})&&n.push(s)}return{...t,required:n}},ke=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(qo):t&&qo(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(ke));return s&&(p.not=ke(s)),p},ts=({},e)=>{if(e.isResponse)throw new J("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Bo}}},rs=({},e)=>{if(!e.isResponse)throw new J("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Bo}}},os=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),ns=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},ss=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Fo?.[t]},is=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],as=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!ce(o,"transform"))return t;let s=ke(pr(n,{ctx:r}));if((0,he.isSchemaObject)(s))if(r.isResponse){let i=yt(o,ss(s));if(i&&["number","string","boolean"].includes(i))return{type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},ps=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},ir=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,cs=(e,t)=>t?.includes(e)||e.startsWith("x-")||Ho.includes(e),Uo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ue(r),m=ut(e),h=o.includes("query"),b=o.includes("params"),g=o.includes("headers"),A=O=>b&&m.includes(O),C=l.chain(l.filter(O=>O.type==="header"),p??[]).map(({name:O})=>O),$=O=>g&&(i?.(O,t,e)??cs(O,C));return Object.entries(c.properties).reduce((O,[I,N])=>{let _=A(I)?"path":$(I)?"header":h?"query":void 0;if(!_)return O;let j=ke(N),re=s==="components"?n(N,j,de(d,I)):j;return O.concat({name:I,in:_,deprecated:N.deprecated,required:c.required?.includes(I)||!1,description:j.description||d,schema:re,examples:ir((0,he.isSchemaObject)(j)&&j.examples?.length?j.examples:l.pluck(I,c.examples?.filter(l.both(L,l.has(I)))||[]))})},[])},ar={nullable:Yn,default:Vn,union:Gn,bigint:os,intersection:Wn,tuple:ns,pipe:as,literal:Xn,enum:Qn,object:es,[Pe]:ts,[we]:rs,[me]:_n,[le]:Jn,[B]:ps},ds=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{let o={...t},n=Re({schema:e,variant:r?"parsed":"original",validate:!0,pullProps:!0});return n.length&&(o.examples=n.slice()),o},ms=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,he.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,ke(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},pr=(e,{ctx:t,rules:r=ar})=>{let{$defs:o={},properties:n={}}=rt.z.toJSONSchema(rt.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=te(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)}Object.assign(s.jsonSchema,ds(s,t))}});return ms(n.subject,o,t)},Vo=(e,t)=>{if((0,he.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Vo(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]},_o=({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} ${Ft(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=ke(pr(r,{rules:{...c,...ar},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,he.isSchemaObject)(h)&&h.examples&&(b.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,de(m)):h,examples:ir(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},ls=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},us=({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},fs=({name:e})=>({type:"apiKey",in:"header",name:e}),ys=({name:e})=>({type:"apiKey",in:"cookie",name:e}),gs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),hs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Jo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ls(o):o.type==="input"?us(o,t):o.type==="header"?fs(o):o.type==="cookie"?ys(o):o.type==="openid"?gs(o):hs(o);return e.map(o=>o.map(r))},Go=(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})=>pr(e,{rules:{...t,...ar},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Yo=({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]=Vo(ke(o),p),h=[];(0,he.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,de(d)):c,examples:ir(h.length?h:Ue(o).examples?.filter(A=>L(A)&&!Array.isArray(A)).map(l.omit(p))||[])},g={description:d,content:{[n]:b}};return(m||n===v.raw)&&(g.required=!0),g},Qo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),cr=e=>e.length<=Ko?e:e.slice(0,Ko-1)+"\u2026",Pt=e=>e.length?e.slice():void 0;var wt=class extends Xo.OpenApiBuilder{#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||de(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new J(`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:h="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});Ve({routing:t,onEndpoint:(g,A,C)=>{let $={path:A,method:C,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:I,scopes:N,inputSchema:_}=g,j=I?cr(I):m&&O?cr(O):void 0,re=r.inputSources?.[C]||qt[C],Ne=this.#n(A,C,g.getOperationId(C)),it=Wo({...$,schema:_}),xe=$o(g.security),at=Uo({...$,inputSources:re,isHeader:c,security:xe,request:it,description:i?.requestParameter?.call(null,{method:C,path:A,operationId:Ne})}),pt={};for(let oe of He){let Se=g.getResponses(oe);for(let{mimeTypes:dt,schema:$t,statusCodes:kr}of Se)for(let Ht of kr)pt[Ht]=_o({...$,variant:oe,schema:$t,mimeTypes:dt,statusCode:Ht,hasMultipleStatusCodes:Se.length>1||kr.length>1,description:i?.[`${oe}Response`]?.call(null,{method:C,path:A,operationId:Ne,statusCode:Ht})})}let ct=re.includes("body")?Yo({...$,request:it,paramNames:en.pluck("name",at),schema:_,mimeType:v[g.requestType],description:i?.requestBody?.call(null,{method:C,path:A,operationId:Ne})}):void 0,Lt=Go(Jo(xe,re),N,oe=>{let Se=this.#s(oe);return this.addSecurityScheme(Se,oe),Se}),Zt={operationId:Ne,summary:j,description:O,deprecated:g.isDeprecated||void 0,tags:Pt(g.tags),parameters:Pt(at),requestBody:ct,security:Pt(Lt),responses:pt};this.addPath(Do(A),{[C]:Zt})}}),d&&(this.rootDoc.tags=Qo(d))}};var Et=require("node-mocks-http");var bs=e=>(0,Et.createRequest)({...e,headers:{"content-type":v.json,...e?.headers}}),xs=e=>(0,Et.createResponse)(e),Ss=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},tn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=bs(e),s=xs({req:n,...t});s.req=t?.req||n,n.res=s;let i=Ss(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},rn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=tn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},on=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=ye}}=tn(r),d=ft(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:pe(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=y(require("ramda"),1),st=y(require("typescript"),1),mn=require("zod/v4");var pn=y(require("ramda"),1),U=y(require("typescript"),1);var Q=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,vt=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],Rs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],ot={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},dr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),mr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Os=/^[A-Za-z_$][A-Za-z0-9_$]*$/,lr=e=>typeof e=="string"&&Os.test(e)?a.createIdentifier(e):E(e),kt=(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)))),At=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),_e=e=>Object.entries(e).map(([t,r])=>At(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),ur=(e,t=[])=>a.createConstructorDeclaration(ot.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?a.createTypeReferenceNode(e,t&&Q.map(f,t)):e,fr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ae=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,lr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=Q.reject(Q.isNil,[o?"@deprecated":void 0,n]);return p.length?dr(i,p.join(" ")):i},yr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),gr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&vt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),hr=(e,t)=>X(e,a.createUnionTypeNode(Q.map(q,t)),{expose:!0}),X=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?vt:void 0,e,n&&Rr(n),t);return o?dr(s,o):s},nn=(e,t)=>a.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),br=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(ot.public,void 0,e,void 0,o&&Rr(o),t,n,a.createBlock(r)),xr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(vt,e,r&&Rr(r),void 0,t),Sr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Ct=e=>f(Promise.name,[e]),It=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?dr(n,o):n},Rr=e=>(Array.isArray(e)?e.map(t=>Q.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)}),Ce=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?Rs:void 0,void 0,Array.isArray(e)?Q.map(At,e):_e(e),void 0,void 0,t),P=e=>e,nt=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.default.SyntaxKind.QuestionToken),t,a.createToken(u.default.SyntaxKind.ColonToken),r),w=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Je=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Nt=(e,t)=>f("Extract",[e,t]),Or=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),D=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>a.createUnionTypeNode([f(e),Ct(e)]),Tr=(e,t)=>a.createFunctionTypeNode(void 0,_e(e),f(t)),E=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),q=e=>a.createLiteralTypeNode(E(e)),Ts=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>Ts.includes(e.kind);var zt=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=hr("Method",rr);someOfType=X("SomeOf",D("T",Sr("T")),{params:["T"]});requestType=X("Request",Sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>hr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>It(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ae(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(lr(t),a.createArrayLiteralExpression(pn.map(E,r))))),{expose:!0});makeImplementationType=()=>X(this.#e.implementationType,Tr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:fr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ct(U.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:U.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,Ce({[this.#e.requestParameter.text]:U.default.SyntaxKind.StringKeyword},a.createAsExpression(w(this.#e.requestParameter,P("split"))(a.createRegularExpressionLiteral("/ (.+)/"),E(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>z(this.#e.substituteFn,Ce({[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:fr},a.createBlock([z(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],U.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Or(this.#e.pathParameter,w(this.#e.pathParameter,P("replace"))(kt(":",[this.#e.keyParameter]),Ce([],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=()=>br(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:D(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(gr(this.#e.methodParameter,this.#e.pathParameter),w(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(w(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(w(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ct(D(this.interfaces.response,"K"))});makeClientClass=t=>xr(t,[ur([At(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:ot.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>kt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,kt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(P("method"),w(this.#e.methodParameter,P("toUpperCase"))()),r=a.createPropertyAssignment(P("headers"),nt(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(E("Content-Type"),E(v.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(P("body"),nt(this.#e.hasBodyConst,w(JSON[Symbol.toStringTag],P("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=z(this.#e.responseConst,a.createAwaitExpression(w(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=z(this.#e.hasBodyConst,a.createLogicalNot(w(a.createArrayLiteralExpression([E("get"),E("delete")]),P("includes"))(this.#e.methodParameter))),i=z(this.#e.searchParamsConst,nt(this.#e.hasBodyConst,E(""),this.#r(this.#e.paramsArgument))),p=z(this.#e.contentTypeConst,w(this.#e.responseConst,P("headers"),P("get"))(E("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(U.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=z(this.#e.isJsonConst,w(this.#e.contentTypeConst,P("startsWith"))(E(v.json))),m=a.createReturnStatement(w(this.#e.responseConst,nt(this.#e.isJsonConst,E(P("json")),E(P("text"))))());return z(this.#e.defaultImplementationConst,Ce([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=()=>ur(_e({request:"K",params:D(this.interfaces.input,"K")}),[z(gr(this.#e.pathParameter,this.#e.restConst),w(this.#e.substituteFn)(a.createElementAccessExpression(w(this.#e.parseRequestFn)(this.#e.requestParameter),E(1)),this.#e.paramsArgument)),z(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Or(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Ae(P("event"),t)]);#i=()=>br(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Tr({[this.#e.dataParameter.text]:D(Nt("R",yr(this.#s("E"))),q(P("data")))},sn(U.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(w(a.createThis(),this.#e.sourceProp,P("addEventListener"))(this.#e.eventParameter,Ce([this.#e.msgParameter],w(this.#e.handlerParameter)(w(JSON[Symbol.toStringTag],P("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),P("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:D("R",q(P("event")))}});makeSubscriptionClass=t=>xr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Nt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(U.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Nt(D(this.interfaces.positive,"K"),yr(this.#s(U.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,Je(t)),w(this.#e.clientConst,this.#e.provideMethod)(E("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",E("10"))])),w(Je(r,E("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(E("time"),Ce(["time"],a.createBlock([])))]};var k=y(require("ramda"),1),x=y(require("typescript"),1),cn=require("zod/v4");var Pr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=te(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Pr(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:V}=x.default,Ps={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},wr={name:k.path(["name","text"]),type:k.path(["type"]),optional:k.path(["questionToken"])},ws=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):q(r));return t.length===1?t[0]:V.createUnionTypeNode(t)},Es=(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}=cn.globalRegistry.get(p)||{};return Ae(i,r(p),{comment:d,isDeprecated:c,isOptional:gt(p,{isResponse:t})})});return V.createTypeLiteralNode(s)};return Dr(e,{io:t?"output":"input"})?o(e,n):n()},vs=({_zod:{def:e}},{next:t})=>V.createArrayTypeNode(t(e.element)),ks=({_zod:{def:e}})=>V.createUnionTypeNode(Object.values(e.entries).map(q)),As=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(an(n)?n.kind:n,n)}return V.createUnionTypeNode(Array.from(r.values()))},Cs=e=>Ps?.[e.kind],Is=({_zod:{def:e}},{next:t})=>t(e.innerType),Ns=({_zod:{def:e}},{next:t})=>V.createUnionTypeNode([t(e.innerType),q(null)]),zs=({_zod:{def:e}},{next:t})=>V.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:V.createRestTypeNode(t(e.rest)))),js=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ms=k.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=k.chain(k.prop("members"),e),r=k.uniqWith((...o)=>{if(!k.eqBy(wr.name,...o))return!1;if(k.both(k.eqBy(wr.type),k.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return V.createTypeLiteralNode(r)},(e,t)=>V.createIntersectionTypeNode(t)),Ls=({_zod:{def:e}},{next:t})=>Ms([e.left,e.right].map(t)),be=e=>()=>f(e),Er=({_zod:{def:e}},{next:t})=>t(e.innerType),Zs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!ce(o,"transform"))return t(o);let s=t(n),i=yt(o,Cs(s)),p={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||x.default.SyntaxKind.AnyKeyword)},$s=()=>q(null),Hs=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ks=e=>{let t=f(x.default.SyntaxKind.StringKeyword),r=f("Buffer"),o=V.createUnionTypeNode([t,r]);return ce(e,"string")?t:ce(e,"union")?o:r},qs=(e,{next:t})=>t(e._zod.def.shape.raw),Bs={string:be(x.default.SyntaxKind.StringKeyword),number:be(x.default.SyntaxKind.NumberKeyword),bigint:be(x.default.SyntaxKind.BigIntKeyword),boolean:be(x.default.SyntaxKind.BooleanKeyword),any:be(x.default.SyntaxKind.AnyKeyword),undefined:be(x.default.SyntaxKind.UndefinedKeyword),[Pe]:be(x.default.SyntaxKind.StringKeyword),[we]:be(x.default.SyntaxKind.StringKeyword),null:$s,array:vs,tuple:zs,record:js,object:Es,literal:ws,intersection:Ls,union:As,default:Er,enum:ks,optional:Is,nullable:Ns,catch:Er,pipe:Zs,lazy:Hs,readonly:Er,[le]:Ks,[B]:qs},vr=(e,{brandHandling:t,ctx:r})=>Pr(e,{rules:{...t,...Bs},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var jt=class extends zt{#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=q(null);this.#t.set(t,X(o,n)),this.#t.set(t,X(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=mn.z.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};Ve({routing:t,onEndpoint:(b,g,A)=>{let C=de.bind(null,A,g),{isDeprecated:$,inputSchema:O,tags:I}=b,N=`${A} ${g}`,_=X(C("input"),vr(O,c),{comment:N});this.#e.push(_);let j=He.reduce((it,xe)=>{let at=b.getResponses(xe),pt=dn.chain(([Lt,{schema:Zt,mimeTypes:oe,statusCodes:Se}])=>{let dt=X(C(xe,"variant",`${Lt+1}`),vr(oe?Zt:p,m),{comment:N});return this.#e.push(dt),Se.map($t=>Ae($t,dt.name))},Array.from(at.entries())),ct=It(C(xe,"response","variants"),pt,{comment:N});return this.#e.push(ct),Object.assign(it,{[xe]:ct})},{});this.paths.add(g);let re=q(N),Ne={input:f(_.name),positive:this.someOf(j.positive),negative:this.someOf(j.negative),response:a.createUnionTypeNode([D(this.interfaces.positive,re),D(this.interfaces.negative,re)]),encoded:a.createIntersectionTypeNode([f(j.positive.name),f(j.negative.name)])};this.registry.set(N,{isDeprecated:$,store:Ne}),this.tags.set(N,I)}}),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:mr(r,t)).join(`
19
- `):void 0}print(t){let r=this.#n(t),o=r&&st.default.addSyntheticLeadingComment(st.default.addSyntheticLeadingComment(a.createEmptyStatement(),st.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),st.default.SyntaxKind.MultiLineCommentTrivia,`
18
+ `))};var zo=e=>{e.startupLogo!==!1&&Co(process.stdout);let t=e.errorHandler||ue,r=Qr(e.logger)?e.logger:new Ke(e.logger);r.debug("Running",{build:"v24.0.0-beta.2 (CJS)",env:process.env.NODE_ENV||"development"}),ko(r);let o=Eo({logger:r,config:e}),s={getLogger:vo(r),errorHandler:t},i=To(s),p=Oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},jo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return nr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Lo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=zo(e),p=(0,et.default)().disable("x-powered-by").use(i);if(e.compression){let b=await Fe("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||et.default.json()],raw:[e.rawParser||et.default.raw(),wo],form:[e.formParser||et.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};nr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,g)=>()=>b.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let b=Io.default.createServer(p);c.push(b),h.push(m(b,e.http.listen))}if(e.https){let b=No.default.createServer(e.https.options,p);c.push(b),h.push(m(b,e.https.listen))}return e.gracefulShutdown&&Ao({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(b=>b())}};var Xo=require("openapi3-ts/oas31"),en=y(require("ramda"),1);var S=y(require("ramda"),1);var Mo=e=>M(e)&&"or"in e,Zo=e=>M(e)&&"and"in e,sr=e=>!Zo(e)&&!Mo(e),$o=e=>{let t=S.filter(sr,e),r=S.chain(S.prop("and"),S.filter(Zo,e)),[o,n]=S.partition(sr,r),s=S.concat(t,o),i=S.filter(Mo,e);return S.map(S.prop("or"),S.concat(i,n)).reduce((d,c)=>xe(d,S.map(m=>sr(m)?[m]:m.and,c),([m,h])=>S.concat(m,h)),S.reject(S.isEmpty,[s]))};var ye=require("openapi3-ts/oas31"),l=y(require("ramda"),1),tt=require("zod/v4");var Ho=["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 Ko=50,Bo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Fo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Uo=e=>e.replace(Kt,t=>`{${t.slice(1)}}`),Dn=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},_n=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),Vn=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Jn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ue(e,"throw")},(e,{jsonSchema:t})=>t),Gn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ns(t.type)})},qo=e=>e in Fo,Wn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Yn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Qn=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{if(r||!q(e,"object"))return t;let{required:o=[]}=t,n=[];for(let s of o){let i=e._zod.def.shape[s];i&&!gt(i,{isResponse:r})&&n.push(s)}return{...t,required:n}},we=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(qo):t&&qo(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(we));return s&&(p.not=we(s)),p},Xn=({zodSchema:e},t)=>{if(t.isResponse)throw new J("Please use ez.dateOut() for output.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Bo}},o=tt.globalRegistry.get(e)?.examples?.filter(n=>n instanceof Date).map(n=>n.toISOString());return o?.length&&(r.examples=o),r},es=({jsonSchema:{examples:e}},t)=>{if(!t.isResponse)throw new J("Please use ez.dateIn() for input.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Bo}};return e?.length&&(r.examples=e),r},ts=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),rs=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Fo?.[t]},ns=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ss=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!q(o,"transform"))return t;let s=we(pr(n,{ctx:r}));if((0,ye.isSchemaObject)(s))if(r.isResponse){let i=yt(o,os(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},is=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},ir=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,as=(e,t)=>t?.includes(e)||e.startsWith("x-")||Ho.includes(e),Do=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ue(r),m=lt(e),h=o.includes("query"),b=o.includes("params"),g=o.includes("headers"),k=O=>b&&m.includes(O),A=l.chain(l.filter(O=>O.type==="header"),p??[]).map(({name:O})=>O),$=O=>g&&(i?.(O,t,e)??as(O,A));return Object.entries(c.properties).reduce((O,[I,N])=>{let V=k(I)?"path":$(I)?"header":h?"query":void 0;if(!V)return O;let j=we(N),re=s==="components"?n(N,j,pe(d,I)):j;return O.concat({name:I,in:V,deprecated:N.deprecated,required:c.required?.includes(I)||!1,description:j.description||d,schema:re,examples:ir((0,ye.isSchemaObject)(j)&&j.examples?.length?j.examples:l.pluck(I,c.examples?.filter(l.both(M,l.has(I)))||[]))})},[])},ar={nullable:Gn,union:Vn,bigint:ts,intersection:Jn,tuple:rs,pipe:ss,literal:Yn,enum:Wn,object:Qn,[Re]:Xn,[Oe]:es,[ce]:Dn,[de]:_n,[B]:is},ps=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,ye.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,we(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},pr=(e,{ctx:t,rules:r=ar})=>{let{$defs:o={},properties:n={}}=tt.z.toJSONSchema(tt.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=te(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 ps(n.subject,o,t)},_o=(e,t)=>{if((0,ye.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=_o(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]},Vo=({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} ${Ft(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=we(pr(r,{rules:{...c,...ar},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,ye.isSchemaObject)(h)&&h.examples&&(b.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,pe(m)):h,examples:ir(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ds=({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},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),ls=({name:e})=>({type:"apiKey",in:"cookie",name:e}),us=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),fs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Jo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?cs(o):o.type==="input"?ds(o,t):o.type==="header"?ms(o):o.type==="cookie"?ls(o):o.type==="openid"?us(o):fs(o);return e.map(o=>o.map(r))},Go=(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})=>pr(e,{rules:{...t,...ar},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Yo=({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]=_o(we(o),p),h=[];(0,ye.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,pe(d)):c,examples:ir(h.length?h:Ue(o).examples?.filter(k=>M(k)&&!Array.isArray(k)).map(l.omit(p))||[])},g={description:d,content:{[n]:b}};return(m||n===E.raw)&&(g.required=!0),g},Qo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),cr=e=>e.length<=Ko?e:e.slice(0,Ko-1)+"\u2026",Pt=e=>e.length?e.slice():void 0;var wt=class extends Xo.OpenApiBuilder{#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||pe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new J(`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:h="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});De({routing:t,onEndpoint:(g,k,A)=>{let $={path:k,method:A,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:I,scopes:N,inputSchema:V}=g,j=I?cr(I):m&&O?cr(O):void 0,re=r.inputSources?.[A]||qt[A],Ae=this.#n(k,A,g.getOperationId(A)),st=Wo({...$,schema:V}),he=$o(g.security),it=Do({...$,inputSources:re,isHeader:c,security:he,request:st,description:i?.requestParameter?.call(null,{method:A,path:k,operationId:Ae})}),at={};for(let oe of $e){let be=g.getResponses(oe);for(let{mimeTypes:ct,schema:$t,statusCodes:kr}of be)for(let Ht of kr)at[Ht]=Vo({...$,variant:oe,schema:$t,mimeTypes:ct,statusCode:Ht,hasMultipleStatusCodes:be.length>1||kr.length>1,description:i?.[`${oe}Response`]?.call(null,{method:A,path:k,operationId:Ae,statusCode:Ht})})}let pt=re.includes("body")?Yo({...$,request:st,paramNames:en.pluck("name",it),schema:V,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:A,path:k,operationId:Ae})}):void 0,Mt=Go(Jo(he,re),N,oe=>{let be=this.#s(oe);return this.addSecurityScheme(be,oe),be}),Zt={operationId:Ae,summary:j,description:O,deprecated:g.isDeprecated||void 0,tags:Pt(g.tags),parameters:Pt(it),requestBody:pt,security:Pt(Mt),responses:at};this.addPath(Uo(k),{[A]:Zt})}}),d&&(this.rootDoc.tags=Qo(d))}};var Et=require("node-mocks-http");var ys=e=>(0,Et.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),gs=e=>(0,Et.createResponse)(e),hs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},tn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ys(e),s=gs({req:n,...t});s.req=t?.req||n,n.res=s;let i=hs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},rn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=tn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},on=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=ue}}=tn(r),d=ut(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:ae(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=y(require("ramda"),1),nt=y(require("typescript"),1),mn=require("zod/v4");var pn=y(require("ramda"),1),D=y(require("typescript"),1);var Q=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,vt=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],bs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],rt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},dr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),mr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},xs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,lr=e=>typeof e=="string"&&xs.test(e)?a.createIdentifier(e):w(e),kt=(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)))),At=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),_e=e=>Object.entries(e).map(([t,r])=>At(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),ur=(e,t=[])=>a.createConstructorDeclaration(rt.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?a.createTypeReferenceNode(e,t&&Q.map(f,t)):e,fr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ee=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,lr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=Q.reject(Q.isNil,[o?"@deprecated":void 0,n]);return p.length?dr(i,p.join(" ")):i},yr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),gr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&vt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),hr=(e,t)=>X(e,a.createUnionTypeNode(Q.map(K,t)),{expose:!0}),X=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?vt:void 0,e,n&&Rr(n),t);return o?dr(s,o):s},nn=(e,t)=>a.createPropertyDeclaration(rt.public,e,void 0,f(t),void 0),br=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(rt.public,void 0,e,void 0,o&&Rr(o),t,n,a.createBlock(r)),xr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(vt,e,r&&Rr(r),void 0,t),Sr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Ct=e=>f(Promise.name,[e]),It=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?dr(n,o):n},Rr=e=>(Array.isArray(e)?e.map(t=>Q.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)}),ve=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?bs:void 0,void 0,Array.isArray(e)?Q.map(At,e):_e(e),void 0,void 0,t),T=e=>e,ot=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.default.SyntaxKind.QuestionToken),t,a.createToken(u.default.SyntaxKind.ColonToken),r),P=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Ve=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Nt=(e,t)=>f("Extract",[e,t]),Or=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),U=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>a.createUnionTypeNode([f(e),Ct(e)]),Tr=(e,t)=>a.createFunctionTypeNode(void 0,_e(e),f(t)),w=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),K=e=>a.createLiteralTypeNode(w(e)),Ss=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>Ss.includes(e.kind);var zt=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=hr("Method",rr);someOfType=X("SomeOf",U("T",Sr("T")),{params:["T"]});requestType=X("Request",Sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>hr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>It(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ee(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(lr(t),a.createArrayLiteralExpression(pn.map(w,r))))),{expose:!0});makeImplementationType=()=>X(this.#e.implementationType,Tr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:D.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:fr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ct(D.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:D.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:D.default.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),w(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>z(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:D.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:fr},a.createBlock([z(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],D.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Or(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(kt(":",[this.#e.keyParameter]),ve([],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=()=>br(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:U(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(gr(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ct(U(this.interfaces.response,"K"))});makeClientClass=t=>xr(t,[ur([At(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:rt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>kt("?",[Ve(URLSearchParams.name,t)]);#o=()=>Ve(URL.name,kt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),ot(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),ot(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=z(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=z(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=z(this.#e.searchParamsConst,ot(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=z(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(D.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=z(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(w(E.json))),m=a.createReturnStatement(P(this.#e.responseConst,ot(this.#e.isJsonConst,w(T("json")),w(T("text"))))());return z(this.#e.defaultImplementationConst,ve([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=()=>ur(_e({request:"K",params:U(this.interfaces.input,"K")}),[z(gr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),z(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Or(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Ve("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Ee(T("event"),t)]);#i=()=>br(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Tr({[this.#e.dataParameter.text]:U(Nt("R",yr(this.#s("E"))),K(T("data")))},sn(D.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:U("R",K(T("event")))}});makeSubscriptionClass=t=>xr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Nt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(D.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Nt(U(this.interfaces.positive,"K"),yr(this.#s(D.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,Ve(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Ve(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),ve(["time"],a.createBlock([])))]};var v=y(require("ramda"),1),x=y(require("typescript"),1),cn=require("zod/v4");var Pr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=te(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Pr(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:_}=x.default,Rs={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},wr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Os=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):K(r));return t.length===1?t[0]:_.createUnionTypeNode(t)},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}=cn.globalRegistry.get(p)||{};return Ee(i,r(p),{comment:d,isDeprecated:c,isOptional:gt(p,{isResponse:t})})});return _.createTypeLiteralNode(s)};return Ur(e,{io:t?"output":"input"})?o(e,n):n()},Ps=({_zod:{def:e}},{next:t})=>_.createArrayTypeNode(t(e.element)),ws=({_zod:{def:e}})=>_.createUnionTypeNode(Object.values(e.entries).map(K)),Es=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(an(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},vs=e=>Rs?.[e.kind],ks=({_zod:{def:e}},{next:t})=>t(e.innerType),As=({_zod:{def:e}},{next:t})=>_.createUnionTypeNode([t(e.innerType),K(null)]),Cs=({_zod:{def:e}},{next:t})=>_.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:_.createRestTypeNode(t(e.rest)))),Is=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ns=v.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(wr.name,...o))return!1;if(v.both(v.eqBy(wr.type),v.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),zs=({_zod:{def:e}},{next:t})=>Ns([e.left,e.right].map(t)),ge=e=>()=>f(e),Er=({_zod:{def:e}},{next:t})=>t(e.innerType),js=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!q(o,"transform"))return t(o);let s=t(n),i=yt(o,vs(s)),p={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||x.default.SyntaxKind.AnyKeyword)},Ls=()=>K(null),Ms=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Zs=e=>{let t=f(x.default.SyntaxKind.StringKeyword),r=f("Buffer"),o=_.createUnionTypeNode([t,r]);return q(e,"string")?t:q(e,"union")?o:r},$s=(e,{next:t})=>t(e._zod.def.shape.raw),Hs={string:ge(x.default.SyntaxKind.StringKeyword),number:ge(x.default.SyntaxKind.NumberKeyword),bigint:ge(x.default.SyntaxKind.BigIntKeyword),boolean:ge(x.default.SyntaxKind.BooleanKeyword),any:ge(x.default.SyntaxKind.AnyKeyword),undefined:ge(x.default.SyntaxKind.UndefinedKeyword),[Re]:ge(x.default.SyntaxKind.StringKeyword),[Oe]:ge(x.default.SyntaxKind.StringKeyword),null:Ls,array:Ps,tuple:Cs,record:Is,object:Ts,literal:Os,intersection:zs,union:Es,default:Er,enum:ws,optional:ks,nullable:As,catch:Er,pipe:js,lazy:Ms,readonly:Er,[de]:Zs,[B]:$s},vr=(e,{brandHandling:t,ctx:r})=>Pr(e,{rules:{...t,...Hs},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var jt=class extends zt{#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=K(null);this.#t.set(t,X(o,n)),this.#t.set(t,X(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=mn.z.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};De({routing:t,onEndpoint:(b,g,k)=>{let A=pe.bind(null,k,g),{isDeprecated:$,inputSchema:O,tags:I}=b,N=`${k} ${g}`,V=X(A("input"),vr(O,c),{comment:N});this.#e.push(V);let j=$e.reduce((st,he)=>{let it=b.getResponses(he),at=dn.chain(([Mt,{schema:Zt,mimeTypes:oe,statusCodes:be}])=>{let ct=X(A(he,"variant",`${Mt+1}`),vr(oe?Zt:p,m),{comment:N});return this.#e.push(ct),be.map($t=>Ee($t,ct.name))},Array.from(it.entries())),pt=It(A(he,"response","variants"),at,{comment:N});return this.#e.push(pt),Object.assign(st,{[he]:pt})},{});this.paths.add(g);let re=K(N),Ae={input:f(V.name),positive:this.someOf(j.positive),negative:this.someOf(j.negative),response:a.createUnionTypeNode([U(this.interfaces.positive,re),U(this.interfaces.negative,re)]),encoded:a.createIntersectionTypeNode([f(j.positive.name),f(j.negative.name)])};this.registry.set(N,{isDeprecated:$,store:Ae}),this.tags.set(N,I)}}),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:mr(r,t)).join(`
19
+ `):void 0}print(t){let r=this.#n(t),o=r&&nt.default.addSyntheticLeadingComment(nt.default.addSyntheticLeadingComment(a.createEmptyStatement(),nt.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),nt.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>mr(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
22
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await De("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var Ie=require("zod/v4");var un=(e,t)=>Ie.z.object({data:t,event:Ie.z.literal(e),id:Ie.z.string().optional(),retry:Ie.z.int().positive().optional()}),Fs=(e,t,r)=>un(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),Ds=1e4,ln=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":v.sse,"cache-control":"no-cache"}),Us=e=>new F({handler:async({response:t})=>setTimeout(()=>ln(t),Ds)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{ln(t),t.write(Fs(e,r,o),"utf-8"),t.flush?.()}}}),Vs=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>un(o,n));return{mimeType:v.sse,schema:r.length?Ie.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ie.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);Xe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ve(i),"utf-8")}t.end()}}),Mt=class extends ge{constructor(t){super(Vs(t)),this.middlewares=[Us(t)]}};var fn={dateIn:zr,dateOut:Mr,form:Lr,file:ht,upload:$r,raw:Br};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
22
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Fe("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var ke=require("zod/v4");var un=(e,t)=>ke.z.object({data:t,event:ke.z.literal(e),id:ke.z.string().optional(),retry:ke.z.int().positive().optional()}),Ks=(e,t,r)=>un(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),qs=1e4,ln=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Bs=e=>new F({handler:async({response:t})=>setTimeout(()=>ln(t),qs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{ln(t),t.write(Ks(e,r,o),"utf-8"),t.flush?.()}}}),Fs=e=>new le({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>un(o,n));return{mimeType:E.sse,schema:r.length?ke.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ke.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Te(r);Qe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(Pe(i),"utf-8")}t.end()}}),Lt=class extends fe{constructor(t){super(Fs(t)),this.middlewares=[Bs(t)]}};var fn={dateIn:zr,dateOut:Lr,form:Mr,file:ht,upload:$r,raw:Br};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getMessageFromError,testEndpoint,testMiddleware});
package/dist/index.d.cts CHANGED
@@ -556,33 +556,6 @@ interface TagOverrides {
556
556
  }
557
557
  type Tag = NoNever<keyof TagOverrides, string>;
558
558
  declare const getMessageFromError: (error: Error) => string;
559
- declare const getExamples: <T extends $ZodType, V extends "original" | "parsed" | undefined>({ schema, variant, validate, pullProps, }: {
560
- schema: T;
561
- /**
562
- * @desc examples variant: original or parsed
563
- * @example "parsed" — for the case when possible schema transformations should be applied
564
- * @default "original"
565
- * @override validate: variant "parsed" activates validation as well
566
- * */
567
- variant?: V;
568
- /**
569
- * @desc filters out the examples that do not match the schema
570
- * @default variant === "parsed"
571
- * */
572
- validate?: boolean;
573
- /**
574
- * @desc should pull examples from properties — applicable to ZodObject only
575
- * @default false
576
- * */
577
- pullProps?: boolean;
578
- }) => ReadonlyArray<V extends "parsed" ? z.output<T> : z.input<T>>;
579
-
580
- declare const metaSymbol: unique symbol;
581
- interface Metadata {
582
- examples: unknown[];
583
- /** @override ZodDefault::_zod.def.defaultValue() in depictDefault */
584
- defaultLabel?: string;
585
- }
586
559
 
587
560
  /**
588
561
  * @fileoverview Mapping utils for Zod Runtime Plugin (remap)
@@ -603,18 +576,18 @@ type Intact<T, U> = {
603
576
 
604
577
  declare module "zod/v4/core" {
605
578
  interface GlobalMeta {
606
- [metaSymbol]?: Metadata;
607
579
  deprecated?: boolean;
580
+ default?: unknown;
608
581
  }
609
582
  }
610
583
  declare module "zod/v4" {
611
584
  interface ZodType {
612
- /** @desc Add an example value (before any transformations, can be called multiple times) */
613
- example(example: z.input<this>): this;
585
+ /** @desc Shorthand for .meta({examples}), it can be called multiple times */
586
+ example(example: z.output<this>): this;
614
587
  deprecated(): this;
615
588
  }
616
589
  interface ZodDefault<T extends $ZodType = $ZodType> extends ZodType {
617
- /** @desc Change the default value in the generated Documentation to a label */
590
+ /** @desc Change the default value in the generated Documentation to a label, alias for .meta({ default }) */
618
591
  label(label: string): this;
619
592
  }
620
593
  interface ZodObject<out Shape extends $ZodShape = $ZodLooseShape, out Config extends $ZodObjectConfig = $ZodObjectConfig> extends ZodType {
@@ -968,4 +941,4 @@ declare const ez: {
968
941
  raw: typeof raw;
969
942
  };
970
943
 
971
- export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getExamples, getMessageFromError, testEndpoint, testMiddleware };
944
+ export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getMessageFromError, testEndpoint, testMiddleware };
package/dist/index.d.ts CHANGED
@@ -556,33 +556,6 @@ interface TagOverrides {
556
556
  }
557
557
  type Tag = NoNever<keyof TagOverrides, string>;
558
558
  declare const getMessageFromError: (error: Error) => string;
559
- declare const getExamples: <T extends $ZodType, V extends "original" | "parsed" | undefined>({ schema, variant, validate, pullProps, }: {
560
- schema: T;
561
- /**
562
- * @desc examples variant: original or parsed
563
- * @example "parsed" — for the case when possible schema transformations should be applied
564
- * @default "original"
565
- * @override validate: variant "parsed" activates validation as well
566
- * */
567
- variant?: V;
568
- /**
569
- * @desc filters out the examples that do not match the schema
570
- * @default variant === "parsed"
571
- * */
572
- validate?: boolean;
573
- /**
574
- * @desc should pull examples from properties — applicable to ZodObject only
575
- * @default false
576
- * */
577
- pullProps?: boolean;
578
- }) => ReadonlyArray<V extends "parsed" ? z.output<T> : z.input<T>>;
579
-
580
- declare const metaSymbol: unique symbol;
581
- interface Metadata {
582
- examples: unknown[];
583
- /** @override ZodDefault::_zod.def.defaultValue() in depictDefault */
584
- defaultLabel?: string;
585
- }
586
559
 
587
560
  /**
588
561
  * @fileoverview Mapping utils for Zod Runtime Plugin (remap)
@@ -603,18 +576,18 @@ type Intact<T, U> = {
603
576
 
604
577
  declare module "zod/v4/core" {
605
578
  interface GlobalMeta {
606
- [metaSymbol]?: Metadata;
607
579
  deprecated?: boolean;
580
+ default?: unknown;
608
581
  }
609
582
  }
610
583
  declare module "zod/v4" {
611
584
  interface ZodType {
612
- /** @desc Add an example value (before any transformations, can be called multiple times) */
613
- example(example: z.input<this>): this;
585
+ /** @desc Shorthand for .meta({examples}), it can be called multiple times */
586
+ example(example: z.output<this>): this;
614
587
  deprecated(): this;
615
588
  }
616
589
  interface ZodDefault<T extends $ZodType = $ZodType> extends ZodType {
617
- /** @desc Change the default value in the generated Documentation to a label */
590
+ /** @desc Change the default value in the generated Documentation to a label, alias for .meta({ default }) */
618
591
  label(label: string): this;
619
592
  }
620
593
  interface ZodObject<out Shape extends $ZodShape = $ZodLooseShape, out Config extends $ZodObjectConfig = $ZodObjectConfig> extends ZodType {
@@ -968,4 +941,4 @@ declare const ez: {
968
941
  raw: typeof raw;
969
942
  };
970
943
 
971
- export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getExamples, getMessageFromError, testEndpoint, testMiddleware };
944
+ export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getMessageFromError, testEndpoint, testMiddleware };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import*as L from"ramda";import{z as Y}from"zod/v4";import*as j from"ramda";import{globalRegistry as yr,z as rt}from"zod/v4";var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var me=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},J=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"},tt=class extends He{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},le=class extends He{constructor(r){super(te(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends He{constructor(r){super(te(r),{cause:r});this.cause=r}name="InputValidationError"},ee=class extends Error{constructor(r,o){super(te(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var At=/:([A-Za-z0-9_]+)/g,ot=e=>e.match(At)?.map(t=>t.slice(1))||[],Bo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Ct={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Fo=["body","query","params"],It=e=>e.method.toLowerCase(),nt=(e,t={})=>{let r=It(e);return r==="options"?{}:(t[r]||Ct[r]||Fo).filter(o=>o==="files"?Bo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},re=e=>e instanceof Error?e:e instanceof rt.ZodError?new Error(te(e),{cause:e}):new Error(String(e)),te=e=>e instanceof rt.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof le?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,oe=(e,t)=>e._zod.def.type===t,Do=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=yr.get(o)?.[O]||{};return ue(t,n.map(j.objOf(r)),([s,i])=>({...s,...i}))},[]),we=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=yr.get(e)?.[O]?.examples||[];if(!n.length&&o&&oe(e,"object")&&(n=Do(e)),!r&&t==="original")return n;let s=[];for(let i of n){let p=rt.safeParse(e,i);p.success&&s.push(t==="parsed"?p.data:i)}return s},ue=(e,t,r)=>e.length&&t.length?j.xprod(e,t).map(r):e.concat(t),Nt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ne=(...e)=>{let t=j.chain(o=>o.split(/[^A-Z0-9]/gi),e);return j.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Nt).join("")},st=j.tryCatch((e,t)=>typeof rt.parse(e,t),j.always(void 0)),it=({_zod:{optin:e,optout:t}},{isResponse:r})=>(r?t:e)==="optional",M=e=>typeof e=="object"&&e!==null,fe=j.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as gr from"ramda";var O=Symbol.for("express-zod-api"),hr=(e,t)=>{let r=e.meta(),o=t.meta();if(!r?.[O])return t;let n=ue(o?.[O]?.examples||[],r[O].examples||[],([s,i])=>typeof s=="object"&&typeof i=="object"&&s&&i?gr.mergeDeepRight(s,i):i);return t.meta({...o,[O]:{...o?.[O],examples:n}})},W=e=>{let{brand:t}=e._zod.bag;if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Uo=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=()=>{}}),Vo=function(e){let{[O]:t,...r}=this.meta()||{},o=t?.examples.slice()||[];return o.push(e),this.meta({...r,[O]:{...t,examples:o}})},_o=function(){return this.meta({...this.meta(),deprecated:!0})},Jo=function(e){let{[O]:t={examples:[]},...r}=this.meta()||{};return this.meta({...r,[O]:{...t,defaultLabel:e}})},Go=function(e){return this.check(new Uo({brand:e,check:"$EZBrandCheck"}))},Wo=function(e){let t=typeof e=="function"?e:L.pipe(L.toPairs,L.map(([s,i])=>L.pair(e[String(s)]||s,i)),L.fromPairs),r=t(L.map(L.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(!(O in globalThis)){globalThis[O]=!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:{get(){return Vo.bind(this)}},deprecated:{get(){return _o.bind(this)}},brand:{set(){},get(){return Go.bind(this)}}})}Object.defineProperty(Y.ZodDefault.prototype,"label",{get(){return Jo.bind(this)}}),Object.defineProperty(Y.ZodObject.prototype,"remap",{get(){return Wo.bind(this)}})}function Yo(e){return e}import{z as Mr}from"zod/v4";import*as Ae from"ramda";import{z as Nr}from"zod/v4";import*as ae from"ramda";import{z as Er}from"zod/v4";import{z as qe}from"zod/v4";var ye=Symbol("DateIn"),br=()=>qe.union([qe.iso.date(),qe.iso.datetime(),qe.iso.datetime({local:!0})]).transform(t=>new Date(t)).pipe(qe.date()).brand(ye);import{z as Qo}from"zod/v4";var ge=Symbol("DateOut"),xr=()=>Qo.date().transform(e=>e.toISOString()).brand(ge);import{z as Sr}from"zod/v4";var Be=Symbol("Form"),Rr=e=>(e instanceof Sr.ZodObject?e:Sr.object(e)).brand(Be);import{z as Xo}from"zod/v4";var se=Symbol("Upload"),Or=()=>Xo.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(se);import{z as tn}from"zod/v4";import{z as at}from"zod/v4";var ie=Symbol("File"),Tr=at.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),en={buffer:()=>Tr.brand(ie),string:()=>at.string().brand(ie),binary:()=>Tr.or(at.string()).brand(ie),base64:()=>at.base64().brand(ie)};function pt(e){return en[e||"string"]()}var H=Symbol("Raw"),Pr=tn.object({raw:pt("buffer")}),rn=e=>Pr.extend(e).brand(H);function wr(e){return e?rn(e):Pr.brand(H)}var vr=(e,{io:t,condition:r})=>ae.tryCatch(()=>{Er.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new tt(o)}})},o=>o.cause)(),kr=(e,{io:t})=>{let o=[Er.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];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},Ar=e=>vr(e,{condition:t=>{let r=W(t);return typeof r=="symbol"&&[se,H,Be].includes(r)},io:"input"}),on=["nan","symbol","map","set","bigint","void","promise","never"],zt=(e,t)=>vr(e,{io:t,condition:r=>{let o=W(r),{type:n}=r._zod.def;return!!(on.includes(n)||t==="input"&&(n==="date"||o===ge)||t==="output"&&(o===ye||o===H||o===se))}});import an,{isHttpError as pn}from"http-errors";import Cr,{isHttpError as nn}from"http-errors";import{z as sn}from"zod/v4";var jt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof sn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ee(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}))},Fe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>nn(e)?e:Cr(e instanceof G?400:500,te(e),{cause:e.cause||e}),he=e=>fe()&&!e.expose?Cr(e.statusCode).message:e.message;var ct=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=he(an(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:pn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ir}from"zod/v4";var Mt=class{},D=class extends Mt{#e;#t;#r;constructor({input:t=Ir.object({}),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.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Ir.ZodError?new G(o):o}}},ve=class extends D{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 ke=class{nest(t){return Object.assign(t,{"":this})}};var De=class extends ke{},dt=class e extends De{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}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.#e.outputSchema}get requestType(){let t=Ar(this.#e.inputSchema);if(t){let r=W(t);if(r===se)return"upload";if(r===H)return"raw";if(r===Be)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=Ae.pluck("security",this.#e.middlewares||[]);return Ae.reject(Ae.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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Nr.ZodError?new le(r):r}}async#o({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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Nr.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){ct({...t,error:new ee(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=It(t),i={},p={output:{},error:null},d=nt(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as zr from"ramda";var jr=(e,t)=>{let r=zr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>hr(s,n),o)};import{z as K}from"zod/v4";var Ce={positive:200,negative:400},Ie=Object.keys(Ce);var Lt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Lt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return jt(this.#e,{variant:"positive",args:[t],statusCodes:[Ce.positive],mimeTypes:[E.json]})}getNegativeResponse(){return jt(this.#t,{variant:"negative",args:[],statusCodes:[Ce.negative],mimeTypes:[E.json]})}},xe=new be({positive:e=>{let t=we({schema:e,pullProps:!0}),r=K.object({status:K.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},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=Ee(e);return Fe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:he(i)}})}n.status(Ce.positive).json({status:"success",data:r})}}),Zt=new be({positive:e=>{let t=we({schema:e}),r=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());return t.reduce((o,n)=>M(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:K.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);return Fe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(he(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ce.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Se=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof D?t:new D(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new ve(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new D({handler:t})),this.resultHandler)}build({input:t=Mr.object({}),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,h=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new dt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:y,methods:m,getOperationId:g,inputSchema:jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Mr.object({}),handler:async o=>(await t(o),{})})}},cn=new Se(xe),dn=new Se(Zt);import hn from"ansis";import{inspect as bn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as mn,green as ln,hex as un,red as fn,cyanBright as yn}from"ansis";import*as Lr from"ramda";var $t={debug:mn,info:ln,warn:un("#FFA500"),error:fn,ctx:yn},mt={debug:10,info:20,warn:30,error:40},Zr=e=>M(e)&&Object.keys(mt).some(t=>t in e),$r=e=>e in mt,Hr=(e,t)=>mt[e]<mt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ne=Lr.memoizeWith((e,t)=>`${e}${t}`,gn),Kr=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 Ue=class e{config;constructor({color:t=hn.isSupported(),level:r=fe()?"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 bn(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"||Hr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?$t.ctx(s):s),d.push(p?`${$t[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=qr.now();return()=>{let o=qr.now()-r,{message:n,severity:s="debug",formatter:i=Kr}=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 ke{#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 xn from"express";var _e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,xn.static(...this.#e))}};import ft from"express";import Mn from"node:http";import Ln from"node:https";var ze=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import En from"http-errors";import{z as Dr}from"zod/v4";import*as S from"ramda";var Sn=e=>e.type==="object",Rn=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),On=S.pipe(Object.keys,S.without(["type","properties","required","examples","description"]),S.isEmpty),Fr=S.pair(!0),je=(e,t="coerce")=>{let r=[S.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"&&On(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(Fr,i.anyOf)),i.oneOf&&r.push(...S.map(Fr,i.oneOf)),!!Sn(i)&&(i.properties&&(o.properties=(t==="throw"?Rn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=ue(o.examples?.filter(M)||[],i.examples.filter(M),([p,d])=>S.mergeDeepRight(p,d))),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};var lt=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=[Dr.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 Ie)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.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=ot(t);if(s.length===0)return;let i=n?.flat||je(Dr.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 Ht=["get","post","put","delete","patch"],Ur=e=>Ht.includes(e);var Tn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Ur(t)?[r,t]:[e]},Pn=e=>e.trim().split("/").filter(Boolean).join("/"),Vr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Tn(r);return[[t||""].concat(Pn(n)||[]).join("/"),o,s]}),wn=(e,t)=>{throw new me("Route with explicit method can only be assigned with Endpoint",e,t)},_r=(e,t,r)=>{if(!(!r||r.includes(e)))throw new me(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Kt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new me("Route has a duplicate",e,t);r.add(o)},Me=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Vr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof De)if(p)Kt(p,s,n),_r(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)Kt(c,s,n),t(i,s,c)}else if(p&&wn(p,s),i instanceof _e)r&&i.apply(s,r);else if(i instanceof Ve)for(let[d,c]of i.entries){let{methods:m}=c;Kt(d,s,n),_r(d,s,m),t(c,s,d)}else o.unshift(...Vr(i,s))}};import*as Jr from"ramda";var Gr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=Gr(e);r.set({Allow:n});let s=En(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Gr(e),"Access-Control-Allow-Headers":"content-type"}),qt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=fe()?void 0:new lt(t()),i=new Map;Me({routing:o,onEndpoint:(c,m,g)=>{fe()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let h=n?.[c.requestType]||[],y=Jr.pair(h,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[h,[y,k]]of m){let A=async(Z,R)=>{let C=t(Z);if(r.cors){let I=kn(g),F=typeof r.cors=="function"?await r.cors({request:Z,endpoint:k,logger:C,defaultHeaders:I}):I;R.set(F)}return k.execute({request:Z,response:R,logger:C,config:r})};e[h](c,...y,A)}r.wrongMethodBehavior!==404&&d.set(c,vn(g))}for(let[c,m]of d)e.all(c,m)};import Cn from"http-errors";import{setInterval as An}from"node:timers/promises";var Wr=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",Yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Xr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),eo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Wr(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",Xr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Qr(c)||Yr(c))&&i(c);for await(let c of An(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(eo))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({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(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Cn(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){ct({response:o,logger:s,error:new ee(re(i),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Nn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await ze("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:Nn(m)})(p,d,c)}),o&&i.push(In(o)),i},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({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[O]={logger:i}),s()},ao=e=>t=>t?.res?.locals[O]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
1
+ import*as L from"ramda";import{z as Y}from"zod/v4";import*as z from"ramda";import{globalRegistry as Bo,z as At}from"zod/v4";var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var de=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},J=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.`}},$e=class extends Error{name="IOSchemaError"},et=class extends $e{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},me=class extends $e{constructor(r){super(te(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends $e{constructor(r){super(te(r),{cause:r});this.cause=r}name="InputValidationError"},ee=class extends Error{constructor(r,o){super(te(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},He=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ct=/:([A-Za-z0-9_]+)/g,tt=e=>e.match(Ct)?.map(t=>t.slice(1))||[],Fo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},It={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Uo=["body","query","params"],Nt=e=>e.method.toLowerCase(),rt=(e,t={})=>{let r=Nt(e);return r==="options"?{}:(t[r]||It[r]||Uo).filter(o=>o==="files"?Fo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},re=e=>e instanceof Error?e:e instanceof At.ZodError?new Error(te(e),{cause:e}):new Error(String(e)),te=e=>e instanceof At.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof me?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,$=(e,t)=>e._zod.def.type===t,ot=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=Bo.get(o)||{};return le(t,n.map(z.objOf(r)),([s,i])=>({...s,...i}))},[]),le=(e,t,r)=>e.length&&t.length?z.xprod(e,t).map(r):e.concat(t),zt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),oe=(...e)=>{let t=z.chain(o=>o.split(/[^A-Z0-9]/gi),e);return z.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(zt).join("")},nt=z.tryCatch((e,t)=>typeof At.parse(e,t),z.always(void 0)),st=({_zod:{optin:e,optout:t}},{isResponse:r})=>(r?t:e)==="optional",j=e=>typeof e=="object"&&e!==null,ue=z.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as gr from"ramda";var Pe=Symbol.for("express-zod-api"),hr=(e,t)=>{let{examples:r=$(e,"object")?ot(e):void 0}=e.meta()||{};if(!r?.length)return t;let{examples:o=[]}=t.meta()||{},n=le(o,r,([s,i])=>typeof s=="object"&&typeof i=="object"&&s&&i?gr.mergeDeepRight(s,i):i);return t.meta({examples:n})},W=e=>{let{brand:t}=e._zod.bag;if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Do=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=()=>{}}),_o=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},Vo=function(){return this.meta({deprecated:!0})},Jo=function(e){return this.meta({default:e})},Go=function(e){return this.check(new Do({brand:e,check:"$EZBrandCheck"}))},Wo=function(e){let t=typeof e=="function"?e:L.pipe(L.toPairs,L.map(([s,i])=>L.pair(e[String(s)]||s,i)),L.fromPairs),r=t(L.map(L.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(!(Pe in globalThis)){globalThis[Pe]=!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:{get(){return _o.bind(this)}},deprecated:{get(){return Vo.bind(this)}},brand:{set(){},get(){return Go.bind(this)}}})}Object.defineProperty(Y.ZodDefault.prototype,"label",{get(){return Jo.bind(this)}}),Object.defineProperty(Y.ZodObject.prototype,"remap",{get(){return Wo.bind(this)}})}function Yo(e){return e}import{z as Lr}from"zod/v4";import*as ke from"ramda";import{z as Nr}from"zod/v4";import*as ie from"ramda";import{z as Er}from"zod/v4";import{z as Ke}from"zod/v4";var fe=Symbol("DateIn"),br=()=>Ke.union([Ke.iso.date(),Ke.iso.datetime(),Ke.iso.datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ke.date()).brand(fe);import{z as Qo}from"zod/v4";var ye=Symbol("DateOut"),xr=()=>Qo.date().transform(e=>e.toISOString()).brand(ye);import{z as Sr}from"zod/v4";var qe=Symbol("Form"),Rr=e=>(e instanceof Sr.ZodObject?e:Sr.object(e)).brand(qe);import{z as Xo}from"zod/v4";var ne=Symbol("Upload"),Or=()=>Xo.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(ne);import{z as tn}from"zod/v4";import{z as it}from"zod/v4";var se=Symbol("File"),Tr=it.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),en={buffer:()=>Tr.brand(se),string:()=>it.string().brand(se),binary:()=>Tr.or(it.string()).brand(se),base64:()=>it.base64().brand(se)};function at(e){return en[e||"string"]()}var H=Symbol("Raw"),Pr=tn.object({raw:at("buffer")}),rn=e=>Pr.extend(e).brand(H);function wr(e){return e?rn(e):Pr.brand(H)}var vr=(e,{io:t,condition:r})=>ie.tryCatch(()=>{Er.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new et(o)}})},o=>o.cause)(),kr=(e,{io:t})=>{let o=[Er.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(ie.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ie.values(n))}ie.is(Array,n)&&o.push(...ie.values(n))}return!1},Ar=e=>vr(e,{condition:t=>{let r=W(t);return typeof r=="symbol"&&[ne,H,qe].includes(r)},io:"input"}),on=["nan","symbol","map","set","bigint","void","promise","never"],jt=(e,t)=>vr(e,{io:t,condition:r=>{let o=W(r),{type:n}=r._zod.def;return!!(on.includes(n)||t==="input"&&(n==="date"||o===ye)||t==="output"&&(o===fe||o===H||o===ne))}});import an,{isHttpError as pn}from"http-errors";import Cr,{isHttpError as nn}from"http-errors";import{z as sn}from"zod/v4";var Lt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof sn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ee(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}))},Be=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>nn(e)?e:Cr(e instanceof G?400:500,te(e),{cause:e.cause||e}),ge=e=>ue()&&!e.expose?Cr(e.statusCode).message:e.message;var pt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ge(an(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:pn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ir}from"zod/v4";var Mt=class{},U=class extends Mt{#e;#t;#r;constructor({input:t=Ir.object({}),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.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Ir.ZodError?new G(o):o}}},Ee=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 Fe=class extends ve{},ct=class e extends Fe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}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.#e.outputSchema}get requestType(){let t=Ar(this.#e.inputSchema);if(t){let r=W(t);if(r===ne)return"upload";if(r===H)return"raw";if(r===qe)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ke.pluck("security",this.#e.middlewares||[]);return ke.reject(ke.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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Nr.ZodError?new me(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ee))&&(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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Nr.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){pt({...t,error:new ee(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=rt(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as zr from"ramda";var jr=(e,t)=>{let r=zr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>hr(s,n),o)};import{globalRegistry as dt,z as K}from"zod/v4";var Ae={positive:200,negative:400},Ce=Object.keys(Ae);var Zt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},he=class extends Zt{#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]})}},be=new he({positive:e=>{let{examples:t=[]}=dt.get(e)||{};!t.length&&$(e,"object")&&t.push(...ot(e)),t.length&&!dt.has(e)&&dt.add(e,{examples:t});let r=K.object({status:K.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},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=we(e);return Be(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ge(i)}})}n.status(Ae.positive).json({status:"success",data:r})}}),$t=new he({positive:e=>{let{examples:t=[]}=dt.get(e)||{},r=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());return t.reduce((o,n)=>j(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:K.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);return Be(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ge(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 xe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof U?t:new U(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new U({handler:t})),this.resultHandler)}build({input:t=Lr.object({}),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,h=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new ct({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:y,methods:m,getOperationId:g,inputSchema:jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Lr.object({}),handler:async o=>(await t(o),{})})}},cn=new xe(be),dn=new xe($t);import hn from"ansis";import{inspect as bn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as mn,green as ln,hex as un,red as fn,cyanBright as yn}from"ansis";import*as Mr from"ramda";var Ht={debug:mn,info:ln,warn:un("#FFA500"),error:fn,ctx:yn},mt={debug:10,info:20,warn:30,error:40},Zr=e=>j(e)&&Object.keys(mt).some(t=>t in e),$r=e=>e in mt,Hr=(e,t)=>mt[e]<mt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ie=Mr.memoizeWith((e,t)=>`${e}${t}`,gn),Kr=e=>e<1e-6?Ie("nanosecond",3).format(e/1e-6):e<.001?Ie("nanosecond").format(e/1e-6):e<1?Ie("microsecond").format(e/.001):e<1e3?Ie("millisecond").format(e):e<6e4?Ie("second",2).format(e/1e3):Ie("minute",2).format(e/6e4);var Ue=class e{config;constructor({color:t=hn.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 bn(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"||Hr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Ht.ctx(s):s),d.push(p?`${Ht[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=qr.now();return()=>{let o=qr.now()-r,{message:n,severity:s="debug",formatter:i=Kr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Br from"ramda";var De=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 xn from"express";var _e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,xn.static(...this.#e))}};import ft from"express";import Ln from"node:http";import Mn from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new He(e)};import En from"http-errors";import{z as Ur}from"zod/v4";import*as S from"ramda";var Sn=e=>e.type==="object",Rn=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),On=S.pipe(Object.keys,S.without(["type","properties","required","examples","description"]),S.isEmpty),Fr=S.pair(!0),ze=(e,t="coerce")=>{let r=[S.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"&&On(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(Fr,i.anyOf)),i.oneOf&&r.push(...S.map(Fr,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(j)||[],i.examples.filter(j),([p,d])=>S.mergeDeepRight(p,d))),!!Sn(i)&&(i.properties&&(o.properties=(t==="throw"?Rn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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};var lt=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=[Ur.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=jt(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=jt(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=tt(t);if(s.length===0)return;let i=n?.flat||ze(Ur.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"],Dr=e=>Kt.includes(e);var Tn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Dr(t)?[r,t]:[e]},Pn=e=>e.trim().split("/").filter(Boolean).join("/"),_r=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Tn(r);return[[t||""].concat(Pn(n)||[]).join("/"),o,s]}),wn=(e,t)=>{throw new de("Route with explicit method can only be assigned with Endpoint",e,t)},Vr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new de(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},qt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new de("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=_r(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Fe)if(p)qt(p,s,n),Vr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)qt(c,s,n),t(i,s,c)}else if(p&&wn(p,s),i instanceof _e)r&&i.apply(s,r);else if(i instanceof De)for(let[d,c]of i.entries){let{methods:m}=c;qt(d,s,n),Vr(d,s,m),t(c,s,d)}else o.unshift(..._r(i,s))}};import*as Jr from"ramda";var Gr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=Gr(e);r.set({Allow:n});let s=En(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Gr(e),"Access-Control-Allow-Headers":"content-type"}),Bt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new lt(t()),i=new Map;je({routing:o,onEndpoint:(c,m,g)=>{ue()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let h=n?.[c.requestType]||[],y=Jr.pair(h,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[h,[y,v]]of m){let k=async(M,R)=>{let A=t(M);if(r.cors){let C=kn(g),F=typeof r.cors=="function"?await r.cors({request:M,endpoint:v,logger:A,defaultHeaders:C}):C;R.set(F)}return v.execute({request:M,response:R,logger:A,config:r})};e[h](c,...y,k)}r.wrongMethodBehavior!==404&&d.set(c,vn(g))}for(let[c,m]of d)e.all(c,m)};import Cn from"http-errors";import{setInterval as An}from"node:timers/promises";var Wr=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",Yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Xr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),eo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Wr(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",Xr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Qr(c)||Yr(c))&&i(c);for await(let c of An(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(eo))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({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(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Cn(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){pt({response:o,logger:s,error:new ee(re(i),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Nn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await Ne("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:Nn(m)})(p,d,c)}),o&&i.push(In(o)),i},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({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[Pe]={logger:i}),s()},ao=e=>t=>t?.res?.locals[Pe]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
3
  `).slice(1))),co=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=to(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let i of o)process.on(i,s)};import{gray as zn,hex as mo,italic as ut,whiteBright as jn}from"ansis";var lo=e=>{if(e.columns<132)return;let t=ut("Proudly supports transgender community.".padStart(109)),r=ut("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=ut("Thank you for choosing Express Zod API for your project.".padStart(132)),n=ut("for Ashley".padEnd(20)),s=mo("#F5A9B8"),i=mo("#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(zn,12,13),d=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
@@ -15,9 +15,9 @@ ${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 uo=e=>{e.startupLogo!==!1&&lo(process.stdout);let t=e.errorHandler||xe,r=Zr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v24.0.0-beta.1 (ESM)",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},i=oo(s),p=ro(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=uo(e);return qt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},$n=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=uo(e),p=ft().disable("x-powered-by").use(i);if(e.compression){let h=await ze("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||ft.json()],raw:[e.rawParser||ft.raw(),so],form:[e.formParser||ft.urlencoded()],upload:e.upload?await no({config:e,getLogger:o}):[]};qt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,y)=>()=>h.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let h=Mn.createServer(p);c.push(h),g.push(m(h,e.http.listen))}if(e.https){let h=Ln.createServer(e.https.options,p);c.push(h),g.push(m(h,e.https.listen))}return e.gracefulShutdown&&co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(h=>h())}};import{OpenApiBuilder as us}from"openapi3-ts/oas31";import*as zo from"ramda";import*as x from"ramda";var fo=e=>M(e)&&"or"in e,yo=e=>M(e)&&"and"in e,Bt=e=>!yo(e)&&!fo(e),go=e=>{let t=x.filter(Bt,e),r=x.chain(x.prop("and"),x.filter(yo,e)),[o,n]=x.partition(Bt,r),s=x.concat(t,o),i=x.filter(fo,e);return x.map(x.prop("or"),x.concat(i,n)).reduce((d,c)=>ue(d,x.map(m=>Bt(m)?[m]:m.and,c),([m,g])=>x.concat(m,g)),x.reject(x.isEmpty,[s]))};import{isReferenceObject as Ro,isSchemaObject as yt}from"openapi3-ts/oas31";import*as l from"ramda";import{globalRegistry as Kn,z as bo}from"zod/v4";var ho=["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 xo=50,Oo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",To={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Po=e=>e.replace(At,t=>`{${t.slice(1)}}`),qn=({zodSchema:e,jsonSchema:t})=>{let r=Kn.get(e)?.[O]?.defaultLabel??t.default;return{...t,default:typeof r=="bigint"?String(r):r}},Bn=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Fn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),Dn=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Un=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return je(e,"throw")},(e,{jsonSchema:t})=>t),Vn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ts(t.type)})},So=e=>e in To,_n=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Jn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Gn=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{if(r||!oe(e,"object"))return t;let{required:o=[]}=t,n=[];for(let s of o){let i=e._zod.def.shape[s];i&&!it(i,{isResponse:r})&&n.push(s)}return{...t,required:n}},Re=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(So):t&&So(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(Re));return s&&(p.not=Re(s)),p},Wn=({},e)=>{if(e.isResponse)throw new J("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Oo}}},Yn=({},e)=>{if(!e.isResponse)throw new J("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Oo}}},Qn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Xn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},es=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},ts=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],rs=({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=Re(Ut(n,{ctx:r}));if(yt(s))if(r.isResponse){let i=st(o,es(s));if(i&&["number","string","boolean"].includes(i))return{type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},os=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},Ft=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ns=(e,t)=>t?.includes(e)||e.startsWith("x-")||ho.includes(e),wo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=je(r),m=ot(e),g=o.includes("query"),h=o.includes("params"),y=o.includes("headers"),k=R=>h&&m.includes(R),A=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),Z=R=>y&&(i?.(R,t,e)??ns(R,A));return Object.entries(c.properties).reduce((R,[C,I])=>{let F=k(C)?"path":Z(C)?"header":g?"query":void 0;if(!F)return R;let z=Re(I),Q=s==="components"?n(I,z,ne(d,C)):z;return R.concat({name:C,in:F,deprecated:I.deprecated,required:c.required?.includes(C)||!1,description:z.description||d,schema:Q,examples:Ft(yt(z)&&z.examples?.length?z.examples:l.pluck(C,c.examples?.filter(l.both(M,l.has(C)))||[]))})},[])},Dt={nullable:Vn,default:qn,union:Dn,bigint:Qn,intersection:Un,tuple:Xn,pipe:rs,literal:Jn,enum:_n,object:Gn,[ye]:Wn,[ge]:Yn,[se]:Bn,[ie]:Fn,[H]:os},ss=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{let o={...t},n=we({schema:e,variant:r?"parsed":"original",validate:!0,pullProps:!0});return n.length&&(o.examples=n.slice()),o},is=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(Ro(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,Re(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Ut=(e,{ctx:t,rules:r=Dt})=>{let{$defs:o={},properties:n={}}=bo.toJSONSchema(bo.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)}Object.assign(s.jsonSchema,ss(s,t))}});return is(n.subject,o,t)},Eo=(e,t)=>{if(Ro(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Eo(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]},vo=({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} ${Nt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Re(Ut(r,{rules:{...c,...Dt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];yt(g)&&g.examples&&(h.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,ne(m)):g,examples:Ft(h)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},as=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ps=({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},cs=({name:e})=>({type:"apiKey",in:"header",name:e}),ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ms=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ls=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),ko=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?as(o):o.type==="input"?ps(o,t):o.type==="header"?cs(o):o.type==="cookie"?ds(o):o.type==="openid"?ms(o):ls(o);return e.map(o=>o.map(r))},Ao=(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:[]})},{})),Co=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Ut(e,{rules:{...t,...Dt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Io=({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]=Eo(Re(o),p),g=[];yt(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,ne(d)):c,examples:Ft(g.length?g:je(o).examples?.filter(k=>M(k)&&!Array.isArray(k)).map(l.omit(p))||[])},y={description:d,content:{[n]:h}};return(m||n===E.raw)&&(y.required=!0),y},No=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)},[]),Vt=e=>e.length<=xo?e:e.slice(0,xo-1)+"\u2026",gt=e=>e.length?e.slice():void 0;var _t=class extends us{#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 J(`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});Me({routing:t,onEndpoint:(y,k,A)=>{let Z={path:k,method:A,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:C,scopes:I,inputSchema:F}=y,z=C?Vt(C):m&&R?Vt(R):void 0,Q=r.inputSources?.[A]||Ct[A],Pe=this.#n(k,A,y.getOperationId(A)),We=Co({...Z,schema:F}),ce=go(y.security),Ye=wo({...Z,inputSources:Q,isHeader:c,security:ce,request:We,description:i?.requestParameter?.call(null,{method:A,path:k,operationId:Pe})}),Qe={};for(let X of Ie){let de=y.getResponses(X);for(let{mimeTypes:et,schema:vt,statusCodes:fr}of de)for(let kt of fr)Qe[kt]=vo({...Z,variant:X,schema:vt,mimeTypes:et,statusCode:kt,hasMultipleStatusCodes:de.length>1||fr.length>1,description:i?.[`${X}Response`]?.call(null,{method:A,path:k,operationId:Pe,statusCode:kt})})}let Xe=Q.includes("body")?Io({...Z,request:We,paramNames:zo.pluck("name",Ye),schema:F,mimeType:E[y.requestType],description:i?.requestBody?.call(null,{method:A,path:k,operationId:Pe})}):void 0,wt=Ao(ko(ce,Q),I,X=>{let de=this.#s(X);return this.addSecurityScheme(de,X),de}),Et={operationId:Pe,summary:z,description:R,deprecated:y.isDeprecated||void 0,tags:gt(y.tags),parameters:gt(Ye),requestBody:Xe,security:gt(wt),responses:Qe};this.addPath(Po(k),{[A]:Et})}}),d&&(this.rootDoc.tags=No(d))}};import{createRequest as fs,createResponse as ys}from"node-mocks-http";var gs=e=>fs({...e,headers:{"content-type":E.json,...e?.headers}}),hs=e=>ys(e),bs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:$r(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=gs(e),s=hs({req:n,...t});s.req=t?.req||n,n.res=s;let i=bs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},xs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Ss=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=xe}}=jo(r),d=nt(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 Ho from"ramda";import Pt from"typescript";import{z as Ds}from"zod/v4";import*as $o from"ramda";import _ from"typescript";import*as U from"ramda";import u from"typescript";var a=u.factory,ht=[a.createModifier(u.SyntaxKind.ExportKeyword)],Rs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Je={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Jt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Gt=(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)},Os=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Wt=e=>typeof e=="string"&&Os.test(e)?a.createIdentifier(e):w(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)))),xt=(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),Le=e=>Object.entries(e).map(([t,r])=>xt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Yt=(e,t=[])=>a.createConstructorDeclaration(Je.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&U.map(f,t)):e,Qt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Wt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=U.reject(U.isNil,[o?"@deprecated":void 0,n]);return p.length?Jt(i,p.join(" ")):i},Xt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),er=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),N=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&ht,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),tr=(e,t)=>V(e,a.createUnionTypeNode(U.map($,t)),{expose:!0}),V=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?ht:void 0,e,n&&sr(n),t);return o?Jt(s,o):s},Mo=(e,t)=>a.createPropertyDeclaration(Je.public,e,void 0,f(t),void 0),rr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Je.public,void 0,e,void 0,o&&sr(o),t,n,a.createBlock(r)),or=(e,t,{typeParams:r}={})=>a.createClassDeclaration(ht,e,r&&sr(r),void 0,t),nr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),St=e=>f(Promise.name,[e]),Rt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?ht:void 0,e,void 0,void 0,t);return o?Jt(n,o):n},sr=e=>(Array.isArray(e)?e.map(t=>U.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?Rs:void 0,void 0,Array.isArray(e)?U.map(xt,e):Le(e),void 0,void 0,t),T=e=>e,Ge=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),P=(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),Ze=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ot=(e,t)=>f("Extract",[e,t]),ir=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),q=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Lo=e=>a.createUnionTypeNode([f(e),St(e)]),ar=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),w=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(w(e)),Ts=[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],Zo=e=>Ts.includes(e.kind);var Tt=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=tr("Method",Ht);someOfType=V("SomeOf",q("T",nr("T")),{params:["T"]});requestType=V("Request",nr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>tr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Rt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>N("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Wt(t),a.createArrayLiteralExpression($o.map(w,r))))),{expose:!0});makeImplementationType=()=>V(this.#e.implementationType,ar({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Qt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},St(_.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:_.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.#e.parseRequestFn,Te({[this.#e.requestParameter.text]:_.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),w(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>N(this.#e.substituteFn,Te({[this.#e.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Qt},a.createBlock([N(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],_.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([ir(this.#e.pathParameter,P(this.#e.pathParameter,T("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=()=>rr(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[N(er(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:St(q(this.interfaces.response,"K"))});makeClientClass=t=>or(t,[Yt([xt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Je.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>bt("?",[Ze(URLSearchParams.name,t)]);#o=()=>Ze(URL.name,bt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),Ge(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),Ge(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=N(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=N(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=N(this.#e.searchParamsConst,Ge(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=N(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(_.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=N(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(w(E.json))),m=a.createReturnStatement(P(this.#e.responseConst,Ge(this.#e.isJsonConst,w(T("json")),w(T("text"))))());return N(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=()=>Yt(Le({request:"K",params:q(this.interfaces.input,"K")}),[N(er(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),N(this.#e.searchParamsConst,this.#r(this.#e.restConst)),ir(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Ze("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Oe(T("event"),t)]);#i=()=>rr(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:ar({[this.#e.dataParameter.text]:q(Ot("R",Xt(this.#s("E"))),$(T("data")))},Lo(_.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Te([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:q("R",$(T("event")))}});makeSubscriptionClass=t=>or(t,[Mo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ot(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(_.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ot(q(this.interfaces.positive,"K"),Xt(this.#s(_.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.#e.clientConst,Ze(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Ze(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),Te(["time"],a.createBlock([])))]};import*as v from"ramda";import b from"typescript";import{globalRegistry as Ps}from"zod/v4";var pr=(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=>pr(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:B}=b,ws={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},cr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Es=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(b.SyntaxKind.UndefinedKeyword):$(r));return t.length===1?t[0]:B.createUnionTypeNode(t)},vs=(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}=Ps.get(p)||{};return Oe(i,r(p),{comment:d,isDeprecated:c,isOptional:it(p,{isResponse:t})})});return B.createTypeLiteralNode(s)};return kr(e,{io:t?"output":"input"})?o(e,n):n()},ks=({_zod:{def:e}},{next:t})=>B.createArrayTypeNode(t(e.element)),As=({_zod:{def:e}})=>B.createUnionTypeNode(Object.values(e.entries).map($)),Cs=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(Zo(n)?n.kind:n,n)}return B.createUnionTypeNode(Array.from(r.values()))},Is=e=>ws?.[e.kind],Ns=({_zod:{def:e}},{next:t})=>t(e.innerType),zs=({_zod:{def:e}},{next:t})=>B.createUnionTypeNode([t(e.innerType),$(null)]),js=({_zod:{def:e}},{next:t})=>B.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:B.createRestTypeNode(t(e.rest)))),Ms=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ls=v.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(cr.name,...o))return!1;if(v.both(v.eqBy(cr.type),v.eqBy(cr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return B.createTypeLiteralNode(r)},(e,t)=>B.createIntersectionTypeNode(t)),Zs=({_zod:{def:e}},{next:t})=>Ls([e.left,e.right].map(t)),pe=e=>()=>f(e),dr=({_zod:{def:e}},{next:t})=>t(e.innerType),$s=({_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=st(o,Is(s)),p={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(i&&p[i]||b.SyntaxKind.AnyKeyword)},Hs=()=>$(null),Ks=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),qs=e=>{let t=f(b.SyntaxKind.StringKeyword),r=f("Buffer"),o=B.createUnionTypeNode([t,r]);return oe(e,"string")?t:oe(e,"union")?o:r},Bs=(e,{next:t})=>t(e._zod.def.shape.raw),Fs={string:pe(b.SyntaxKind.StringKeyword),number:pe(b.SyntaxKind.NumberKeyword),bigint:pe(b.SyntaxKind.BigIntKeyword),boolean:pe(b.SyntaxKind.BooleanKeyword),any:pe(b.SyntaxKind.AnyKeyword),undefined:pe(b.SyntaxKind.UndefinedKeyword),[ye]:pe(b.SyntaxKind.StringKeyword),[ge]:pe(b.SyntaxKind.StringKeyword),null:Hs,array:ks,tuple:js,record:Ms,object:vs,literal:Es,intersection:Zs,union:Cs,default:dr,enum:As,optional:Ns,nullable:zs,catch:dr,pipe:$s,lazy:Ks,readonly:dr,[ie]:qs,[H]:Bs},mr=(e,{brandHandling:t,ctx:r})=>pr(e,{rules:{...t,...Fs},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var lr=class extends Tt{#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=Ds.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};Me({routing:t,onEndpoint:(h,y,k)=>{let A=ne.bind(null,k,y),{isDeprecated:Z,inputSchema:R,tags:C}=h,I=`${k} ${y}`,F=V(A("input"),mr(R,c),{comment:I});this.#e.push(F);let z=Ie.reduce((We,ce)=>{let Ye=h.getResponses(ce),Qe=Ho.chain(([wt,{schema:Et,mimeTypes:X,statusCodes:de}])=>{let et=V(A(ce,"variant",`${wt+1}`),mr(X?Et:p,m),{comment:I});return this.#e.push(et),de.map(vt=>Oe(vt,et.name))},Array.from(Ye.entries())),Xe=Rt(A(ce,"response","variants"),Qe,{comment:I});return this.#e.push(Xe),Object.assign(We,{[ce]:Xe})},{});this.paths.add(y);let Q=$(I),Pe={input:f(F.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:a.createUnionTypeNode([q(this.interfaces.positive,Q),q(this.interfaces.negative,Q)]),encoded:a.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(I,{isDeprecated:Z,store:Pe}),this.tags.set(I,C)}}),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:Gt(r,t)).join(`
18
+ `))};var uo=e=>{e.startupLogo!==!1&&lo(process.stdout);let t=e.errorHandler||be,r=Zr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v24.0.0-beta.2 (ESM)",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},i=oo(s),p=ro(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=uo(e);return Bt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},$n=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=uo(e),p=ft().disable("x-powered-by").use(i);if(e.compression){let h=await Ne("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||ft.json()],raw:[e.rawParser||ft.raw(),so],form:[e.formParser||ft.urlencoded()],upload:e.upload?await no({config:e,getLogger:o}):[]};Bt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,y)=>()=>h.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let h=Ln.createServer(p);c.push(h),g.push(m(h,e.http.listen))}if(e.https){let h=Mn.createServer(e.https.options,p);c.push(h),g.push(m(h,e.https.listen))}return e.gracefulShutdown&&co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(h=>h())}};import{OpenApiBuilder as ms}from"openapi3-ts/oas31";import*as zo from"ramda";import*as x from"ramda";var fo=e=>j(e)&&"or"in e,yo=e=>j(e)&&"and"in e,Ft=e=>!yo(e)&&!fo(e),go=e=>{let t=x.filter(Ft,e),r=x.chain(x.prop("and"),x.filter(yo,e)),[o,n]=x.partition(Ft,r),s=x.concat(t,o),i=x.filter(fo,e);return x.map(x.prop("or"),x.concat(i,n)).reduce((d,c)=>le(d,x.map(m=>Ft(m)?[m]:m.and,c),([m,g])=>x.concat(m,g)),x.reject(x.isEmpty,[s]))};import{isReferenceObject as Ro,isSchemaObject as yt}from"openapi3-ts/oas31";import*as l from"ramda";import{globalRegistry as Kn,z as bo}from"zod/v4";var ho=["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 xo=50,Oo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",To={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Po=e=>e.replace(Ct,t=>`{${t.slice(1)}}`),qn=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Bn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),Fn=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Un=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:es(t.type)})},So=e=>e in To,_n=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Vn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Jn=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{if(r||!$(e,"object"))return t;let{required:o=[]}=t,n=[];for(let s of o){let i=e._zod.def.shape[s];i&&!st(i,{isResponse:r})&&n.push(s)}return{...t,required:n}},Se=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(So):t&&So(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(Se));return s&&(p.not=Se(s)),p},Gn=({zodSchema:e},t)=>{if(t.isResponse)throw new J("Please use ez.dateOut() for output.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Oo}},o=Kn.get(e)?.examples?.filter(n=>n instanceof Date).map(n=>n.toISOString());return o?.length&&(r.examples=o),r},Wn=({jsonSchema:{examples:e}},t)=>{if(!t.isResponse)throw new J("Please use ez.dateIn() for input.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Oo}};return e?.length&&(r.examples=e),r},Yn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Qn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Xn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},es=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ts=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!$(o,"transform"))return t;let s=Se(_t(n,{ctx:r}));if(yt(s))if(r.isResponse){let i=nt(o,Xn(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},rs=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},Ut=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,os=(e,t)=>t?.includes(e)||e.startsWith("x-")||ho.includes(e),wo=({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=tt(e),g=o.includes("query"),h=o.includes("params"),y=o.includes("headers"),v=R=>h&&m.includes(R),k=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),M=R=>y&&(i?.(R,t,e)??os(R,k));return Object.entries(c.properties).reduce((R,[A,C])=>{let F=v(A)?"path":M(A)?"header":g?"query":void 0;if(!F)return R;let N=Se(C),Q=s==="components"?n(C,N,oe(d,A)):N;return R.concat({name:A,in:F,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:Q,examples:Ut(yt(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(j,l.has(A)))||[]))})},[])},Dt={nullable:Dn,union:Fn,bigint:Yn,intersection:Un,tuple:Qn,pipe:ts,literal:Vn,enum:_n,object:Jn,[fe]:Gn,[ye]:Wn,[ne]:qn,[se]:Bn,[H]:rs},ns=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(Ro(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,Se(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=Dt})=>{let{$defs:o={},properties:n={}}=bo.toJSONSchema(bo.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 ns(n.subject,o,t)},Eo=(e,t)=>{if(Ro(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Eo(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]},vo=({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} ${zt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Se(_t(r,{rules:{...c,...Dt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];yt(g)&&g.examples&&(h.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,oe(m)):g,examples:Ut(h)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},ss=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},is=({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},as=({name:e})=>({type:"apiKey",in:"header",name:e}),ps=({name:e})=>({type:"apiKey",in:"cookie",name:e}),cs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ds=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),ko=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ss(o):o.type==="input"?is(o,t):o.type==="header"?as(o):o.type==="cookie"?ps(o):o.type==="openid"?cs(o):ds(o);return e.map(o=>o.map(r))},Ao=(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:[]})},{})),Co=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>_t(e,{rules:{...t,...Dt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Io=({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]=Eo(Se(o),p),g=[];yt(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,oe(d)):c,examples:Ut(g.length?g:ze(o).examples?.filter(v=>j(v)&&!Array.isArray(v)).map(l.omit(p))||[])},y={description:d,content:{[n]:h}};return(m||n===w.raw)&&(y.required=!0),y},No=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)},[]),Vt=e=>e.length<=xo?e:e.slice(0,xo-1)+"\u2026",gt=e=>e.length?e.slice():void 0;var Jt=class extends ms{#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||oe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new J(`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});je({routing:t,onEndpoint:(y,v,k)=>{let M={path:v,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:A,scopes:C,inputSchema:F}=y,N=A?Vt(A):m&&R?Vt(R):void 0,Q=r.inputSources?.[k]||It[k],Te=this.#n(v,k,y.getOperationId(k)),Ge=Co({...M,schema:F}),pe=go(y.security),We=wo({...M,inputSources:Q,isHeader:c,security:pe,request:Ge,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Te})}),Ye={};for(let X of Ce){let ce=y.getResponses(X);for(let{mimeTypes:Xe,schema:vt,statusCodes:yr}of ce)for(let kt of yr)Ye[kt]=vo({...M,variant:X,schema:vt,mimeTypes:Xe,statusCode:kt,hasMultipleStatusCodes:ce.length>1||yr.length>1,description:i?.[`${X}Response`]?.call(null,{method:k,path:v,operationId:Te,statusCode:kt})})}let Qe=Q.includes("body")?Io({...M,request:Ge,paramNames:zo.pluck("name",We),schema:F,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Te})}):void 0,wt=Ao(ko(pe,Q),C,X=>{let ce=this.#s(X);return this.addSecurityScheme(ce,X),ce}),Et={operationId:Te,summary:N,description:R,deprecated:y.isDeprecated||void 0,tags:gt(y.tags),parameters:gt(We),requestBody:Qe,security:gt(wt),responses:Ye};this.addPath(Po(v),{[k]:Et})}}),d&&(this.rootDoc.tags=No(d))}};import{createRequest as ls,createResponse as us}from"node-mocks-http";var fs=e=>ls({...e,headers:{"content-type":w.json,...e?.headers}}),ys=e=>us(e),gs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:$r(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=fs(e),s=ys({req:n,...t});s.req=t?.req||n,n.res=s;let i=gs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},hs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},bs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=jo(r),d=rt(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 Ho from"ramda";import Pt from"typescript";import{z as Bs}from"zod/v4";import*as $o from"ramda";import V from"typescript";import*as D from"ramda";import u from"typescript";var a=u.factory,ht=[a.createModifier(u.SyntaxKind.ExportKeyword)],xs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ve={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)},Ss=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yt=e=>typeof e=="string"&&Ss.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)))),xt=(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),Le=e=>Object.entries(e).map(([t,r])=>xt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Qt=(e,t=[])=>a.createConstructorDeclaration(Ve.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&D.map(f,t)):e,Xt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(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?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=D.reject(D.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))),I=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&ht,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),rr=(e,t)=>_(e,a.createUnionTypeNode(D.map(Z,t)),{expose:!0}),_=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?ht:void 0,e,n&&ir(n),t);return o?Gt(s,o):s},Lo=(e,t)=>a.createPropertyDeclaration(Ve.public,e,void 0,f(t),void 0),or=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ve.public,void 0,e,void 0,o&&ir(o),t,n,a.createBlock(r)),nr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(ht,e,r&&ir(r),void 0,t),sr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),St=e=>f(Promise.name,[e]),Rt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?ht:void 0,e,void 0,void 0,t);return o?Gt(n,o):n},ir=e=>(Array.isArray(e)?e.map(t=>D.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)}),Oe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?D.map(xt,e):Le(e),void 0,void 0,t),O=e=>e,Je=(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),Ot=(e,t)=>f("Extract",[e,t]),ar=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),q=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Mo=e=>a.createUnionTypeNode([f(e),St(e)]),pr=(e,t)=>a.createFunctionTypeNode(void 0,Le(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),Z=e=>a.createLiteralTypeNode(P(e)),Rs=[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],Zo=e=>Rs.includes(e.kind);var Tt=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=_("SomeOf",q("T",sr("T")),{params:["T"]});requestType=_("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=>Rt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>I("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Yt(t),a.createArrayLiteralExpression($o.map(P,r))))),{expose:!0});makeImplementationType=()=>_(this.#e.implementationType,pr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},St(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>I(this.#e.parseRequestFn,Oe({[this.#e.requestParameter.text]:V.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=()=>I(this.#e.substituteFn,Oe({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt},a.createBlock([I(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],V.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([ar(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(bt(":",[this.#e.keyParameter]),Oe([],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,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[I(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:St(q(this.interfaces.response,"K"))});makeClientClass=t=>nr(t,[Qt([xt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ve.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"),Je(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Je(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=I(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=I(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=I(this.#e.searchParamsConst,Je(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=I(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=I(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,Je(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return I(this.#e.defaultImplementationConst,Oe([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(Le({request:"K",params:q(this.interfaces.input,"K")}),[I(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)),I(this.#e.searchParamsConst,this.#r(this.#e.restConst)),ar(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Re(O("event"),t)]);#i=()=>or(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:pr({[this.#e.dataParameter.text]:q(Ot("R",er(this.#s("E"))),Z(O("data")))},Mo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Oe([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:q("R",Z(O("event")))}});makeSubscriptionClass=t=>nr(t,[Lo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ot(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ot(q(this.interfaces.positive,"K"),er(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[I(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"),Oe(["time"],a.createBlock([])))]};import*as E from"ramda";import b from"typescript";import{globalRegistry as Os}from"zod/v4";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:B}=b,Ts={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},dr={name:E.path(["name","text"]),type:E.path(["type"]),optional:E.path(["questionToken"])},Ps=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(b.SyntaxKind.UndefinedKeyword):Z(r));return t.length===1?t[0]:B.createUnionTypeNode(t)},ws=(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}=Os.get(p)||{};return Re(i,r(p),{comment:d,isDeprecated:c,isOptional:st(p,{isResponse:t})})});return B.createTypeLiteralNode(s)};return kr(e,{io:t?"output":"input"})?o(e,n):n()},Es=({_zod:{def:e}},{next:t})=>B.createArrayTypeNode(t(e.element)),vs=({_zod:{def:e}})=>B.createUnionTypeNode(Object.values(e.entries).map(Z)),ks=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(Zo(n)?n.kind:n,n)}return B.createUnionTypeNode(Array.from(r.values()))},As=e=>Ts?.[e.kind],Cs=({_zod:{def:e}},{next:t})=>t(e.innerType),Is=({_zod:{def:e}},{next:t})=>B.createUnionTypeNode([t(e.innerType),Z(null)]),Ns=({_zod:{def:e}},{next:t})=>B.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:B.createRestTypeNode(t(e.rest)))),zs=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),js=E.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=E.chain(E.prop("members"),e),r=E.uniqWith((...o)=>{if(!E.eqBy(dr.name,...o))return!1;if(E.both(E.eqBy(dr.type),E.eqBy(dr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return B.createTypeLiteralNode(r)},(e,t)=>B.createIntersectionTypeNode(t)),Ls=({_zod:{def:e}},{next:t})=>js([e.left,e.right].map(t)),ae=e=>()=>f(e),mr=({_zod:{def:e}},{next:t})=>t(e.innerType),Ms=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!$(o,"transform"))return t(o);let s=t(n),i=nt(o,As(s)),p={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(i&&p[i]||b.SyntaxKind.AnyKeyword)},Zs=()=>Z(null),$s=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Hs=e=>{let t=f(b.SyntaxKind.StringKeyword),r=f("Buffer"),o=B.createUnionTypeNode([t,r]);return $(e,"string")?t:$(e,"union")?o:r},Ks=(e,{next:t})=>t(e._zod.def.shape.raw),qs={string:ae(b.SyntaxKind.StringKeyword),number:ae(b.SyntaxKind.NumberKeyword),bigint:ae(b.SyntaxKind.BigIntKeyword),boolean:ae(b.SyntaxKind.BooleanKeyword),any:ae(b.SyntaxKind.AnyKeyword),undefined:ae(b.SyntaxKind.UndefinedKeyword),[fe]:ae(b.SyntaxKind.StringKeyword),[ye]:ae(b.SyntaxKind.StringKeyword),null:Zs,array:Es,tuple:Ns,record:zs,object:ws,literal:Ps,intersection:Ls,union:ks,default:mr,enum:vs,optional:Cs,nullable:Is,catch:mr,pipe:Ms,lazy:$s,readonly:mr,[se]:Hs,[H]:Ks},lr=(e,{brandHandling:t,ctx:r})=>cr(e,{rules:{...t,...qs},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var ur=class extends Tt{#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=Z(null);this.#t.set(t,_(o,n)),this.#t.set(t,_(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}};je({routing:t,onEndpoint:(h,y,v)=>{let k=oe.bind(null,v,y),{isDeprecated:M,inputSchema:R,tags:A}=h,C=`${v} ${y}`,F=_(k("input"),lr(R,c),{comment:C});this.#e.push(F);let N=Ce.reduce((Ge,pe)=>{let We=h.getResponses(pe),Ye=Ho.chain(([wt,{schema:Et,mimeTypes:X,statusCodes:ce}])=>{let Xe=_(k(pe,"variant",`${wt+1}`),lr(X?Et:p,m),{comment:C});return this.#e.push(Xe),ce.map(vt=>Re(vt,Xe.name))},Array.from(We.entries())),Qe=Rt(k(pe,"response","variants"),Ye,{comment:C});return this.#e.push(Qe),Object.assign(Ge,{[pe]:Qe})},{});this.paths.add(y);let Q=Z(C),Te={input:f(F.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([q(this.interfaces.positive,Q),q(this.interfaces.negative,Q)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:M,store:Te}),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&&Pt.addSyntheticLeadingComment(Pt.addSyntheticLeadingComment(a.createEmptyStatement(),Pt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Pt.SyntaxKind.MultiLineCommentTrivia,`
20
- ${r}`);return this.#e.concat(o||[]).map((n,s)=>Gt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
20
+ ${r}`);return this.#e.concat(o||[]).map((n,s)=>Wt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
22
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await ze("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};import{z as $e}from"zod/v4";var qo=(e,t)=>$e.object({data:t,event:$e.literal(e),id:$e.string().optional(),retry:$e.int().positive().optional()}),Us=(e,t,r)=>qo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),Vs=1e4,Ko=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),_s=e=>new D({handler:async({response:t})=>setTimeout(()=>Ko(t),Vs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Ko(t),t.write(Us(e,r,o),"utf-8"),t.flush?.()}}}),Js=e=>new be({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>qo(o,n));return{mimeType:E.sse,schema:r.length?$e.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:$e.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);Fe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(he(i),"utf-8")}t.end()}}),ur=class extends Se{constructor(t){super(Js(t)),this.middlewares=[_s(t)]}};var Gs={dateIn:br,dateOut:xr,form:Rr,file:pt,upload:Or,raw:wr};export{Ue as BuiltinLogger,Ve as DependsOnMethod,_t as Documentation,J as DocumentationError,Se as EndpointsFactory,ur as EventStreamFactory,G as InputValidationError,lr as Integration,D as Middleware,Ke as MissingPeerError,le as OutputValidationError,be as ResultHandler,me as RoutingError,_e as ServeStatic,dn as arrayEndpointsFactory,Zt as arrayResultHandler,Zn as attachRouting,Yo as createConfig,$n as createServer,cn as defaultEndpointsFactory,xe as defaultResultHandler,Ee as ensureHttpError,Gs as ez,we as getExamples,te as getMessageFromError,xs as testEndpoint,Ss as testMiddleware};
22
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Ne("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};import{z as Ze}from"zod/v4";var qo=(e,t)=>Ze.object({data:t,event:Ze.literal(e),id:Ze.string().optional(),retry:Ze.int().positive().optional()}),Fs=(e,t,r)=>qo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),Us=1e4,Ko=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":w.sse,"cache-control":"no-cache"}),Ds=e=>new U({handler:async({response:t})=>setTimeout(()=>Ko(t),Us)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Ko(t),t.write(Fs(e,r,o),"utf-8"),t.flush?.()}}}),_s=e=>new he({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>qo(o,n));return{mimeType:w.sse,schema:r.length?Ze.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);Be(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ge(i),"utf-8")}t.end()}}),fr=class extends xe{constructor(t){super(_s(t)),this.middlewares=[Ds(t)]}};var Vs={dateIn:br,dateOut:xr,form:Rr,file:at,upload:Or,raw:wr};export{Ue as BuiltinLogger,De as DependsOnMethod,Jt as Documentation,J as DocumentationError,xe as EndpointsFactory,fr as EventStreamFactory,G as InputValidationError,ur as Integration,U as Middleware,He as MissingPeerError,me as OutputValidationError,he as ResultHandler,de as RoutingError,_e as ServeStatic,dn as arrayEndpointsFactory,$t as arrayResultHandler,Zn as attachRouting,Yo as createConfig,$n as createServer,cn as defaultEndpointsFactory,be as defaultResultHandler,we as ensureHttpError,Vs as ez,te as getMessageFromError,hs as testEndpoint,bs as testMiddleware};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "24.0.0-beta.1",
3
+ "version": "24.0.0-beta.2",
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": {