express-zod-api 24.7.0 → 24.7.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
@@ -2,6 +2,27 @@
2
2
 
3
3
  ## Version 24
4
4
 
5
+ ### v24.7.3
6
+
7
+ - Fixed the depiction of the negative response to `HEAD` requests:
8
+ - Should have no response body, exactly as the positive one;
9
+ - This version corrects the implementation introduced in [v24.7.0](#v2470).
10
+
11
+ ### v24.7.2
12
+
13
+ - Fixed the negative response MIME type for ~~`arrayResultHandler`~~ (deprecated entity):
14
+ - Should have been `text/plain`.
15
+
16
+ ### v24.7.1
17
+
18
+ - Compatibility fix for `zod@^3.25.68` and `^4.0.0`:
19
+ - Previously typed metadata properties `example` and `examples` were removed from `zod` core:
20
+ See [Commit ee5615d](https://github.com/colinhacks/zod/commit/ee5615d76b93aac15d7428a17b834a062235f6a1);
21
+ - This version restores those properties as a part of Zod plugin in order to comply to the existing implementation;
22
+ - The `example` property is marked as deprecated and will be removed in v25 — please refrain from using it;
23
+ - The `examples` property still supports an object for backward compatibility, but it will only support array in v25;
24
+ - To avoid confusion, consider using the Zod plugin's method `.example()` where possible (except `ez.dateIn()`).
25
+
5
26
  ### v24.7.0
6
27
 
7
28
  - Supporting `HEAD` method:
@@ -9,10 +30,10 @@
9
30
  - It is the built-in feature of Express to handle `HEAD` requests by the handlers for `GET` requests;
10
31
  - Therefore, each `Endpoint` supporting `get` method also handles `head` requests (no work needed);
11
32
  - Added `HEAD` method to CORS response headers, along with `OPTIONS`, for `GET` method supporting endpoints;
12
- - Positive response to `HEAD` request should contain same headers as `GET` would, but without the body:
33
+ - ~~Positive~~ Response to `HEAD` request should contain same headers as `GET` would, but without the body:
13
34
  - Added `head` request depiction to the generated `Documentation`;
14
35
  - Added `head` request types to the generated `Integration` client;
15
- - Positive response to `HEAD` request should contain the `Content-Length` header:
36
+ - ~~Positive~~ Response to `HEAD` request should contain the `Content-Length` header:
16
37
  - `ResultHandler`s using `response.send()` (as well as its shorthands such as `.json()`) automatically do that
17
38
  instead of sending the response body (no work needed);
18
39
  - Other approaches, such as stream piping, might require to implement `Content-Length` header for `HEAD` requests;
@@ -1,132 +1,96 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- We as members, contributors, and leaders pledge to make participation in our
6
- community a harassment-free experience for everyone, regardless of age, body
7
- size, visible or invisible disability, ethnicity, sex characteristics, gender
8
- identity and expression, level of experience, education, socio-economic status,
9
- nationality, personal appearance, race, caste, color, religion, or sexual
10
- identity and orientation.
11
-
12
- We pledge to act and interact in ways that contribute to an open, welcoming,
13
- diverse, inclusive, and healthy community.
14
-
15
- ## Our Standards
16
-
17
- Examples of behavior that contributes to a positive environment for our
18
- community include:
19
-
20
- - Demonstrating empathy and kindness toward other people
21
- - Being respectful of differing opinions, viewpoints, and experiences
22
- - Giving and gracefully accepting constructive feedback
23
- - Accepting responsibility and apologizing to those affected by our mistakes,
24
- and learning from the experience
25
- - Focusing on what is best not just for us as individuals, but for the overall
26
- community
27
-
28
- Examples of unacceptable behavior include:
29
-
30
- - The use of sexualized language or imagery, and sexual attention or advances of
31
- any kind
32
- - Trolling, insulting or derogatory comments, and personal or political attacks
33
- - Public or private harassment
34
- - Publishing others' private information, such as a physical or email address,
35
- without their explicit permission
36
- - Other conduct which could reasonably be considered inappropriate in a
37
- professional setting
38
-
39
- ## Enforcement Responsibilities
40
-
41
- Community leaders are responsible for clarifying and enforcing our standards of
42
- acceptable behavior and will take appropriate and fair corrective action in
43
- response to any behavior that they deem inappropriate, threatening, offensive,
44
- or harmful.
45
-
46
- Community leaders have the right and responsibility to remove, edit, or reject
47
- comments, commits, code, wiki edits, issues, and other contributions that are
48
- not aligned to this Code of Conduct, and will communicate reasons for moderation
49
- decisions when appropriate.
50
-
51
- ## Scope
52
-
53
- This Code of Conduct applies within all community spaces, and also applies when
54
- an individual is officially representing the community in public spaces.
55
- Examples of representing our community include using an official e-mail address,
56
- posting via an official social media account, or acting as an appointed
57
- representative at an online or offline event.
58
-
59
- ## Enforcement
60
-
61
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
- reported to the community leaders responsible for enforcement by
63
- [email](https://github.com/RobinTail/express-zod-api/blob/master/package.json#L14).
64
- All complaints will be reviewed and investigated promptly and fairly.
65
-
66
- All community leaders are obligated to respect the privacy and security of the
67
- reporter of any incident.
68
-
69
- ## Enforcement Guidelines
70
-
71
- Community leaders will follow these Community Impact Guidelines in determining
72
- the consequences for any action they deem in violation of this Code of Conduct:
73
-
74
- ### 1. Correction
75
-
76
- **Community Impact**: Use of inappropriate language or other behavior deemed
77
- unprofessional or unwelcome in the community.
78
-
79
- **Consequence**: A private, written warning from community leaders, providing
80
- clarity around the nature of the violation and an explanation of why the
81
- behavior was inappropriate. A public apology may be requested.
82
-
83
- ### 2. Warning
84
-
85
- **Community Impact**: A violation through a single incident or series of
86
- actions.
87
-
88
- **Consequence**: A warning with consequences for continued behavior. No
89
- interaction with the people involved, including unsolicited interaction with
90
- those enforcing the Code of Conduct, for a specified period of time. This
91
- includes avoiding interactions in community spaces as well as external channels
92
- like social media. Violating these terms may lead to a temporary or permanent
93
- ban.
94
-
95
- ### 3. Temporary Ban
96
-
97
- **Community Impact**: A serious violation of community standards, including
98
- sustained inappropriate behavior.
99
-
100
- **Consequence**: A temporary ban from any sort of interaction or public
101
- communication with the community for a specified period of time. No public or
102
- private interaction with the people involved, including unsolicited interaction
103
- with those enforcing the Code of Conduct, is allowed during this period.
104
- Violating these terms may lead to a permanent ban.
105
-
106
- ### 4. Permanent Ban
107
-
108
- **Community Impact**: Demonstrating a pattern of violation of community
109
- standards, including sustained inappropriate behavior, harassment of an
110
- individual, or aggression toward or disparagement of classes of individuals.
111
-
112
- **Consequence**: A permanent ban from any sort of public interaction within the
113
- community.
114
-
115
- ## Attribution
116
-
117
- This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
- version 2.1, available at
119
- [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
-
121
- Community Impact Guidelines were inspired by
122
- [Mozilla's code of conduct enforcement ladder][mozilla coc].
123
-
124
- For answers to common questions about this code of conduct, see the FAQ at
125
- [https://www.contributor-covenant.org/faq][faq]. Translations are available at
126
- [https://www.contributor-covenant.org/translations][translations].
127
-
128
- [homepage]: https://www.contributor-covenant.org
129
- [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
- [mozilla coc]: https://github.com/mozilla/diversity
131
- [faq]: https://www.contributor-covenant.org/faq
132
- [translations]: https://www.contributor-covenant.org/translations
1
+ # Code of Conduct for the Express Zod API Community
2
+
3
+ This Code of Conduct is adapted from the [Berlin Code of Conduct](https://berlincodeofconduct.org/en),
4
+ licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
5
+
6
+ Our primary goal is to foster an inclusive, friendly, safe, and welcoming environment for all
7
+ contributors, users, and participants in the Express Zod API project, regardless of gender,
8
+ sexual orientation, ability, ethnicity, socioeconomic status, or religion.
9
+
10
+ A supplemental goal is to promote **open-source citizenship** by encouraging all participants to
11
+ understand the impact of their actions on the community and to actively counteract inequality and
12
+ abuses of power within our project spaces.
13
+
14
+ ## Key Expectations for Participants
15
+
16
+ The Express Zod API community expects participants to:
17
+
18
+ - **Participate authentically and actively.** Your contributions should be genuine and made in good
19
+ faith towards the project's goals.
20
+ - **Exercise consideration and respect** in your speech and actions within all project communications
21
+ (e.g., GitHub issues, pull requests, discussions, Discord/chat).
22
+ - **Attempt collaboration before conflict.** When disagreements arise, seek to understand different
23
+ perspectives and find common ground respectfully before escalating.
24
+ - **Refrain from demeaning, discriminatory, or harassing behavior and speech.** This applies to all
25
+ online interactions, written communication, and any in-person events related to the project.
26
+ - **Be mindful of your surroundings** in shared online spaces. If you notice a dangerous situation,
27
+ someone in distress, or violations of this Code of Conduct, please report it to the project
28
+ maintainers.
29
+
30
+ ## Unacceptable Behaviors
31
+
32
+ The following behaviors are considered unacceptable within the Express Zod API community:
33
+
34
+ - **Intimidating, harassing, abusive, discriminatory, derogatory, or demeaning speech or actions** by
35
+ any participant in our community online or in any related context.
36
+ - **Harmful or prejudiced comments** related to gender, sexual orientation, disability, mental
37
+ illness, neuro(a)typicality, physical appearance, body size, race, ethnicity, age, religion, or
38
+ other personal attributes.
39
+ - **Inappropriate use of nudity and/or sexual images** in public online spaces (e.g., as profile
40
+ pictures, in discussions).
41
+ - **Deliberate intimidation, stalking, or following** of community members.
42
+ - **Harassing photography or recording** of in-person interactions without explicit consent.
43
+ - **Sustained disruption** of discussions, talks, or other online activities.
44
+ - **Inappropriate physical contact** (in in-person contexts).
45
+ - **Unwelcome sexual attention.** This includes sexualized comments or jokes, inappropriate touching,
46
+ groping, and unwelcome sexual advances.
47
+ - **Advocating for, or encouraging, any of the above behaviors.**
48
+
49
+ ## Consequences of Unacceptable Behavior
50
+
51
+ Unacceptable behavior from any participant will not be tolerated.
52
+
53
+ - Anyone asked to stop unacceptable behavior is expected to comply **immediately**.
54
+ - If a participant engages in unacceptable behavior, the project maintainers may take any action they
55
+ deem appropriate, including a temporary ban, permanent expulsion from the community, or
56
+ editing/deletion of offending content, without warning or refund (if applicable to any paid
57
+ access/materials).
58
+
59
+ ## Reporting Guidelines
60
+
61
+ If you are subject to, or witness, unacceptable behavior, or have any other concerns, please notify
62
+ the project maintainers as soon as possible.
63
+
64
+ **How to Report:**
65
+
66
+ - **For private and sensitive reports:** Contact the core maintainers directly via
67
+ [email](https://github.com/RobinTail/express-zod-api/blob/master/express-zod-api/package.json#L14).
68
+ - **For less sensitive or public issues:** You may open a GitHub issue, but be mindful of privacy and
69
+ consider if direct email is more appropriate.
70
+
71
+ Project maintainers will be available to help participants contact local law enforcement, provide
72
+ escorts, or otherwise assist those experiencing unacceptable behavior to feel safe. Your grievance
73
+ will be handled seriously and investigated according to existing project governing policies. We
74
+ respect concerns about false accusations and will handle them according to our project's dispute
75
+ resolution processes.
76
+
77
+ ## Scope and Applicability
78
+
79
+ This Code of Conduct applies to all Express Zod API community participants in all official project
80
+ venues, both online and potentially in-person (e.g., meetups, sprints), and in one-on-one
81
+ communications related to project business. This includes, but is not limited to:
82
+
83
+ - The [GitHub repository](https://github.com/RobinTail/express-zod-api);
84
+ - GitHub Issues and Pull Requests;
85
+ - GitHub Discussions;
86
+ - Project-related chat platforms (e.g., Discord, Slack if applicable);
87
+ - Any official project social media accounts;
88
+ - Any future in-person events or workshops organized by the project.
89
+
90
+ ## License
91
+
92
+ This Code of Conduct, being a derivative work of the Berlin Code of Conduct, is also licensed under
93
+ the [CC BY-SA 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/). You are free to share
94
+ and adapt this work, provided you give appropriate credit, provide a link to the license, and
95
+ indicate if changes were made. If you remix, transform, or build upon the material, you must
96
+ distribute your contributions under the same license as the original.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var bn=Object.create;var ft=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var On=Object.getPrototypeOf,Tn=Object.prototype.hasOwnProperty;var Pn=(e,t)=>{for(var r in t)ft(e,r,{get:t[r],enumerable:!0})},Ir=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rn(t))!Tn.call(e,n)&&n!==r&&ft(e,n,{get:()=>t[n],enumerable:!(o=Sn(t,n))||o.enumerable});return e};var g=(e,t,r)=>(r=e!=null?bn(On(e)):{},Ir(t||!e||!e.__esModule?ft(r,"default",{value:e,enumerable:!0}):r,e)),wn=e=>Ir(ft({},"__esModule",{value:!0}),e);var Gs={};Pn(Gs,{BuiltinLogger:()=>qe,DependsOnMethod:()=>De,Documentation:()=>vt,DocumentationError:()=>W,EndpointsFactory:()=>he,EventStreamFactory:()=>Bt,InputValidationError:()=>Y,Integration:()=>Zt,Middleware:()=>D,MissingPeerError:()=>Le,OutputValidationError:()=>ze,ResultHandler:()=>ye,RoutingError:()=>de,ServeStatic:()=>Ue,arrayEndpointsFactory:()=>to,arrayResultHandler:()=>Pt,attachRouting:()=>Zo,createConfig:()=>Nr,createServer:()=>Bo,defaultEndpointsFactory:()=>eo,defaultResultHandler:()=>ge,ensureHttpError:()=>Ce,ez:()=>xn,getExamples:()=>B,getMessageFromError:()=>ae,testEndpoint:()=>an,testMiddleware:()=>pn});module.exports=wn(Gs);var G=g(require("ramda"),1),V=require("zod/v4");var Ar=require("zod/v4"),Ne=Symbol.for("express-zod-api"),re=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},B=e=>{let{examples:t,example:r}=Ar.globalRegistry.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Cn=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=()=>{}}),En=function(e){let t=B(this).slice();return t.push(e),this.meta({examples:t})},kn=function(){return this.meta({deprecated:!0})},vn=function(e){return this.meta({default:e})},In=function(e){return this.check(new Cn({brand:e,check:"$EZBrandCheck"}))},An=function(e){let t=typeof e=="function"?e:G.renameKeys(G.reject(G.isNil,e)),r=t(G.map(G.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(!(Ne in globalThis)){globalThis[Ne]=!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:{value:En,writable:!1},deprecated:{value:kn,writable:!1},brand:{set(){},get(){return In.bind(this)}}})}Object.defineProperty(V.z.ZodDefault.prototype,"label",{value:vn,writable:!1}),Object.defineProperty(V.z.ZodObject.prototype,"remap",{value:An,writable:!1})}function Nr(e){return e}var tr=require("zod/v4");var fe=g(require("ramda"),1),et=require("zod/v4");var ue=g(require("ramda"),1),Gt=require("zod/v4");var Mr=require("zod/v4"),Se=Symbol("Buffer"),yt=()=>Mr.z.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(Se);var Me=require("zod/v4"),Re=Symbol("DateIn"),jr=({examples:e,...t}={})=>Me.z.union([Me.z.iso.date(),Me.z.iso.datetime(),Me.z.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Me.z.date()).brand(Re).meta(t);var zr=require("zod/v4"),Oe=Symbol("DateOut"),Lr=(e={})=>zr.z.date().transform(t=>t.toISOString()).brand(Oe).meta(e);var Br=require("zod/v4");var $=g(require("ramda"),1),je=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 $r=["get","post","put","delete","patch"],Zr=[...$r,"head"],Te=e=>$r.includes(e);var Ut=/:([A-Za-z0-9_]+)/g,gt=e=>e.match(Ut)?.map(t=>t.slice(1))||[],Nn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Mn={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},jn=["body","query","params"],Ft=e=>e.method.toLowerCase(),_t=(e,t={})=>{if(e==="options")return[];let r=e==="head"?"get":Te(e)?e:void 0;return(r?t[r]||Mn[r]:void 0)||jn},ht=(e,t={})=>{let r=Ft(e);return _t(r,t).filter(o=>o==="files"?Nn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},ie=e=>e instanceof Error?e:e instanceof je.z.ZodError?new je.z.ZodRealError(e.issues):new Error(String(e)),ae=e=>e instanceof je.z.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${je.z.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,pe=(e,t)=>k(e)&&"_zod"in e&&(t?$.path(["_zod","def","type"],e)===t:!0),Pe=(e,t,r)=>e.length&&t.length?$.xprod(e,t).map(r):e.concat(t),Jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ce=(...e)=>{let t=$.chain(o=>o.split(/[^A-Z0-9]/gi),e);return $.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Jt).join("")},xt=$.tryCatch((e,t)=>typeof je.z.parse(e,t),$.always(void 0)),k=e=>typeof e=="object"&&e!==null,we=$.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production"),bt=(e,t)=>!(e==="head"&&t==="positive");var de=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},W=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.`}},We=class extends Error{name="IOSchemaError"},St=class extends We{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},ze=class extends We{constructor(r){let o=new Br.z.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(ae(o),{cause:r});this.cause=r}name="OutputValidationError"},Y=class extends We{constructor(r){super(ae(r),{cause:r});this.cause=r}name="InputValidationError"},me=class extends Error{constructor(r,o){super(ae(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Le=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Vt=require("zod/v4"),Ye=Symbol("Form"),Hr=e=>(e instanceof Vt.z.ZodObject?e:Vt.z.object(e)).brand(Ye);var Kr=require("zod/v4"),le=Symbol("Upload"),qr=()=>Kr.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(le);var Dr=require("zod/v4");var q=Symbol("Raw"),Ur=Dr.z.object({raw:yt()}),zn=e=>Ur.extend(e).brand(q);function Fr(e){return e?zn(e):Ur.brand(q)}var _r=(e,{io:t,condition:r})=>ue.tryCatch(()=>{Gt.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new St(o)}})},o=>o.cause)(),Jr=(e,{io:t})=>{let o=[Gt.z.toJSONSchema(e,{io:t,unrepresentable:"any"})];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},Vr=e=>_r(e,{condition:t=>{let r=re(t);return typeof r=="symbol"&&[le,q,Ye].includes(r)},io:"input"}),Ln=["nan","symbol","map","set","bigint","void","promise","never"],Wt=(e,t)=>_r(e,{io:t,condition:r=>{let o=re(r),{type:n}=r._zod.def;return!!(Ln.includes(n)||o===Se||t==="input"&&(n==="date"||o===Oe)||t==="output"&&(o===Re||o===q||o===le))}});var Rt=g(require("http-errors"),1);var Qe=g(require("http-errors"),1),Gr=g(require("ramda"),1),Wr=require("zod/v4");var Yt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Wr.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 me(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}),Ce=e=>(0,Qe.isHttpError)(e)?e:(0,Qe.default)(e instanceof Y?400:500,ae(e),{cause:e.cause||e}),Ee=e=>we()&&!e.expose?(0,Qe.default)(e.statusCode).message:e.message,Yr=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>Pe(t,B(o).map(Gr.objOf(r)),([n,s])=>({...n,...s})),[]);var Ot=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ee((0,Rt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:(0,Rt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Qt=require("zod/v4");var Xt=class{},D=class extends Xt{#e;#t;#r;constructor({input:t=Qt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}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 Qt.z.ZodError?new Y(o):o}}},$e=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 Ze=class{nest(t){return Object.assign(t,{"":this})}};var tt=class extends Ze{},Tt=class e extends tt{#e;#t=fe.once(()=>{if(B(this.#e.outputSchema).length||!pe(this.#e.outputSchema,"object"))return;let t=Yr(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();et.globalRegistry.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Vr(this.#e.inputSchema);if(t){let r=re(t);if(r===le)return"upload";if(r===q)return"raw";if(r===Ye)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=fe.pluck("security",this.#e.middlewares||[]);return fe.reject(fe.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof et.z.ZodError?new ze(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof $e))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof et.z.ZodError?new Y(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){Ot({...t,error:new me(ie(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ft(t),i={},p={output:{},error:null},d=ht(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:ie(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Qr=g(require("ramda"),1),Xr=(e,t)=>Qr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));var j=require("zod/v4");var Be={positive:200,negative:400},He=Object.keys(Be);var er=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ye=class extends er{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Yt(this.#e,{variant:"positive",args:[t],statusCodes:[Be.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[Be.negative],mimeTypes:[E.json]})}},ge=new ye({positive:e=>{let t=j.z.object({status:j.z.literal("success"),data:e}),r=B(e);return r.length&&j.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:j.z.object({status:j.z.literal("error"),error:j.z.object({message:j.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Ce(e);return Xe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Ee(i)}})}n.status(Be.positive).json({status:"success",data:r})}}),Pt=new ye({positive:e=>{let t=e instanceof j.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof j.z.ZodArray?e.shape.items:j.z.array(j.z.any());if(B(t).length)return t;let r=B(e).filter(o=>k(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();j.globalRegistry.remove(t).add(t,{...o,examples:r})}return t},negative:j.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ce(r);return Xe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Ee(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Be.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var he=class e{constructor(t){this.resultHandler=t}middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r}addMiddleware(t){return this.#e(t instanceof D?t:new D(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new $e(...t))}addOptions(t){return this.#e(new D({handler:t}))}build({input:t=tr.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,y=typeof o=="function"?o:C=>o&&`${o}${C==="head"?"__HEAD":""}`,b=typeof n=="string"?[n]:n||[],h=typeof s=="string"?[s]:s||[];return new Tt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:h,methods:m,getOperationId:y,inputSchema:Xr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:tr.z.object({}),handler:async o=>(await t(o),{})})}},eo=new he(ge),to=new he(Pt);var ao=g(require("ansis"),1),po=require("node:util"),or=require("node:perf_hooks");var Q=require("ansis"),ro=g(require("ramda"),1);var rr={debug:Q.blue,info:Q.green,warn:(0,Q.hex)("#FFA500"),error:Q.red,ctx:Q.cyanBright},wt={debug:10,info:20,warn:30,error:40},oo=e=>k(e)&&Object.keys(wt).some(t=>t in e),no=e=>e in wt,so=(e,t)=>wt[e]<wt[t],$n=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ke=ro.memoizeWith((e,t)=>`${e}${t}`,$n),io=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=ao.default.isSupported(),level:r=we()?"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,po.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"||so(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?rr.ctx(s):s),d.push(p?`${rr[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=or.performance.now();return()=>{let o=or.performance.now()-r,{message:n,severity:s="debug",formatter:i=io}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var co=g(require("ramda"),1);var De=class e extends Ze{#e;constructor(t){super(),this.#e=t}get entries(){let t=co.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 mo=g(require("express"),1),Ue=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,mo.default.static(...this.#e))}};var rt=g(require("express"),1),zo=g(require("node:http"),1),Lo=g(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>g(require(e))))[t]}catch{}throw new Le(e)};var yo=g(require("http-errors"),1);var nr=require("zod/v4");var S=g(require("ramda"),1);var Zn=e=>e.type==="object",Bn=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",{cause:{a:e,b:t}})}),Hn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),lo=S.pair(!0),_e=(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"&&Hn(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(lo,i.anyOf)),i.oneOf&&r.push(...S.map(lo,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=Pe(o.examples?.filter(k)||[],i.examples.filter(k),([p,d])=>S.mergeDeepRight(p,d))),!!Zn(i)&&(r.push([s,{examples:Kn(i)}]),i.properties&&(o.properties=(t==="throw"?Bn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),k(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},Kn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=k(o)?o:{};return Pe(t,n.map(S.objOf(r)),([s,i])=>({...s,...i}))},[]);var Ct=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=[nr.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=Wt(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(E.json))continue;let i=Wt(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=gt(t);if(s.length===0)return;let i=n?.flat||_e(nr.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 Et=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},qn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Te(t)?[r,t]:[e]},Dn=e=>e.trim().split("/").filter(Boolean).join("/"),uo=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=qn(r);return[[t||""].concat(Dn(n)||[]).join("/"),o,s]}),Un=(e,t)=>{throw new de("Route with explicit method can only be assigned with Endpoint",e,t)},fo=(e,t,r)=>{if(!(!r||r.includes(e)))throw new de(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},sr=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new de("Route has a duplicate",e,t);r.add(o)},Je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=uo(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof tt)if(p)sr(p,s,n),fo(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)sr(c,s,n),t(c,s,i)}else if(p&&Un(p,s),i instanceof Ue)r&&i.apply(s,r);else if(i instanceof De)for(let[d,c]of i.entries){let{methods:m}=c;sr(d,s,n),fo(d,s,m),t(d,s,c)}else o.unshift(...uo(i,s))}};var go=g(require("ramda"),1),ho=e=>e.sort((t,r)=>+Te(r)-+Te(t)||t.localeCompare(r)).join(", ").toUpperCase(),Fn=e=>({method:t},r,o)=>{let n=ho(e);r.set({Allow:n});let s=(0,yo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},_n=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":ho(e),"Access-Control-Allow-Headers":"content-type"}),ir=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=we()?void 0:new Ct(t()),i=new Map;Je({routing:o,onEndpoint:(c,m,y)=>{we()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let b=n?.[y.requestType]||[],h=go.pair(b,y);i.has(m)||i.set(m,new Map(r.cors?[["options",h]]:[])),i.get(m)?.set(c,h)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[b,[h,C]]of m){let I=h.slice().concat(async(L,R)=>{let A=t(L);return C.execute({request:L,response:R,logger:A,config:r})});r.cors&&I.unshift(async(L,R,A)=>{let N=t(L),K=_n(y),M=typeof r.cors=="function"?await r.cors({request:L,endpoint:C,logger:N,defaultHeaders:K}):K;R.set(M),A()}),e[b](c,...I)}r.wrongMethodBehavior!==404&&d.set(c,Fn(y))}for(let[c,m]of d)e.all(c,m)};var wo=g(require("http-errors"),1);var To=require("node:timers/promises");var xo=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",bo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",So=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Ro=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Oo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Po=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(xo(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",Ro);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(So(c)||bo(c))&&i(c);for await(let c of(0,To.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(Oo))};return{sockets:n,shutdown:()=>o??=d()}};var Co=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:ie(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Eo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,wo.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){Ot({response:o,logger:s,error:new me(ie(i),n)})}},Jn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Vn=e=>({log:e.debug.bind(e)}),ko=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:Vn(m)})(p,d,c)}),o&&i.push(Jn(o)),i},vo=(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[Ne]={logger:i}),s()},Ao=e=>t=>t?.res?.locals[Ne]?.logger||e,No=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),Mo=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=Po(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};var H=require("ansis"),jo=e=>{if(e.columns<132)return;let t=(0,H.italic)("Proudly supports transgender community.".padStart(109)),r=(0,H.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,H.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,H.italic)("for Ashley".padEnd(20)),s=(0,H.hex)("#F5A9B8"),i=(0,H.hex)("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(H.whiteBright,5,7).fill(s,7,9).fill(i,9,12).fill(H.gray,12,13),d=`
1
+ "use strict";var bn=Object.create;var ft=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var On=Object.getPrototypeOf,Tn=Object.prototype.hasOwnProperty;var Pn=(e,t)=>{for(var r in t)ft(e,r,{get:t[r],enumerable:!0})},Ir=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rn(t))!Tn.call(e,n)&&n!==r&&ft(e,n,{get:()=>t[n],enumerable:!(o=Sn(t,n))||o.enumerable});return e};var g=(e,t,r)=>(r=e!=null?bn(On(e)):{},Ir(t||!e||!e.__esModule?ft(r,"default",{value:e,enumerable:!0}):r,e)),wn=e=>Ir(ft({},"__esModule",{value:!0}),e);var Gs={};Pn(Gs,{BuiltinLogger:()=>qe,DependsOnMethod:()=>De,Documentation:()=>vt,DocumentationError:()=>W,EndpointsFactory:()=>ge,EventStreamFactory:()=>Ht,InputValidationError:()=>Y,Integration:()=>Zt,Middleware:()=>D,MissingPeerError:()=>Le,OutputValidationError:()=>je,ResultHandler:()=>fe,RoutingError:()=>ce,ServeStatic:()=>Fe,arrayEndpointsFactory:()=>to,arrayResultHandler:()=>Pt,attachRouting:()=>Zo,createConfig:()=>Nr,createServer:()=>Ho,defaultEndpointsFactory:()=>eo,defaultResultHandler:()=>ye,ensureHttpError:()=>Ce,ez:()=>xn,getExamples:()=>H,getMessageFromError:()=>ie,testEndpoint:()=>an,testMiddleware:()=>pn});module.exports=wn(Gs);var G=g(require("ramda"),1),V=require("zod/v4");var Ar=require("zod/v4"),Ne=Symbol.for("express-zod-api"),re=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},H=e=>{let{examples:t,example:r}=Ar.globalRegistry.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Cn=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=()=>{}}),En=function(e){let t=H(this).slice();return t.push(e),this.meta({examples:t})},kn=function(){return this.meta({deprecated:!0})},vn=function(e){return this.meta({default:e})},In=function(e){return this.check(new Cn({brand:e,check:"$EZBrandCheck"}))},An=function(e){let t=typeof e=="function"?e:G.renameKeys(G.reject(G.isNil,e)),r=t(G.map(G.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(!(Ne in globalThis)){globalThis[Ne]=!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:{value:En,writable:!1},deprecated:{value:kn,writable:!1},brand:{set(){},get(){return In.bind(this)}}})}Object.defineProperty(V.z.ZodDefault.prototype,"label",{value:vn,writable:!1}),Object.defineProperty(V.z.ZodObject.prototype,"remap",{value:An,writable:!1})}function Nr(e){return e}var tr=require("zod/v4");var ue=g(require("ramda"),1),et=require("zod/v4");var le=g(require("ramda"),1),Gt=require("zod/v4");var Mr=require("zod/v4"),Se=Symbol("Buffer"),yt=()=>Mr.z.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(Se);var Me=require("zod/v4"),Re=Symbol("DateIn"),zr=({examples:e,...t}={})=>Me.z.union([Me.z.iso.date(),Me.z.iso.datetime(),Me.z.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Me.z.date()).brand(Re).meta(t);var jr=require("zod/v4"),Oe=Symbol("DateOut"),Lr=(e={})=>jr.z.date().transform(t=>t.toISOString()).brand(Oe).meta(e);var Hr=require("zod/v4");var $=g(require("ramda"),1),ze=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 $r=["get","post","put","delete","patch"],Zr=[...$r,"head"],Te=e=>$r.includes(e);var Ft=/:([A-Za-z0-9_]+)/g,gt=e=>e.match(Ft)?.map(t=>t.slice(1))||[],Nn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Mn={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},zn=["body","query","params"],Ut=e=>e.method.toLowerCase(),_t=(e,t={})=>{if(e==="options")return[];let r=e==="head"?"get":Te(e)?e:void 0;return(r?t[r]||Mn[r]:void 0)||zn},ht=(e,t={})=>{let r=Ut(e);return _t(r,t).filter(o=>o==="files"?Nn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},se=e=>e instanceof Error?e:e instanceof ze.z.ZodError?new ze.z.ZodRealError(e.issues):new Error(String(e)),ie=e=>e instanceof ze.z.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${ze.z.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,ae=(e,t)=>k(e)&&"_zod"in e&&(t?$.path(["_zod","def","type"],e)===t:!0),Pe=(e,t,r)=>e.length&&t.length?$.xprod(e,t).map(r):e.concat(t),Jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),pe=(...e)=>{let t=$.chain(o=>o.split(/[^A-Z0-9]/gi),e);return $.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Jt).join("")},xt=$.tryCatch((e,t)=>typeof ze.z.parse(e,t),$.always(void 0)),k=e=>typeof e=="object"&&e!==null,we=$.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production"),bt=(e,t)=>!!t&&e!=="head";var ce=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},W=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.`}},We=class extends Error{name="IOSchemaError"},St=class extends We{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},je=class extends We{constructor(r){let o=new Hr.z.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(ie(o),{cause:r});this.cause=r}name="OutputValidationError"},Y=class extends We{constructor(r){super(ie(r),{cause:r});this.cause=r}name="InputValidationError"},de=class extends Error{constructor(r,o){super(ie(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Le=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Vt=require("zod/v4"),Ye=Symbol("Form"),Br=e=>(e instanceof Vt.z.ZodObject?e:Vt.z.object(e)).brand(Ye);var Kr=require("zod/v4"),me=Symbol("Upload"),qr=()=>Kr.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 Dr=require("zod/v4");var q=Symbol("Raw"),Fr=Dr.z.object({raw:yt()}),jn=e=>Fr.extend(e).brand(q);function Ur(e){return e?jn(e):Fr.brand(q)}var _r=(e,{io:t,condition:r})=>le.tryCatch(()=>{Gt.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new St(o)}})},o=>o.cause)(),Jr=(e,{io:t})=>{let o=[Gt.z.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(le.is(Object,n)){if(n.$ref==="#")return!0;o.push(...le.values(n))}le.is(Array,n)&&o.push(...le.values(n))}return!1},Vr=e=>_r(e,{condition:t=>{let r=re(t);return typeof r=="symbol"&&[me,q,Ye].includes(r)},io:"input"}),Ln=["nan","symbol","map","set","bigint","void","promise","never"],Wt=(e,t)=>_r(e,{io:t,condition:r=>{let o=re(r),{type:n}=r._zod.def;return!!(Ln.includes(n)||o===Se||t==="input"&&(n==="date"||o===Oe)||t==="output"&&(o===Re||o===q||o===me))}});var Rt=g(require("http-errors"),1);var Qe=g(require("http-errors"),1),Gr=g(require("ramda"),1),Wr=require("zod/v4");var Yt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Wr.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 de(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}),Ce=e=>(0,Qe.isHttpError)(e)?e:(0,Qe.default)(e instanceof Y?400:500,ie(e),{cause:e.cause||e}),Ee=e=>we()&&!e.expose?(0,Qe.default)(e.statusCode).message:e.message,Yr=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>Pe(t,H(o).map(Gr.objOf(r)),([n,s])=>({...n,...s})),[]);var Ot=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ee((0,Rt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:(0,Rt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Qt=require("zod/v4");var Xt=class{},D=class extends Xt{#e;#t;#r;constructor({input:t=Qt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}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 Qt.z.ZodError?new Y(o):o}}},$e=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 Ze=class{nest(t){return Object.assign(t,{"":this})}};var tt=class extends Ze{},Tt=class e extends tt{#e;#t=ue.once(()=>{if(H(this.#e.outputSchema).length||!ae(this.#e.outputSchema,"object"))return;let t=Yr(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();et.globalRegistry.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Vr(this.#e.inputSchema);if(t){let r=re(t);if(r===me)return"upload";if(r===q)return"raw";if(r===Ye)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ue.pluck("security",this.#e.middlewares||[]);return ue.reject(ue.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof et.z.ZodError?new je(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof $e))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof et.z.ZodError?new Y(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){Ot({...t,error:new de(se(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ut(t),i={},p={output:{},error:null},d=ht(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:se(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Qr=g(require("ramda"),1),Xr=(e,t)=>Qr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));var z=require("zod/v4");var He={positive:200,negative:400},Be=Object.keys(He);var er=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends er{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Yt(this.#e,{variant:"positive",args:[t],statusCodes:[He.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[He.negative],mimeTypes:[E.json]})}},ye=new fe({positive:e=>{let t=z.z.object({status:z.z.literal("success"),data:e}),r=H(e);return r.length&&z.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:z.z.object({status:z.z.literal("error"),error:z.z.object({message:z.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=Ce(e);return Xe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Ee(i)}})}n.status(He.positive).json({status:"success",data:r})}}),Pt=new fe({positive:e=>{let t=e instanceof z.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof z.z.ZodArray?e.shape.items:z.z.array(z.z.any());if(H(t).length)return t;let r=H(e).filter(o=>k(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();z.globalRegistry.remove(t).add(t,{...o,examples:r})}return t},negative:{schema:z.z.string().example("Sample error message"),mimeType:"text/plain"},handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ce(r);return Xe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Ee(i))}if("items"in t&&Array.isArray(t.items))return void e.status(He.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=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r}addMiddleware(t){return this.#e(t instanceof D?t:new D(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new $e(...t))}addOptions(t){return this.#e(new D({handler:t}))}build({input:t=tr.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,y=typeof o=="function"?o:C=>o&&`${o}${C==="head"?"__HEAD":""}`,b=typeof n=="string"?[n]:n||[],h=typeof s=="string"?[s]:s||[];return new Tt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:h,methods:m,getOperationId:y,inputSchema:Xr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:tr.z.object({}),handler:async o=>(await t(o),{})})}},eo=new ge(ye),to=new ge(Pt);var ao=g(require("ansis"),1),po=require("node:util"),or=require("node:perf_hooks");var Q=require("ansis"),ro=g(require("ramda"),1);var rr={debug:Q.blue,info:Q.green,warn:(0,Q.hex)("#FFA500"),error:Q.red,ctx:Q.cyanBright},wt={debug:10,info:20,warn:30,error:40},oo=e=>k(e)&&Object.keys(wt).some(t=>t in e),no=e=>e in wt,so=(e,t)=>wt[e]<wt[t],$n=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ke=ro.memoizeWith((e,t)=>`${e}${t}`,$n),io=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=ao.default.isSupported(),level:r=we()?"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,po.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"||so(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?rr.ctx(s):s),d.push(p?`${rr[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=or.performance.now();return()=>{let o=or.performance.now()-r,{message:n,severity:s="debug",formatter:i=io}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var co=g(require("ramda"),1);var De=class e extends Ze{#e;constructor(t){super(),this.#e=t}get entries(){let t=co.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 mo=g(require("express"),1),Fe=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,mo.default.static(...this.#e))}};var rt=g(require("express"),1),jo=g(require("node:http"),1),Lo=g(require("node:https"),1);var Ue=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>g(require(e))))[t]}catch{}throw new Le(e)};var yo=g(require("http-errors"),1);var nr=require("zod/v4");var S=g(require("ramda"),1);var Zn=e=>e.type==="object",Hn=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",{cause:{a:e,b:t}})}),Bn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),lo=S.pair(!0),_e=(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"&&Bn(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(lo,i.anyOf)),i.oneOf&&r.push(...S.map(lo,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=Pe(o.examples?.filter(k)||[],i.examples.filter(k),([p,d])=>S.mergeDeepRight(p,d))),!!Zn(i)&&(r.push([s,{examples:Kn(i)}]),i.properties&&(o.properties=(t==="throw"?Hn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),k(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},Kn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=k(o)?o:{};return Pe(t,n.map(S.objOf(r)),([s,i])=>({...s,...i}))},[]);var Ct=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=[nr.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=Wt(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 Be)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=Wt(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=gt(t);if(s.length===0)return;let i=n?.flat||_e(nr.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 Et=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},qn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Te(t)?[r,t]:[e]},Dn=e=>e.trim().split("/").filter(Boolean).join("/"),uo=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=qn(r);return[[t||""].concat(Dn(n)||[]).join("/"),o,s]}),Fn=(e,t)=>{throw new ce("Route with explicit method can only be assigned with Endpoint",e,t)},fo=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ce(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},sr=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ce("Route has a duplicate",e,t);r.add(o)},Je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=uo(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof tt)if(p)sr(p,s,n),fo(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)sr(c,s,n),t(c,s,i)}else if(p&&Fn(p,s),i instanceof Fe)r&&i.apply(s,r);else if(i instanceof De)for(let[d,c]of i.entries){let{methods:m}=c;sr(d,s,n),fo(d,s,m),t(d,s,c)}else o.unshift(...uo(i,s))}};var go=g(require("ramda"),1),ho=e=>e.sort((t,r)=>+Te(r)-+Te(t)||t.localeCompare(r)).join(", ").toUpperCase(),Un=e=>({method:t},r,o)=>{let n=ho(e);r.set({Allow:n});let s=(0,yo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},_n=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":ho(e),"Access-Control-Allow-Headers":"content-type"}),ir=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=we()?void 0:new Ct(t()),i=new Map;Je({routing:o,onEndpoint:(c,m,y)=>{we()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let b=n?.[y.requestType]||[],h=go.pair(b,y);i.has(m)||i.set(m,new Map(r.cors?[["options",h]]:[])),i.get(m)?.set(c,h)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[b,[h,C]]of m){let I=h.slice().concat(async(L,R)=>{let A=t(L);return C.execute({request:L,response:R,logger:A,config:r})});r.cors&&I.unshift(async(L,R,A)=>{let N=t(L),K=_n(y),M=typeof r.cors=="function"?await r.cors({request:L,endpoint:C,logger:N,defaultHeaders:K}):K;R.set(M),A()}),e[b](c,...I)}r.wrongMethodBehavior!==404&&d.set(c,Un(y))}for(let[c,m]of d)e.all(c,m)};var wo=g(require("http-errors"),1);var To=require("node:timers/promises");var xo=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",bo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",So=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Ro=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Oo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Po=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(xo(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",Ro);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(So(c)||bo(c))&&i(c);for await(let c of(0,To.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(Oo))};return{sockets:n,shutdown:()=>o??=d()}};var Co=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:se(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Eo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,wo.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){Ot({response:o,logger:s,error:new de(se(i),n)})}},Jn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Vn=e=>({log:e.debug.bind(e)}),ko=async({getLogger:e,config:t})=>{let r=await Ue("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:Vn(m)})(p,d,c)}),o&&i.push(Jn(o)),i},vo=(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[Ne]={logger:i}),s()},Ao=e=>t=>t?.res?.locals[Ne]?.logger||e,No=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),Mo=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=Po(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};var B=require("ansis"),zo=e=>{if(e.columns<132)return;let t=(0,B.italic)("Proudly supports transgender community.".padStart(109)),r=(0,B.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,B.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,B.italic)("for Ashley".padEnd(20)),s=(0,B.hex)("#F5A9B8"),i=(0,B.hex)("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(B.whiteBright,5,7).fill(s,7,9).fill(i,9,12).fill(B.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 $o=e=>{e.startupLogo!==!1&&jo(process.stdout);let t=e.errorHandler||ge,r=oo(e.logger)?e.logger:new qe(e.logger);r.debug("Running",{build:"v24.7.0 (CJS)",env:process.env.NODE_ENV||"development"}),No(r);let o=Io({logger:r,config:e}),s={getLogger:Ao(r),errorHandler:t},i=Eo(s),p=Co(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=$o(e);return ir({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Bo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=$o(e),p=(0,rt.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||rt.default.json()],raw:[e.rawParser||rt.default.raw(),vo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await ko({config:e,getLogger:o}):[]};ir({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,h)=>()=>b.listen(h,()=>r.info("Listening",h)),y=[];if(e.http){let b=zo.default.createServer(p);c.push(b),y.push(m(b,e.http.listen))}if(e.https){let b=Lo.default.createServer(e.https.options,p);c.push(b),y.push(m(b,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&Mo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(b=>b())}};var on=require("openapi3-ts/oas31"),nn=g(require("ramda"),1);var O=g(require("ramda"),1);var Ho=e=>k(e)&&"or"in e,Ko=e=>k(e)&&"and"in e,ar=e=>!Ko(e)&&!Ho(e),qo=e=>{let t=O.filter(ar,e),r=O.chain(O.prop("and"),O.filter(Ko,e)),[o,n]=O.partition(ar,r),s=O.concat(t,o),i=O.filter(Ho,e);return O.map(O.prop("or"),O.concat(i,n)).reduce((d,c)=>Pe(d,O.map(m=>ar(m)?[m]:m.and,c),([m,y])=>O.concat(m,y)),O.reject(O.isEmpty,[s]))};var xe=require("openapi3-ts/oas31"),l=g(require("ramda"),1),pr=require("zod/v4");var Do=["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 Uo=50,Fo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",_o={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Jo=e=>e.replace(Ut,t=>`{${t.slice(1)}}`),Wn=({},e)=>{if(e.isResponse)throw new W("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Yn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Qn=({zodSchema:e,jsonSchema:t})=>{if(!pe(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Xn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return _e(e,"throw")},(e,{jsonSchema:t})=>t),es=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ps(t.type)})},Vo=e=>e in _o,ts=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&Vo(t)&&(e.type=t),e},rs=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&Vo(t)&&(e.type=t),e},ot=e=>e,os=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new W("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Fo}};return e?.length&&(o.examples=e),o},ns=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new W("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Fo}};return e?.length&&(o.examples=e),o},ss=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),is=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},as=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return _o?.[t]},ps=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],cs=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!pe(o,"transform"))return t;let s=ot(mr(n,{ctx:r}));if((0,xe.isSchemaObject)(s))if(r.isResponse){let i=xt(o,as(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},ds=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!k(t.properties.raw)?e:t.properties.raw},cr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ms=(e,t)=>t?.includes(e)||e.startsWith("x-")||Do.includes(e),Go=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=_e(r),m=gt(e),y=o.includes("query"),b=o.includes("params"),h=o.includes("headers"),C=R=>b&&m.includes(R),I=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),L=R=>h&&(i?.(R,t,e)??ms(R,I));return Object.entries(c.properties).reduce((R,[A,N])=>{if(!k(N))return R;let K=C(A)?"path":L(A)?"header":y?"query":void 0;if(!K)return R;let M=ot(N),oe=s==="components"?n(N.id||JSON.stringify(N),M,ce(d,A)):M;return R.concat({name:A,in:K,deprecated:N.deprecated,required:c.required?.includes(A)||!1,description:M.description||d,schema:oe,examples:cr((0,xe.isSchemaObject)(M)&&M.examples?.length?M.examples:l.pluck(A,c.examples?.filter(l.both(k,l.has(A)))||[]))})},[])},dr={nullable:es,union:Qn,bigint:ss,intersection:Xn,tuple:is,pipe:cs,literal:rs,enum:ts,[Re]:os,[Oe]:ns,[le]:Wn,[q]:ds,[Se]:Yn},ls=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,xe.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,ot(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},mr=(e,{ctx:t,rules:r=dr})=>{let{$defs:o={},properties:n={}}=pr.z.toJSONSchema(pr.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=re(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 ls(k(n.subject)?n.subject:{},o,t)},Wo=(e,t)=>{if((0,xe.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Wo(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]},Yo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${Jt(n)} response ${p?d:""}`.trim()})=>{if(!o||!bt(e,n))return{description:m};let y=ot(mr(r,{rules:{...c,...dr},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,xe.isSchemaObject)(y)&&y.examples&&(b.push(...y.examples),delete y.examples);let h={schema:i==="components"?s(r,y,ce(m)):y,examples:cr(b)};return{description:m,content:l.fromPairs(l.xprod(o,[h]))}},us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},fs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ys=({name:e})=>({type:"apiKey",in:"header",name:e}),gs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),hs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),xs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Qo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?us(o):o.type==="input"?fs(o,t):o.type==="header"?ys(o):o.type==="cookie"?gs(o):o.type==="openid"?hs(o):xs(o);return e.map(o=>o.map(r))},Xo=(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:[]})},{})),en=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>mr(e,{rules:{...t,...dr},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),tn=({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]=Wo(ot(o),p),y=[];(0,xe.isSchemaObject)(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,ce(d)):c,examples:cr(y.length?y:_e(o).examples?.filter(C=>k(C)&&!Array.isArray(C)).map(l.omit(p))||[])},h={description:d,content:{[n]:b}};return(m||n===E.raw)&&(h.required=!0),h},rn=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)},[]),lr=e=>e.length<=Uo?e:e.slice(0,Uo-1)+"\u2026",kt=e=>e.length?e.slice():void 0;var vt=class extends on.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||ce(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new W(`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:y="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});Je({routing:t,onEndpoint:Et((h,C,I)=>{let L={path:C,method:h,endpoint:I,composition:y,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:A,scopes:N,inputSchema:K}=I,M=A?lr(A):m&&R?lr(R):void 0,oe=_t(h,r.inputSources),Ae=this.#n(C,h,I.getOperationId(h)),pt=en({...L,schema:K}),ne=qo(I.security),ct=Go({...L,inputSources:oe,isHeader:c,security:ne,request:pt,description:i?.requestParameter?.call(null,{method:h,path:C,operationId:Ae})}),dt={};for(let se of He){let be=I.getResponses(se);for(let{mimeTypes:qt,schema:lt,statusCodes:ut}of be)for(let Dt of ut)dt[Dt]=Yo({...L,variant:se,schema:lt,mimeTypes:qt,statusCode:Dt,hasMultipleStatusCodes:be.length>1||ut.length>1,description:i?.[`${se}Response`]?.call(null,{method:h,path:C,operationId:Ae,statusCode:Dt})})}let mt=oe.includes("body")?tn({...L,request:pt,paramNames:nn.pluck("name",ct),schema:K,mimeType:E[I.requestType],description:i?.requestBody?.call(null,{method:h,path:C,operationId:Ae})}):void 0,Ht=Xo(Qo(ne,oe),N,se=>{let be=this.#s(se);return this.addSecurityScheme(be,se),be}),Kt={operationId:Ae,summary:M,description:R,deprecated:I.isDeprecated||void 0,tags:kt(I.tags),parameters:kt(ct),requestBody:mt,security:kt(Ht),responses:dt};this.addPath(Jo(C),{[h]:Kt})})}),d&&(this.rootDoc.tags=rn(d))}};var It=require("node-mocks-http");var bs=e=>(0,It.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),Ss=e=>(0,It.createResponse)(e),Rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:no(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},sn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=bs(e),s=Ss({req:n,...t});s.req=t?.req||n,n.res=s;let i=Rs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},an=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=sn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},pn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=ge}}=sn(r),d=ht(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:ie(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var fn=g(require("ramda"),1),at=g(require("typescript"),1),yn=require("zod/v4");var mn=g(require("ramda"),1),F=g(require("typescript"),1);var X=g(require("ramda"),1),u=g(require("typescript"),1),a=u.default.factory,At=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],Os=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],nt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ur=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),fr=(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)},Ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yr=e=>typeof e=="string"&&Ts.test(e)?a.createIdentifier(e):T(e),Nt=(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)))),Mt=(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),Ve=e=>Object.entries(e).map(([t,r])=>Mt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),gr=(e,t=[])=>a.createConstructorDeclaration(nt.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&&X.map(f,t)):e,hr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),ee=e=>{let t=new Map;for(let r of e)t.set(ws(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},ke=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,yr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?ee([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=X.reject(X.isNil,[o?"@deprecated":void 0,n]);return p.length?ur(i,p.join(" ")):i},xr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),br=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&At,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),Sr=(e,t)=>te(e,ee(X.map(Z,t)),{expose:!0}),te=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?At:void 0,e,n&&Pr(n),t);return o?ur(s,o):s},cn=(e,t)=>a.createPropertyDeclaration(nt.public,e,void 0,f(t),void 0),Rr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(nt.public,void 0,e,void 0,o&&Pr(o),t,n,a.createBlock(r)),Or=(e,t,{typeParams:r}={})=>a.createClassDeclaration(At,e,r&&Pr(r),void 0,t),Tr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),jt=e=>f(Promise.name,[e]),zt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?At:void 0,e,void 0,void 0,t);return o?ur(n,o):n},Pr=e=>(Array.isArray(e)?e.map(t=>X.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?Os:void 0,void 0,Array.isArray(e)?X.map(Mt,e):Ve(e),void 0,void 0,t),P=e=>e,st=(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),Ge=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Lt=(e,t)=>f("Extract",[e,t]),wr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),U=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),dn=e=>ee([f(e),jt(e)]),Cr=(e,t)=>a.createFunctionTypeNode(void 0,Ve(e),f(t)),T=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),Z=e=>a.createLiteralTypeNode(T(e)),Ps=[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],ws=e=>Ps.includes(e.kind);var $t=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=Sr("Method",Zr);someOfType=te("SomeOf",U("T",Tr("T")),{params:["T"]});requestType=te("Request",Tr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>zt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>ke(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(yr(t),a.createArrayLiteralExpression(mn.map(T,r))))),{expose:!0});makeImplementationType=()=>te(this.#e.implementationType,Cr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:F.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},jt(F.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:F.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:F.default.SyntaxKind.StringKeyword},a.createAsExpression(w(this.#e.requestParameter,P("split"))(a.createRegularExpressionLiteral("/ (.+)/"),T(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>z(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:F.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr},a.createBlock([z(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],F.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([wr(this.#e.pathParameter,w(this.#e.pathParameter,P("replace"))(Nt(":",[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=()=>Rr(this.#e.provideMethod,Ve({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:U(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(br(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:jt(U(this.interfaces.response,"K"))});makeClientClass=t=>Or(t,[gr([Mt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:nt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Nt("?",[Ge(URLSearchParams.name,t)]);#o=()=>Ge(URL.name,Nt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),T(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(P("method"),w(this.#e.methodParameter,P("toUpperCase"))()),r=a.createPropertyAssignment(P("headers"),st(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(T("Content-Type"),T(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(P("body"),st(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([T("get"),T("head"),T("delete")]),P("includes"))(this.#e.methodParameter))),i=z(this.#e.searchParamsConst,st(this.#e.hasBodyConst,T(""),this.#r(this.#e.paramsArgument))),p=z(this.#e.contentTypeConst,w(this.#e.responseConst,P("headers"),P("get"))(T("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(F.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=z(this.#e.isJsonConst,w(this.#e.contentTypeConst,P("startsWith"))(T(E.json))),m=a.createReturnStatement(w(this.#e.responseConst,st(this.#e.isJsonConst,T(P("json")),T(P("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=()=>gr(Ve({request:"K",params:U(this.interfaces.input,"K")}),[z(br(this.#e.pathParameter,this.#e.restConst),w(this.#e.substituteFn)(a.createElementAccessExpression(w(this.#e.parseRequestFn)(this.#e.requestParameter),T(1)),this.#e.paramsArgument)),z(this.#e.searchParamsConst,this.#r(this.#e.restConst)),wr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Ge("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([ke(P("event"),t)]);#i=()=>Rr(this.#e.onMethod,Ve({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Cr({[this.#e.dataParameter.text]:U(Lt("R",xr(this.#s("E"))),Z(P("data")))},dn(F.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(w(a.createThis(),this.#e.sourceProp,P("addEventListener"))(this.#e.eventParameter,ve([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:U("R",Z(P("event")))}});makeSubscriptionClass=t=>Or(t,[cn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Lt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(F.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Lt(U(this.interfaces.positive,"K"),xr(this.#s(F.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,Ge(t)),w(this.#e.clientConst,this.#e.provideMethod)(T("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",T("10"))])),w(Ge(r,T("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(T("time"),ve(["time"],a.createBlock([])))]};var v=g(require("ramda"),1),x=g(require("typescript"),1),ln=require("zod/v4");var Er=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=re(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Er(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:J}=x.default,Cs={[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},kr={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(x.default.SyntaxKind.UndefinedKeyword):Z(r));return t.length===1?t[0]:ee(t)},ks=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(pe(p)){r.unshift(p);break}i+=p??""}return i},n=J.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?J.createTemplateMiddle:J.createTemplateTail;s.push(J.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?J.createTemplateLiteralType(n,s):Z(n.text)},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}=ln.globalRegistry.get(p)||{};return ke(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return J.createTypeLiteralNode(s)};return Jr(e,{io:t?"output":"input"})?o(e,n):n()},Is=({_zod:{def:e}},{next:t})=>J.createArrayTypeNode(t(e.element)),As=({_zod:{def:e}})=>ee(Object.values(e.entries).map(Z)),Ns=({_zod:{def:e}},{next:t})=>ee(e.options.map(t)),Ms=e=>Cs?.[e.kind],js=({_zod:{def:e}},{next:t})=>ee([t(e.innerType),Z(null)]),zs=({_zod:{def:e}},{next:t})=>J.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:J.createRestTypeNode(t(e.rest)))),Ls=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),$s=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(kr.name,...o))return!1;if(v.both(v.eqBy(kr.type),v.eqBy(kr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return J.createTypeLiteralNode(r)},(e,t)=>J.createIntersectionTypeNode(t)),Zs=({_zod:{def:e}},{next:t})=>$s([e.left,e.right].map(t)),_=e=>()=>f(e),it=({_zod:{def:e}},{next:t})=>t(e.innerType),un=e=>f(e?x.default.SyntaxKind.UnknownKeyword:x.default.SyntaxKind.AnyKeyword),Bs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!pe(o,"transform"))return t(o);let s=t(n),i=xt(o,Ms(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]||un(r))},Hs=()=>Z(null),Ks=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),qs=()=>f("Buffer"),Ds=(e,{next:t})=>t(e._zod.def.shape.raw),Us={string:_(x.default.SyntaxKind.StringKeyword),number:_(x.default.SyntaxKind.NumberKeyword),bigint:_(x.default.SyntaxKind.BigIntKeyword),boolean:_(x.default.SyntaxKind.BooleanKeyword),any:_(x.default.SyntaxKind.AnyKeyword),undefined:_(x.default.SyntaxKind.UndefinedKeyword),[Re]:_(x.default.SyntaxKind.StringKeyword),[Oe]:_(x.default.SyntaxKind.StringKeyword),never:_(x.default.SyntaxKind.NeverKeyword),void:_(x.default.SyntaxKind.UndefinedKeyword),unknown:_(x.default.SyntaxKind.UnknownKeyword),null:Hs,array:Is,tuple:zs,record:Ls,object:vs,literal:Es,template_literal:ks,intersection:Zs,union:Ns,default:it,enum:As,optional:it,nonoptional:it,nullable:js,catch:it,pipe:Bs,lazy:Ks,readonly:it,[Se]:qs,[q]:Ds},vr=(e,{brandHandling:t,ctx:r})=>Er(e,{rules:{...t,...Us},onMissing:({},{isResponse:o})=>un(o),ctx:r});var Zt=class extends $t{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=Z(null);this.#t.set(t,te(o,n)),this.#t.set(t,te(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=yn.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}};Je({routing:t,onEndpoint:Et((b,h,C)=>{let I=ce.bind(null,b,h),{isDeprecated:L,inputSchema:R,tags:A}=C,N=`${b} ${h}`,K=te(I("input"),vr(R,c),{comment:N});this.#e.push(K);let M=He.reduce((pt,ne)=>{let ct=C.getResponses(ne),dt=fn.chain(([Ht,{schema:Kt,mimeTypes:se,statusCodes:be}])=>{let qt=se&&bt(b,ne),lt=te(I(ne,"variant",`${Ht+1}`),vr(qt?Kt:p,m),{comment:N});return this.#e.push(lt),be.map(ut=>ke(ut,lt.name))},Array.from(ct.entries())),mt=zt(I(ne,"response","variants"),dt,{comment:N});return this.#e.push(mt),Object.assign(pt,{[ne]:mt})},{});this.paths.add(h);let oe=Z(N),Ae={input:f(K.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:ee([U(this.interfaces.positive,oe),U(this.interfaces.negative,oe)]),encoded:a.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(N,{isDeprecated:L,store:Ae}),this.tags.set(N,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:fr(r,t)).join(`
18
+ `))};var $o=e=>{e.startupLogo!==!1&&zo(process.stdout);let t=e.errorHandler||ye,r=oo(e.logger)?e.logger:new qe(e.logger);r.debug("Running",{build:"v24.7.3 (CJS)",env:process.env.NODE_ENV||"development"}),No(r);let o=Io({logger:r,config:e}),s={getLogger:Ao(r),errorHandler:t},i=Eo(s),p=Co(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=$o(e);return ir({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Ho=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=$o(e),p=(0,rt.default)().disable("x-powered-by").use(i);if(e.compression){let b=await Ue("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||rt.default.json()],raw:[e.rawParser||rt.default.raw(),vo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await ko({config:e,getLogger:o}):[]};ir({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,h)=>()=>b.listen(h,()=>r.info("Listening",h)),y=[];if(e.http){let b=jo.default.createServer(p);c.push(b),y.push(m(b,e.http.listen))}if(e.https){let b=Lo.default.createServer(e.https.options,p);c.push(b),y.push(m(b,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&Mo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(b=>b())}};var on=require("openapi3-ts/oas31"),nn=g(require("ramda"),1);var O=g(require("ramda"),1);var Bo=e=>k(e)&&"or"in e,Ko=e=>k(e)&&"and"in e,ar=e=>!Ko(e)&&!Bo(e),qo=e=>{let t=O.filter(ar,e),r=O.chain(O.prop("and"),O.filter(Ko,e)),[o,n]=O.partition(ar,r),s=O.concat(t,o),i=O.filter(Bo,e);return O.map(O.prop("or"),O.concat(i,n)).reduce((d,c)=>Pe(d,O.map(m=>ar(m)?[m]:m.and,c),([m,y])=>O.concat(m,y)),O.reject(O.isEmpty,[s]))};var he=require("openapi3-ts/oas31"),l=g(require("ramda"),1),pr=require("zod/v4");var Do=["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 Fo=50,Uo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",_o={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Jo=e=>e.replace(Ft,t=>`{${t.slice(1)}}`),Wn=({},e)=>{if(e.isResponse)throw new W("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Yn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Qn=({zodSchema:e,jsonSchema:t})=>{if(!ae(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Xn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return _e(e,"throw")},(e,{jsonSchema:t})=>t),es=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ps(t.type)})},Vo=e=>e in _o,ts=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&Vo(t)&&(e.type=t),e},rs=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&Vo(t)&&(e.type=t),e},ot=e=>e,os=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new W("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Uo}};return e?.length&&(o.examples=e),o},ns=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new W("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Uo}};return e?.length&&(o.examples=e),o},ss=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),is=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},as=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return _o?.[t]},ps=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],cs=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!ae(o,"transform"))return t;let s=ot(mr(n,{ctx:r}));if((0,he.isSchemaObject)(s))if(r.isResponse){let i=xt(o,as(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},ds=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!k(t.properties.raw)?e:t.properties.raw},cr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ms=(e,t)=>t?.includes(e)||e.startsWith("x-")||Do.includes(e),Go=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=_e(r),m=gt(e),y=o.includes("query"),b=o.includes("params"),h=o.includes("headers"),C=R=>b&&m.includes(R),I=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),L=R=>h&&(i?.(R,t,e)??ms(R,I));return Object.entries(c.properties).reduce((R,[A,N])=>{if(!k(N))return R;let K=C(A)?"path":L(A)?"header":y?"query":void 0;if(!K)return R;let M=ot(N),oe=s==="components"?n(N.id||JSON.stringify(N),M,pe(d,A)):M;return R.concat({name:A,in:K,deprecated:N.deprecated,required:c.required?.includes(A)||!1,description:M.description||d,schema:oe,examples:cr((0,he.isSchemaObject)(M)&&M.examples?.length?M.examples:l.pluck(A,c.examples?.filter(l.both(k,l.has(A)))||[]))})},[])},dr={nullable:es,union:Qn,bigint:ss,intersection:Xn,tuple:is,pipe:cs,literal:rs,enum:ts,[Re]:os,[Oe]:ns,[me]:Wn,[q]:ds,[Se]:Yn},ls=(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.id||i,ot(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},mr=(e,{ctx:t,rules:r=dr})=>{let{$defs:o={},properties:n={}}=pr.z.toJSONSchema(pr.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=re(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 ls(k(n.subject)?n.subject:{},o,t)},Wo=(e,t)=>{if((0,he.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Wo(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]},Yo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${Jt(n)} response ${p?d:""}`.trim()})=>{if(!bt(e,o))return{description:m};let y=ot(mr(r,{rules:{...c,...dr},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,he.isSchemaObject)(y)&&y.examples&&(b.push(...y.examples),delete y.examples);let h={schema:i==="components"?s(r,y,pe(m)):y,examples:cr(b)};return{description:m,content:l.fromPairs(l.xprod(o,[h]))}},us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},fs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ys=({name:e})=>({type:"apiKey",in:"header",name:e}),gs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),hs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),xs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Qo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?us(o):o.type==="input"?fs(o,t):o.type==="header"?ys(o):o.type==="cookie"?gs(o):o.type==="openid"?hs(o):xs(o);return e.map(o=>o.map(r))},Xo=(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:[]})},{})),en=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>mr(e,{rules:{...t,...dr},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),tn=({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]=Wo(ot(o),p),y=[];(0,he.isSchemaObject)(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,pe(d)):c,examples:cr(y.length?y:_e(o).examples?.filter(C=>k(C)&&!Array.isArray(C)).map(l.omit(p))||[])},h={description:d,content:{[n]:b}};return(m||n===E.raw)&&(h.required=!0),h},rn=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)},[]),lr=e=>e.length<=Fo?e:e.slice(0,Fo-1)+"\u2026",kt=e=>e.length?e.slice():void 0;var vt=class extends on.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||pe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new W(`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:y="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});Je({routing:t,onEndpoint:Et((h,C,I)=>{let L={path:C,method:h,endpoint:I,composition:y,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:A,scopes:N,inputSchema:K}=I,M=A?lr(A):m&&R?lr(R):void 0,oe=_t(h,r.inputSources),Ae=this.#n(C,h,I.getOperationId(h)),pt=en({...L,schema:K}),xe=qo(I.security),ct=Go({...L,inputSources:oe,isHeader:c,security:xe,request:pt,description:i?.requestParameter?.call(null,{method:h,path:C,operationId:Ae})}),dt={};for(let ne of Be){let be=I.getResponses(ne);for(let{mimeTypes:qt,schema:lt,statusCodes:ut}of be)for(let Dt of ut)dt[Dt]=Yo({...L,variant:ne,schema:lt,mimeTypes:qt,statusCode:Dt,hasMultipleStatusCodes:be.length>1||ut.length>1,description:i?.[`${ne}Response`]?.call(null,{method:h,path:C,operationId:Ae,statusCode:Dt})})}let mt=oe.includes("body")?tn({...L,request:pt,paramNames:nn.pluck("name",ct),schema:K,mimeType:E[I.requestType],description:i?.requestBody?.call(null,{method:h,path:C,operationId:Ae})}):void 0,Bt=Xo(Qo(xe,oe),N,ne=>{let be=this.#s(ne);return this.addSecurityScheme(be,ne),be}),Kt={operationId:Ae,summary:M,description:R,deprecated:I.isDeprecated||void 0,tags:kt(I.tags),parameters:kt(ct),requestBody:mt,security:kt(Bt),responses:dt};this.addPath(Jo(C),{[h]:Kt})})}),d&&(this.rootDoc.tags=rn(d))}};var It=require("node-mocks-http");var bs=e=>(0,It.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),Ss=e=>(0,It.createResponse)(e),Rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:no(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},sn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=bs(e),s=Ss({req:n,...t});s.req=t?.req||n,n.res=s;let i=Rs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},an=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=sn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},pn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=ye}}=sn(r),d=ht(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:se(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var fn=g(require("ramda"),1),at=g(require("typescript"),1),yn=require("zod/v4");var mn=g(require("ramda"),1),U=g(require("typescript"),1);var X=g(require("ramda"),1),u=g(require("typescript"),1),a=u.default.factory,At=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],Os=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],nt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ur=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),fr=(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)},Ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yr=e=>typeof e=="string"&&Ts.test(e)?a.createIdentifier(e):T(e),Nt=(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)))),Mt=(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),Ve=e=>Object.entries(e).map(([t,r])=>Mt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),gr=(e,t=[])=>a.createConstructorDeclaration(nt.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&&X.map(f,t)):e,hr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),ee=e=>{let t=new Map;for(let r of e)t.set(ws(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},ke=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,yr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?ee([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=X.reject(X.isNil,[o?"@deprecated":void 0,n]);return p.length?ur(i,p.join(" ")):i},xr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),br=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&At,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),Sr=(e,t)=>te(e,ee(X.map(Z,t)),{expose:!0}),te=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?At:void 0,e,n&&Pr(n),t);return o?ur(s,o):s},cn=(e,t)=>a.createPropertyDeclaration(nt.public,e,void 0,f(t),void 0),Rr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(nt.public,void 0,e,void 0,o&&Pr(o),t,n,a.createBlock(r)),Or=(e,t,{typeParams:r}={})=>a.createClassDeclaration(At,e,r&&Pr(r),void 0,t),Tr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),zt=e=>f(Promise.name,[e]),jt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?At:void 0,e,void 0,void 0,t);return o?ur(n,o):n},Pr=e=>(Array.isArray(e)?e.map(t=>X.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?Os:void 0,void 0,Array.isArray(e)?X.map(Mt,e):Ve(e),void 0,void 0,t),P=e=>e,st=(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),Ge=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Lt=(e,t)=>f("Extract",[e,t]),wr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),F=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),dn=e=>ee([f(e),zt(e)]),Cr=(e,t)=>a.createFunctionTypeNode(void 0,Ve(e),f(t)),T=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),Z=e=>a.createLiteralTypeNode(T(e)),Ps=[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],ws=e=>Ps.includes(e.kind);var $t=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=Sr("Method",Zr);someOfType=te("SomeOf",F("T",Tr("T")),{params:["T"]});requestType=te("Request",Tr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>jt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>ke(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(yr(t),a.createArrayLiteralExpression(mn.map(T,r))))),{expose:!0});makeImplementationType=()=>te(this.#e.implementationType,Cr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},zt(U.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:U.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:U.default.SyntaxKind.StringKeyword},a.createAsExpression(w(this.#e.requestParameter,P("split"))(a.createRegularExpressionLiteral("/ (.+)/"),T(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr},a.createBlock([j(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([wr(this.#e.pathParameter,w(this.#e.pathParameter,P("replace"))(Nt(":",[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=()=>Rr(this.#e.provideMethod,Ve({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:F(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(br(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:zt(F(this.interfaces.response,"K"))});makeClientClass=t=>Or(t,[gr([Mt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:nt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Nt("?",[Ge(URLSearchParams.name,t)]);#o=()=>Ge(URL.name,Nt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),T(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(P("method"),w(this.#e.methodParameter,P("toUpperCase"))()),r=a.createPropertyAssignment(P("headers"),st(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(T("Content-Type"),T(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(P("body"),st(this.#e.hasBodyConst,w(JSON[Symbol.toStringTag],P("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,a.createAwaitExpression(w(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,a.createLogicalNot(w(a.createArrayLiteralExpression([T("get"),T("head"),T("delete")]),P("includes"))(this.#e.methodParameter))),i=j(this.#e.searchParamsConst,st(this.#e.hasBodyConst,T(""),this.#r(this.#e.paramsArgument))),p=j(this.#e.contentTypeConst,w(this.#e.responseConst,P("headers"),P("get"))(T("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(U.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=j(this.#e.isJsonConst,w(this.#e.contentTypeConst,P("startsWith"))(T(E.json))),m=a.createReturnStatement(w(this.#e.responseConst,st(this.#e.isJsonConst,T(P("json")),T(P("text"))))());return j(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=()=>gr(Ve({request:"K",params:F(this.interfaces.input,"K")}),[j(br(this.#e.pathParameter,this.#e.restConst),w(this.#e.substituteFn)(a.createElementAccessExpression(w(this.#e.parseRequestFn)(this.#e.requestParameter),T(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),wr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Ge("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([ke(P("event"),t)]);#i=()=>Rr(this.#e.onMethod,Ve({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Cr({[this.#e.dataParameter.text]:F(Lt("R",xr(this.#s("E"))),Z(P("data")))},dn(U.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(w(a.createThis(),this.#e.sourceProp,P("addEventListener"))(this.#e.eventParameter,ve([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:F("R",Z(P("event")))}});makeSubscriptionClass=t=>Or(t,[cn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Lt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(U.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Lt(F(this.interfaces.positive,"K"),xr(this.#s(U.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Ge(t)),w(this.#e.clientConst,this.#e.provideMethod)(T("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",T("10"))])),w(Ge(r,T("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(T("time"),ve(["time"],a.createBlock([])))]};var v=g(require("ramda"),1),x=g(require("typescript"),1),ln=require("zod/v4");var Er=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=re(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Er(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:J}=x.default,Cs={[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},kr={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(x.default.SyntaxKind.UndefinedKeyword):Z(r));return t.length===1?t[0]:ee(t)},ks=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(ae(p)){r.unshift(p);break}i+=p??""}return i},n=J.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?J.createTemplateMiddle:J.createTemplateTail;s.push(J.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?J.createTemplateLiteralType(n,s):Z(n.text)},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}=ln.globalRegistry.get(p)||{};return ke(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return J.createTypeLiteralNode(s)};return Jr(e,{io:t?"output":"input"})?o(e,n):n()},Is=({_zod:{def:e}},{next:t})=>J.createArrayTypeNode(t(e.element)),As=({_zod:{def:e}})=>ee(Object.values(e.entries).map(Z)),Ns=({_zod:{def:e}},{next:t})=>ee(e.options.map(t)),Ms=e=>Cs?.[e.kind],zs=({_zod:{def:e}},{next:t})=>ee([t(e.innerType),Z(null)]),js=({_zod:{def:e}},{next:t})=>J.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:J.createRestTypeNode(t(e.rest)))),Ls=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),$s=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(kr.name,...o))return!1;if(v.both(v.eqBy(kr.type),v.eqBy(kr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return J.createTypeLiteralNode(r)},(e,t)=>J.createIntersectionTypeNode(t)),Zs=({_zod:{def:e}},{next:t})=>$s([e.left,e.right].map(t)),_=e=>()=>f(e),it=({_zod:{def:e}},{next:t})=>t(e.innerType),un=e=>f(e?x.default.SyntaxKind.UnknownKeyword:x.default.SyntaxKind.AnyKeyword),Hs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!ae(o,"transform"))return t(o);let s=t(n),i=xt(o,Ms(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]||un(r))},Bs=()=>Z(null),Ks=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),qs=()=>f("Buffer"),Ds=(e,{next:t})=>t(e._zod.def.shape.raw),Fs={string:_(x.default.SyntaxKind.StringKeyword),number:_(x.default.SyntaxKind.NumberKeyword),bigint:_(x.default.SyntaxKind.BigIntKeyword),boolean:_(x.default.SyntaxKind.BooleanKeyword),any:_(x.default.SyntaxKind.AnyKeyword),undefined:_(x.default.SyntaxKind.UndefinedKeyword),[Re]:_(x.default.SyntaxKind.StringKeyword),[Oe]:_(x.default.SyntaxKind.StringKeyword),never:_(x.default.SyntaxKind.NeverKeyword),void:_(x.default.SyntaxKind.UndefinedKeyword),unknown:_(x.default.SyntaxKind.UnknownKeyword),null:Bs,array:Is,tuple:js,record:Ls,object:vs,literal:Es,template_literal:ks,intersection:Zs,union:Ns,default:it,enum:As,optional:it,nonoptional:it,nullable:zs,catch:it,pipe:Hs,lazy:Ks,readonly:it,[Se]:qs,[q]:Ds},vr=(e,{brandHandling:t,ctx:r})=>Er(e,{rules:{...t,...Fs},onMissing:({},{isResponse:o})=>un(o),ctx:r});var Zt=class extends $t{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=Z(null);this.#t.set(t,te(o,n)),this.#t.set(t,te(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=yn.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}};Je({routing:t,onEndpoint:Et((b,h,C)=>{let I=pe.bind(null,b,h),{isDeprecated:L,inputSchema:R,tags:A}=C,N=`${b} ${h}`,K=te(I("input"),vr(R,c),{comment:N});this.#e.push(K);let M=Be.reduce((pt,xe)=>{let ct=C.getResponses(xe),dt=fn.chain(([Bt,{schema:Kt,mimeTypes:ne,statusCodes:be}])=>{let qt=bt(b,ne),lt=te(I(xe,"variant",`${Bt+1}`),vr(qt?Kt:p,m),{comment:N});return this.#e.push(lt),be.map(ut=>ke(ut,lt.name))},Array.from(ct.entries())),mt=jt(I(xe,"response","variants"),dt,{comment:N});return this.#e.push(mt),Object.assign(pt,{[xe]:mt})},{});this.paths.add(h);let oe=Z(N),Ae={input:f(K.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:ee([F(this.interfaces.positive,oe),F(this.interfaces.negative,oe)]),encoded:a.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(N,{isDeprecated:L,store:Ae}),this.tags.set(N,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:fr(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&at.default.addSyntheticLeadingComment(at.default.addSyntheticLeadingComment(a.createEmptyStatement(),at.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),at.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>fr(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 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 Ie=require("zod/v4");var hn=(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)=>hn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),_s=1e4,gn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Js=e=>new D({handler:async({response:t})=>setTimeout(()=>gn(t),_s)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{gn(t),t.write(Fs(e,r,o),"utf-8"),t.flush?.()}}}),Vs=e=>new ye({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>hn(o,n));return{mimeType:E.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=Ce(r);Xe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(Ee(i),"utf-8")}t.end()}}),Bt=class extends he{constructor(t){super(Vs(t)),this.middlewares=[Js(t)]}};var xn={dateIn:jr,dateOut:Lr,form:Hr,upload:qr,raw:Fr,buffer:yt};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 Ue("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 hn=(e,t)=>Ie.z.object({data:t,event:Ie.z.literal(e),id:Ie.z.string().optional(),retry:Ie.z.int().positive().optional()}),Us=(e,t,r)=>hn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),_s=1e4,gn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Js=e=>new D({handler:async({response:t})=>setTimeout(()=>gn(t),_s)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{gn(t),t.write(Us(e,r,o),"utf-8"),t.flush?.()}}}),Vs=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>hn(o,n));return{mimeType:E.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=Ce(r);Xe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(Ee(i),"utf-8")}t.end()}}),Ht=class extends ge{constructor(t){super(Vs(t)),this.middlewares=[Js(t)]}};var xn={dateIn:zr,dateOut:Lr,form:Br,upload:qr,raw:Ur,buffer:yt};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});
package/dist/index.d.cts CHANGED
@@ -35,15 +35,15 @@ type Intact<T, U> = {
35
35
  [K in Exclude<keyof T, keyof U>]: T[K];
36
36
  };
37
37
 
38
- /** @todo remove when typed, https://github.com/ramda/types/pull/140 */
39
- declare module "ramda" {
40
- function renameKeys<V extends string, T extends object, U extends {
41
- [P in keyof T]?: V;
42
- }>(mapping: U): (subject: T) => Remap<T, U, V>;
43
- }
44
38
  declare module "zod/v4/core" {
45
39
  interface GlobalMeta {
46
40
  default?: unknown;
41
+ examples?: unknown[] | Record<string, {
42
+ value: unknown;
43
+ [k: string]: unknown;
44
+ }>;
45
+ /** @deprecated use examples instead */
46
+ example?: unknown;
47
47
  }
48
48
  }
49
49
  declare module "zod/v4" {
@@ -388,7 +388,10 @@ declare const defaultResultHandler: ResultHandler<z.ZodObject<{
388
388
  * @desc Responding with array is a bad practice keeping your endpoints from evolving without breaking changes.
389
389
  * @desc This handler expects your endpoint to have the property 'items' in the output object schema
390
390
  * */
391
- declare const arrayResultHandler: ResultHandler<z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>, z.ZodString>;
391
+ declare const arrayResultHandler: ResultHandler<z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>, {
392
+ schema: z.ZodString;
393
+ mimeType: string;
394
+ }>;
392
395
 
393
396
  /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
394
397
  type GetLogger = (request?: Request) => ActualLogger;
@@ -917,8 +920,10 @@ declare class EventStreamFactory<E extends EventsMap> extends EndpointsFactory<u
917
920
  }
918
921
 
919
922
  /**
920
- * @since zod 3.25.44
923
+ * @since zod 3.25.44 can be an object
921
924
  * @link https://github.com/colinhacks/zod/pull/4586
925
+ * @since zod 3.25.68 and 4.0.0 was completely removed
926
+ * @link https://github.com/colinhacks/zod/commit/ee5615d76b93aac15d7428a17b834a062235f6a1
922
927
  * */
923
928
  declare const getExamples: (subject: $ZodType) => ReadonlyArray<unknown>;
924
929
 
package/dist/index.d.ts CHANGED
@@ -35,15 +35,15 @@ type Intact<T, U> = {
35
35
  [K in Exclude<keyof T, keyof U>]: T[K];
36
36
  };
37
37
 
38
- /** @todo remove when typed, https://github.com/ramda/types/pull/140 */
39
- declare module "ramda" {
40
- function renameKeys<V extends string, T extends object, U extends {
41
- [P in keyof T]?: V;
42
- }>(mapping: U): (subject: T) => Remap<T, U, V>;
43
- }
44
38
  declare module "zod/v4/core" {
45
39
  interface GlobalMeta {
46
40
  default?: unknown;
41
+ examples?: unknown[] | Record<string, {
42
+ value: unknown;
43
+ [k: string]: unknown;
44
+ }>;
45
+ /** @deprecated use examples instead */
46
+ example?: unknown;
47
47
  }
48
48
  }
49
49
  declare module "zod/v4" {
@@ -388,7 +388,10 @@ declare const defaultResultHandler: ResultHandler<z.ZodObject<{
388
388
  * @desc Responding with array is a bad practice keeping your endpoints from evolving without breaking changes.
389
389
  * @desc This handler expects your endpoint to have the property 'items' in the output object schema
390
390
  * */
391
- declare const arrayResultHandler: ResultHandler<z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>, z.ZodString>;
391
+ declare const arrayResultHandler: ResultHandler<z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>, {
392
+ schema: z.ZodString;
393
+ mimeType: string;
394
+ }>;
392
395
 
393
396
  /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
394
397
  type GetLogger = (request?: Request) => ActualLogger;
@@ -917,8 +920,10 @@ declare class EventStreamFactory<E extends EventsMap> extends EndpointsFactory<u
917
920
  }
918
921
 
919
922
  /**
920
- * @since zod 3.25.44
923
+ * @since zod 3.25.44 can be an object
921
924
  * @link https://github.com/colinhacks/zod/pull/4586
925
+ * @since zod 3.25.68 and 4.0.0 was completely removed
926
+ * @link https://github.com/colinhacks/zod/commit/ee5615d76b93aac15d7428a17b834a062235f6a1
922
927
  * */
923
928
  declare const getExamples: (subject: $ZodType) => ReadonlyArray<unknown>;
924
929
 
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as U from"ramda";import{z as Y}from"zod/v4";import{globalRegistry as Do}from"zod/v4";var Ce=Symbol.for("express-zod-api"),W=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},Z=e=>{let{examples:t,example:r}=Do.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};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=()=>{}}),Fo=function(e){let t=Z(this).slice();return t.push(e),this.meta({examples:t})},_o=function(){return this.meta({deprecated:!0})},Jo=function(e){return this.meta({default:e})},Vo=function(e){return this.check(new Uo({brand:e,check:"$EZBrandCheck"}))},Go=function(e){let t=typeof e=="function"?e:U.renameKeys(U.reject(U.isNil,e)),r=t(U.map(U.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(!(Ce in globalThis)){globalThis[Ce]=!0;for(let e of Object.keys(Y)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=Y[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:Fo,writable:!1},deprecated:{value:_o,writable:!1},brand:{set(){},get(){return Vo.bind(this)}}})}Object.defineProperty(Y.ZodDefault.prototype,"label",{value:Jo,writable:!1}),Object.defineProperty(Y.ZodObject.prototype,"remap",{value:Go,writable:!1})}function Wo(e){return e}import{z as $r}from"zod/v4";import*as ce from"ramda";import{z as Mr,globalRegistry as ln}from"zod/v4";import*as pe from"ramda";import{z as wr}from"zod/v4";import{z as Yo}from"zod/v4";var me=Symbol("Buffer"),it=()=>Yo.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(me);import{z as Be}from"zod/v4";var le=Symbol("DateIn"),gr=({examples:e,...t}={})=>Be.union([Be.iso.date(),Be.iso.datetime(),Be.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Be.date()).brand(le).meta(t);import{z as Qo}from"zod/v4";var ue=Symbol("DateOut"),hr=(e={})=>Qo.date().transform(t=>t.toISOString()).brand(ue).meta(e);import{z as rn}from"zod/v4";import*as z from"ramda";import{z as He}from"zod/v4";var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var xr=["get","post","put","delete","patch"],br=[...xr,"head"],fe=e=>xr.includes(e);var Mt=/:([A-Za-z0-9_]+)/g,at=e=>e.match(Mt)?.map(t=>t.slice(1))||[],Xo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},en={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},tn=["body","query","params"],jt=e=>e.method.toLowerCase(),zt=(e,t={})=>{if(e==="options")return[];let r=e==="head"?"get":fe(e)?e:void 0;return(r?t[r]||en[r]:void 0)||tn},pt=(e,t={})=>{let r=jt(e);return zt(r,t).filter(o=>o==="files"?Xo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:e instanceof He.ZodError?new He.ZodRealError(e.issues):new Error(String(e)),ye=e=>e instanceof He.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${He.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,ne=(e,t)=>E(e)&&"_zod"in e&&(t?z.path(["_zod","def","type"],e)===t:!0),ge=(e,t,r)=>e.length&&t.length?z.xprod(e,t).map(r):e.concat(t),Lt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...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(Lt).join("")},ct=z.tryCatch((e,t)=>typeof He.parse(e,t),z.always(void 0)),E=e=>typeof e=="object"&&e!==null,he=z.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production"),dt=(e,t)=>!(e==="head"&&t==="positive");var xe=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},Q=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Ke=class extends Error{name="IOSchemaError"},mt=class extends Ke{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},qe=class extends Ke{constructor(r){let o=new rn.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(ye(o),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends Ke{constructor(r){super(ye(r),{cause:r});this.cause=r}name="InputValidationError"},ie=class extends Error{constructor(r,o){super(ye(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},De=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as Sr}from"zod/v4";var Ue=Symbol("Form"),Rr=e=>(e instanceof Sr.ZodObject?e:Sr.object(e)).brand(Ue);import{z as on}from"zod/v4";var ae=Symbol("Upload"),Or=()=>on.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(ae);import{z as nn}from"zod/v4";var B=Symbol("Raw"),Tr=nn.object({raw:it()}),sn=e=>Tr.extend(e).brand(B);function Pr(e){return e?sn(e):Tr.brand(B)}var Cr=(e,{io:t,condition:r})=>pe.tryCatch(()=>{wr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new mt(o)}})},o=>o.cause)(),Er=(e,{io:t})=>{let o=[wr.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(pe.is(Object,n)){if(n.$ref==="#")return!0;o.push(...pe.values(n))}pe.is(Array,n)&&o.push(...pe.values(n))}return!1},kr=e=>Cr(e,{condition:t=>{let r=W(t);return typeof r=="symbol"&&[ae,B,Ue].includes(r)},io:"input"}),an=["nan","symbol","map","set","bigint","void","promise","never"],$t=(e,t)=>Cr(e,{io:t,condition:r=>{let o=W(r),{type:n}=r._zod.def;return!!(an.includes(n)||o===me||t==="input"&&(n==="date"||o===ue)||t==="output"&&(o===le||o===B||o===ae))}});import dn,{isHttpError as mn}from"http-errors";import vr,{isHttpError as pn}from"http-errors";import*as Ir from"ramda";import{z as cn}from"zod/v4";var Zt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof cn.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}))},Fe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>pn(e)?e:vr(e instanceof X?400:500,ye(e),{cause:e.cause||e}),be=e=>he()&&!e.expose?vr(e.statusCode).message:e.message,Ar=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>ge(t,Z(o).map(Ir.objOf(r)),([n,s])=>({...n,...s})),[]);var lt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=be(dn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:mn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Nr}from"zod/v4";var Bt=class{},F=class extends Bt{#e;#t;#r;constructor({input:t=Nr.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 Nr.ZodError?new X(o):o}}},ke=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 ve=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends ve{},ut=class e extends _e{#e;#t=ce.once(()=>{if(Z(this.#e.outputSchema).length||!ne(this.#e.outputSchema,"object"))return;let t=Ar(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();ln.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=kr(this.#e.inputSchema);if(t){let r=W(t);if(r===ae)return"upload";if(r===B)return"raw";if(r===Ue)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ce.pluck("security",this.#e.middlewares||[]);return ce.reject(ce.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Mr.ZodError?new qe(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof ke))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Mr.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){lt({...t,error:new ie(oe(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=jt(t),i={},p={output:{},error:null},d=pt(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:oe(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as jr from"ramda";var zr=(e,t)=>jr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as Lr,z as H}from"zod/v4";var Ie={positive:200,negative:400},Ae=Object.keys(Ie);var Ht=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Se=class extends Ht{#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:[Ie.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Zt(this.#t,{variant:"negative",args:[],statusCodes:[Ie.negative],mimeTypes:[C.json]})}},Re=new Se({positive:e=>{let t=H.object({status:H.literal("success"),data:e}),r=Z(e);return r.length&&Lr.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},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=Ee(e);return Fe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:be(i)}})}n.status(Ie.positive).json({status:"success",data:r})}}),Kt=new Se({positive:e=>{let t=e instanceof H.ZodObject&&"items"in e.shape&&e.shape.items instanceof H.ZodArray?e.shape.items:H.array(H.any());if(Z(t).length)return t;let r=Z(e).filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();Lr.remove(t).add(t,{...o,examples:r})}return t},negative:H.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(be(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ie.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Oe=class e{constructor(t){this.resultHandler=t}middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r}addMiddleware(t){return this.#e(t instanceof F?t:new F(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new ke(...t))}addOptions(t){return this.#e(new F({handler:t}))}build({input:t=$r.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,y=typeof o=="function"?o:w=>o&&`${o}${w==="head"?"__HEAD":""}`,h=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new ut({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:g,methods:m,getOperationId:y,inputSchema:zr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:$r.object({}),handler:async o=>(await t(o),{})})}},un=new Oe(Re),fn=new Oe(Kt);import Rn from"ansis";import{inspect as On}from"node:util";import{performance as Dr}from"node:perf_hooks";import{blue as yn,green as gn,hex as hn,red as xn,cyanBright as bn}from"ansis";import*as Zr from"ramda";var qt={debug:yn,info:gn,warn:hn("#FFA500"),error:xn,ctx:bn},ft={debug:10,info:20,warn:30,error:40},Br=e=>E(e)&&Object.keys(ft).some(t=>t in e),Hr=e=>e in ft,Kr=(e,t)=>ft[e]<ft[t],Sn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ne=Zr.memoizeWith((e,t)=>`${e}${t}`,Sn),qr=e=>e<1e-6?Ne("nanosecond",3).format(e/1e-6):e<.001?Ne("nanosecond").format(e/1e-6):e<1?Ne("microsecond").format(e/.001):e<1e3?Ne("millisecond").format(e):e<6e4?Ne("second",2).format(e/1e3):Ne("minute",2).format(e/6e4);var Je=class e{config;constructor({color:t=Rn.isSupported(),level:r=he()?"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 On(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"||Kr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?qt.ctx(s):s),d.push(p?`${qt[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=Dr.now();return()=>{let o=Dr.now()-r,{message:n,severity:s="debug",formatter:i=qr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Ur from"ramda";var Ve=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Ur.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 Tn from"express";var Ge=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,Tn.static(...this.#e))}};import xt from"express";import Hn from"node:http";import Kn from"node:https";var Me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new De(e)};import An from"http-errors";import{z as _r}from"zod/v4";import*as b from"ramda";var Pn=e=>e.type==="object",wn=b.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return b.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),Cn=b.pipe(Object.keys,b.without(["type","properties","required","examples","description","additionalProperties"]),b.isEmpty),Fr=b.pair(!0),je=(e,t="coerce")=>{let r=[b.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&Cn(p)))throw new Error("Can not merge");return b.pair(s,p)})),i.anyOf&&r.push(...b.map(Fr,i.anyOf)),i.oneOf&&r.push(...b.map(Fr,i.oneOf)),i.examples?.length&&(s?o.examples=b.concat(o.examples||[],i.examples):o.examples=ge(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>b.mergeDeepRight(p,d))),!!Pn(i)&&(r.push([s,{examples:En(i)}]),i.properties&&(o.properties=(t==="throw"?wn:b.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},En=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return ge(t,n.map(b.objOf(r)),([s,i])=>({...s,...i}))},[]);var yt=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=[_r.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=$t(t.inputSchema,"input");o&&this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ae)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(C.json))continue;let i=$t(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=at(t);if(s.length===0)return;let i=n?.flat||je(_r.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 gt=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},kn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&fe(t)?[r,t]:[e]},vn=e=>e.trim().split("/").filter(Boolean).join("/"),Jr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=kn(r);return[[t||""].concat(vn(n)||[]).join("/"),o,s]}),In=(e,t)=>{throw new xe("Route with explicit method can only be assigned with Endpoint",e,t)},Vr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new xe(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Dt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new xe("Route has a duplicate",e,t);r.add(o)},ze=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Jr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof _e)if(p)Dt(p,s,n),Vr(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)Dt(c,s,n),t(c,s,i)}else if(p&&In(p,s),i instanceof Ge)r&&i.apply(s,r);else if(i instanceof Ve)for(let[d,c]of i.entries){let{methods:m}=c;Dt(d,s,n),Vr(d,s,m),t(d,s,c)}else o.unshift(...Jr(i,s))}};import*as Gr from"ramda";var Wr=e=>e.sort((t,r)=>+fe(r)-+fe(t)||t.localeCompare(r)).join(", ").toUpperCase(),Nn=e=>({method:t},r,o)=>{let n=Wr(e);r.set({Allow:n});let s=An(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Mn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Wr(e),"Access-Control-Allow-Headers":"content-type"}),Ut=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=he()?void 0:new yt(t()),i=new Map;ze({routing:o,onEndpoint:(c,m,y)=>{he()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let h=n?.[y.requestType]||[],g=Gr.pair(h,y);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(c,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[h,[g,w]]of m){let v=g.slice().concat(async(j,S)=>{let I=t(j);return w.execute({request:j,response:S,logger:I,config:r})});r.cors&&v.unshift(async(j,S,I)=>{let A=t(j),$=Mn(y),N=typeof r.cors=="function"?await r.cors({request:j,endpoint:w,logger:A,defaultHeaders:$}):$;S.set(N),I()}),e[h](c,...v)}r.wrongMethodBehavior!==404&&d.set(c,Nn(y))}for(let[c,m]of d)e.all(c,m)};import zn from"http-errors";import{setInterval as jn}from"node:timers/promises";var Yr=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",Qr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Xr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,eo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),to=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var ro=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Yr(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",eo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Xr(c)||Qr(c))&&i(c);for await(let c of jn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(to))};return{sockets:n,shutdown:()=>o??=d()}};var oo=({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(),no=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=zn(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){lt({response:o,logger:s,error:new ie(oe(i),n)})}},Ln=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},$n=e=>({log:e.debug.bind(e)}),so=async({getLogger:e,config:t})=>{let r=await Me("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:$n(m)})(p,d,c)}),o&&i.push(Ln(o)),i},io=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ao=({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()},po=e=>t=>t?.res?.locals[Ce]?.logger||e,co=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),mo=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=ro(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};import{gray as Zn,hex as lo,italic as ht,whiteBright as Bn}from"ansis";var uo=e=>{if(e.columns<132)return;let t=ht("Proudly supports transgender community.".padStart(109)),r=ht("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=ht("Thank you for choosing Express Zod API for your project.".padStart(132)),n=ht("for Ashley".padEnd(20)),s=lo("#F5A9B8"),i=lo("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(Bn,5,7).fill(s,7,9).fill(i,9,12).fill(Zn,12,13),d=`
1
+ import*as F from"ramda";import{z as Y}from"zod/v4";import{globalRegistry as Do}from"zod/v4";var Ce=Symbol.for("express-zod-api"),W=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},Z=e=>{let{examples:t,example:r}=Do.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Fo=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=()=>{}}),Uo=function(e){let t=Z(this).slice();return t.push(e),this.meta({examples:t})},_o=function(){return this.meta({deprecated:!0})},Jo=function(e){return this.meta({default:e})},Vo=function(e){return this.check(new Fo({brand:e,check:"$EZBrandCheck"}))},Go=function(e){let t=typeof e=="function"?e:F.renameKeys(F.reject(F.isNil,e)),r=t(F.map(F.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(!(Ce in globalThis)){globalThis[Ce]=!0;for(let e of Object.keys(Y)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=Y[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:Uo,writable:!1},deprecated:{value:_o,writable:!1},brand:{set(){},get(){return Vo.bind(this)}}})}Object.defineProperty(Y.ZodDefault.prototype,"label",{value:Jo,writable:!1}),Object.defineProperty(Y.ZodObject.prototype,"remap",{value:Go,writable:!1})}function Wo(e){return e}import{z as $r}from"zod/v4";import*as pe from"ramda";import{z as Mr,globalRegistry as ln}from"zod/v4";import*as ae from"ramda";import{z as wr}from"zod/v4";import{z as Yo}from"zod/v4";var me=Symbol("Buffer"),it=()=>Yo.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(me);import{z as He}from"zod/v4";var le=Symbol("DateIn"),gr=({examples:e,...t}={})=>He.union([He.iso.date(),He.iso.datetime(),He.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(He.date()).brand(le).meta(t);import{z as Qo}from"zod/v4";var ue=Symbol("DateOut"),hr=(e={})=>Qo.date().transform(t=>t.toISOString()).brand(ue).meta(e);import{z as rn}from"zod/v4";import*as j from"ramda";import{z as Be}from"zod/v4";var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var xr=["get","post","put","delete","patch"],br=[...xr,"head"],fe=e=>xr.includes(e);var Mt=/:([A-Za-z0-9_]+)/g,at=e=>e.match(Mt)?.map(t=>t.slice(1))||[],Xo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},en={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},tn=["body","query","params"],zt=e=>e.method.toLowerCase(),jt=(e,t={})=>{if(e==="options")return[];let r=e==="head"?"get":fe(e)?e:void 0;return(r?t[r]||en[r]:void 0)||tn},pt=(e,t={})=>{let r=zt(e);return jt(r,t).filter(o=>o==="files"?Xo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},re=e=>e instanceof Error?e:e instanceof Be.ZodError?new Be.ZodRealError(e.issues):new Error(String(e)),ye=e=>e instanceof Be.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Be.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,oe=(e,t)=>E(e)&&"_zod"in e&&(t?j.path(["_zod","def","type"],e)===t:!0),ge=(e,t,r)=>e.length&&t.length?j.xprod(e,t).map(r):e.concat(t),Lt=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(Lt).join("")},ct=j.tryCatch((e,t)=>typeof Be.parse(e,t),j.always(void 0)),E=e=>typeof e=="object"&&e!==null,he=j.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production"),dt=(e,t)=>!!t&&e!=="head";var xe=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},Q=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Ke=class extends Error{name="IOSchemaError"},mt=class extends Ke{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},qe=class extends Ke{constructor(r){let o=new rn.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(ye(o),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends Ke{constructor(r){super(ye(r),{cause:r});this.cause=r}name="InputValidationError"},se=class extends Error{constructor(r,o){super(ye(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},De=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as Sr}from"zod/v4";var Fe=Symbol("Form"),Rr=e=>(e instanceof Sr.ZodObject?e:Sr.object(e)).brand(Fe);import{z as on}from"zod/v4";var ie=Symbol("Upload"),Or=()=>on.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ie);import{z as nn}from"zod/v4";var H=Symbol("Raw"),Tr=nn.object({raw:it()}),sn=e=>Tr.extend(e).brand(H);function Pr(e){return e?sn(e):Tr.brand(H)}var Cr=(e,{io:t,condition:r})=>ae.tryCatch(()=>{wr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new mt(o)}})},o=>o.cause)(),Er=(e,{io:t})=>{let o=[wr.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(ae.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ae.values(n))}ae.is(Array,n)&&o.push(...ae.values(n))}return!1},kr=e=>Cr(e,{condition:t=>{let r=W(t);return typeof r=="symbol"&&[ie,H,Fe].includes(r)},io:"input"}),an=["nan","symbol","map","set","bigint","void","promise","never"],$t=(e,t)=>Cr(e,{io:t,condition:r=>{let o=W(r),{type:n}=r._zod.def;return!!(an.includes(n)||o===me||t==="input"&&(n==="date"||o===ue)||t==="output"&&(o===le||o===H||o===ie))}});import dn,{isHttpError as mn}from"http-errors";import vr,{isHttpError as pn}from"http-errors";import*as Ir from"ramda";import{z as cn}from"zod/v4";var Zt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof cn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new se(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Ue=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>pn(e)?e:vr(e instanceof X?400:500,ye(e),{cause:e.cause||e}),be=e=>he()&&!e.expose?vr(e.statusCode).message:e.message,Ar=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>ge(t,Z(o).map(Ir.objOf(r)),([n,s])=>({...n,...s})),[]);var lt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=be(dn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:mn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Nr}from"zod/v4";var Ht=class{},U=class extends Ht{#e;#t;#r;constructor({input:t=Nr.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 Nr.ZodError?new X(o):o}}},ke=class extends U{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var ve=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends ve{},ut=class e extends _e{#e;#t=pe.once(()=>{if(Z(this.#e.outputSchema).length||!oe(this.#e.outputSchema,"object"))return;let t=Ar(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();ln.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=kr(this.#e.inputSchema);if(t){let r=W(t);if(r===ie)return"upload";if(r===H)return"raw";if(r===Fe)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=pe.pluck("security",this.#e.middlewares||[]);return pe.reject(pe.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Mr.ZodError?new qe(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof ke))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Mr.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){lt({...t,error:new se(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=zt(t),i={},p={output:{},error:null},d=pt(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as zr from"ramda";var jr=(e,t)=>zr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as Lr,z as B}from"zod/v4";var Ie={positive:200,negative:400},Ae=Object.keys(Ie);var Bt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Se=class extends Bt{#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:[Ie.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Zt(this.#t,{variant:"negative",args:[],statusCodes:[Ie.negative],mimeTypes:[C.json]})}},Re=new Se({positive:e=>{let t=B.object({status:B.literal("success"),data:e}),r=Z(e);return r.length&&Lr.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:B.object({status:B.literal("error"),error:B.object({message:B.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 Ue(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:be(i)}})}n.status(Ie.positive).json({status:"success",data:r})}}),Kt=new Se({positive:e=>{let t=e instanceof B.ZodObject&&"items"in e.shape&&e.shape.items instanceof B.ZodArray?e.shape.items:B.array(B.any());if(Z(t).length)return t;let r=Z(e).filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();Lr.remove(t).add(t,{...o,examples:r})}return t},negative:{schema:B.string().example("Sample error message"),mimeType:"text/plain"},handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);return Ue(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(be(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ie.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Oe=class e{constructor(t){this.resultHandler=t}middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r}addMiddleware(t){return this.#e(t instanceof U?t:new U(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new ke(...t))}addOptions(t){return this.#e(new U({handler:t}))}build({input:t=$r.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,y=typeof o=="function"?o:w=>o&&`${o}${w==="head"?"__HEAD":""}`,h=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new ut({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:g,methods:m,getOperationId:y,inputSchema:jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:$r.object({}),handler:async o=>(await t(o),{})})}},un=new Oe(Re),fn=new Oe(Kt);import Rn from"ansis";import{inspect as On}from"node:util";import{performance as Dr}from"node:perf_hooks";import{blue as yn,green as gn,hex as hn,red as xn,cyanBright as bn}from"ansis";import*as Zr from"ramda";var qt={debug:yn,info:gn,warn:hn("#FFA500"),error:xn,ctx:bn},ft={debug:10,info:20,warn:30,error:40},Hr=e=>E(e)&&Object.keys(ft).some(t=>t in e),Br=e=>e in ft,Kr=(e,t)=>ft[e]<ft[t],Sn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ne=Zr.memoizeWith((e,t)=>`${e}${t}`,Sn),qr=e=>e<1e-6?Ne("nanosecond",3).format(e/1e-6):e<.001?Ne("nanosecond").format(e/1e-6):e<1?Ne("microsecond").format(e/.001):e<1e3?Ne("millisecond").format(e):e<6e4?Ne("second",2).format(e/1e3):Ne("minute",2).format(e/6e4);var Je=class e{config;constructor({color:t=Rn.isSupported(),level:r=he()?"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 On(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"||Kr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?qt.ctx(s):s),d.push(p?`${qt[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=Dr.now();return()=>{let o=Dr.now()-r,{message:n,severity:s="debug",formatter:i=qr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Fr from"ramda";var Ve=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Fr.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 Tn from"express";var Ge=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,Tn.static(...this.#e))}};import xt from"express";import Bn from"node:http";import Kn from"node:https";var Me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new De(e)};import An from"http-errors";import{z as _r}from"zod/v4";import*as b from"ramda";var Pn=e=>e.type==="object",wn=b.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return b.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),Cn=b.pipe(Object.keys,b.without(["type","properties","required","examples","description","additionalProperties"]),b.isEmpty),Ur=b.pair(!0),ze=(e,t="coerce")=>{let r=[b.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&Cn(p)))throw new Error("Can not merge");return b.pair(s,p)})),i.anyOf&&r.push(...b.map(Ur,i.anyOf)),i.oneOf&&r.push(...b.map(Ur,i.oneOf)),i.examples?.length&&(s?o.examples=b.concat(o.examples||[],i.examples):o.examples=ge(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>b.mergeDeepRight(p,d))),!!Pn(i)&&(r.push([s,{examples:En(i)}]),i.properties&&(o.properties=(t==="throw"?wn:b.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},En=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return ge(t,n.map(b.objOf(r)),([s,i])=>({...s,...i}))},[]);var yt=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=[_r.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=$t(t.inputSchema,"input");o&&this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ae)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(C.json))continue;let i=$t(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=at(t);if(s.length===0)return;let i=n?.flat||ze(_r.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 gt=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},kn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&fe(t)?[r,t]:[e]},vn=e=>e.trim().split("/").filter(Boolean).join("/"),Jr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=kn(r);return[[t||""].concat(vn(n)||[]).join("/"),o,s]}),In=(e,t)=>{throw new xe("Route with explicit method can only be assigned with Endpoint",e,t)},Vr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new xe(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Dt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new xe("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Jr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof _e)if(p)Dt(p,s,n),Vr(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)Dt(c,s,n),t(c,s,i)}else if(p&&In(p,s),i instanceof Ge)r&&i.apply(s,r);else if(i instanceof Ve)for(let[d,c]of i.entries){let{methods:m}=c;Dt(d,s,n),Vr(d,s,m),t(d,s,c)}else o.unshift(...Jr(i,s))}};import*as Gr from"ramda";var Wr=e=>e.sort((t,r)=>+fe(r)-+fe(t)||t.localeCompare(r)).join(", ").toUpperCase(),Nn=e=>({method:t},r,o)=>{let n=Wr(e);r.set({Allow:n});let s=An(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Mn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Wr(e),"Access-Control-Allow-Headers":"content-type"}),Ft=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=he()?void 0:new yt(t()),i=new Map;je({routing:o,onEndpoint:(c,m,y)=>{he()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let h=n?.[y.requestType]||[],g=Gr.pair(h,y);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(c,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[h,[g,w]]of m){let v=g.slice().concat(async(z,S)=>{let I=t(z);return w.execute({request:z,response:S,logger:I,config:r})});r.cors&&v.unshift(async(z,S,I)=>{let A=t(z),$=Mn(y),N=typeof r.cors=="function"?await r.cors({request:z,endpoint:w,logger:A,defaultHeaders:$}):$;S.set(N),I()}),e[h](c,...v)}r.wrongMethodBehavior!==404&&d.set(c,Nn(y))}for(let[c,m]of d)e.all(c,m)};import jn from"http-errors";import{setInterval as zn}from"node:timers/promises";var Yr=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",Qr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Xr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,eo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),to=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var ro=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Yr(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",eo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Xr(c)||Qr(c))&&i(c);for await(let c of zn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(to))};return{sockets:n,shutdown:()=>o??=d()}};var oo=({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(),no=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=jn(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){lt({response:o,logger:s,error:new se(re(i),n)})}},Ln=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},$n=e=>({log:e.debug.bind(e)}),so=async({getLogger:e,config:t})=>{let r=await Me("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:$n(m)})(p,d,c)}),o&&i.push(Ln(o)),i},io=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ao=({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()},po=e=>t=>t?.res?.locals[Ce]?.logger||e,co=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),mo=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=ro(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};import{gray as Zn,hex as lo,italic as ht,whiteBright as Hn}from"ansis";var uo=e=>{if(e.columns<132)return;let t=ht("Proudly supports transgender community.".padStart(109)),r=ht("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=ht("Thank you for choosing Express Zod API for your project.".padStart(132)),n=ht("for Ashley".padEnd(20)),s=lo("#F5A9B8"),i=lo("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(Hn,5,7).fill(s,7,9).fill(i,9,12).fill(Zn,12,13),d=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
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 fo=e=>{e.startupLogo!==!1&&uo(process.stdout);let t=e.errorHandler||Re,r=Br(e.logger)?e.logger:new Je(e.logger);r.debug("Running",{build:"v24.7.0 (ESM)",env:process.env.NODE_ENV||"development"}),co(r);let o=ao({logger:r,config:e}),s={getLogger:po(r),errorHandler:t},i=no(s),p=oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},qn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=fo(e);return Ut({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Dn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=fo(e),p=xt().disable("x-powered-by").use(i);if(e.compression){let h=await Me("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||xt.json()],raw:[e.rawParser||xt.raw(),io],form:[e.formParser||xt.urlencoded()],upload:e.upload?await so({config:e,getLogger:o}):[]};Ut({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,g)=>()=>h.listen(g,()=>r.info("Listening",g)),y=[];if(e.http){let h=Hn.createServer(p);c.push(h),y.push(m(h,e.http.listen))}if(e.https){let h=Kn.createServer(e.https.options,p);c.push(h),y.push(m(h,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&mo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(h=>h())}};import{OpenApiBuilder as fs}from"openapi3-ts/oas31";import*as jo from"ramda";import*as R from"ramda";var yo=e=>E(e)&&"or"in e,go=e=>E(e)&&"and"in e,Ft=e=>!go(e)&&!yo(e),ho=e=>{let t=R.filter(Ft,e),r=R.chain(R.prop("and"),R.filter(go,e)),[o,n]=R.partition(Ft,r),s=R.concat(t,o),i=R.filter(yo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>ge(d,R.map(m=>Ft(m)?[m]:m.and,c),([m,y])=>R.concat(m,y)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as Ro,isSchemaObject as bt}from"openapi3-ts/oas31";import*as l from"ramda";import{z as bo}from"zod/v4";var xo=["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 So=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(Mt,t=>`{${t.slice(1)}}`),Fn=({},e)=>{if(e.isResponse)throw new Q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},_n=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Jn=({zodSchema:e,jsonSchema:t})=>{if(!ne(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Vn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return je(e,"throw")},(e,{jsonSchema:t})=>t),Gn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:os(t.type)})},wo=e=>e in To,Wn=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&wo(t)&&(e.type=t),e},Yn=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&wo(t)&&(e.type=t),e},We=e=>e,Qn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Q("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Oo}};return e?.length&&(o.examples=e),o},Xn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Q("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Oo}};return e?.length&&(o.examples=e),o},es=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),ts=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},rs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},os=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ns=({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(Vt(n,{ctx:r}));if(bt(s))if(r.isResponse){let i=ct(o,rs(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},ss=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},_t=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,is=(e,t)=>t?.includes(e)||e.startsWith("x-")||xo.includes(e),Co=({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=at(e),y=o.includes("query"),h=o.includes("params"),g=o.includes("headers"),w=S=>h&&m.includes(S),v=l.chain(l.filter(S=>S.type==="header"),p??[]).map(({name:S})=>S),j=S=>g&&(i?.(S,t,e)??is(S,v));return Object.entries(c.properties).reduce((S,[I,A])=>{if(!E(A))return S;let $=w(I)?"path":j(I)?"header":y?"query":void 0;if(!$)return S;let N=We(A),ee=s==="components"?n(A.id||JSON.stringify(A),N,se(d,I)):N;return S.concat({name:I,in:$,deprecated:A.deprecated,required:c.required?.includes(I)||!1,description:N.description||d,schema:ee,examples:_t(bt(N)&&N.examples?.length?N.examples:l.pluck(I,c.examples?.filter(l.both(E,l.has(I)))||[]))})},[])},Jt={nullable:Gn,union:Jn,bigint:es,intersection:Vn,tuple:ts,pipe:ns,literal:Yn,enum:Wn,[le]:Qn,[ue]:Xn,[ae]:Fn,[B]:ss,[me]:_n},as=(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.id||i,We(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Vt=(e,{ctx:t,rules:r=Jt})=>{let{$defs:o={},properties:n={}}=bo.toJSONSchema(bo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=W(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return as(E(n.subject)?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]},ko=({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} ${Lt(n)} response ${p?d:""}`.trim()})=>{if(!o||!dt(e,n))return{description:m};let y=We(Vt(r,{rules:{...c,...Jt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];bt(y)&&y.examples&&(h.push(...y.examples),delete y.examples);let g={schema:i==="components"?s(r,y,se(m)):y,examples:_t(h)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},ps=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},cs=({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},ds=({name:e})=>({type:"apiKey",in:"header",name:e}),ms=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ls=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),us=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),vo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ps(o):o.type==="input"?cs(o,t):o.type==="header"?ds(o):o.type==="cookie"?ms(o):o.type==="openid"?ls(o):us(o);return e.map(o=>o.map(r))},Io=(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:[]})},{})),Ao=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Vt(e,{rules:{...t,...Jt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),No=({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(We(o),p),y=[];bt(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,se(d)):c,examples:_t(y.length?y:je(o).examples?.filter(w=>E(w)&&!Array.isArray(w)).map(l.omit(p))||[])},g={description:d,content:{[n]:h}};return(m||n===C.raw)&&(g.required=!0),g},Mo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Gt=e=>e.length<=So?e:e.slice(0,So-1)+"\u2026",St=e=>e.length?e.slice():void 0;var Wt=class extends fs{#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 Q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});ze({routing:t,onEndpoint:gt((g,w,v)=>{let j={path:w,method:g,endpoint:v,composition:y,brandHandling:p,makeRef:this.#o.bind(this)},{description:S,shortDescription:I,scopes:A,inputSchema:$}=v,N=I?Gt(I):m&&S?Gt(S):void 0,ee=zt(g,r.inputSources),we=this.#n(w,g,v.getOperationId(g)),et=Ao({...j,schema:$}),te=ho(v.security),tt=Co({...j,inputSources:ee,isHeader:c,security:te,request:et,description:i?.requestParameter?.call(null,{method:g,path:w,operationId:we})}),rt={};for(let re of Ae){let de=v.getResponses(re);for(let{mimeTypes:At,schema:nt,statusCodes:st}of de)for(let Nt of st)rt[Nt]=ko({...j,variant:re,schema:nt,mimeTypes:At,statusCode:Nt,hasMultipleStatusCodes:de.length>1||st.length>1,description:i?.[`${re}Response`]?.call(null,{method:g,path:w,operationId:we,statusCode:Nt})})}let ot=ee.includes("body")?No({...j,request:et,paramNames:jo.pluck("name",tt),schema:$,mimeType:C[v.requestType],description:i?.requestBody?.call(null,{method:g,path:w,operationId:we})}):void 0,vt=Io(vo(te,ee),A,re=>{let de=this.#s(re);return this.addSecurityScheme(de,re),de}),It={operationId:we,summary:N,description:S,deprecated:v.isDeprecated||void 0,tags:St(v.tags),parameters:St(tt),requestBody:ot,security:St(vt),responses:rt};this.addPath(Po(w),{[g]:It})})}),d&&(this.rootDoc.tags=Mo(d))}};import{createRequest as ys,createResponse as gs}from"node-mocks-http";var hs=e=>ys({...e,headers:{"content-type":C.json,...e?.headers}}),xs=e=>gs(e),bs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Hr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},zo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=hs(e),s=xs({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}},Ss=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=zo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Rs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=Re}}=zo(r),d=pt(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:{}}}};import*as Ho from"ramda";import kt from"typescript";import{z as _s}from"zod/v4";import*as Zo from"ramda";import G from"typescript";import*as _ from"ramda";import u from"typescript";var a=u.factory,Rt=[a.createModifier(u.SyntaxKind.ExportKeyword)],Os=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Yt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Qt=(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)},Ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Xt=e=>typeof e=="string"&&Ts.test(e)?a.createIdentifier(e):O(e),Ot=(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)))),Tt=(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])=>Tt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),er=(e,t=[])=>a.createConstructorDeclaration(Ye.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&_.map(f,t)):e,tr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),J=e=>{let t=new Map;for(let r of e)t.set(ws(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Te=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Xt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?J([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=_.reject(_.isNil,[o?"@deprecated":void 0,n]);return p.length?Yt(i,p.join(" ")):i},rr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),or=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&Rt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),nr=(e,t)=>V(e,J(_.map(L,t)),{expose:!0}),V=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?Rt:void 0,e,n&&pr(n),t);return o?Yt(s,o):s},Lo=(e,t)=>a.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),sr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&pr(o),t,n,a.createBlock(r)),ir=(e,t,{typeParams:r}={})=>a.createClassDeclaration(Rt,e,r&&pr(r),void 0,t),ar=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Pt=e=>f(Promise.name,[e]),wt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?Rt:void 0,e,void 0,void 0,t);return o?Yt(n,o):n},pr=e=>(Array.isArray(e)?e.map(t=>_.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Pe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?Os:void 0,void 0,Array.isArray(e)?_.map(Tt,e):Le(e),void 0,void 0,t),T=e=>e,Qe=(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),$e=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),cr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),K=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),$o=e=>J([f(e),Pt(e)]),dr=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),O=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),L=e=>a.createLiteralTypeNode(O(e)),Ps=[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],ws=e=>Ps.includes(e.kind);var Et=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=nr("Method",br);someOfType=V("SomeOf",K("T",ar("T")),{params:["T"]});requestType=V("Request",ar(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>nr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>wt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Te(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Xt(t),a.createArrayLiteralExpression(Zo.map(O,r))))),{expose:!0});makeImplementationType=()=>V(this.#e.implementationType,dr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:tr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Pt(G.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:G.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.#e.parseRequestFn,Pe({[this.#e.requestParameter.text]:G.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),O(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>M(this.#e.substituteFn,Pe({[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:tr},a.createBlock([M(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],G.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([cr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Ot(":",[this.#e.keyParameter]),Pe([],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=()=>sr(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"}}),[M(or(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:Pt(K(this.interfaces.response,"K"))});makeClientClass=t=>ir(t,[er([Tt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Ot("?",[$e(URLSearchParams.name,t)]);#o=()=>$e(URL.name,Ot("",[this.#e.pathParameter],[this.#e.searchParamsConst]),O(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),Qe(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(O("Content-Type"),O(C.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),Qe(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=M(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=M(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([O("get"),O("head"),O("delete")]),T("includes"))(this.#e.methodParameter))),i=M(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,O(""),this.#r(this.#e.paramsArgument))),p=M(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(O("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(G.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=M(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(O(C.json))),m=a.createReturnStatement(P(this.#e.responseConst,Qe(this.#e.isJsonConst,O(T("json")),O(T("text"))))());return M(this.#e.defaultImplementationConst,Pe([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=()=>er(Le({request:"K",params:K(this.interfaces.input,"K")}),[M(or(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),O(1)),this.#e.paramsArgument)),M(this.#e.searchParamsConst,this.#r(this.#e.restConst)),cr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),$e("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Te(T("event"),t)]);#i=()=>sr(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:dr({[this.#e.dataParameter.text]:K(Ct("R",rr(this.#s("E"))),L(T("data")))},$o(G.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Pe([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:K("R",L(T("event")))}});makeSubscriptionClass=t=>ir(t,[Lo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ct(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(G.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ct(K(this.interfaces.positive,"K"),rr(this.#s(G.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.#e.clientConst,$e(t)),P(this.#e.clientConst,this.#e.provideMethod)(O("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",O("10"))])),P($e(r,O("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(O("time"),Pe(["time"],a.createBlock([])))]};import*as k from"ramda";import x from"typescript";import{globalRegistry as Cs}from"zod/v4";var mr=(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=>mr(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,Es={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},lr={name:k.path(["name","text"]),type:k.path(["type"]),optional:k.path(["questionToken"])},ks=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.SyntaxKind.UndefinedKeyword):L(r));return t.length===1?t[0]:J(t)},vs=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(ne(p)){r.unshift(p);break}i+=p??""}return i},n=D.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?D.createTemplateMiddle:D.createTemplateTail;s.push(D.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?D.createTemplateLiteralType(n,s):L(n.text)},Is=(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}=Cs.get(p)||{};return Te(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return D.createTypeLiteralNode(s)};return Er(e,{io:t?"output":"input"})?o(e,n):n()},As=({_zod:{def:e}},{next:t})=>D.createArrayTypeNode(t(e.element)),Ns=({_zod:{def:e}})=>J(Object.values(e.entries).map(L)),Ms=({_zod:{def:e}},{next:t})=>J(e.options.map(t)),js=e=>Es?.[e.kind],zs=({_zod:{def:e}},{next:t})=>J([t(e.innerType),L(null)]),Ls=({_zod:{def:e}},{next:t})=>D.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:D.createRestTypeNode(t(e.rest)))),$s=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Zs=k.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=k.chain(k.prop("members"),e),r=k.uniqWith((...o)=>{if(!k.eqBy(lr.name,...o))return!1;if(k.both(k.eqBy(lr.type),k.eqBy(lr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return D.createTypeLiteralNode(r)},(e,t)=>D.createIntersectionTypeNode(t)),Bs=({_zod:{def:e}},{next:t})=>Zs([e.left,e.right].map(t)),q=e=>()=>f(e),Xe=({_zod:{def:e}},{next:t})=>t(e.innerType),Bo=e=>f(e?x.SyntaxKind.UnknownKeyword:x.SyntaxKind.AnyKeyword),Hs=({_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=ct(o,js(s)),p={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(i&&p[i]||Bo(r))},Ks=()=>L(null),qs=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ds=()=>f("Buffer"),Us=(e,{next:t})=>t(e._zod.def.shape.raw),Fs={string:q(x.SyntaxKind.StringKeyword),number:q(x.SyntaxKind.NumberKeyword),bigint:q(x.SyntaxKind.BigIntKeyword),boolean:q(x.SyntaxKind.BooleanKeyword),any:q(x.SyntaxKind.AnyKeyword),undefined:q(x.SyntaxKind.UndefinedKeyword),[le]:q(x.SyntaxKind.StringKeyword),[ue]:q(x.SyntaxKind.StringKeyword),never:q(x.SyntaxKind.NeverKeyword),void:q(x.SyntaxKind.UndefinedKeyword),unknown:q(x.SyntaxKind.UnknownKeyword),null:Ks,array:As,tuple:Ls,record:$s,object:Is,literal:ks,template_literal:vs,intersection:Bs,union:Ms,default:Xe,enum:Ns,optional:Xe,nonoptional:Xe,nullable:zs,catch:Xe,pipe:Hs,lazy:qs,readonly:Xe,[me]:Ds,[B]:Us},ur=(e,{brandHandling:t,ctx:r})=>mr(e,{rules:{...t,...Fs},onMissing:({},{isResponse:o})=>Bo(o),ctx:r});var fr=class extends Et{#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=L(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=_s.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};ze({routing:t,onEndpoint:gt((h,g,w)=>{let v=se.bind(null,h,g),{isDeprecated:j,inputSchema:S,tags:I}=w,A=`${h} ${g}`,$=V(v("input"),ur(S,c),{comment:A});this.#e.push($);let N=Ae.reduce((et,te)=>{let tt=w.getResponses(te),rt=Ho.chain(([vt,{schema:It,mimeTypes:re,statusCodes:de}])=>{let At=re&&dt(h,te),nt=V(v(te,"variant",`${vt+1}`),ur(At?It:p,m),{comment:A});return this.#e.push(nt),de.map(st=>Te(st,nt.name))},Array.from(tt.entries())),ot=wt(v(te,"response","variants"),rt,{comment:A});return this.#e.push(ot),Object.assign(et,{[te]:ot})},{});this.paths.add(g);let ee=L(A),we={input:f($.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:J([K(this.interfaces.positive,ee),K(this.interfaces.negative,ee)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(A,{isDeprecated:j,store:we}),this.tags.set(A,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:Qt(r,t)).join(`
18
+ `))};var fo=e=>{e.startupLogo!==!1&&uo(process.stdout);let t=e.errorHandler||Re,r=Hr(e.logger)?e.logger:new Je(e.logger);r.debug("Running",{build:"v24.7.3 (ESM)",env:process.env.NODE_ENV||"development"}),co(r);let o=ao({logger:r,config:e}),s={getLogger:po(r),errorHandler:t},i=no(s),p=oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},qn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=fo(e);return Ft({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Dn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=fo(e),p=xt().disable("x-powered-by").use(i);if(e.compression){let h=await Me("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||xt.json()],raw:[e.rawParser||xt.raw(),io],form:[e.formParser||xt.urlencoded()],upload:e.upload?await so({config:e,getLogger:o}):[]};Ft({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,g)=>()=>h.listen(g,()=>r.info("Listening",g)),y=[];if(e.http){let h=Bn.createServer(p);c.push(h),y.push(m(h,e.http.listen))}if(e.https){let h=Kn.createServer(e.https.options,p);c.push(h),y.push(m(h,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&mo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(h=>h())}};import{OpenApiBuilder as fs}from"openapi3-ts/oas31";import*as zo from"ramda";import*as R from"ramda";var yo=e=>E(e)&&"or"in e,go=e=>E(e)&&"and"in e,Ut=e=>!go(e)&&!yo(e),ho=e=>{let t=R.filter(Ut,e),r=R.chain(R.prop("and"),R.filter(go,e)),[o,n]=R.partition(Ut,r),s=R.concat(t,o),i=R.filter(yo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>ge(d,R.map(m=>Ut(m)?[m]:m.and,c),([m,y])=>R.concat(m,y)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as Ro,isSchemaObject as bt}from"openapi3-ts/oas31";import*as l from"ramda";import{z as bo}from"zod/v4";var xo=["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 So=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(Mt,t=>`{${t.slice(1)}}`),Un=({},e)=>{if(e.isResponse)throw new Q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},_n=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Jn=({zodSchema:e,jsonSchema:t})=>{if(!oe(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Vn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return ze(e,"throw")},(e,{jsonSchema:t})=>t),Gn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:os(t.type)})},wo=e=>e in To,Wn=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&wo(t)&&(e.type=t),e},Yn=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&wo(t)&&(e.type=t),e},We=e=>e,Qn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Q("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Oo}};return e?.length&&(o.examples=e),o},Xn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Q("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Oo}};return e?.length&&(o.examples=e),o},es=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),ts=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},rs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},os=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ns=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!oe(o,"transform"))return t;let s=We(Vt(n,{ctx:r}));if(bt(s))if(r.isResponse){let i=ct(o,rs(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},ss=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},_t=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,is=(e,t)=>t?.includes(e)||e.startsWith("x-")||xo.includes(e),Co=({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=at(e),y=o.includes("query"),h=o.includes("params"),g=o.includes("headers"),w=S=>h&&m.includes(S),v=l.chain(l.filter(S=>S.type==="header"),p??[]).map(({name:S})=>S),z=S=>g&&(i?.(S,t,e)??is(S,v));return Object.entries(c.properties).reduce((S,[I,A])=>{if(!E(A))return S;let $=w(I)?"path":z(I)?"header":y?"query":void 0;if(!$)return S;let N=We(A),ee=s==="components"?n(A.id||JSON.stringify(A),N,ne(d,I)):N;return S.concat({name:I,in:$,deprecated:A.deprecated,required:c.required?.includes(I)||!1,description:N.description||d,schema:ee,examples:_t(bt(N)&&N.examples?.length?N.examples:l.pluck(I,c.examples?.filter(l.both(E,l.has(I)))||[]))})},[])},Jt={nullable:Gn,union:Jn,bigint:es,intersection:Vn,tuple:ts,pipe:ns,literal:Yn,enum:Wn,[le]:Qn,[ue]:Xn,[ie]:Un,[H]:ss,[me]:_n},as=(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.id||i,We(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Vt=(e,{ctx:t,rules:r=Jt})=>{let{$defs:o={},properties:n={}}=bo.toJSONSchema(bo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=W(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return as(E(n.subject)?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]},ko=({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} ${Lt(n)} response ${p?d:""}`.trim()})=>{if(!dt(e,o))return{description:m};let y=We(Vt(r,{rules:{...c,...Jt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];bt(y)&&y.examples&&(h.push(...y.examples),delete y.examples);let g={schema:i==="components"?s(r,y,ne(m)):y,examples:_t(h)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},ps=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},cs=({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},ds=({name:e})=>({type:"apiKey",in:"header",name:e}),ms=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ls=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),us=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),vo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ps(o):o.type==="input"?cs(o,t):o.type==="header"?ds(o):o.type==="cookie"?ms(o):o.type==="openid"?ls(o):us(o);return e.map(o=>o.map(r))},Io=(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:[]})},{})),Ao=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Vt(e,{rules:{...t,...Jt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),No=({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(We(o),p),y=[];bt(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,ne(d)):c,examples:_t(y.length?y:ze(o).examples?.filter(w=>E(w)&&!Array.isArray(w)).map(l.omit(p))||[])},g={description:d,content:{[n]:h}};return(m||n===C.raw)&&(g.required=!0),g},Mo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Gt=e=>e.length<=So?e:e.slice(0,So-1)+"\u2026",St=e=>e.length?e.slice():void 0;var Wt=class extends fs{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||ne(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});je({routing:t,onEndpoint:gt((g,w,v)=>{let z={path:w,method:g,endpoint:v,composition:y,brandHandling:p,makeRef:this.#o.bind(this)},{description:S,shortDescription:I,scopes:A,inputSchema:$}=v,N=I?Gt(I):m&&S?Gt(S):void 0,ee=jt(g,r.inputSources),we=this.#n(w,g,v.getOperationId(g)),et=Ao({...z,schema:$}),ce=ho(v.security),tt=Co({...z,inputSources:ee,isHeader:c,security:ce,request:et,description:i?.requestParameter?.call(null,{method:g,path:w,operationId:we})}),rt={};for(let te of Ae){let de=v.getResponses(te);for(let{mimeTypes:At,schema:nt,statusCodes:st}of de)for(let Nt of st)rt[Nt]=ko({...z,variant:te,schema:nt,mimeTypes:At,statusCode:Nt,hasMultipleStatusCodes:de.length>1||st.length>1,description:i?.[`${te}Response`]?.call(null,{method:g,path:w,operationId:we,statusCode:Nt})})}let ot=ee.includes("body")?No({...z,request:et,paramNames:zo.pluck("name",tt),schema:$,mimeType:C[v.requestType],description:i?.requestBody?.call(null,{method:g,path:w,operationId:we})}):void 0,vt=Io(vo(ce,ee),A,te=>{let de=this.#s(te);return this.addSecurityScheme(de,te),de}),It={operationId:we,summary:N,description:S,deprecated:v.isDeprecated||void 0,tags:St(v.tags),parameters:St(tt),requestBody:ot,security:St(vt),responses:rt};this.addPath(Po(w),{[g]:It})})}),d&&(this.rootDoc.tags=Mo(d))}};import{createRequest as ys,createResponse as gs}from"node-mocks-http";var hs=e=>ys({...e,headers:{"content-type":C.json,...e?.headers}}),xs=e=>gs(e),bs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Br(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=hs(e),s=xs({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}},Ss=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}},Rs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=Re}}=jo(r),d=pt(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 Bo from"ramda";import kt from"typescript";import{z as _s}from"zod/v4";import*as Zo from"ramda";import G from"typescript";import*as _ from"ramda";import u from"typescript";var a=u.factory,Rt=[a.createModifier(u.SyntaxKind.ExportKeyword)],Os=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Yt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Qt=(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)},Ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Xt=e=>typeof e=="string"&&Ts.test(e)?a.createIdentifier(e):O(e),Ot=(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)))),Tt=(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])=>Tt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),er=(e,t=[])=>a.createConstructorDeclaration(Ye.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&_.map(f,t)):e,tr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),J=e=>{let t=new Map;for(let r of e)t.set(ws(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Te=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Xt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?J([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=_.reject(_.isNil,[o?"@deprecated":void 0,n]);return p.length?Yt(i,p.join(" ")):i},rr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),or=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&Rt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),nr=(e,t)=>V(e,J(_.map(L,t)),{expose:!0}),V=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?Rt:void 0,e,n&&pr(n),t);return o?Yt(s,o):s},Lo=(e,t)=>a.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),sr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&pr(o),t,n,a.createBlock(r)),ir=(e,t,{typeParams:r}={})=>a.createClassDeclaration(Rt,e,r&&pr(r),void 0,t),ar=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Pt=e=>f(Promise.name,[e]),wt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?Rt:void 0,e,void 0,void 0,t);return o?Yt(n,o):n},pr=e=>(Array.isArray(e)?e.map(t=>_.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Pe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?Os:void 0,void 0,Array.isArray(e)?_.map(Tt,e):Le(e),void 0,void 0,t),T=e=>e,Qe=(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),$e=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),cr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),K=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),$o=e=>J([f(e),Pt(e)]),dr=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),O=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),L=e=>a.createLiteralTypeNode(O(e)),Ps=[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],ws=e=>Ps.includes(e.kind);var Et=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=nr("Method",br);someOfType=V("SomeOf",K("T",ar("T")),{params:["T"]});requestType=V("Request",ar(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>nr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>wt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Te(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Xt(t),a.createArrayLiteralExpression(Zo.map(O,r))))),{expose:!0});makeImplementationType=()=>V(this.#e.implementationType,dr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:tr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Pt(G.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:G.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.#e.parseRequestFn,Pe({[this.#e.requestParameter.text]:G.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),O(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>M(this.#e.substituteFn,Pe({[this.#e.pathParameter.text]:G.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:tr},a.createBlock([M(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],G.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([cr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Ot(":",[this.#e.keyParameter]),Pe([],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=()=>sr(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"}}),[M(or(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:Pt(K(this.interfaces.response,"K"))});makeClientClass=t=>ir(t,[er([Tt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Ot("?",[$e(URLSearchParams.name,t)]);#o=()=>$e(URL.name,Ot("",[this.#e.pathParameter],[this.#e.searchParamsConst]),O(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),Qe(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(O("Content-Type"),O(C.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),Qe(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=M(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=M(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([O("get"),O("head"),O("delete")]),T("includes"))(this.#e.methodParameter))),i=M(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,O(""),this.#r(this.#e.paramsArgument))),p=M(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(O("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(G.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=M(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(O(C.json))),m=a.createReturnStatement(P(this.#e.responseConst,Qe(this.#e.isJsonConst,O(T("json")),O(T("text"))))());return M(this.#e.defaultImplementationConst,Pe([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=()=>er(Le({request:"K",params:K(this.interfaces.input,"K")}),[M(or(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),O(1)),this.#e.paramsArgument)),M(this.#e.searchParamsConst,this.#r(this.#e.restConst)),cr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),$e("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Te(T("event"),t)]);#i=()=>sr(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:dr({[this.#e.dataParameter.text]:K(Ct("R",rr(this.#s("E"))),L(T("data")))},$o(G.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Pe([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:K("R",L(T("event")))}});makeSubscriptionClass=t=>ir(t,[Lo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ct(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(G.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ct(K(this.interfaces.positive,"K"),rr(this.#s(G.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.#e.clientConst,$e(t)),P(this.#e.clientConst,this.#e.provideMethod)(O("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",O("10"))])),P($e(r,O("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(O("time"),Pe(["time"],a.createBlock([])))]};import*as k from"ramda";import x from"typescript";import{globalRegistry as Cs}from"zod/v4";var mr=(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=>mr(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,Es={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},lr={name:k.path(["name","text"]),type:k.path(["type"]),optional:k.path(["questionToken"])},ks=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.SyntaxKind.UndefinedKeyword):L(r));return t.length===1?t[0]:J(t)},vs=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(oe(p)){r.unshift(p);break}i+=p??""}return i},n=D.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?D.createTemplateMiddle:D.createTemplateTail;s.push(D.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?D.createTemplateLiteralType(n,s):L(n.text)},Is=(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}=Cs.get(p)||{};return Te(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return D.createTypeLiteralNode(s)};return Er(e,{io:t?"output":"input"})?o(e,n):n()},As=({_zod:{def:e}},{next:t})=>D.createArrayTypeNode(t(e.element)),Ns=({_zod:{def:e}})=>J(Object.values(e.entries).map(L)),Ms=({_zod:{def:e}},{next:t})=>J(e.options.map(t)),zs=e=>Es?.[e.kind],js=({_zod:{def:e}},{next:t})=>J([t(e.innerType),L(null)]),Ls=({_zod:{def:e}},{next:t})=>D.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:D.createRestTypeNode(t(e.rest)))),$s=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Zs=k.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=k.chain(k.prop("members"),e),r=k.uniqWith((...o)=>{if(!k.eqBy(lr.name,...o))return!1;if(k.both(k.eqBy(lr.type),k.eqBy(lr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return D.createTypeLiteralNode(r)},(e,t)=>D.createIntersectionTypeNode(t)),Hs=({_zod:{def:e}},{next:t})=>Zs([e.left,e.right].map(t)),q=e=>()=>f(e),Xe=({_zod:{def:e}},{next:t})=>t(e.innerType),Ho=e=>f(e?x.SyntaxKind.UnknownKeyword:x.SyntaxKind.AnyKeyword),Bs=({_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=ct(o,zs(s)),p={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(i&&p[i]||Ho(r))},Ks=()=>L(null),qs=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ds=()=>f("Buffer"),Fs=(e,{next:t})=>t(e._zod.def.shape.raw),Us={string:q(x.SyntaxKind.StringKeyword),number:q(x.SyntaxKind.NumberKeyword),bigint:q(x.SyntaxKind.BigIntKeyword),boolean:q(x.SyntaxKind.BooleanKeyword),any:q(x.SyntaxKind.AnyKeyword),undefined:q(x.SyntaxKind.UndefinedKeyword),[le]:q(x.SyntaxKind.StringKeyword),[ue]:q(x.SyntaxKind.StringKeyword),never:q(x.SyntaxKind.NeverKeyword),void:q(x.SyntaxKind.UndefinedKeyword),unknown:q(x.SyntaxKind.UnknownKeyword),null:Ks,array:As,tuple:Ls,record:$s,object:Is,literal:ks,template_literal:vs,intersection:Hs,union:Ms,default:Xe,enum:Ns,optional:Xe,nonoptional:Xe,nullable:js,catch:Xe,pipe:Bs,lazy:qs,readonly:Xe,[me]:Ds,[H]:Fs},ur=(e,{brandHandling:t,ctx:r})=>mr(e,{rules:{...t,...Us},onMissing:({},{isResponse:o})=>Ho(o),ctx:r});var fr=class extends Et{#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=L(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=_s.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:gt((h,g,w)=>{let v=ne.bind(null,h,g),{isDeprecated:z,inputSchema:S,tags:I}=w,A=`${h} ${g}`,$=V(v("input"),ur(S,c),{comment:A});this.#e.push($);let N=Ae.reduce((et,ce)=>{let tt=w.getResponses(ce),rt=Bo.chain(([vt,{schema:It,mimeTypes:te,statusCodes:de}])=>{let At=dt(h,te),nt=V(v(ce,"variant",`${vt+1}`),ur(At?It:p,m),{comment:A});return this.#e.push(nt),de.map(st=>Te(st,nt.name))},Array.from(tt.entries())),ot=wt(v(ce,"response","variants"),rt,{comment:A});return this.#e.push(ot),Object.assign(et,{[ce]:ot})},{});this.paths.add(g);let ee=L(A),we={input:f($.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:J([K(this.interfaces.positive,ee),K(this.interfaces.negative,ee)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(A,{isDeprecated:z,store:we}),this.tags.set(A,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:Qt(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&kt.addSyntheticLeadingComment(kt.addSyntheticLeadingComment(a.createEmptyStatement(),kt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),kt.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>Qt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
22
22
  `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Me("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};import{z as Ze}from"zod/v4";var qo=(e,t)=>Ze.object({data:t,event:Ze.literal(e),id:Ze.string().optional(),retry:Ze.int().positive().optional()}),Js=(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":C.sse,"cache-control":"no-cache"}),Gs=e=>new F({handler:async({response:t})=>setTimeout(()=>Ko(t),Vs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Ko(t),t.write(Js(e,r,o),"utf-8"),t.flush?.()}}}),Ws=e=>new Se({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>qo(o,n));return{mimeType:C.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=Ee(r);Fe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(be(i),"utf-8")}t.end()}}),yr=class extends Oe{constructor(t){super(Ws(t)),this.middlewares=[Gs(t)]}};var Ys={dateIn:gr,dateOut:hr,form:Rr,upload:Or,raw:Pr,buffer:it};export{Je as BuiltinLogger,Ve as DependsOnMethod,Wt as Documentation,Q as DocumentationError,Oe as EndpointsFactory,yr as EventStreamFactory,X as InputValidationError,fr as Integration,F as Middleware,De as MissingPeerError,qe as OutputValidationError,Se as ResultHandler,xe as RoutingError,Ge as ServeStatic,fn as arrayEndpointsFactory,Kt as arrayResultHandler,qn as attachRouting,Wo as createConfig,Dn as createServer,un as defaultEndpointsFactory,Re as defaultResultHandler,Ee as ensureHttpError,Ys as ez,Z as getExamples,ye as getMessageFromError,Ss as testEndpoint,Rs as testMiddleware};
23
+ `)).parse({event:t,data:r}),Vs=1e4,Ko=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":C.sse,"cache-control":"no-cache"}),Gs=e=>new U({handler:async({response:t})=>setTimeout(()=>Ko(t),Vs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Ko(t),t.write(Js(e,r,o),"utf-8"),t.flush?.()}}}),Ws=e=>new Se({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>qo(o,n));return{mimeType:C.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=Ee(r);Ue(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(be(i),"utf-8")}t.end()}}),yr=class extends Oe{constructor(t){super(Ws(t)),this.middlewares=[Gs(t)]}};var Ys={dateIn:gr,dateOut:hr,form:Rr,upload:Or,raw:Pr,buffer:it};export{Je as BuiltinLogger,Ve as DependsOnMethod,Wt as Documentation,Q as DocumentationError,Oe as EndpointsFactory,yr as EventStreamFactory,X as InputValidationError,fr as Integration,U as Middleware,De as MissingPeerError,qe as OutputValidationError,Se as ResultHandler,xe as RoutingError,Ge as ServeStatic,fn as arrayEndpointsFactory,Kt as arrayResultHandler,qn as attachRouting,Wo as createConfig,Dn as createServer,un as defaultEndpointsFactory,Re as defaultResultHandler,Ee as ensureHttpError,Ys as ez,Z as getExamples,ye as getMessageFromError,Ss as testEndpoint,Rs as testMiddleware};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "24.7.0",
3
+ "version": "24.7.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": {
@@ -85,7 +85,7 @@
85
85
  "@types/express-fileupload": "^1.5.1",
86
86
  "@types/http-errors": "^2.0.5",
87
87
  "@types/node-forge": "^1.3.11",
88
- "@types/ramda": "^0.30.0",
88
+ "@types/ramda": "^0.31.0",
89
89
  "@types/semver": "^7.7.0",
90
90
  "camelize-ts": "^3.0.0",
91
91
  "compression": "^1.8.0",