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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -13,9 +13,15 @@
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
+ - The transforming proprietary schemas `ez.dateIn()` and `ez.dateOut()` now accept metadata as its argument:
23
+ - This allows to set examples before transformation (`ez.dateIn()`) and to avoid the examples "branding";
24
+ - Generating Documentation is mostly delegated to Zod 4 `z.toJSONSchema()`:
19
25
  - The basic depiction of each schema is now natively performed by Zod 4;
20
26
  - Express Zod API implements some overrides and improvements to fit it into OpenAPI 3.1 that extends JSON Schema;
21
27
  - The `numericRange` option removed from `Documentation` class constructor argument;
@@ -26,6 +32,7 @@
26
32
  - Use `.or(z.undefined())` to add `undefined` to the type of the object property;
27
33
  - Reasoning: https://x.com/colinhacks/status/1919292504861491252;
28
34
  - `z.any()` and `z.unknown()` are not optional, details: https://v4.zod.dev/v4/changelog#changes-zunknown-optionality.
35
+ - The `getExamples()` public helper removed — use `.meta()?.examples` instead;
29
36
  - Consider the automated migration using the built-in ESLint rule.
30
37
 
31
38
  ```js
@@ -44,6 +51,19 @@ export default [
44
51
  + import { z } from "zod/v4";
45
52
  ```
46
53
 
54
+ ```diff
55
+ z.string()
56
+ + .example("123")
57
+ .transform(Number)
58
+ - .example("123")
59
+ + .example(123)
60
+ ```
61
+
62
+ ```diff
63
+ - ez.dateIn().example("2021-12-31");
64
+ + ez.dateIn({ examples: ["2021-12-31"] });
65
+ ```
66
+
47
67
  ## Version 23
48
68
 
49
69
  ### v23.5.0
package/README.md CHANGED
@@ -561,7 +561,7 @@ in actual response by calling
561
561
  which in turn calls
562
562
  [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString).
563
563
  It is also impossible to transmit the `Date` in its original form to your endpoints within JSON. Therefore, there is
564
- confusion with original method ~~z.date()~~ that should not be used within IO schemas of your API.
564
+ confusion with original method ~~z.date()~~ that is not recommended to use without transformations.
565
565
 
566
566
  In order to solve this problem, the framework provides two custom methods for dealing with dates: `ez.dateIn()` and
567
567
  `ez.dateOut()` for using within input and output schemas accordingly.
@@ -577,7 +577,7 @@ provides your endpoint handler or middleware with a `Date`. It supports the foll
577
577
  ```
578
578
 
579
579
  `ez.dateOut()`, on the contrary, accepts a `Date` and provides `ResultHandler` with a `string` representation in ISO
580
- format for the response transmission. Consider the following simplified example for better understanding:
580
+ format for the response transmission. Both schemas accept metadata as an argument. Consider the following example:
581
581
 
582
582
  ```typescript
583
583
  import { z } from "zod/v4";
@@ -587,10 +587,10 @@ const updateUserEndpoint = defaultEndpointsFactory.build({
587
587
  method: "post",
588
588
  input: z.object({
589
589
  userId: z.string(),
590
- birthday: ez.dateIn(), // string -> Date in handler
590
+ birthday: ez.dateIn({ examples: ["1963-04-21"] }), // string -> Date in handler
591
591
  }),
592
592
  output: z.object({
593
- createdAt: ez.dateOut(), // Date -> string in response
593
+ createdAt: ez.dateOut({ examples: ["2021-12-31"] }), // Date -> string in response
594
594
  }),
595
595
  handler: async ({ input }) => ({
596
596
  createdAt: new Date("2022-01-22"), // 2022-01-22T00:00:00.000Z
@@ -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 un=Object.create;var pt=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,hn=Object.prototype.hasOwnProperty;var bn=(e,t)=>{for(var r in t)pt(e,r,{get:t[r],enumerable:!0})},kr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of yn(t))!hn.call(e,n)&&n!==r&&pt(e,n,{get:()=>t[n],enumerable:!(o=fn(t,n))||o.enumerable});return e};var y=(e,t,r)=>(r=e!=null?un(gn(e)):{},kr(t||!e||!e.__esModule?pt(r,"default",{value:e,enumerable:!0}):r,e)),xn=e=>kr(pt({},"__esModule",{value:!0}),e);var Fs={};bn(Fs,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>Tt,DocumentationError:()=>J,EndpointsFactory:()=>fe,EventStreamFactory:()=>zt,InputValidationError:()=>G,Integration:()=>Nt,Middleware:()=>F,MissingPeerError:()=>Ne,OutputValidationError:()=>ie,ResultHandler:()=>le,RoutingError:()=>ae,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Jr,arrayResultHandler:()=>xt,attachRouting:()=>No,createConfig:()=>Ar,createServer:()=>zo,defaultEndpointsFactory:()=>Vr,defaultResultHandler:()=>ue,ensureHttpError:()=>Te,ez:()=>ln,getMessageFromError:()=>ee,testEndpoint:()=>en,testMiddleware:()=>tn});module.exports=xn(Fs);var L=y(require("ramda"),1),V=require("zod/v4");var Ce=Symbol.for("express-zod-api"),X=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Sn=V.z.core.$constructor("$EZBrandCheck",(e,t)=>{V.z.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),Rn=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},On=function(){return this.meta({deprecated:!0})},Tn=function(e){return this.meta({default:e})},Pn=function(e){return this.check(new Sn({brand:e,check:"$EZBrandCheck"}))},wn=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 V.z.ZodUnknown?V.z.looseObject:V.z.object)(r);return this.transform(t).pipe(n)};if(!(Ce in globalThis)){globalThis[Ce]=!0;for(let e of Object.keys(V.z)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=V.z[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return Rn.bind(this)}},deprecated:{get(){return On.bind(this)}},brand:{set(){},get(){return Pn.bind(this)}}})}Object.defineProperty(V.z.ZodDefault.prototype,"label",{get(){return Tn.bind(this)}}),Object.defineProperty(V.z.ZodObject.prototype,"remap",{get(){return wn.bind(this)}})}function Ar(e){return e}var Wt=require("zod/v4");var Le=y(require("ramda"),1),Jt=require("zod/v4");var me=y(require("ramda"),1),Bt=require("zod/v4");var Ie=require("zod/v4"),xe=Symbol("DateIn"),Cr=(e={})=>Ie.z.union([Ie.z.iso.date(),Ie.z.iso.datetime(),Ie.z.iso.datetime({local:!0})]).meta(e).transform(r=>new Date(r)).pipe(Ie.z.date()).brand(xe);var Ir=require("zod/v4"),Se=Symbol("DateOut"),Nr=({examples:e,...t}={})=>Ir.z.date().transform(r=>r.toISOString()).brand(Se).meta({...t,examples:e});var K=y(require("ramda"),1),ct=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 $t=/:([A-Za-z0-9_]+)/g,dt=e=>e.match($t)?.map(t=>t.slice(1))||[],En=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Ht={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},vn=["body","query","params"],Kt=e=>e.method.toLowerCase(),mt=(e,t={})=>{let r=Kt(e);return r==="options"?{}:(t[r]||Ht[r]||vn).filter(o=>o==="files"?En(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:e instanceof ct.z.ZodError?new Error(ee(e),{cause:e}):new Error(String(e)),ee=e=>e instanceof ct.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ie?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,ne=(e,t)=>e._zod.def.type===t,Re=(e,t,r)=>e.length&&t.length?K.xprod(e,t).map(r):e.concat(t),qt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=K.chain(o=>o.split(/[^A-Z0-9]/gi),e);return K.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(qt).join("")},lt=K.tryCatch((e,t)=>typeof ct.z.parse(e,t),K.always(void 0)),M=e=>typeof e=="object"&&e!==null,Oe=K.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ae=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.`}},Ve=class extends Error{name="IOSchemaError"},ut=class extends Ve{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},ie=class extends Ve{constructor(r){super(ee(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Ve{constructor(r){super(ee(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(ee(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ne=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ft=require("zod/v4"),Je=Symbol("Form"),zr=e=>(e instanceof Ft.z.ZodObject?e:Ft.z.object(e)).brand(Je);var jr=require("zod/v4"),ce=Symbol("Upload"),Lr=()=>jr.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 Zr=require("zod/v4");var Ge=require("zod/v4"),de=Symbol("File"),Mr=Ge.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),kn={buffer:()=>Mr.brand(de),string:()=>Ge.z.string().brand(de),binary:()=>Mr.or(Ge.z.string()).brand(de),base64:()=>Ge.z.base64().brand(de)};function ft(e){return kn[e||"string"]()}var q=Symbol("Raw"),$r=Zr.z.object({raw:ft("buffer")}),An=e=>$r.extend(e).brand(q);function Hr(e){return e?An(e):$r.brand(q)}var Kr=(e,{io:t,condition:r})=>me.tryCatch(()=>{Bt.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ut(o)}})},o=>o.cause)(),qr=(e,{io:t})=>{let o=[Bt.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},Fr=e=>Kr(e,{condition:t=>{let r=X(t);return typeof r=="symbol"&&[ce,q,Je].includes(r)},io:"input"}),Cn=["nan","symbol","map","set","bigint","void","promise","never"],Ut=(e,t)=>Kr(e,{io:t,condition:r=>{let o=X(r),{type:n}=r._zod.def;return!!(Cn.includes(n)||t==="input"&&(n==="date"||o===Se)||t==="output"&&(o===xe||o===q||o===ce))}});var gt=y(require("http-errors"),1);var We=y(require("http-errors"),1),Br=y(require("ramda"),1),yt=require("zod/v4");var Dt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof yt.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Ye=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Te=e=>(0,We.isHttpError)(e)?e:(0,We.default)(e instanceof G?400:500,ee(e),{cause:e.cause||e}),Pe=e=>Oe()&&!e.expose?(0,We.default)(e.statusCode).message:e.message,Ur=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=yt.globalRegistry.get(o)||{};return Re(t,n.map(Br.objOf(r)),([s,i])=>({...s,...i}))},[]);var ht=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Pe((0,gt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:(0,gt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var _t=require("zod/v4");var Vt=class{},F=class extends Vt{#e;#t;#r;constructor({input:t=_t.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 _t.z.ZodError?new G(o):o}}},ze=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 je=class{nest(t){return Object.assign(t,{"":this})}};var Qe=class extends je{},bt=class e extends Qe{#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=Fr(this.#e.inputSchema);if(t){let r=X(t);if(r===ce)return"upload";if(r===q)return"raw";if(r===Je)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=Le.pluck("security",this.#e.middlewares||[]);return Le.reject(Le.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 Jt.z.ZodError?new ie(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 ze))&&(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 Jt.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){ht({...t,error:new pe(oe(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Kt(t),i={},p={output:{},error:null},d=mt(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:oe(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};var Dr=y(require("ramda"),1),_r=(e,t)=>Dr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));var C=require("zod/v4");var Me={positive:200,negative:400},Ze=Object.keys(Me);var Gt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},le=class extends Gt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Dt(this.#e,{variant:"positive",args:[t],statusCodes:[Me.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[Me.negative],mimeTypes:[E.json]})}},ue=new le({positive:e=>{let{examples:t=[]}=C.globalRegistry.get(e)||{};!t.length&&ne(e,"object")&&t.push(...Ur(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 Ye(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Pe(i)}})}n.status(Me.positive).json({status:"success",data:r})}}),xt=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 Ye(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(Me.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 ze(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Wt.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 bt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:g,methods:m,getOperationId:h,inputSchema:_r(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Wt.z.object({}),handler:async o=>(await t(o),{})})}},Vr=new fe(ue),Jr=new fe(xt);var eo=y(require("ansis"),1),to=require("node:util"),Qt=require("node:perf_hooks");var W=require("ansis"),Gr=y(require("ramda"),1);var Yt={debug:W.blue,info:W.green,warn:(0,W.hex)("#FFA500"),error:W.red,ctx:W.cyanBright},St={debug:10,info:20,warn:30,error:40},Wr=e=>M(e)&&Object.keys(St).some(t=>t in e),Yr=e=>e in St,Qr=(e,t)=>St[e]<St[t],In=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),$e=Gr.memoizeWith((e,t)=>`${e}${t}`,In),Xr=e=>e<1e-6?$e("nanosecond",3).format(e/1e-6):e<.001?$e("nanosecond").format(e/1e-6):e<1?$e("microsecond").format(e/.001):e<1e3?$e("millisecond").format(e):e<6e4?$e("second",2).format(e/1e3):$e("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=eo.default.isSupported(),level:r=Oe()?"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,to.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"||Qr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Yt.ctx(s):s),d.push(p?`${Yt[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=Qt.performance.now();return()=>{let o=Qt.performance.now()-r,{message:n,severity:s="debug",formatter:i=Xr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var ro=y(require("ramda"),1);var Ke=class e extends je{#e;constructor(t){super(),this.#e=t}get entries(){let t=ro.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 oo=y(require("express"),1),qe=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,oo.default.static(...this.#e))}};var Xe=y(require("express"),1),Ao=y(require("node:http"),1),Co=y(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new Ne(e)};var po=y(require("http-errors"),1);var Xt=require("zod/v4");var S=y(require("ramda"),1);var Nn=e=>e.type==="object",zn=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")}),jn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description"]),S.isEmpty),no=S.pair(!0),Be=(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"&&jn(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(no,i.anyOf)),i.oneOf&&r.push(...S.map(no,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=Re(o.examples?.filter(M)||[],i.examples.filter(M),([p,d])=>S.mergeDeepRight(p,d))),!!Nn(i)&&(r.push([s,{examples:Ln(i)}]),i.properties&&(o.properties=(t==="throw"?zn: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},Ln=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>Re(t,o.map(S.objOf(r)),([n,s])=>({...n,...s})),[]);var Rt=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=[Xt.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=Ut(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 Ze)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=Ut(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=dt(t);if(s.length===0)return;let i=n?.flat||Be(Xt.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 er=["get","post","put","delete","patch"],so=e=>er.includes(e);var Mn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&so(t)?[r,t]:[e]},Zn=e=>e.trim().split("/").filter(Boolean).join("/"),io=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Mn(r);return[[t||""].concat(Zn(n)||[]).join("/"),o,s]}),$n=(e,t)=>{throw new ae("Route with explicit method can only be assigned with Endpoint",e,t)},ao=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ae(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},tr=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ae("Route has a duplicate",e,t);r.add(o)},Ue=({routing:e,onEndpoint:t,onStatic:r})=>{let o=io(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Qe)if(p)tr(p,s,n),ao(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)tr(c,s,n),t(i,s,c)}else if(p&&$n(p,s),i instanceof qe)r&&i.apply(s,r);else if(i instanceof Ke)for(let[d,c]of i.entries){let{methods:m}=c;tr(d,s,n),ao(d,s,m),t(c,s,d)}else o.unshift(...io(i,s))}};var co=y(require("ramda"),1),mo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),Hn=e=>({method:t},r,o)=>{let n=mo(e);r.set({Allow:n});let s=(0,po.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":mo(e),"Access-Control-Allow-Headers":"content-type"}),rr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Oe()?void 0:new Rt(t()),i=new Map;Ue({routing:o,onEndpoint:(c,m,h)=>{Oe()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let b=n?.[c.requestType]||[],g=co.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(Z,O)=>{let I=t(Z);if(r.cors){let N=Kn(h),_=typeof r.cors=="function"?await r.cors({request:Z,endpoint:k,logger:I,defaultHeaders:N}):N;O.set(_)}return k.execute({request:Z,response:O,logger:I,config:r})};e[b](c,...g,A)}r.wrongMethodBehavior!==404&&d.set(c,Hn(h))}for(let[c,m]of d)e.all(c,m)};var xo=y(require("http-errors"),1);var ho=require("node:timers/promises");var lo=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",uo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",fo=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,yo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),go=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var bo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(lo(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",yo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(fo(c)||uo(c))&&i(c);for await(let c of(0,ho.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(go))};return{sockets:n,shutdown:()=>o??=d()}};var So=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:oe(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Ro=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,xo.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){ht({response:o,logger:s,error:new pe(oe(i),n)})}},qn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Fn=e=>({log:e.debug.bind(e)}),Oo=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(qn(o)),i},To=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Po=({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[Ce]={logger:i}),s()},wo=e=>t=>t?.res?.locals[Ce]?.logger||e,Eo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),vo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=bo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let i of o)process.on(i,s)};var $=require("ansis"),ko=e=>{if(e.columns<132)return;let t=(0,$.italic)("Proudly supports transgender community.".padStart(109)),r=(0,$.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,$.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,$.italic)("for Ashley".padEnd(20)),s=(0,$.hex)("#F5A9B8"),i=(0,$.hex)("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill($.whiteBright,5,7).fill(s,7,9).fill(i,9,12).fill($.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,`
20
- ${r}`);return this.#e.concat(o||[]).map((n,s)=>mr(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
18
+ `))};var Io=e=>{e.startupLogo!==!1&&ko(process.stdout);let t=e.errorHandler||ue,r=Wr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v24.0.0-beta.3 (CJS)",env:process.env.NODE_ENV||"development"}),Eo(r);let o=Po({logger:r,config:e}),s={getLogger:wo(r),errorHandler:t},i=Ro(s),p=So(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},No=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Io(e);return rr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},zo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=Io(e),p=(0,Xe.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||Xe.default.json()],raw:[e.rawParser||Xe.default.raw(),To],form:[e.formParser||Xe.default.urlencoded()],upload:e.upload?await Oo({config:e,getLogger:o}):[]};rr({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=Ao.default.createServer(p);c.push(b),h.push(m(b,e.http.listen))}if(e.https){let b=Co.default.createServer(e.https.options,p);c.push(b),h.push(m(b,e.https.listen))}return e.gracefulShutdown&&vo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(b=>b())}};var Yo=require("openapi3-ts/oas31"),Qo=y(require("ramda"),1);var R=y(require("ramda"),1);var jo=e=>M(e)&&"or"in e,Lo=e=>M(e)&&"and"in e,or=e=>!Lo(e)&&!jo(e),Mo=e=>{let t=R.filter(or,e),r=R.chain(R.prop("and"),R.filter(Lo,e)),[o,n]=R.partition(or,r),s=R.concat(t,o),i=R.filter(jo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>Re(d,R.map(m=>or(m)?[m]:m.and,c),([m,h])=>R.concat(m,h)),R.reject(R.isEmpty,[s]))};var ye=require("openapi3-ts/oas31"),l=y(require("ramda"),1),nr=require("zod/v4");var Zo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var $o=50,Ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Fo=e=>e.replace($t,t=>`{${t.slice(1)}}`),Un=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Dn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),_n=({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}}},Vn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Be(e,"throw")},(e,{jsonSchema:t})=>t),Jn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:rs(t.type)})},Ho=e=>e in qo,Gn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Wn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),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(Ho):t&&Ho(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},Yn=({jsonSchema:{examples: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:Ko}};return e?.length&&(r.examples=e),r},Qn=({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:Ko}};return e?.length&&(r.examples=e),r},Xn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),es=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},ts=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},rs=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],os=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!ne(o,"transform"))return t;let s=we(ar(n,{ctx:r}));if((0,ye.isSchemaObject)(s))if(r.isResponse){let i=lt(o,ts(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},ns=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},sr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ss=(e,t)=>t?.includes(e)||e.startsWith("x-")||Zo.includes(e),Bo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Be(r),m=dt(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),Z=O=>g&&(i?.(O,t,e)??ss(O,A));return Object.entries(c.properties).reduce((O,[I,N])=>{let _=k(I)?"path":Z(I)?"header":h?"query":void 0;if(!_)return O;let j=we(N),te=s==="components"?n(N,j,se(d,I)):j;return O.concat({name:I,in:_,deprecated:N.deprecated,required:c.required?.includes(I)||!1,description:j.description||d,schema:te,examples:sr((0,ye.isSchemaObject)(j)&&j.examples?.length?j.examples:l.pluck(I,c.examples?.filter(l.both(M,l.has(I)))||[]))})},[])},ir={nullable:Jn,union:_n,bigint:Xn,intersection:Vn,tuple:es,pipe:os,literal:Wn,enum:Gn,[xe]:Yn,[Se]:Qn,[ce]:Un,[de]:Dn,[q]:ns},is=(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},ar=(e,{ctx:t,rules:r=ir})=>{let{$defs:o={},properties:n={}}=nr.z.toJSONSchema(nr.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=X(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 is(n.subject,o,t)},Uo=(e,t)=>{if((0,ye.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Uo(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]},Do=({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} ${qt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=we(ar(r,{rules:{...c,...ir},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,se(m)):h,examples:sr(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},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))}),_o=(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))},Vo=(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:[]})},{})),Jo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>ar(e,{rules:{...t,...ir},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Go=({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]=Uo(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,se(d)):c,examples:sr(h.length?h:Be(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},Wo=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)},[]),pr=e=>e.length<=$o?e:e.slice(0,$o-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Tt=class extends Yo.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||se(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});Ue({routing:t,onEndpoint:(g,k,A)=>{let Z={path:k,method:A,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:I,scopes:N,inputSchema:_}=g,j=I?pr(I):m&&O?pr(O):void 0,te=r.inputSources?.[A]||Ht[A],Ae=this.#n(k,A,g.getOperationId(A)),ot=Jo({...Z,schema:_}),he=Mo(g.security),nt=Bo({...Z,inputSources:te,isHeader:c,security:he,request:ot,description:i?.requestParameter?.call(null,{method:A,path:k,operationId:Ae})}),st={};for(let re of Ze){let be=g.getResponses(re);for(let{mimeTypes:at,schema:Mt,statusCodes:vr}of be)for(let Zt of vr)st[Zt]=Do({...Z,variant:re,schema:Mt,mimeTypes:at,statusCode:Zt,hasMultipleStatusCodes:be.length>1||vr.length>1,description:i?.[`${re}Response`]?.call(null,{method:A,path:k,operationId:Ae,statusCode:Zt})})}let it=te.includes("body")?Go({...Z,request:ot,paramNames:Qo.pluck("name",nt),schema:_,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:A,path:k,operationId:Ae})}):void 0,jt=Vo(_o(he,te),N,re=>{let be=this.#s(re);return this.addSecurityScheme(be,re),be}),Lt={operationId:Ae,summary:j,description:O,deprecated:g.isDeprecated||void 0,tags:Ot(g.tags),parameters:Ot(nt),requestBody:it,security:Ot(jt),responses:st};this.addPath(Fo(k),{[A]:Lt})}}),d&&(this.rootDoc.tags=Wo(d))}};var Pt=require("node-mocks-http");var us=e=>(0,Pt.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),fs=e=>(0,Pt.createResponse)(e),ys=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Yr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Xo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=us(e),s=fs({req:n,...t});s.req=t?.req||n,n.res=s;let i=ys(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},en=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Xo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},tn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=ue}}=Xo(r),d=mt(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:oe(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var pn=y(require("ramda"),1),rt=y(require("typescript"),1),cn=require("zod/v4");var sn=y(require("ramda"),1),U=y(require("typescript"),1);var Y=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,wt=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],gs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],et={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),dr=(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)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mr=e=>typeof e=="string"&&hs.test(e)?a.createIdentifier(e):w(e),Et=(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)))),vt=(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),De=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),lr=(e,t=[])=>a.createConstructorDeclaration(et.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&&Y.map(f,t)):e,ur=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,mr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return p.length?cr(i,p.join(" ")):i},fr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),yr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&wt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),gr=(e,t)=>Q(e,a.createUnionTypeNode(Y.map(H,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?wt:void 0,e,n&&Sr(n),t);return o?cr(s,o):s},rn=(e,t)=>a.createPropertyDeclaration(et.public,e,void 0,f(t),void 0),hr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(et.public,void 0,e,void 0,o&&Sr(o),t,n,a.createBlock(r)),br=(e,t,{typeParams:r}={})=>a.createClassDeclaration(wt,e,r&&Sr(r),void 0,t),xr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),kt=e=>f(Promise.name,[e]),At=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?wt:void 0,e,void 0,void 0,t);return o?cr(n,o):n},Sr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?Y.map(vt,e):De(e),void 0,void 0,t),T=e=>e,tt=(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),_e=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),Rr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),B=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),on=e=>a.createUnionTypeNode([f(e),kt(e)]),Or=(e,t)=>a.createFunctionTypeNode(void 0,De(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),H=e=>a.createLiteralTypeNode(w(e)),bs=[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],nn=e=>bs.includes(e.kind);var It=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=gr("Method",er);someOfType=Q("SomeOf",B("T",xr("T")),{params:["T"]});requestType=Q("Request",xr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>gr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>At(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(mr(t),a.createArrayLiteralExpression(sn.map(w,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,Or({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},kt(U.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:U.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:U.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]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur},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([Rr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Et(":",[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=()=>hr(this.#e.provideMethod,De({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:B(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(yr(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:kt(B(this.interfaces.response,"K"))});makeClientClass=t=>br(t,[lr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:et.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Et("?",[_e(URLSearchParams.name,t)]);#o=()=>_e(URL.name,Et("",[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"),tt(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),tt(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,tt(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(U.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,tt(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=()=>lr(De({request:"K",params:B(this.interfaces.input,"K")}),[z(yr(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)),Rr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),_e("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Ee(T("event"),t)]);#i=()=>hr(this.#e.onMethod,De({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Or({[this.#e.dataParameter.text]:B(Ct("R",fr(this.#s("E"))),H(T("data")))},on(U.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:B("R",H(T("event")))}});makeSubscriptionClass=t=>br(t,[rn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ct(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(U.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ct(B(this.interfaces.positive,"K"),fr(this.#s(U.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,_e(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(_e(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),an=require("zod/v4");var Tr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=X(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Tr(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:D}=x.default,xs={[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},Pr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Ss=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):H(r));return t.length===1?t[0]:D.createUnionTypeNode(t)},Rs=(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}=an.globalRegistry.get(p)||{};return Ee(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return D.createTypeLiteralNode(s)};return qr(e,{io:t?"output":"input"})?o(e,n):n()},Os=({_zod:{def:e}},{next:t})=>D.createArrayTypeNode(t(e.element)),Ts=({_zod:{def:e}})=>D.createUnionTypeNode(Object.values(e.entries).map(H)),Ps=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(nn(n)?n.kind:n,n)}return D.createUnionTypeNode(Array.from(r.values()))},ws=e=>xs?.[e.kind],Es=({_zod:{def:e}},{next:t})=>t(e.innerType),vs=({_zod:{def:e}},{next:t})=>D.createUnionTypeNode([t(e.innerType),H(null)]),ks=({_zod:{def:e}},{next:t})=>D.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:D.createRestTypeNode(t(e.rest)))),As=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Cs=v.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(Pr.name,...o))return!1;if(v.both(v.eqBy(Pr.type),v.eqBy(Pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return D.createTypeLiteralNode(r)},(e,t)=>D.createIntersectionTypeNode(t)),Is=({_zod:{def:e}},{next:t})=>Cs([e.left,e.right].map(t)),ge=e=>()=>f(e),wr=({_zod:{def:e}},{next:t})=>t(e.innerType),Ns=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!ne(o,"transform"))return t(o);let s=t(n),i=lt(o,ws(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)},zs=()=>H(null),js=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ls=e=>{let t=f(x.default.SyntaxKind.StringKeyword),r=f("Buffer"),o=D.createUnionTypeNode([t,r]);return ne(e,"string")?t:ne(e,"union")?o:r},Ms=(e,{next:t})=>t(e._zod.def.shape.raw),Zs={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),[xe]:ge(x.default.SyntaxKind.StringKeyword),[Se]:ge(x.default.SyntaxKind.StringKeyword),null:zs,array:Os,tuple:ks,record:As,object:Rs,literal:Ss,intersection:Is,union:Ps,default:wr,enum:Ts,optional:Es,nullable:vs,catch:wr,pipe:Ns,lazy:js,readonly:wr,[de]:Ls,[q]:Ms},Er=(e,{brandHandling:t,ctx:r})=>Tr(e,{rules:{...t,...Zs},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Nt=class extends It{#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=H(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(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=cn.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}};Ue({routing:t,onEndpoint:(b,g,k)=>{let A=se.bind(null,k,g),{isDeprecated:Z,inputSchema:O,tags:I}=b,N=`${k} ${g}`,_=Q(A("input"),Er(O,c),{comment:N});this.#e.push(_);let j=Ze.reduce((ot,he)=>{let nt=b.getResponses(he),st=pn.chain(([jt,{schema:Lt,mimeTypes:re,statusCodes:be}])=>{let at=Q(A(he,"variant",`${jt+1}`),Er(re?Lt:p,m),{comment:N});return this.#e.push(at),be.map(Mt=>Ee(Mt,at.name))},Array.from(nt.entries())),it=At(A(he,"response","variants"),st,{comment:N});return this.#e.push(it),Object.assign(ot,{[he]:it})},{});this.paths.add(g);let te=H(N),Ae={input:f(_.name),positive:this.someOf(j.positive),negative:this.someOf(j.negative),response:a.createUnionTypeNode([B(this.interfaces.positive,te),B(this.interfaces.negative,te)]),encoded:a.createIntersectionTypeNode([f(j.positive.name),f(j.negative.name)])};this.registry.set(N,{isDeprecated:Z,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:dr(r,t)).join(`
19
+ `):void 0}print(t){let r=this.#n(t),o=r&&rt.default.addSyntheticLeadingComment(rt.default.addSyntheticLeadingComment(a.createEmptyStatement(),rt.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),rt.default.SyntaxKind.MultiLineCommentTrivia,`
20
+ ${r}`);return this.#e.concat(o||[]).map((n,s)=>dr(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 mn=(e,t)=>ke.z.object({data:t,event:ke.z.literal(e),id:ke.z.string().optional(),retry:ke.z.int().positive().optional()}),$s=(e,t,r)=>mn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),Hs=1e4,dn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Ks=e=>new F({handler:async({response:t})=>setTimeout(()=>dn(t),Hs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{dn(t),t.write($s(e,r,o),"utf-8"),t.flush?.()}}}),qs=e=>new le({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>mn(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);Ye(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(Pe(i),"utf-8")}t.end()}}),zt=class extends fe{constructor(t){super(qs(t)),this.middlewares=[Ks(t)]}};var ln={dateIn:Cr,dateOut:Nr,form:zr,file:ft,upload:Lr,raw:Hr};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 {
@@ -960,12 +933,12 @@ declare function raw(): ReturnType<typeof base.brand<symbol>>;
960
933
  declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<S>>;
961
934
 
962
935
  declare const ez: {
963
- dateIn: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
964
- dateOut: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
936
+ dateIn: (meta?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
937
+ dateOut: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
965
938
  form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<{ -readonly [P in keyof S]: S[P]; }, zod_v4_core.$strip>, symbol>;
966
939
  file: typeof file;
967
940
  upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
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 {
@@ -960,12 +933,12 @@ declare function raw(): ReturnType<typeof base.brand<symbol>>;
960
933
  declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<S>>;
961
934
 
962
935
  declare const ez: {
963
- dateIn: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
964
- dateOut: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
936
+ dateIn: (meta?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
937
+ dateOut: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
965
938
  form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<{ -readonly [P in keyof S]: S[P]; }, zod_v4_core.$strip>, symbol>;
966
939
  file: typeof file;
967
940
  upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
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,6 +1,6 @@
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(`
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=`
1
+ import*as z from"ramda";import{z as J}from"zod/v4";var Pe=Symbol.for("express-zod-api"),V=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Ko=J.core.$constructor("$EZBrandCheck",(e,t)=>{J.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),qo=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},Fo=function(){return this.meta({deprecated:!0})},Bo=function(e){return this.meta({default:e})},Uo=function(e){return this.check(new Ko({brand:e,check:"$EZBrandCheck"}))},Do=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 J.ZodUnknown?J.looseObject:J.object)(r);return this.transform(t).pipe(n)};if(!(Pe in globalThis)){globalThis[Pe]=!0;for(let e of Object.keys(J)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=J[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return qo.bind(this)}},deprecated:{get(){return Fo.bind(this)}},brand:{set(){},get(){return Uo.bind(this)}}})}Object.defineProperty(J.ZodDefault.prototype,"label",{get(){return Bo.bind(this)}}),Object.defineProperty(J.ZodObject.prototype,"remap",{get(){return Do.bind(this)}})}function _o(e){return e}import{z as zr}from"zod/v4";import*as ke from"ramda";import{z as Cr}from"zod/v4";import*as ie from"ramda";import{z as Or}from"zod/v4";import{z as $e}from"zod/v4";var de=Symbol("DateIn"),fr=(e={})=>$e.union([$e.iso.date(),$e.iso.datetime(),$e.iso.datetime({local:!0})]).meta(e).transform(r=>new Date(r)).pipe($e.date()).brand(de);import{z as Vo}from"zod/v4";var me=Symbol("DateOut"),yr=({examples:e,...t}={})=>Vo.date().transform(r=>r.toISOString()).brand(me).meta({...t,examples:e});import*as Z from"ramda";import{z as vt}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 kt=/:([A-Za-z0-9_]+)/g,et=e=>e.match(kt)?.map(t=>t.slice(1))||[],Jo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},At={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Go=["body","query","params"],Ct=e=>e.method.toLowerCase(),tt=(e,t={})=>{let r=Ct(e);return r==="options"?{}:(t[r]||At[r]||Go).filter(o=>o==="files"?Jo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},X=e=>e instanceof Error?e:e instanceof vt.ZodError?new Error(ee(e),{cause:e}):new Error(String(e)),ee=e=>e instanceof vt.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof fe?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,te=(e,t)=>e._zod.def.type===t,le=(e,t,r)=>e.length&&t.length?Z.xprod(e,t).map(r):e.concat(t),It=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),re=(...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(It).join("")},rt=Z.tryCatch((e,t)=>typeof vt.parse(e,t),Z.always(void 0)),j=e=>typeof e=="object"&&e!==null,ue=Z.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ye=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},G=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"},ot=class extends He{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},fe=class extends He{constructor(r){super(ee(r),{cause:r});this.cause=r}name="OutputValidationError"},W=class extends He{constructor(r){super(ee(r),{cause:r});this.cause=r}name="InputValidationError"},oe=class extends Error{constructor(r,o){super(ee(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.`)}};import{z as gr}from"zod/v4";var qe=Symbol("Form"),hr=e=>(e instanceof gr.ZodObject?e:gr.object(e)).brand(qe);import{z as Wo}from"zod/v4";var ne=Symbol("Upload"),br=()=>Wo.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ne);import{z as Qo}from"zod/v4";import{z as nt}from"zod/v4";var se=Symbol("File"),xr=nt.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Yo={buffer:()=>xr.brand(se),string:()=>nt.string().brand(se),binary:()=>xr.or(nt.string()).brand(se),base64:()=>nt.base64().brand(se)};function st(e){return Yo[e||"string"]()}var $=Symbol("Raw"),Sr=Qo.object({raw:st("buffer")}),Xo=e=>Sr.extend(e).brand($);function Rr(e){return e?Xo(e):Sr.brand($)}var Tr=(e,{io:t,condition:r})=>ie.tryCatch(()=>{Or.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ot(o)}})},o=>o.cause)(),Pr=(e,{io:t})=>{let o=[Or.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},wr=e=>Tr(e,{condition:t=>{let r=V(t);return typeof r=="symbol"&&[ne,$,qe].includes(r)},io:"input"}),en=["nan","symbol","map","set","bigint","void","promise","never"],Nt=(e,t)=>Tr(e,{io:t,condition:r=>{let o=V(r),{type:n}=r._zod.def;return!!(en.includes(n)||t==="input"&&(n==="date"||o===me)||t==="output"&&(o===de||o===$||o===ne))}});import nn,{isHttpError as sn}from"http-errors";import Er,{isHttpError as tn}from"http-errors";import*as vr from"ramda";import{globalRegistry as rn,z as on}from"zod/v4";var zt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof on.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new oe(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}),we=e=>tn(e)?e:Er(e instanceof W?400:500,ee(e),{cause:e.cause||e}),ge=e=>ue()&&!e.expose?Er(e.statusCode).message:e.message,kr=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=rn.get(o)||{};return le(t,n.map(vr.objOf(r)),([s,i])=>({...s,...i}))},[]);var it=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ge(nn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:sn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ar}from"zod/v4";var jt=class{},B=class extends jt{#e;#t;#r;constructor({input:t=Ar.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 Ar.ZodError?new W(o):o}}},Ee=class extends B{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 Be=class extends ve{},at=class e extends Be{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}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=wr(this.#e.inputSchema);if(t){let r=V(t);if(r===ne)return"upload";if(r===$)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 Cr.ZodError?new fe(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 Cr.ZodError?new W(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){it({...t,error:new oe(X(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ct(t),i={},p={output:{},error:null},d=tt(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:X(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as Ir from"ramda";var Nr=(e,t)=>Ir.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as pt,z as H}from"zod/v4";var Ae={positive:200,negative:400},Ce=Object.keys(Ae);var Lt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},he=class extends Lt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return zt(this.#e,{variant:"positive",args:[t],statusCodes:[Ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return zt(this.#t,{variant:"negative",args:[],statusCodes:[Ae.negative],mimeTypes:[w.json]})}},be=new he({positive:e=>{let{examples:t=[]}=pt.get(e)||{};!t.length&&te(e,"object")&&t.push(...kr(e)),t.length&&!pt.has(e)&&pt.add(e,{examples:t});let r=H.object({status:H.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:H.object({status:H.literal("error"),error:H.object({message:H.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 Fe(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})}}),Mt=new he({positive:e=>{let{examples:t=[]}=pt.get(e)||{},r=e instanceof H.ZodObject&&"items"in e.shape&&e.shape.items instanceof H.ZodArray?e.shape.items:H.array(H.any());return t.reduce((o,n)=>j(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:H.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 Fe(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 B?t:new B(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 B({handler:t})),this.resultHandler)}build({input:t=zr.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 at({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:y,methods:m,getOperationId:g,inputSchema:Nr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:zr.object({}),handler:async o=>(await t(o),{})})}},an=new xe(be),pn=new xe(Mt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as Hr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as jr from"ramda";var Zt={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},ct={debug:10,info:20,warn:30,error:40},Lr=e=>j(e)&&Object.keys(ct).some(t=>t in e),Mr=e=>e in ct,Zr=(e,t)=>ct[e]<ct[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ie=jr.memoizeWith((e,t)=>`${e}${t}`,fn),$r=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=yn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return gn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||Zr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Zt.ctx(s):s),d.push(p?`${Zt[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=Hr.now();return()=>{let o=Hr.now()-r,{message:n,severity:s="debug",formatter:i=$r}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Kr from"ramda";var De=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Kr.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import hn from"express";var _e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import lt from"express";import jn from"node:http";import Ln from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import wn from"http-errors";import{z as Fr}from"zod/v4";import*as x from"ramda";var bn=e=>e.type==="object",xn=x.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return x.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),Sn=x.pipe(Object.keys,x.without(["type","properties","required","examples","description"]),x.isEmpty),qr=x.pair(!0),ze=(e,t="coerce")=>{let r=[x.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&Sn(p)))throw new Error("Can not merge");return x.pair(s,p)})),i.anyOf&&r.push(...x.map(qr,i.anyOf)),i.oneOf&&r.push(...x.map(qr,i.oneOf)),i.examples?.length&&(s?o.examples=x.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(j)||[],i.examples.filter(j),([p,d])=>x.mergeDeepRight(p,d))),!!bn(i)&&(r.push([s,{examples:Rn(i)}]),i.properties&&(o.properties=(t==="throw"?xn:x.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},Rn=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>le(t,o.map(x.objOf(r)),([n,s])=>({...n,...s})),[]);var dt=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=[Fr.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=Nt(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=Nt(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=et(t);if(s.length===0)return;let i=n?.flat||ze(Fr.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 $t=["get","post","put","delete","patch"],Br=e=>$t.includes(e);var On=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Br(t)?[r,t]:[e]},Tn=e=>e.trim().split("/").filter(Boolean).join("/"),Ur=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=On(r);return[[t||""].concat(Tn(n)||[]).join("/"),o,s]}),Pn=(e,t)=>{throw new ye("Route with explicit method can only be assigned with Endpoint",e,t)},Dr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ye(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ht=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ye("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Ur(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Be)if(p)Ht(p,s,n),Dr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)Ht(c,s,n),t(i,s,c)}else if(p&&Pn(p,s),i instanceof _e)r&&i.apply(s,r);else if(i instanceof De)for(let[d,c]of i.entries){let{methods:m}=c;Ht(d,s,n),Dr(d,s,m),t(c,s,d)}else o.unshift(...Ur(i,s))}};import*as _r from"ramda";var Vr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),En=e=>({method:t},r,o)=>{let n=Vr(e);r.set({Allow:n});let s=wn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},vn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Vr(e),"Access-Control-Allow-Headers":"content-type"}),Kt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new dt(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=_r.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(L,R)=>{let A=t(L);if(r.cors){let C=vn(g),F=typeof r.cors=="function"?await r.cors({request:L,endpoint:v,logger:A,defaultHeaders:C}):C;R.set(F)}return v.execute({request:L,response:R,logger:A,config:r})};e[h](c,...y,k)}r.wrongMethodBehavior!==404&&d.set(c,En(g))}for(let[c,m]of d)e.all(c,m)};import An from"http-errors";import{setInterval as kn}from"node:timers/promises";var Jr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Gr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Wr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Yr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Qr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Xr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Jr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Yr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Wr(c)||Gr(c))&&i(c);for await(let c of kn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(Qr))};return{sockets:n,shutdown:()=>o??=d()}};var eo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:X(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),to=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=An(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){it({response:o,logger:s,error:new oe(X(i),n)})}},Cn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},In=e=>({log:e.debug.bind(e)}),ro=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:In(m)})(p,d,c)}),o&&i.push(Cn(o)),i},oo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},no=({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()},so=e=>t=>t?.res?.locals[Pe]?.logger||e,io=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=Xr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let i of o)process.on(i,s)};import{gray as Nn,hex as po,italic as mt,whiteBright as zn}from"ansis";var co=e=>{if(e.columns<132)return;let t=mt("Proudly supports transgender community.".padStart(109)),r=mt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=mt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=mt("for Ashley".padEnd(20)),s=po("#F5A9B8"),i=po("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(zn,5,7).fill(s,7,9).fill(i,9,12).fill(Nn,12,13),d=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
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 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(`
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(`
18
+ `))};var mo=e=>{e.startupLogo!==!1&&co(process.stdout);let t=e.errorHandler||be,r=Lr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v24.0.0-beta.3 (ESM)",env:process.env.NODE_ENV||"development"}),io(r);let o=no({logger:r,config:e}),s={getLogger:so(r),errorHandler:t},i=to(s),p=eo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Mn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=mo(e);return Kt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=mo(e),p=lt().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||lt.json()],raw:[e.rawParser||lt.raw(),oo],form:[e.formParser||lt.urlencoded()],upload:e.upload?await ro({config:e,getLogger:o}):[]};Kt({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=jn.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&&ao({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(h=>h())}};import{OpenApiBuilder as ps}from"openapi3-ts/oas31";import*as Io from"ramda";import*as S from"ramda";var lo=e=>j(e)&&"or"in e,uo=e=>j(e)&&"and"in e,qt=e=>!uo(e)&&!lo(e),fo=e=>{let t=S.filter(qt,e),r=S.chain(S.prop("and"),S.filter(uo,e)),[o,n]=S.partition(qt,r),s=S.concat(t,o),i=S.filter(lo,e);return S.map(S.prop("or"),S.concat(i,n)).reduce((d,c)=>le(d,S.map(m=>qt(m)?[m]:m.and,c),([m,g])=>S.concat(m,g)),S.reject(S.isEmpty,[s]))};import{isReferenceObject as xo,isSchemaObject as ut}from"openapi3-ts/oas31";import*as l from"ramda";import{z as go}from"zod/v4";var yo=["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 ho=50,So="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Ro={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Oo=e=>e.replace(kt,t=>`{${t.slice(1)}}`),Hn=({},e)=>{if(e.isResponse)throw new G("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Kn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),qn=({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}}},Fn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return ze(e,"throw")},(e,{jsonSchema:t})=>t),Bn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Yn(t.type)})},bo=e=>e in Ro,Un=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Dn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),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(bo):t&&bo(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},_n=({jsonSchema:{examples:e}},t)=>{if(t.isResponse)throw new G("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:So}};return e?.length&&(r.examples=e),r},Vn=({jsonSchema:{examples:e}},t)=>{if(!t.isResponse)throw new G("Please use ez.dateIn() for input.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:So}};return e?.length&&(r.examples=e),r},Jn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Gn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Wn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Ro?.[t]},Yn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],Qn=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!te(o,"transform"))return t;let s=Se(Ut(n,{ctx:r}));if(ut(s))if(r.isResponse){let i=rt(o,Wn(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},Xn=({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,es=(e,t)=>t?.includes(e)||e.startsWith("x-")||yo.includes(e),To=({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=et(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),L=R=>y&&(i?.(R,t,e)??es(R,k));return Object.entries(c.properties).reduce((R,[A,C])=>{let F=v(A)?"path":L(A)?"header":g?"query":void 0;if(!F)return R;let N=Se(C),Y=s==="components"?n(C,N,re(d,A)):N;return R.concat({name:A,in:F,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:Y,examples:Ft(ut(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(j,l.has(A)))||[]))})},[])},Bt={nullable:Bn,union:qn,bigint:Jn,intersection:Fn,tuple:Gn,pipe:Qn,literal:Dn,enum:Un,[de]:_n,[me]:Vn,[ne]:Hn,[se]:Kn,[$]:Xn},ts=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(xo(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},Ut=(e,{ctx:t,rules:r=Bt})=>{let{$defs:o={},properties:n={}}=go.toJSONSchema(go.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=V(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 ts(n.subject,o,t)},Po=(e,t)=>{if(xo(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Po(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]},wo=({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} ${It(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Se(Ut(r,{rules:{...c,...Bt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];ut(g)&&g.examples&&(h.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,re(m)):g,examples:Ft(h)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},rs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},os=({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},ns=({name:e})=>({type:"apiKey",in:"header",name:e}),ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),is=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),as=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Eo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?rs(o):o.type==="input"?os(o,t):o.type==="header"?ns(o):o.type==="cookie"?ss(o):o.type==="openid"?is(o):as(o);return e.map(o=>o.map(r))},vo=(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:[]})},{})),ko=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Ut(e,{rules:{...t,...Bt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Ao=({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]=Po(Se(o),p),g=[];ut(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,re(d)):c,examples:Ft(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},Co=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)},[]),Dt=e=>e.length<=ho?e:e.slice(0,ho-1)+"\u2026",ft=e=>e.length?e.slice():void 0;var _t=class extends ps{#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||re(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new G(`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 L={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?Dt(A):m&&R?Dt(R):void 0,Y=r.inputSources?.[k]||At[k],Te=this.#n(v,k,y.getOperationId(k)),Ge=ko({...L,schema:F}),pe=fo(y.security),We=To({...L,inputSources:Y,isHeader:c,security:pe,request:Ge,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Te})}),Ye={};for(let Q of Ce){let ce=y.getResponses(Q);for(let{mimeTypes:Xe,schema:wt,statusCodes:ur}of ce)for(let Et of ur)Ye[Et]=wo({...L,variant:Q,schema:wt,mimeTypes:Xe,statusCode:Et,hasMultipleStatusCodes:ce.length>1||ur.length>1,description:i?.[`${Q}Response`]?.call(null,{method:k,path:v,operationId:Te,statusCode:Et})})}let Qe=Y.includes("body")?Ao({...L,request:Ge,paramNames:Io.pluck("name",We),schema:F,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Te})}):void 0,Tt=vo(Eo(pe,Y),C,Q=>{let ce=this.#s(Q);return this.addSecurityScheme(ce,Q),ce}),Pt={operationId:Te,summary:N,description:R,deprecated:y.isDeprecated||void 0,tags:ft(y.tags),parameters:ft(We),requestBody:Qe,security:ft(Tt),responses:Ye};this.addPath(Oo(v),{[k]:Pt})}}),d&&(this.rootDoc.tags=Co(d))}};import{createRequest as cs,createResponse as ds}from"node-mocks-http";var ms=e=>cs({...e,headers:{"content-type":w.json,...e?.headers}}),ls=e=>ds(e),us=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Mr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},No=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ms(e),s=ls({req:n,...t});s.req=t?.req||n,n.res=s;let i=us(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},fs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=No(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},ys=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=No(r),d=tt(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:X(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Zo from"ramda";import Ot from"typescript";import{z as Hs}from"zod/v4";import*as Mo from"ramda";import _ from"typescript";import*as U from"ramda";import u from"typescript";var a=u.factory,yt=[a.createModifier(u.SyntaxKind.ExportKeyword)],gs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ve={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Vt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Jt=(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)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gt=e=>typeof e=="string"&&hs.test(e)?a.createIdentifier(e):P(e),gt=(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)))),ht=(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])=>ht(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Wt=(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&&U.map(f,t)):e,Yt=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,Gt(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?Vt(i,p.join(" ")):i},Qt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),Xt=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),I=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&yt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),er=(e,t)=>D(e,a.createUnionTypeNode(U.map(M,t)),{expose:!0}),D=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?yt:void 0,e,n&&nr(n),t);return o?Vt(s,o):s},zo=(e,t)=>a.createPropertyDeclaration(Ve.public,e,void 0,f(t),void 0),tr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ve.public,void 0,e,void 0,o&&nr(o),t,n,a.createBlock(r)),rr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(yt,e,r&&nr(r),void 0,t),or=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),bt=e=>f(Promise.name,[e]),xt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?yt:void 0,e,void 0,void 0,t);return o?Vt(n,o):n},nr=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)}),Oe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?U.map(ht,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),St=(e,t)=>f("Extract",[e,t]),sr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),K=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),jo=e=>a.createUnionTypeNode([f(e),bt(e)]),ir=(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),M=e=>a.createLiteralTypeNode(P(e)),bs=[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],Lo=e=>bs.includes(e.kind);var Rt=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=er("Method",$t);someOfType=D("SomeOf",K("T",or("T")),{params:["T"]});requestType=D("Request",or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>er(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>xt(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(Gt(t),a.createArrayLiteralExpression(Mo.map(P,r))))),{expose:!0});makeImplementationType=()=>D(this.#e.implementationType,ir({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},bt(_.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:_.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>I(this.#e.parseRequestFn,Oe({[this.#e.requestParameter.text]:_.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]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt},a.createBlock([I(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([sr(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(gt(":",[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=()=>tr(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:K(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[I(Xt(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:bt(K(this.interfaces.response,"K"))});makeClientClass=t=>rr(t,[Wt([ht(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ve.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>gt("?",[Me(URLSearchParams.name,t)]);#o=()=>Me(URL.name,gt("",[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(_.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=()=>Wt(Le({request:"K",params:K(this.interfaces.input,"K")}),[I(Xt(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)),sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Re(O("event"),t)]);#i=()=>tr(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:ir({[this.#e.dataParameter.text]:K(St("R",Qt(this.#s("E"))),M(O("data")))},jo(_.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:K("R",M(O("event")))}});makeSubscriptionClass=t=>rr(t,[zo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:St(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(_.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:St(K(this.interfaces.positive,"K"),Qt(this.#s(_.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 xs}from"zod/v4";var ar=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=V(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>ar(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:q}=b,Ss={[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},pr={name:E.path(["name","text"]),type:E.path(["type"]),optional:E.path(["questionToken"])},Rs=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(b.SyntaxKind.UndefinedKeyword):M(r));return t.length===1?t[0]:q.createUnionTypeNode(t)},Os=(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}=xs.get(p)||{};return Re(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return q.createTypeLiteralNode(s)};return Pr(e,{io:t?"output":"input"})?o(e,n):n()},Ts=({_zod:{def:e}},{next:t})=>q.createArrayTypeNode(t(e.element)),Ps=({_zod:{def:e}})=>q.createUnionTypeNode(Object.values(e.entries).map(M)),ws=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(Lo(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},Es=e=>Ss?.[e.kind],vs=({_zod:{def:e}},{next:t})=>t(e.innerType),ks=({_zod:{def:e}},{next:t})=>q.createUnionTypeNode([t(e.innerType),M(null)]),As=({_zod:{def:e}},{next:t})=>q.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:q.createRestTypeNode(t(e.rest)))),Cs=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Is=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(pr.name,...o))return!1;if(E.both(E.eqBy(pr.type),E.eqBy(pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),Ns=({_zod:{def:e}},{next:t})=>Is([e.left,e.right].map(t)),ae=e=>()=>f(e),cr=({_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(!te(o,"transform"))return t(o);let s=t(n),i=rt(o,Es(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)},js=()=>M(null),Ls=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ms=e=>{let t=f(b.SyntaxKind.StringKeyword),r=f("Buffer"),o=q.createUnionTypeNode([t,r]);return te(e,"string")?t:te(e,"union")?o:r},Zs=(e,{next:t})=>t(e._zod.def.shape.raw),$s={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),[de]:ae(b.SyntaxKind.StringKeyword),[me]:ae(b.SyntaxKind.StringKeyword),null:js,array:Ts,tuple:As,record:Cs,object:Os,literal:Rs,intersection:Ns,union:ws,default:cr,enum:Ps,optional:vs,nullable:ks,catch:cr,pipe:zs,lazy:Ls,readonly:cr,[se]:Ms,[$]:Zs},dr=(e,{brandHandling:t,ctx:r})=>ar(e,{rules:{...t,...$s},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var mr=class extends Rt{#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=M(null);this.#t.set(t,D(o,n)),this.#t.set(t,D(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=Hs.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=re.bind(null,v,y),{isDeprecated:L,inputSchema:R,tags:A}=h,C=`${v} ${y}`,F=D(k("input"),dr(R,c),{comment:C});this.#e.push(F);let N=Ce.reduce((Ge,pe)=>{let We=h.getResponses(pe),Ye=Zo.chain(([Tt,{schema:Pt,mimeTypes:Q,statusCodes:ce}])=>{let Xe=D(k(pe,"variant",`${Tt+1}`),dr(Q?Pt:p,m),{comment:C});return this.#e.push(Xe),ce.map(wt=>Re(wt,Xe.name))},Array.from(We.entries())),Qe=xt(k(pe,"response","variants"),Ye,{comment:C});return this.#e.push(Qe),Object.assign(Ge,{[pe]:Qe})},{});this.paths.add(y);let Y=M(C),Te={input:f(F.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([K(this.interfaces.positive,Y),K(this.interfaces.negative,Y)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:L,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:Jt(r,t)).join(`
19
+ `):void 0}print(t){let r=this.#n(t),o=r&&Ot.addSyntheticLeadingComment(Ot.addSyntheticLeadingComment(a.createEmptyStatement(),Ot.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Ot.SyntaxKind.MultiLineCommentTrivia,`
20
+ ${r}`);return this.#e.concat(o||[]).map((n,s)=>Jt(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 Ho=(e,t)=>Ze.object({data:t,event:Ze.literal(e),id:Ze.string().optional(),retry:Ze.int().positive().optional()}),Ks=(e,t,r)=>Ho(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),qs=1e4,$o=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":w.sse,"cache-control":"no-cache"}),Fs=e=>new B({handler:async({response:t})=>setTimeout(()=>$o(t),qs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{$o(t),t.write(Ks(e,r,o),"utf-8"),t.flush?.()}}}),Bs=e=>new he({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Ho(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);Fe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ge(i),"utf-8")}t.end()}}),lr=class extends xe{constructor(t){super(Bs(t)),this.middlewares=[Fs(t)]}};var Us={dateIn:fr,dateOut:yr,form:hr,file:st,upload:br,raw:Rr};export{Ue as BuiltinLogger,De as DependsOnMethod,_t as Documentation,G as DocumentationError,xe as EndpointsFactory,lr as EventStreamFactory,W as InputValidationError,mr as Integration,B as Middleware,Ke as MissingPeerError,fe as OutputValidationError,he as ResultHandler,ye as RoutingError,_e as ServeStatic,pn as arrayEndpointsFactory,Mt as arrayResultHandler,Mn as attachRouting,_o as createConfig,Zn as createServer,an as defaultEndpointsFactory,be as defaultResultHandler,we as ensureHttpError,Us as ez,ee as getMessageFromError,fs as testEndpoint,ys 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.3",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {