express-zod-api 23.3.0 → 23.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  ## Version 23
4
4
 
5
+ ### v23.4.0
6
+
7
+ - Feature: flat routing syntax with explicit method support:
8
+ - `Routing` now supports slashes within keys, so that nested segments could be flattened;
9
+ - `Routing` also supports explicitly specified `Method` for the keys assigned with `Endpoint`;
10
+ - Leading slash is optional;
11
+ - The feature suggested by [@williamgcampbell](https://github.com/williamgcampbell).
12
+
13
+ ```ts
14
+ import { Routing } from "express-zod-api";
15
+
16
+ const routing: Routing = {
17
+ // flat syntax:
18
+ "v1/books/:bookId": getBookEndpoint,
19
+ // with method:
20
+ "post /v1/books": addBookEndpoint,
21
+ // nested:
22
+ v1: {
23
+ "delete /books/:bookId": deleteBookEndpoint,
24
+ "patch /books/:bookId": changeBookEndpoint,
25
+ },
26
+ };
27
+ ```
28
+
5
29
  ### v23.3.0
6
30
 
7
31
  - Upgraded `ansis` (direct dependency) to `^4.0.0`.
@@ -613,7 +637,7 @@ import { z } from "zod";
613
637
  import { EventStreamFactory } from "express-zod-api";
614
638
  import { setTimeout } from "node:timers/promises";
615
639
 
616
- const subscriptionEndpoint = EventStreamFactory({
640
+ const subscriptionEndpoint = new EventStreamFactory({
617
641
  events: { time: z.number().int().positive() },
618
642
  }).buildVoid({
619
643
  input: z.object({}), // optional input schema
package/README.md CHANGED
@@ -17,36 +17,33 @@ Start your API server with I/O schema validation and custom middlewares in minut
17
17
  2. [How it works](#how-it-works)
18
18
  3. [Quick start](#quick-start) — **Fast Track**
19
19
  4. [Basic features](#basic-features)
20
- 1. [Middlewares](#middlewares)
21
- 2. [Options](#options)
22
- 3. [Using native express middlewares](#using-native-express-middlewares)
23
- 4. [Refinements](#refinements)
24
- 5. [Transformations](#transformations)
25
- 6. [Top level transformations and mapping](#top-level-transformations-and-mapping)
26
- 7. [Dealing with dates](#dealing-with-dates)
27
- 8. [Cross-Origin Resource Sharing](#cross-origin-resource-sharing) (CORS)
28
- 9. [Enabling HTTPS](#enabling-https)
29
- 10. [Customizing logger](#customizing-logger)
30
- 11. [Child logger](#child-logger)
31
- 12. [Profiling](#profiling)
32
- 13. [Enabling compression](#enabling-compression)
20
+ 1. [Routing](#routing) including static file serving
21
+ 2. [Middlewares](#middlewares)
22
+ 3. [Options](#options)
23
+ 4. [Using native express middlewares](#using-native-express-middlewares)
24
+ 5. [Refinements](#refinements)
25
+ 6. [Transformations](#transformations)
26
+ 7. [Top level transformations and mapping](#top-level-transformations-and-mapping)
27
+ 8. [Dealing with dates](#dealing-with-dates)
28
+ 9. [Cross-Origin Resource Sharing](#cross-origin-resource-sharing) (CORS)
29
+ 10. [Enabling HTTPS](#enabling-https)
30
+ 11. [Customizing logger](#customizing-logger)
31
+ 12. [Child logger](#child-logger)
32
+ 13. [Profiling](#profiling)
33
+ 14. [Enabling compression](#enabling-compression)
33
34
  5. [Advanced features](#advanced-features)
34
35
  1. [Customizing input sources](#customizing-input-sources)
35
36
  2. [Headers as input source](#headers-as-input-source)
36
- 3. [Nested routes](#nested-routes)
37
- 4. [Route path params](#route-path-params)
38
- 5. [Multiple schemas for one route](#multiple-schemas-for-one-route)
39
- 6. [Response customization](#response-customization)
40
- 7. [Empty response](#empty-response)
41
- 8. [Error handling](#error-handling)
42
- 9. [Production mode](#production-mode)
43
- 10. [Non-object response](#non-object-response) including file downloads
44
- 11. [HTML Forms (URL encoded)](#html-forms-url-encoded)
45
- 12. [File uploads](#file-uploads)
46
- 13. [Serving static files](#serving-static-files)
47
- 14. [Connect to your own express app](#connect-to-your-own-express-app)
48
- 15. [Testing endpoints](#testing-endpoints)
49
- 16. [Testing middlewares](#testing-middlewares)
37
+ 3. [Response customization](#response-customization)
38
+ 4. [Empty response](#empty-response)
39
+ 5. [Error handling](#error-handling)
40
+ 6. [Production mode](#production-mode)
41
+ 7. [Non-object response](#non-object-response) including file downloads
42
+ 8. [HTML Forms (URL encoded)](#html-forms-url-encoded)
43
+ 9. [File uploads](#file-uploads)
44
+ 10. [Connect to your own express app](#connect-to-your-own-express-app)
45
+ 11. [Testing endpoints](#testing-endpoints)
46
+ 12. [Testing middlewares](#testing-middlewares)
50
47
  6. [Special needs](#special-needs)
51
48
  1. [Different responses for different status codes](#different-responses-for-different-status-codes)
52
49
  2. [Array response](#array-response) for migrating legacy APIs
@@ -88,6 +85,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
88
85
 
89
86
  These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
90
87
 
88
+ [<img src="https://github.com/williamgcampbell.png" alt="@williamgcampbell" width="50px" />](https://github.com/williamgcampbell)
91
89
  [<img src="https://github.com/gmorgen1.png" alt="@gmorgen1" width="50px" />](https://github.com/gmorgen1)
92
90
  [<img src="https://github.com/crgeary.png" alt="@crgeary" width="50px" />](https://github.com/crgeary)
93
91
  [<img src="https://github.com/danmichaelo.png" alt="@danmichaelo" width="50px" />](https://github.com/danmichaelo)
@@ -99,7 +97,6 @@ These people contributed to the improvement of the framework by reporting bugs,
99
97
  [<img src="https://github.com/LucWag.png" alt="@LucWag" width="50px" />](https://github.com/LucWag)
100
98
  [<img src="https://github.com/HenriJ.png" alt="@HenriJ" width="50px" />](https://github.com/HenriJ)
101
99
  [<img src="https://github.com/JonParton.png" alt="@JonParton" width="50px" />](https://github.com/JonParton)
102
- [<img src="https://github.com/williamgcampbell.png" alt="@williamgcampbell" width="50px" />](https://github.com/williamgcampbell)
103
100
  [<img src="https://github.com/t1nky.png" alt="@t1nky" width="50px" />](https://github.com/t1nky)
104
101
  [<img src="https://github.com/Tomtec331.png" alt="@Tomtec331" width="50px" />](https://github.com/Tomtec331)
105
102
  [<img src="https://github.com/rottmann.png" alt="@rottmann" width="50px" />](https://github.com/rottmann)
@@ -273,6 +270,53 @@ You should receive the following response:
273
270
 
274
271
  # Basic features
275
272
 
273
+ ## Routing
274
+
275
+ The framework offers flexible ways to define your routes, supporting both nested and flat syntaxes, dynamic path
276
+ parameters, method-based routing, and static file serving. This example brings together all supported routing styles
277
+ in one place, illustrating how you can structure your API using whichever method best fits your application’s
278
+ architecture — or even mix them seamlessly.
279
+
280
+ ```ts
281
+ import { Routing, DependsOnMethod, ServeStatic } from "express-zod-api";
282
+
283
+ const routing: Routing = {
284
+ // flax syntax — /v1/users
285
+ "/v1/users": listUsersEndpoint,
286
+ // nested syntax
287
+ v1: {
288
+ // the way to have both — /v1/path and /v1/path/subpath
289
+ path: endpointA.nest({
290
+ subpath: endpointB,
291
+ }),
292
+ // path parameters — /v1/user/:id
293
+ user: {
294
+ ":id": getUserEndpoint,
295
+ },
296
+ // mixed syntax with explicit method — /v1/user/:id
297
+ "delete /user/:id": deleteUserEndpoint,
298
+ // method-based routing — /v1/account
299
+ account: new DependsOnMethod({
300
+ get: endpointA,
301
+ delete: endpointA,
302
+ post: endpointB,
303
+ patch: endpointB,
304
+ }),
305
+ },
306
+ // static file serving — /public serves files from ./assets
307
+ public: new ServeStatic("assets", {
308
+ /** @see https://expressjs.com/en/5x/api.html#express.static */
309
+ dotfiles: "deny",
310
+ index: false,
311
+ redirect: false,
312
+ }),
313
+ };
314
+ ```
315
+
316
+ Same Endpoint can be reused on different routes or handle multiple methods if needed. Path parameters (the `:id` above)
317
+ should be declared in the endpoint’s input schema. Properties assigned with Endpoint can explicitly declare a method.
318
+ When the method is not specified, the one(s) supported by the Endpoint applied (or `get` as a fallback).
319
+
276
320
  ## Middlewares
277
321
 
278
322
  Middleware can authenticate using input or `request` headers, and can provide endpoint handlers with `options`.
@@ -697,7 +741,7 @@ done(); // error: expensive operation '555.55ms'
697
741
 
698
742
  ## Enabling compression
699
743
 
700
- According to [Express.js best practices guide](http://expressjs.com/en/advanced/best-practice-performance.html)
744
+ According to [Express.js best practices guide](https://expressjs.com/en/advanced/best-practice-performance.html)
701
745
  it might be a good idea to enable GZIP and Brotli compression for your API responses.
702
746
 
703
747
  Install `compression` and `@types/compression`, and enable or configure compression:
@@ -767,76 +811,6 @@ factory.build({
767
811
  });
768
812
  ```
769
813
 
770
- ## Nested routes
771
-
772
- Suppose you want to assign both `/v1/path` and `/v1/path/subpath` routes with Endpoints:
773
-
774
- ```typescript
775
- import { Routing } from "express-zod-api";
776
-
777
- const routing: Routing = {
778
- v1: {
779
- path: endpointA.nest({
780
- subpath: endpointB,
781
- }),
782
- },
783
- };
784
- ```
785
-
786
- ## Route path params
787
-
788
- You can assign your Endpoint to a route like `/v1/user/:id` where `:id` is the path parameter:
789
-
790
- ```typescript
791
- import { Routing } from "express-zod-api";
792
-
793
- const routing: Routing = {
794
- v1: {
795
- user: { ":id": getUserEndpoint },
796
- },
797
- };
798
- ```
799
-
800
- You then need to specify these parameters in the endpoint input schema in the usual way:
801
-
802
- ```typescript
803
- const getUserEndpoint = endpointsFactory.build({
804
- input: z.object({
805
- // id is the route path param, always string
806
- id: z.string().transform((value) => parseInt(value, 10)),
807
- // other inputs (in query):
808
- withExtendedInformation: z.boolean().optional(),
809
- }),
810
- output: z.object({}),
811
- handler: async ({ input: { id } }) => ({}), // id is number,
812
- });
813
- ```
814
-
815
- ## Multiple schemas for one route
816
-
817
- Thanks to the `DependsOnMethod` class a route may have multiple Endpoints attached depending on different methods.
818
- It can also be the same Endpoint that handles multiple methods as well. The `method` and `methods` properties can be
819
- omitted for `EndpointsFactory::build()` so that the method determination would be delegated to the `Routing`.
820
-
821
- ```typescript
822
- import { DependsOnMethod } from "express-zod-api";
823
-
824
- // the route /v1/user has two Endpoints
825
- // which handle a couple of methods each
826
- const routing: Routing = {
827
- v1: {
828
- user: new DependsOnMethod({
829
- get: endpointA,
830
- delete: endpointA,
831
- post: endpointB,
832
- patch: endpointB,
833
- }),
834
- },
835
- };
836
- ```
837
-
838
- _See also [Different responses for different status codes](#different-responses-for-different-status-codes)_.
839
-
840
814
  ## Response customization
841
815
 
842
816
  `ResultHandler` is responsible for transmitting consistent responses containing the endpoint output or an error.
@@ -1035,26 +1009,6 @@ const fileUploadEndpoint = defaultEndpointsFactory.build({
1035
1009
 
1036
1010
  _You can still send other data and specify additional `input` parameters, including arrays and objects._
1037
1011
 
1038
- ## Serving static files
1039
-
1040
- In case you want your server to serve static files, you can use `new ServeStatic()` in `Routing` using the arguments
1041
- similar to `express.static()`.
1042
- The documentation on these arguments you may find [here](http://expressjs.com/en/4x/api.html#express.static).
1043
-
1044
- ```typescript
1045
- import { Routing, ServeStatic } from "express-zod-api";
1046
- import { join } from "node:path";
1047
-
1048
- const routing: Routing = {
1049
- // path /public serves static files from ./assets
1050
- public: new ServeStatic(join(__dirname, "assets"), {
1051
- dotfiles: "deny",
1052
- index: false,
1053
- redirect: false,
1054
- }),
1055
- };
1056
- ```
1057
-
1058
1012
  ## Connect to your own express app
1059
1013
 
1060
1014
  If you already have your own configured express application, or you find the framework settings not enough, you can
@@ -1230,7 +1184,7 @@ import { z } from "zod";
1230
1184
  import { EventStreamFactory } from "express-zod-api";
1231
1185
  import { setTimeout } from "node:timers/promises";
1232
1186
 
1233
- const subscriptionEndpoint = EventStreamFactory({
1187
+ const subscriptionEndpoint = new EventStreamFactory({
1234
1188
  time: z.number().int().positive(),
1235
1189
  }).buildVoid({
1236
1190
  input: z.object({}), // optional input schema
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var yn=Object.create;var dt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Sn=(e,t)=>{for(var r in t)dt(e,r,{get:t[r],enumerable:!0})},Er=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hn(t))!xn.call(e,n)&&n!==r&&dt(e,n,{get:()=>t[n],enumerable:!(o=gn(t,n))||o.enumerable});return e};var h=(e,t,r)=>(r=e!=null?yn(bn(e)):{},Er(t||!e||!e.__esModule?dt(r,"default",{value:e,enumerable:!0}):r,e)),Rn=e=>Er(dt({},"__esModule",{value:!0}),e);var ci={};Sn(ci,{BuiltinLogger:()=>Fe,DependsOnMethod:()=>qe,Documentation:()=>Zt,DocumentationError:()=>q,EndpointsFactory:()=>ge,EventStreamFactory:()=>Dt,InputValidationError:()=>X,Integration:()=>Ht,Middleware:()=>V,MissingPeerError:()=>Ce,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>Se,ServeStatic:()=>$e,arrayEndpointsFactory:()=>Jr,arrayResultHandler:()=>Pt,attachRouting:()=>zo,createConfig:()=>Zr,createServer:()=>Zo,defaultEndpointsFactory:()=>Gr,defaultResultHandler:()=>ye,ensureHttpError:()=>Ee,ez:()=>fn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>tn,testMiddleware:()=>rn});module.exports=Rn(ci);var D=h(require("ramda"),1),Pe=require("zod");var H=h(require("ramda"),1),$t=require("zod");var I={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var Se=class extends Error{name="RoutingError"},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.`}},mt=class extends Error{name="IOSchemaError"},ae=class extends mt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends mt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(ce(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ce=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var _t=/:([A-Za-z0-9_]+)/g,lt=e=>e.match(_t)?.map(t=>t.slice(1))||[],Tn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(I.upload);return"files"in e&&r},Vt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},On=["body","query","params"],Gt=e=>e.method.toLowerCase(),ut=(e,t={})=>{let r=Gt(e);return r==="options"?{}:(t[r]||Vt[r]||On).filter(o=>o==="files"?Tn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof $t.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ae?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Pn=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return Re(t,(n[y]?.examples||[]).map(H.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof $t.z.ZodObject&&(n=Pn(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},Re=(e,t,r)=>e.length&&t.length?H.xprod(e,t).map(r):e.concat(t),Jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=H.chain(o=>o.split(/[^A-Z0-9]/gi),e);return H.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Jt).join("")},ft=H.tryCatch((e,t)=>typeof e.parse(t),H.always(void 0)),Te=e=>typeof e=="object"&&e!==null,Oe=H.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var yt=h(require("ramda"),1),y=Symbol.for("express-zod-api"),We=e=>{let t=e.describe(e.description);return t._def[y]=yt.clone(t._def[y])||{examples:[]},t},zr=(e,t)=>{if(!(y in e._def))return t;let r=We(t);return r._def[y].examples=Re(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?yt.mergeDeepRight({...o},{...n}):n),r};var wn=function(e){let t=We(this);return t._def[y].examples.push(e),t},An=function(){let e=We(this);return e._def[y].isDeprecated=!0,e},En=function(e){let t=We(this);return t._def[y].defaultLabel=e,t},zn=function(e){return new Pe.z.ZodBranded({typeName:Pe.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...D.clone(this._def[y]),brand:e}})},Zn=function(e){let t=typeof e=="function"?e:D.pipe(D.toPairs,D.map(([n,s])=>D.pair(e[String(n)]||n,s)),D.fromPairs),r=t(D.clone(this.shape)),o=Pe.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Pe.z.ZodType.prototype,{example:{get(){return wn.bind(this)}},deprecated:{get(){return An.bind(this)}},brand:{set(){},get(){return zn.bind(this)}}}),Object.defineProperty(Pe.z.ZodDefault.prototype,"label",{get(){return En.bind(this)}}),Object.defineProperty(Pe.z.ZodObject.prototype,"remap",{get(){return Zn.bind(this)}}));function Zr(e){return e}var rr=require("zod");var Ue=h(require("ramda"),1),er=require("zod");var N=require("node:assert/strict");var je=require("zod");var gt=e=>!isNaN(e.getTime());var we=Symbol("DateIn"),Ir=()=>je.z.union([je.z.string().date(),je.z.string().datetime(),je.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.z.date().refine(gt)).brand(we);var vr=require("zod");var Ae=Symbol("DateOut"),kr=()=>vr.z.date().refine(gt).transform(e=>e.toISOString()).brand(Ae);var Ye=require("zod"),ee=Symbol("File"),Cr=Ye.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),In={buffer:()=>Cr.brand(ee),string:()=>Ye.z.string().brand(ee),binary:()=>Cr.or(Ye.z.string()).brand(ee),base64:()=>Ye.z.string().base64().brand(ee)};function ht(e){return In[e||"string"]()}var Wt=require("zod"),bt=Symbol("Form"),jr=e=>(e instanceof Wt.z.ZodObject?e:Wt.z.object(e)).brand(bt);var Lr=require("zod");var le=Symbol("Raw"),Nr=Lr.z.object({raw:ht("buffer")});function Mr(e){return(e?Nr.extend(e):Nr).brand(le)}var Ur=require("zod"),Ne=Symbol("Upload"),Hr=()=>Ur.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ne);var Dr=(e,{next:t})=>e.options.some(t),vn=({_def:e},{next:t})=>[e.left,e.right].some(t),xt=(e,{next:t})=>t(e.unwrap()),St={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Dr,ZodDiscriminatedUnion:Dr,ZodIntersection:vn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:xt,ZodNullable:xt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Qe=(e,{condition:t,rules:r=St,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Qe(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Kr=e=>Qe(e,{condition:t=>t._def[y]?.brand===Ne,rules:{...St,[bt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),Fr=e=>Qe(e,{condition:t=>t._def[y]?.brand===le,maxDepth:3}),qr=e=>Qe(e,{condition:t=>t._def[y]?.brand===bt,maxDepth:3}),Br=(e,t)=>{let r=new WeakSet;return Qe(e,{maxDepth:300,rules:{...St,ZodBranded:xt,ZodReadonly:xt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:St.ZodEffects}[t],ZodNaN:()=>(0,N.fail)("z.nan()"),ZodSymbol:()=>(0,N.fail)("z.symbol()"),ZodFunction:()=>(0,N.fail)("z.function()"),ZodMap:()=>(0,N.fail)("z.map()"),ZodSet:()=>(0,N.fail)("z.set()"),ZodBigInt:()=>(0,N.fail)("z.bigint()"),ZodVoid:()=>(0,N.fail)("z.void()"),ZodPromise:()=>(0,N.fail)("z.promise()"),ZodNever:()=>(0,N.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,N.fail)("z.date()"),[Ae]:()=>t==="in"&&(0,N.fail)("ez.dateOut()"),[we]:()=>t==="out"&&(0,N.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,N.fail)("ez.raw()"),[Ne]:()=>t==="out"&&(0,N.fail)("ez.upload()"),[ee]:()=>!1}})};var Rt=h(require("http-errors"),1);var Xe=h(require("http-errors"),1),$r=require("zod");var Yt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof $r.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},et=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>(0,Xe.isHttpError)(e)?e:(0,Xe.default)(e instanceof X?400:500,ce(e),{cause:e.cause||e}),ze=e=>Oe()&&!e.expose?(0,Xe.default)(e.statusCode).message:e.message;var Tt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ze((0,Rt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:(0,Rt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Qt=require("zod");var Xt=class{},V=class extends Xt{#e;#t;#r;constructor({input:t=Qt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}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 X(o):o}}},Le=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Me=class{nest(t){return Object.assign(t,{"":this})}};var tt=class extends Me{},Ot=class e extends tt{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return Kr(this.#e.inputSchema)?"upload":Fr(this.#e.inputSchema)?"raw":qr(this.#e.inputSchema)?"form":"json"}getResponses(t){return 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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof er.z.ZodError?new ae(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Le))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof er.z.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){Tt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Gt(t),a={},c=null,m=null,p=ut(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};var _r=h(require("ramda"),1),ue=require("zod");var Vr=(e,t)=>{let r=_r.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>zr(s,n),o)},G=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?G(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>G(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?G(e._def.schema):e instanceof ue.z.ZodPipeline?G(e._def.in):G(e._def.left).merge(G(e._def.right));var J=require("zod");var He={positive:200,negative:400},De=Object.keys(He);var tr=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends tr{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Yt(this.#e,{variant:"positive",args:[t],statusCodes:[He.positive],mimeTypes:[I.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[He.negative],mimeTypes:[I.json]})}},ye=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.z.object({status:J.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.z.object({status:J.z.literal("error"),error:J.z.object({message:J.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Ee(e);return et(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ze(a)}})}n.status(He.positive).json({status:"success",data:r})}}),Pt=new fe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof J.z.ZodArray?e.shape.items:J.z.array(J.z.any());return t.reduce((o,n)=>Te(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);return et(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ze(a))}if(t&&"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=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=rr.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,S=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],R=typeof s=="string"?[s]:s||[];return new Ot({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:R,methods:l,getOperationId:S,inputSchema:Vr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:rr.z.object({}),handler:async o=>(await t(o),{})})}},Gr=new ge(ye),Jr=new ge(Pt);var to=h(require("ansis"),1),ro=require("node:util"),nr=require("node:perf_hooks");var te=require("ansis"),Wr=h(require("ramda"),1);var or={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},wt={debug:10,info:20,warn:30,error:40},Yr=e=>Te(e)&&Object.keys(wt).some(t=>t in e),Qr=e=>e in wt,Xr=(e,t)=>wt[e]<wt[t],kn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ke=Wr.memoizeWith((e,t)=>`${e}${t}`,kn),eo=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 Fe=class e{config;constructor({color:t=to.default.isSupported(),level:r=Oe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,ro.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Xr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?or.ctx(s):s),m.push(c?`${or[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=nr.performance.now();return()=>{let o=nr.performance.now()-r,{message:n,severity:s="debug",formatter:a=eo}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Be=h(require("ramda"),1);var qe=class e extends Me{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Be.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Be.reject(Be.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var oo=h(require("express"),1),$e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,oo.default.static(...this.#e))}};var rt=h(require("express"),1),wo=h(require("node:http"),1),Ao=h(require("node:https"),1);var _e=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>h(require(e))))[t]}catch{}throw new Ce(e)};var io=h(require("http-errors"),1);var no=h(require("ramda"),1);var At=class{constructor(t){this.logger=t}#e=no.tryCatch(Br);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of De){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(I.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=lt(t);if(s.length===0)return;let{shape:a}=n||G(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var so=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new Se(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Ve=({routing:e,onEndpoint:t,onStatic:r})=>{let o=so(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof tt){let{methods:a=["get"]}=s;for(let c of a)t(s,n,c)}else if(s instanceof $e)r&&s.apply(n,r);else if(s instanceof qe)for(let[a,c,m]of s.entries){let{methods:p}=c;if(p&&!p.includes(a))throw new Se(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...so(s,n))}};var Cn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,io.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},sr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Oe()?void 0:new At(t()),a=new Map;if(Ve({routing:o,onEndpoint:(m,p,l,S)=>{Oe()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],R=async(b,C)=>{let w=t(b);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...S||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:b,endpoint:m,logger:w,defaultHeaders:T}):T;for(let j in Z)C.set(j,Z[j])}return m.execute({request:b,response:C,logger:w,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,R),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,R)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,Cn(p))};var yo=h(require("http-errors"),1);var uo=require("node:timers/promises");var ao=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",po=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",co=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,mo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),lo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var fo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(ao(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",mo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(co(p)||po(p))&&a(p);for await(let p of(0,uo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(lo))};return{sockets:n,shutdown:()=>o??=m()}};var go=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:de(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),ho=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,yo.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){Tt({response:o,logger:s,error:new pe(de(a),n)})}},jn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Nn=e=>({log:e.debug.bind(e)}),bo=async({getLogger:e,config:t})=>{let r=await _e("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Nn(l)})(c,m,p)}),o&&a.push(jn(o)),a},xo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},So=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},Ro=e=>t=>t?.res?.locals[y]?.logger||e,To=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),Oo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=fo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var B=require("ansis"),Po=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 Sonia".padEnd(20)),s=(0,B.hex)("#F5A9B8"),a=(0,B.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(B.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill(B.gray,12,13),m=`
1
+ "use strict";var bn=Object.create;var dt=Object.defineProperty;var xn=Object.getOwnPropertyDescriptor;var Sn=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,Tn=Object.prototype.hasOwnProperty;var On=(e,t)=>{for(var r in t)dt(e,r,{get:t[r],enumerable:!0})},Zr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Sn(t))!Tn.call(e,n)&&n!==r&&dt(e,n,{get:()=>t[n],enumerable:!(o=xn(t,n))||o.enumerable});return e};var h=(e,t,r)=>(r=e!=null?bn(Rn(e)):{},Zr(t||!e||!e.__esModule?dt(r,"default",{value:e,enumerable:!0}):r,e)),Pn=e=>Zr(dt({},"__esModule",{value:!0}),e);var yi={};On(yi,{BuiltinLogger:()=>Fe,DependsOnMethod:()=>qe,Documentation:()=>Zt,DocumentationError:()=>q,EndpointsFactory:()=>he,EventStreamFactory:()=>Dt,InputValidationError:()=>X,Integration:()=>Ht,Middleware:()=>V,MissingPeerError:()=>Ce,OutputValidationError:()=>pe,ResultHandler:()=>ye,RoutingError:()=>ae,ServeStatic:()=>$e,arrayEndpointsFactory:()=>Yr,arrayResultHandler:()=>Pt,attachRouting:()=>ko,createConfig:()=>vr,createServer:()=>Co,defaultEndpointsFactory:()=>Wr,defaultResultHandler:()=>ge,ensureHttpError:()=>Ee,ez:()=>hn,getExamples:()=>ne,getMessageFromError:()=>de,testEndpoint:()=>sn,testMiddleware:()=>an});module.exports=Pn(yi);var D=h(require("ramda"),1),Pe=require("zod");var H=h(require("ramda"),1),$t=require("zod");var I={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var ae=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.`}},mt=class extends Error{name="IOSchemaError"},pe=class extends mt{constructor(r){super(de(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends mt{constructor(r){super(de(r),{cause:r});this.cause=r}name="InputValidationError"},ce=class extends Error{constructor(r,o){super(de(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ce=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var _t=/:([A-Za-z0-9_]+)/g,lt=e=>e.match(_t)?.map(t=>t.slice(1))||[],wn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(I.upload);return"files"in e&&r},Vt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},An=["body","query","params"],Gt=e=>e.method.toLowerCase(),ut=(e,t={})=>{let r=Gt(e);return r==="options"?{}:(t[r]||Vt[r]||An).filter(o=>o==="files"?wn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},me=e=>e instanceof Error?e:new Error(String(e)),de=e=>e instanceof $t.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof pe?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,En=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return Re(t,(n[y]?.examples||[]).map(H.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof $t.z.ZodObject&&(n=En(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},Re=(e,t,r)=>e.length&&t.length?H.xprod(e,t).map(r):e.concat(t),Jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),le=(...e)=>{let t=H.chain(o=>o.split(/[^A-Z0-9]/gi),e);return H.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Jt).join("")},ft=H.tryCatch((e,t)=>typeof e.parse(t),H.always(void 0)),Te=e=>typeof e=="object"&&e!==null,Oe=H.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var yt=h(require("ramda"),1),y=Symbol.for("express-zod-api"),We=e=>{let t=e.describe(e.description);return t._def[y]=yt.clone(t._def[y])||{examples:[]},t},Ir=(e,t)=>{if(!(y in e._def))return t;let r=We(t);return r._def[y].examples=Re(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?yt.mergeDeepRight({...o},{...n}):n),r};var zn=function(e){let t=We(this);return t._def[y].examples.push(e),t},Zn=function(){let e=We(this);return e._def[y].isDeprecated=!0,e},In=function(e){let t=We(this);return t._def[y].defaultLabel=e,t},vn=function(e){return new Pe.z.ZodBranded({typeName:Pe.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...D.clone(this._def[y]),brand:e}})},kn=function(e){let t=typeof e=="function"?e:D.pipe(D.toPairs,D.map(([n,s])=>D.pair(e[String(n)]||n,s)),D.fromPairs),r=t(D.clone(this.shape)),o=Pe.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Pe.z.ZodType.prototype,{example:{get(){return zn.bind(this)}},deprecated:{get(){return Zn.bind(this)}},brand:{set(){},get(){return vn.bind(this)}}}),Object.defineProperty(Pe.z.ZodDefault.prototype,"label",{get(){return In.bind(this)}}),Object.defineProperty(Pe.z.ZodObject.prototype,"remap",{get(){return kn.bind(this)}}));function vr(e){return e}var rr=require("zod");var Ue=h(require("ramda"),1),er=require("zod");var N=require("node:assert/strict");var je=require("zod");var gt=e=>!isNaN(e.getTime());var we=Symbol("DateIn"),kr=()=>je.z.union([je.z.string().date(),je.z.string().datetime(),je.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.z.date().refine(gt)).brand(we);var Cr=require("zod");var Ae=Symbol("DateOut"),jr=()=>Cr.z.date().refine(gt).transform(e=>e.toISOString()).brand(Ae);var Ye=require("zod"),ee=Symbol("File"),Nr=Ye.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Cn={buffer:()=>Nr.brand(ee),string:()=>Ye.z.string().brand(ee),binary:()=>Nr.or(Ye.z.string()).brand(ee),base64:()=>Ye.z.string().base64().brand(ee)};function ht(e){return Cn[e||"string"]()}var Wt=require("zod"),bt=Symbol("Form"),Mr=e=>(e instanceof Wt.z.ZodObject?e:Wt.z.object(e)).brand(bt);var Ur=require("zod");var ue=Symbol("Raw"),Lr=Ur.z.object({raw:ht("buffer")});function Hr(e){return(e?Lr.extend(e):Lr).brand(ue)}var Dr=require("zod"),Ne=Symbol("Upload"),Kr=()=>Dr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ne);var Fr=(e,{next:t})=>e.options.some(t),jn=({_def:e},{next:t})=>[e.left,e.right].some(t),xt=(e,{next:t})=>t(e.unwrap()),St={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Fr,ZodDiscriminatedUnion:Fr,ZodIntersection:jn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:xt,ZodNullable:xt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Qe=(e,{condition:t,rules:r=St,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Qe(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},qr=e=>Qe(e,{condition:t=>t._def[y]?.brand===Ne,rules:{...St,[bt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),Br=e=>Qe(e,{condition:t=>t._def[y]?.brand===ue,maxDepth:3}),$r=e=>Qe(e,{condition:t=>t._def[y]?.brand===bt,maxDepth:3}),_r=(e,t)=>{let r=new WeakSet;return Qe(e,{maxDepth:300,rules:{...St,ZodBranded:xt,ZodReadonly:xt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:St.ZodEffects}[t],ZodNaN:()=>(0,N.fail)("z.nan()"),ZodSymbol:()=>(0,N.fail)("z.symbol()"),ZodFunction:()=>(0,N.fail)("z.function()"),ZodMap:()=>(0,N.fail)("z.map()"),ZodSet:()=>(0,N.fail)("z.set()"),ZodBigInt:()=>(0,N.fail)("z.bigint()"),ZodVoid:()=>(0,N.fail)("z.void()"),ZodPromise:()=>(0,N.fail)("z.promise()"),ZodNever:()=>(0,N.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,N.fail)("z.date()"),[Ae]:()=>t==="in"&&(0,N.fail)("ez.dateOut()"),[we]:()=>t==="out"&&(0,N.fail)("ez.dateIn()"),[ue]:()=>t==="out"&&(0,N.fail)("ez.raw()"),[Ne]:()=>t==="out"&&(0,N.fail)("ez.upload()"),[ee]:()=>!1}})};var Rt=h(require("http-errors"),1);var Xe=h(require("http-errors"),1),Vr=require("zod");var Yt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Vr.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ce(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},et=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>(0,Xe.isHttpError)(e)?e:(0,Xe.default)(e instanceof X?400:500,de(e),{cause:e.cause||e}),ze=e=>Oe()&&!e.expose?(0,Xe.default)(e.statusCode).message:e.message;var Tt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ze((0,Rt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:(0,Rt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Qt=require("zod");var Xt=class{},V=class extends Xt{#e;#t;#r;constructor({input:t=Qt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}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 X(o):o}}},Me=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Le=class{nest(t){return Object.assign(t,{"":this})}};var tt=class extends Le{},Ot=class e extends tt{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return qr(this.#e.inputSchema)?"upload":Br(this.#e.inputSchema)?"raw":$r(this.#e.inputSchema)?"form":"json"}getResponses(t){return 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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof er.z.ZodError?new pe(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Me))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof er.z.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){Tt({...r,error:new ce(me(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Gt(t),a={},c=null,m=null,p=ut(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=me(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};var Gr=h(require("ramda"),1),fe=require("zod");var Jr=(e,t)=>{let r=Gr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ir(s,n),o)},G=e=>e instanceof fe.z.ZodObject?e:e instanceof fe.z.ZodBranded?G(e.unwrap()):e instanceof fe.z.ZodUnion||e instanceof fe.z.ZodDiscriminatedUnion?e.options.map(t=>G(t)).reduce((t,r)=>t.merge(r.partial()),fe.z.object({})):e instanceof fe.z.ZodEffects?G(e._def.schema):e instanceof fe.z.ZodPipeline?G(e._def.in):G(e._def.left).merge(G(e._def.right));var J=require("zod");var He={positive:200,negative:400},De=Object.keys(He);var tr=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ye=class extends tr{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Yt(this.#e,{variant:"positive",args:[t],statusCodes:[He.positive],mimeTypes:[I.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[He.negative],mimeTypes:[I.json]})}},ge=new ye({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.z.object({status:J.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.z.object({status:J.z.literal("error"),error:J.z.object({message:J.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Ee(e);return et(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ze(a)}})}n.status(He.positive).json({status:"success",data:r})}}),Pt=new ye({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof J.z.ZodArray?e.shape.items:J.z.array(J.z.any());return t.reduce((o,n)=>Te(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);return et(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ze(a))}if(t&&"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 he=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Me(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=rr.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],R=typeof s=="string"?[s]:s||[];return new Ot({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:R,methods:l,getOperationId:b,inputSchema:Jr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:rr.z.object({}),handler:async o=>(await t(o),{})})}},Wr=new he(ge),Yr=new he(Pt);var oo=h(require("ansis"),1),no=require("node:util"),nr=require("node:perf_hooks");var te=require("ansis"),Qr=h(require("ramda"),1);var or={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},wt={debug:10,info:20,warn:30,error:40},Xr=e=>Te(e)&&Object.keys(wt).some(t=>t in e),eo=e=>e in wt,to=(e,t)=>wt[e]<wt[t],Nn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ke=Qr.memoizeWith((e,t)=>`${e}${t}`,Nn),ro=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 Fe=class e{config;constructor({color:t=oo.default.isSupported(),level:r=Oe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,no.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||to(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?or.ctx(s):s),m.push(c?`${or[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=nr.performance.now();return()=>{let o=nr.performance.now()-r,{message:n,severity:s="debug",formatter:a=ro}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Be=h(require("ramda"),1);var qe=class e extends Le{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Be.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Be.reject(Be.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var so=h(require("express"),1),$e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,so.default.static(...this.#e))}};var rt=h(require("express"),1),Zo=h(require("node:http"),1),Io=h(require("node:https"),1);var _e=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>h(require(e))))[t]}catch{}throw new Ce(e)};var mo=h(require("http-errors"),1);var io=h(require("ramda"),1);var At=class{constructor(t){this.logger=t}#e=io.tryCatch(_r);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of De){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(I.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=lt(t);if(s.length===0)return;let{shape:a}=n||G(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var sr=["get","post","put","delete","patch"],ao=e=>sr.includes(e);var Mn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&ao(t)?[r,t]:[e]},Ln=e=>e.trim().split("/").filter(Boolean).join("/"),po=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Mn(r);return[[t||""].concat(Ln(n)||[]).join("/"),o,s]}),Un=(e,t)=>{throw new ae("Route with explicit method can only be assigned with Endpoint",e,t)},co=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ae(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},ir=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ae("Route has a duplicate",e,t);r.add(o)},Ve=({routing:e,onEndpoint:t,onStatic:r})=>{let o=po(e),n=new Set;for(;o.length;){let[s,a,c]=o.shift();if(a instanceof tt)if(c)ir(c,s,n),co(c,s,a.methods),t(a,s,c);else{let{methods:m=["get"]}=a;for(let p of m)ir(p,s,n),t(a,s,p)}else if(c&&Un(c,s),a instanceof $e)r&&a.apply(s,r);else if(a instanceof qe)for(let[m,p,l]of a.entries){let{methods:b}=p;ir(m,s,n),co(m,s,b),t(p,s,m,l)}else o.unshift(...po(a,s))}};var Hn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,mo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},ar=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Oe()?void 0:new At(t()),a=new Map;if(Ve({routing:o,onEndpoint:(m,p,l,b)=>{Oe()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],R=async(x,C)=>{let w=t(x);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:x,endpoint:m,logger:w,defaultHeaders:T}):T;for(let j in Z)C.set(j,Z[j])}return m.execute({request:x,response:C,logger:w,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,R),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,R)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,Hn(p))};var xo=h(require("http-errors"),1);var ho=require("node:timers/promises");var lo=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",uo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",fo=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,yo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),go=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var bo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(lo(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",yo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(fo(p)||uo(p))&&a(p);for await(let p of(0,ho.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(go))};return{sockets:n,shutdown:()=>o??=m()}};var So=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:me(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Ro=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,xo.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){Tt({response:o,logger:s,error:new ce(me(a),n)})}},Dn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Kn=e=>({log:e.debug.bind(e)}),To=async({getLogger:e,config:t})=>{let r=await _e("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Kn(l)})(c,m,p)}),o&&a.push(Dn(o)),a},Oo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Po=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},wo=e=>t=>t?.res?.locals[y]?.logger||e,Ao=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),Eo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=bo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};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 Sonia".padEnd(20)),s=(0,B.hex)("#F5A9B8"),a=(0,B.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(B.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill(B.gray,12,13),m=`
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(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var Eo=e=>{e.startupLogo!==!1&&Po(process.stdout);let t=e.errorHandler||ye,r=Yr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.3.0 (CJS)",env:process.env.NODE_ENV||"development"}),To(r);let o=So({logger:r,config:e}),s={getLogger:Ro(r),errorHandler:t},a=ho(s),c=go(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Eo(e);return sr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Eo(e),c=(0,rt.default)().disable("x-powered-by").use(a);if(e.compression){let g=await _e("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||rt.default.json()],raw:[e.rawParser||rt.default.raw(),xo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await bo({config:e,getLogger:o}):[]};sr({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,R)=>()=>g.listen(R,()=>r.info("Listening",R)),S=[];if(e.http){let g=wo.default.createServer(c);p.push(g),S.push(l(g,e.http.listen))}if(e.https){let g=Ao.default.createServer(e.https.options,c);p.push(g),S.push(l(g,e.https.listen))}return e.gracefulShutdown&&Oo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:S.map(g=>g())}};var Qo=require("openapi3-ts/oas31"),Xo=h(require("ramda"),1);var O=h(require("ramda"),1);var Io=e=>Te(e)&&"or"in e,vo=e=>Te(e)&&"and"in e,ir=e=>!vo(e)&&!Io(e),ko=e=>{let t=O.filter(ir,e),r=O.chain(O.prop("and"),O.filter(vo,e)),[o,n]=O.partition(ir,r),s=O.concat(t,o),a=O.filter(Io,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>Re(m,O.map(l=>ir(l)?[l]:l.and,p),([l,S])=>O.concat(l,S)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=h(require("ramda"),1),K=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var Co=["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 jo=50,Lo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Mo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Mn=/^\d{4}-\d{2}-\d{2}$/,Un=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Hn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Uo=e=>e.replace(_t,t=>`{${t.slice(1)}}`),Dn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Kn=({_def:{innerType:e}},{next:t})=>t(e),Fn=()=>({format:"any"}),qn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Bn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},$n=({options:e},{next:t})=>({oneOf:e.map(t)}),_n=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Vn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Ho={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Vn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},Gn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Ho)),d.isEmpty)),Jn=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Gn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Ho);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Wn=({_def:{left:e,right:t}},{next:r})=>Jn([e,t].map(r)),Yn=(e,{next:t})=>t(e.unwrap()),Qn=(e,{next:t})=>t(e.unwrap()),Xn=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Ko(r)),r},es=e=>e in Mo,Do=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":es(t)?t:void 0},No=e=>({type:Do(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ts=({value:e})=>({type:Do(e),const:e}),rs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Et(e,r)),s.length&&(a.required=s),a},os=()=>({type:"null"}),ns=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Lo}}},ss=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Lo}}},is=({},e)=>{throw new q(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},as=()=>({type:"boolean"}),ps=()=>({type:"integer",format:"bigint"}),cs=e=>e.every(t=>t instanceof K.z.ZodLiteral),ds=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Et(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Et(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&cs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Et(K.z.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},ms=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},ls=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),us=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:S,isDate:g,isTime:R,isBase64:b,isNANOID:C,isBase64url:w,isDuration:Q,_def:{checks:M}})=>{let T=M.find(k=>k.kind==="regex"),Z=M.find(k=>k.kind==="datetime"),j=M.some(k=>k.kind==="jwt"),U=M.find(k=>k.kind==="length"),P={type:"string"},_={"date-time":l,byte:b,base64url:w,date:g,time:R,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:j,ip:m,cidr:S,emoji:p};for(let k in _)if(_[k]){P.format=k;break}return U&&([P.minLength,P.maxLength]=[U.value,U.value]),r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),g&&(P.pattern=Mn.source),R&&(P.pattern=Un.source),l&&(P.pattern=Hn(Z?.offset).source),T&&(P.pattern=T.regex.source),P},fs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(b=>b.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(b=>b.kind==="max"),S=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,R={type:e?"integer":"number",format:e?"int64":"double"};return p?R.minimum=m:R.exclusiveMinimum=m,g?R.maximum=S:R.exclusiveMaximum=S,R},Et=({shape:e},t)=>d.map(t,e),ys=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Mo?.[t]},Ko=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",gs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=ft(e,ys(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},hs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ss=(e,{next:t})=>t(e.unwrap().shape.raw),Fo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,qo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Rs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ts=(e,t)=>t?.includes(e)||e.startsWith("x-")||Co.includes(e),Bo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let S=G(r),g=lt(e),R=o.includes("query"),b=o.includes("params"),C=o.includes("headers"),w=T=>b&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),M=T=>C&&(c?.(T,t,e)??Ts(T,Q));return Object.entries(S.shape).reduce((T,[Z,j])=>{let U=w(Z)?"path":M(Z)?"header":R?"query":void 0;if(!U)return T;let P=Ze(j,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),_=s==="components"?n(j,P,me(l,Z)):P,{_def:k}=j;return T.concat({name:Z,in:U,deprecated:k[y]?.isDeprecated,required:!j.isOptional(),description:P.description||l,schema:_,examples:Rs(S,Z)})},[])},ar={ZodString:us,ZodNumber:fs,ZodBigInt:ps,ZodBoolean:as,ZodNull:os,ZodArray:ms,ZodTuple:ls,ZodRecord:ds,ZodObject:rs,ZodLiteral:ts,ZodIntersection:Wn,ZodUnion:$n,ZodAny:Fn,ZodDefault:Dn,ZodEnum:No,ZodNativeEnum:No,ZodEffects:gs,ZodOptional:Yn,ZodNullable:Xn,ZodDiscriminatedUnion:_n,ZodBranded:bs,ZodDate:is,ZodCatch:Kn,ZodPipeline:hs,ZodLazy:xs,ZodReadonly:Qn,[ee]:Bn,[Ne]:qn,[Ae]:ss,[we]:ns,[le]:Ss},pr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[y]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=Ko(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},cr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},$o=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=$o(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},_o=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Vo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:S=`${e.toUpperCase()} ${t} ${Jt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:S};let g=_o(Ze(r,{rules:{...p,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,g,me(S)):g,examples:qo(r,!0)};return{description:S,content:d.fromPairs(d.xprod(o,[R]))}},Os=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ps=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ws=({name:e})=>({type:"apiKey",in:"header",name:e}),As=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Es=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),zs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Go=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Os(o):o.type==="input"?Ps(o,t):o.type==="header"?ws(o):o.type==="cookie"?As(o):o.type==="openid"?Es(o):zs(o);return e.map(o=>o.map(r))},Jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Wo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,S]=$o(Ze(r,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=_o(l),R={schema:s==="components"?n(r,g,me(p)):g,examples:qo(G(r),!1,c)},b={description:p,content:{[o]:R}};return(S||o===I.raw)&&(b.required=!0),b},Yo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),dr=e=>e.length<=jo?e:e.slice(0,jo-1)+"\u2026",zt=e=>e.length?e.slice():void 0;var Zt=class extends Qo.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),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||me(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:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:S=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let b of typeof s=="string"?[s]:s)this.addServer({url:b});Ve({routing:t,onEndpoint:(b,C,w)=>{let Q={path:C,method:w,endpoint:b,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:M,shortDescription:T,scopes:Z,inputSchema:j}=b,U=T?dr(T):S&&M?dr(M):void 0,P=r.inputSources?.[w]||Vt[w],_=this.#n(C,w,b.getOperationId(w)),k=ko(b.security),be=Bo({...Q,inputSources:P,isHeader:p,security:k,schema:j,description:a?.requestParameter?.call(null,{method:w,path:C,operationId:_})}),it={};for(let ie of De){let xe=b.getResponses(ie);for(let{mimeTypes:qt,schema:pt,statusCodes:ct}of xe)for(let Bt of ct)it[Bt]=Vo({...Q,variant:ie,schema:pt,mimeTypes:qt,statusCode:Bt,hasMultipleStatusCodes:xe.length>1||ct.length>1,description:a?.[`${ie}Response`]?.call(null,{method:w,path:C,operationId:_,statusCode:Bt})})}let Kt=P.includes("body")?Wo({...Q,paramNames:Xo.pluck("name",be),schema:j,mimeType:I[b.requestType],description:a?.requestBody?.call(null,{method:w,path:C,operationId:_})}):void 0,at=Jo(Go(k,P),Z,ie=>{let xe=this.#s(ie);return this.addSecurityScheme(xe,ie),xe}),Ft={operationId:_,summary:U,description:M,deprecated:b.isDeprecated||void 0,tags:zt(b.tags),parameters:zt(be),requestBody:Kt,security:zt(at),responses:it};this.addPath(Uo(C),{[w]:Ft})}}),m&&(this.rootDoc.tags=Yo(m))}};var It=require("node-mocks-http");var Zs=e=>(0,It.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),Is=e=>(0,It.createResponse)(e),vs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Qr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},en=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Zs(e),s=Is({req:n,...t});s.req=t?.req||n,n.res=s;let a=vs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},tn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=en(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},rn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ye}}=en(r),m=ut(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:de(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=h(require("ramda"),1),st=h(require("typescript"),1),mn=require("zod");var pn=h(require("ramda"),1),Y=h(require("typescript"),1);var on=["get","post","put","delete","patch"];var re=h(require("ramda"),1),u=h(require("typescript"),1),i=u.default.factory,vt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],ks=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],ot={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},mr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),lr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Cs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ur=e=>typeof e=="string"&&Cs.test(e)?i.createIdentifier(e):z(e),kt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Ct=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ge=e=>Object.entries(e).map(([t,r])=>Ct(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),fr=(e,t=[])=>i.createConstructorDeclaration(ot.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,yr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,ur(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?mr(s,a.join(" ")):s},gr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),hr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&vt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),br=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?vt:void 0,e,n&&Tr(n),t);return o?mr(s,o):s},nn=(e,t)=>i.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),xr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(ot.public,void 0,e,void 0,o&&Tr(o),t,n,i.createBlock(r)),Sr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(vt,e,r&&Tr(r),void 0,t),Rr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),jt=e=>f(Promise.name,[e]),Nt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?mr(n,o):n},Tr=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ks:void 0,void 0,Array.isArray(e)?re.map(Ct,e):Ge(e),void 0,void 0,t),A=e=>e,nt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Je=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Lt=(e,t)=>f("Extract",[e,t]),Or=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>i.createUnionTypeNode([f(e),jt(e)]),Pr=(e,t)=>i.createFunctionTypeNode(void 0,Ge(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(z(e)),js=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>js.includes(e.kind);var Mt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=br("Method",on);someOfType=oe("SomeOf",W("T",Rr("T")),{params:["T"]});requestType=oe("Request",Rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>br(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Nt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>L("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(ur(t),i.createArrayLiteralExpression(pn.map(z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,Pr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:yr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},jt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>L(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:yr},i.createBlock([L(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Y.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([Or(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(kt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>xr(this.#e.provideMethod,Ge({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:W(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[L(hr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:jt(W(this.interfaces.response,"K"))});makeClientClass=t=>Sr(t,[fr([Ct(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:ot.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>kt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,kt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),nt(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(I.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),nt(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=L(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=L(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=L(this.#e.searchParamsConst,nt(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=L(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=L(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(I.json))),l=i.createReturnStatement(E(this.#e.responseConst,nt(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return L(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>fr(Ge({request:"K",params:W(this.interfaces.input,"K")}),[L(hr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),L(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Or(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(A("event"),t)]);#i=()=>xr(this.#e.onMethod,Ge({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Pr({[this.#e.dataParameter.text]:W(Lt("R",gr(this.#s("E"))),F(A("data")))},sn(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(A("event")))}});makeSubscriptionClass=t=>Sr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Lt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Lt(W(this.interfaces.positive,"K"),gr(this.#s(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.#e.clientConst,Je(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Je(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),ve(["time"],i.createBlock([])))]};var v=h(require("ramda"),1),x=h(require("typescript"),1),Ut=require("zod");var{factory:$}=x.default,Ns={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},wr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Ls=({value:e})=>F(e),Ms=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof Ut.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return $.createTypeLiteralNode(n)},Us=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Hs=({options:e})=>$.createUnionTypeNode(e.map(F)),cn=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(an(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},Ds=e=>Ns?.[e.kind],Ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ft(e,Ds(o)),s={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(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Fs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},Bs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),$s=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),_s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Vs=v.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(wr.name,...o))return!1;if(v.both(v.eqBy(wr.type),v.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Gs=({_def:{left:e,right:t}},{next:r})=>Vs([e,t].map(r)),Js=({_def:e},{next:t})=>t(e.innerType),he=e=>()=>f(e),Ws=(e,{next:t})=>t(e.unwrap()),Ys=(e,{next:t})=>t(e.unwrap()),Qs=({_def:e},{next:t})=>t(e.innerType),Xs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ei=()=>F(null),ti=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ri=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Ut.z.ZodString?r:t instanceof Ut.z.ZodUnion?n:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:he(x.default.SyntaxKind.StringKeyword),ZodNumber:he(x.default.SyntaxKind.NumberKeyword),ZodBigInt:he(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:he(x.default.SyntaxKind.BooleanKeyword),ZodAny:he(x.default.SyntaxKind.AnyKeyword),ZodUndefined:he(x.default.SyntaxKind.UndefinedKeyword),[we]:he(x.default.SyntaxKind.StringKeyword),[Ae]:he(x.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Us,ZodTuple:$s,ZodRecord:_s,ZodObject:Ms,ZodLiteral:Ls,ZodIntersection:Gs,ZodUnion:cn,ZodDefault:Js,ZodEnum:Hs,ZodNativeEnum:Fs,ZodEffects:Ks,ZodOptional:qs,ZodNullable:Bs,ZodDiscriminatedUnion:cn,ZodBranded:Ws,ZodCatch:Qs,ZodPipeline:Xs,ZodLazy:ti,ZodReadonly:Ys,[ee]:ri,[le]:oi},Ar=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...ni},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Ht=class extends Mt{#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=F(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=mn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},S={brandHandling:r,ctx:{...p,isResponse:!0}};Ve({routing:t,onEndpoint:(R,b,C)=>{let w=me.bind(null,C,b),{isDeprecated:Q,inputSchema:M,tags:T}=R,Z=`${C} ${b}`,j=oe(w("input"),Ar(M,l),{comment:Z});this.#e.push(j);let U=De.reduce((k,be)=>{let it=R.getResponses(be),Kt=dn.chain(([Ft,{schema:ie,mimeTypes:xe,statusCodes:qt}])=>{let pt=oe(w(be,"variant",`${Ft+1}`),Ar(xe?ie:m,S),{comment:Z});return this.#e.push(pt),qt.map(ct=>Ie(ct,pt.name))},Array.from(it.entries())),at=Nt(w(be,"response","variants"),Kt,{comment:Z});return this.#e.push(at),Object.assign(k,{[be]:at})},{});this.paths.add(b);let P=F(Z),_={input:f(j.name),positive:this.someOf(U.positive),negative:this.someOf(U.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,P),W(this.interfaces.negative,P)]),encoded:i.createIntersectionTypeNode([f(U.positive.name),f(U.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:_}),this.tags.set(Z,T)}}),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:lr(r,t)).join(`
18
+ `))};var vo=e=>{e.startupLogo!==!1&&zo(process.stdout);let t=e.errorHandler||ge,r=Xr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.4.0 (CJS)",env:process.env.NODE_ENV||"development"}),Ao(r);let o=Po({logger:r,config:e}),s={getLogger:wo(r),errorHandler:t},a=Ro(s),c=So(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},ko=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=vo(e);return ar({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Co=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=vo(e),c=(0,rt.default)().disable("x-powered-by").use(a);if(e.compression){let g=await _e("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||rt.default.json()],raw:[e.rawParser||rt.default.raw(),Oo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await To({config:e,getLogger:o}):[]};ar({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,R)=>()=>g.listen(R,()=>r.info("Listening",R)),b=[];if(e.http){let g=Zo.default.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=Io.default.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&Eo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};var rn=require("openapi3-ts/oas31"),on=h(require("ramda"),1);var O=h(require("ramda"),1);var jo=e=>Te(e)&&"or"in e,No=e=>Te(e)&&"and"in e,pr=e=>!No(e)&&!jo(e),Mo=e=>{let t=O.filter(pr,e),r=O.chain(O.prop("and"),O.filter(No,e)),[o,n]=O.partition(pr,r),s=O.concat(t,o),a=O.filter(jo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>Re(m,O.map(l=>pr(l)?[l]:l.and,p),([l,b])=>O.concat(l,b)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=h(require("ramda"),1),K=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var Lo=["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,Do="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Ko={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},qn=/^\d{4}-\d{2}-\d{2}$/,Bn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,$n=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Fo=e=>e.replace(_t,t=>`{${t.slice(1)}}`),_n=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Vn=({_def:{innerType:e}},{next:t})=>t(e),Gn=()=>({format:"any"}),Jn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Wn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Yn=({options:e},{next:t})=>({oneOf:e.map(t)}),Qn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Xn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},qo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Xn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},es=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(qo)),d.isEmpty)),ts=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(es);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,qo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),rs=({_def:{left:e,right:t}},{next:r})=>ts([e,t].map(r)),os=(e,{next:t})=>t(e.unwrap()),ns=(e,{next:t})=>t(e.unwrap()),ss=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=$o(r)),r},is=e=>e in Ko,Bo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":is(t)?t:void 0},Ho=e=>({type:Bo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),as=({value:e})=>({type:Bo(e),const:e}),ps=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Et(e,r)),s.length&&(a.required=s),a},cs=()=>({type:"null"}),ds=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Do}}},ms=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Do}}},ls=({},e)=>{throw new q(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},us=()=>({type:"boolean"}),fs=()=>({type:"integer",format:"bigint"}),ys=e=>e.every(t=>t instanceof K.z.ZodLiteral),gs=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Et(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Et(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&ys(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Et(K.z.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},hs=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},bs=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),xs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:R,isBase64:x,isNANOID:C,isBase64url:w,isDuration:Q,_def:{checks:L}})=>{let T=L.find(k=>k.kind==="regex"),Z=L.find(k=>k.kind==="datetime"),j=L.some(k=>k.kind==="jwt"),U=L.find(k=>k.kind==="length"),P={type:"string"},_={"date-time":l,byte:x,base64url:w,date:g,time:R,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:j,ip:m,cidr:b,emoji:p};for(let k in _)if(_[k]){P.format=k;break}return U&&([P.minLength,P.maxLength]=[U.value,U.value]),r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),g&&(P.pattern=qn.source),R&&(P.pattern=Bn.source),l&&(P.pattern=$n(Z?.offset).source),T&&(P.pattern=T.regex.source),P},Ss=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(x=>x.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(x=>x.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,R={type:e?"integer":"number",format:e?"int64":"double"};return p?R.minimum=m:R.exclusiveMinimum=m,g?R.maximum=b:R.exclusiveMaximum=b,R},Et=({shape:e},t)=>d.map(t,e),Rs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Ko?.[t]},$o=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Ts=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=ft(e,Rs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Os=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ps=(e,{next:t})=>t(e.unwrap()),ws=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),As=(e,{next:t})=>t(e.unwrap().shape.raw),_o=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Vo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),_o)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Es=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),_o)({schema:e,variant:"original",validate:!0,pullProps:!0}),zs=(e,t)=>t?.includes(e)||e.startsWith("x-")||Lo.includes(e),Go=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=G(r),g=lt(e),R=o.includes("query"),x=o.includes("params"),C=o.includes("headers"),w=T=>x&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),L=T=>C&&(c?.(T,t,e)??zs(T,Q));return Object.entries(b.shape).reduce((T,[Z,j])=>{let U=w(Z)?"path":L(Z)?"header":R?"query":void 0;if(!U)return T;let P=Ze(j,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),_=s==="components"?n(j,P,le(l,Z)):P,{_def:k}=j;return T.concat({name:Z,in:U,deprecated:k[y]?.isDeprecated,required:!j.isOptional(),description:P.description||l,schema:_,examples:Es(b,Z)})},[])},cr={ZodString:xs,ZodNumber:Ss,ZodBigInt:fs,ZodBoolean:us,ZodNull:cs,ZodArray:hs,ZodTuple:bs,ZodRecord:gs,ZodObject:ps,ZodLiteral:as,ZodIntersection:rs,ZodUnion:Yn,ZodAny:Gn,ZodDefault:_n,ZodEnum:Ho,ZodNativeEnum:Ho,ZodEffects:Ts,ZodOptional:os,ZodNullable:ss,ZodDiscriminatedUnion:Qn,ZodBranded:Ps,ZodDate:ls,ZodCatch:Vn,ZodPipeline:Os,ZodLazy:ws,ZodReadonly:ns,[ee]:Wn,[Ne]:Jn,[Ae]:ms,[we]:ds,[ue]:As},dr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[y]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=$o(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},mr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},Jo=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Jo(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},Wo=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Yo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Jt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=Wo(Ze(r,{rules:{...p,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,g,le(b)):g,examples:Vo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[R]))}},Zs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Is=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},vs=({name:e})=>({type:"apiKey",in:"header",name:e}),ks=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Cs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),js=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Qo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Zs(o):o.type==="input"?Is(o,t):o.type==="header"?vs(o):o.type==="cookie"?ks(o):o.type==="openid"?Cs(o):js(o);return e.map(o=>o.map(r))},Xo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),en=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Jo(Ze(r,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=Wo(l),R={schema:s==="components"?n(r,g,le(p)):g,examples:Vo(G(r),!1,c)},x={description:p,content:{[o]:R}};return(b||o===I.raw)&&(x.required=!0),x},tn=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",zt=e=>e.length?e.slice():void 0;var Zt=class extends rn.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),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||le(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:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let x of typeof s=="string"?[s]:s)this.addServer({url:x});Ve({routing:t,onEndpoint:(x,C,w)=>{let Q={path:C,method:w,endpoint:x,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:L,shortDescription:T,scopes:Z,inputSchema:j}=x,U=T?lr(T):b&&L?lr(L):void 0,P=r.inputSources?.[w]||Vt[w],_=this.#n(C,w,x.getOperationId(w)),k=Mo(x.security),xe=Go({...Q,inputSources:P,isHeader:p,security:k,schema:j,description:a?.requestParameter?.call(null,{method:w,path:C,operationId:_})}),it={};for(let ie of De){let Se=x.getResponses(ie);for(let{mimeTypes:qt,schema:pt,statusCodes:ct}of Se)for(let Bt of ct)it[Bt]=Yo({...Q,variant:ie,schema:pt,mimeTypes:qt,statusCode:Bt,hasMultipleStatusCodes:Se.length>1||ct.length>1,description:a?.[`${ie}Response`]?.call(null,{method:w,path:C,operationId:_,statusCode:Bt})})}let Kt=P.includes("body")?en({...Q,paramNames:on.pluck("name",xe),schema:j,mimeType:I[x.requestType],description:a?.requestBody?.call(null,{method:w,path:C,operationId:_})}):void 0,at=Xo(Qo(k,P),Z,ie=>{let Se=this.#s(ie);return this.addSecurityScheme(Se,ie),Se}),Ft={operationId:_,summary:U,description:L,deprecated:x.isDeprecated||void 0,tags:zt(x.tags),parameters:zt(xe),requestBody:Kt,security:zt(at),responses:it};this.addPath(Fo(C),{[w]:Ft})}}),m&&(this.rootDoc.tags=tn(m))}};var It=require("node-mocks-http");var Ns=e=>(0,It.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),Ms=e=>(0,It.createResponse)(e),Ls=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:eo(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},nn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ns(e),s=Ms({req:n,...t});s.req=t?.req||n,n.res=s;let a=Ls(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},sn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=nn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},an=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ge}}=nn(r),m=ut(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:me(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var un=h(require("ramda"),1),st=h(require("typescript"),1),fn=require("zod");var mn=h(require("ramda"),1),Y=h(require("typescript"),1);var re=h(require("ramda"),1),u=h(require("typescript"),1),i=u.default.factory,vt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Us=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],ot={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},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)},Hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yr=e=>typeof e=="string"&&Hs.test(e)?i.createIdentifier(e):z(e),kt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Ct=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ge=e=>Object.entries(e).map(([t,r])=>Ct(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),gr=(e,t=[])=>i.createConstructorDeclaration(ot.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,hr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,yr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?ur(s,a.join(" ")):s},br=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),xr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&vt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),Sr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?vt:void 0,e,n&&Pr(n),t);return o?ur(s,o):s},pn=(e,t)=>i.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),Rr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(ot.public,void 0,e,void 0,o&&Pr(o),t,n,i.createBlock(r)),Tr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(vt,e,r&&Pr(r),void 0,t),Or=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),jt=e=>f(Promise.name,[e]),Nt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?ur(n,o):n},Pr=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Us:void 0,void 0,Array.isArray(e)?re.map(Ct,e):Ge(e),void 0,void 0,t),A=e=>e,nt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Je=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Mt=(e,t)=>f("Extract",[e,t]),wr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),cn=e=>i.createUnionTypeNode([f(e),jt(e)]),Ar=(e,t)=>i.createFunctionTypeNode(void 0,Ge(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(z(e)),Ds=[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],dn=e=>Ds.includes(e.kind);var Lt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Sr("Method",sr);someOfType=oe("SomeOf",W("T",Or("T")),{params:["T"]});requestType=oe("Request",Or(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=>Nt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(yr(t),i.createArrayLiteralExpression(mn.map(z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,Ar({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},jt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>M(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr},i.createBlock([M(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Y.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([wr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(kt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>Rr(this.#e.provideMethod,Ge({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:W(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[M(xr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:jt(W(this.interfaces.response,"K"))});makeClientClass=t=>Tr(t,[gr([Ct(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:ot.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>kt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,kt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),nt(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(I.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),nt(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=M(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=M(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=M(this.#e.searchParamsConst,nt(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=M(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=M(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(I.json))),l=i.createReturnStatement(E(this.#e.responseConst,nt(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return M(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>gr(Ge({request:"K",params:W(this.interfaces.input,"K")}),[M(xr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),M(this.#e.searchParamsConst,this.#r(this.#e.restConst)),wr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(A("event"),t)]);#i=()=>Rr(this.#e.onMethod,Ge({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Ar({[this.#e.dataParameter.text]:W(Mt("R",br(this.#s("E"))),F(A("data")))},cn(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(A("event")))}});makeSubscriptionClass=t=>Tr(t,[pn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Mt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Mt(W(this.interfaces.positive,"K"),br(this.#s(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.#e.clientConst,Je(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Je(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),ve(["time"],i.createBlock([])))]};var v=h(require("ramda"),1),S=h(require("typescript"),1),Ut=require("zod");var{factory:$}=S.default,Ks={[S.default.SyntaxKind.AnyKeyword]:"",[S.default.SyntaxKind.BigIntKeyword]:BigInt(0),[S.default.SyntaxKind.BooleanKeyword]:!1,[S.default.SyntaxKind.NumberKeyword]:0,[S.default.SyntaxKind.ObjectKeyword]:{},[S.default.SyntaxKind.StringKeyword]:"",[S.default.SyntaxKind.UndefinedKeyword]:void 0},Er={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Fs=({value:e})=>F(e),qs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof Ut.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return $.createTypeLiteralNode(n)},Bs=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),$s=({options:e})=>$.createUnionTypeNode(e.map(F)),ln=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(dn(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},_s=e=>Ks?.[e.kind],Vs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ft(e,_s(o)),s={number:S.default.SyntaxKind.NumberKeyword,bigint:S.default.SyntaxKind.BigIntKeyword,boolean:S.default.SyntaxKind.BooleanKeyword,string:S.default.SyntaxKind.StringKeyword,undefined:S.default.SyntaxKind.UndefinedKeyword,object:S.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||S.default.SyntaxKind.AnyKeyword)}return o},Gs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),Js=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(S.default.SyntaxKind.UndefinedKeyword)]):o},Ws=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),Ys=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),Qs=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Xs=v.tryCatch(e=>{if(!e.every(S.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(Er.name,...o))return!1;if(v.both(v.eqBy(Er.type),v.eqBy(Er.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),ei=({_def:{left:e,right:t}},{next:r})=>Xs([e,t].map(r)),ti=({_def:e},{next:t})=>t(e.innerType),be=e=>()=>f(e),ri=(e,{next:t})=>t(e.unwrap()),oi=(e,{next:t})=>t(e.unwrap()),ni=({_def:e},{next:t})=>t(e.innerType),si=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ii=()=>F(null),ai=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),pi=e=>{let t=e.unwrap(),r=f(S.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Ut.z.ZodString?r:t instanceof Ut.z.ZodUnion?n:o},ci=(e,{next:t})=>t(e.unwrap().shape.raw),di={ZodString:be(S.default.SyntaxKind.StringKeyword),ZodNumber:be(S.default.SyntaxKind.NumberKeyword),ZodBigInt:be(S.default.SyntaxKind.BigIntKeyword),ZodBoolean:be(S.default.SyntaxKind.BooleanKeyword),ZodAny:be(S.default.SyntaxKind.AnyKeyword),ZodUndefined:be(S.default.SyntaxKind.UndefinedKeyword),[we]:be(S.default.SyntaxKind.StringKeyword),[Ae]:be(S.default.SyntaxKind.StringKeyword),ZodNull:ii,ZodArray:Bs,ZodTuple:Ys,ZodRecord:Qs,ZodObject:qs,ZodLiteral:Fs,ZodIntersection:ei,ZodUnion:ln,ZodDefault:ti,ZodEnum:$s,ZodNativeEnum:Gs,ZodEffects:Vs,ZodOptional:Js,ZodNullable:Ws,ZodDiscriminatedUnion:ln,ZodBranded:ri,ZodCatch:ni,ZodPipeline:si,ZodLazy:ai,ZodReadonly:oi,[ee]:pi,[ue]:ci},zr=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...di},onMissing:()=>f(S.default.SyntaxKind.AnyKeyword),ctx:r});var Ht=class extends Lt{#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=F(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=fn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};Ve({routing:t,onEndpoint:(R,x,C)=>{let w=le.bind(null,C,x),{isDeprecated:Q,inputSchema:L,tags:T}=R,Z=`${C} ${x}`,j=oe(w("input"),zr(L,l),{comment:Z});this.#e.push(j);let U=De.reduce((k,xe)=>{let it=R.getResponses(xe),Kt=un.chain(([Ft,{schema:ie,mimeTypes:Se,statusCodes:qt}])=>{let pt=oe(w(xe,"variant",`${Ft+1}`),zr(Se?ie:m,b),{comment:Z});return this.#e.push(pt),qt.map(ct=>Ie(ct,pt.name))},Array.from(it.entries())),at=Nt(w(xe,"response","variants"),Kt,{comment:Z});return this.#e.push(at),Object.assign(k,{[xe]:at})},{});this.paths.add(x);let P=F(Z),_={input:f(j.name),positive:this.someOf(U.positive),negative:this.someOf(U.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,P),W(this.interfaces.negative,P)]),encoded:i.createIntersectionTypeNode([f(U.positive.name),f(U.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:_}),this.tags.set(Z,T)}}),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&&st.default.addSyntheticLeadingComment(st.default.addSyntheticLeadingComment(i.createEmptyStatement(),st.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),st.default.SyntaxKind.MultiLineCommentTrivia,`
20
- ${r}`);return this.#e.concat(o||[]).map((n,s)=>lr(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
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 a=(await _e("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var ke=require("zod");var un=(e,t)=>ke.z.object({data:t,event:ke.z.literal(e),id:ke.z.string().optional(),retry:ke.z.number().int().positive().optional()}),si=(e,t,r)=>un(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),ii=1e4,ln=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":I.sse,"cache-control":"no-cache"}),ai=e=>new V({handler:async({response:t})=>setTimeout(()=>ln(t),ii)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{ln(t),t.write(si(e,r,o),"utf-8"),t.flush?.()}}}),pi=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>un(o,n));return{mimeType:I.sse,schema:r.length?ke.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ke.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);et(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ze(a),"utf-8")}t.end()}}),Dt=class extends ge{constructor(t){super(pi(t)),this.middlewares=[ai(t)]}};var fn={dateIn:Ir,dateOut:kr,form:jr,file:ht,upload:Hr,raw:Mr};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 a=(await _e("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var ke=require("zod");var gn=(e,t)=>ke.z.object({data:t,event:ke.z.literal(e),id:ke.z.string().optional(),retry:ke.z.number().int().positive().optional()}),mi=(e,t,r)=>gn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),li=1e4,yn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":I.sse,"cache-control":"no-cache"}),ui=e=>new V({handler:async({response:t})=>setTimeout(()=>yn(t),li)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{yn(t),t.write(mi(e,r,o),"utf-8"),t.flush?.()}}}),fi=e=>new ye({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>gn(o,n));return{mimeType:I.sse,schema:r.length?ke.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ke.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);et(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ze(a),"utf-8")}t.end()}}),Dt=class extends he{constructor(t){super(fi(t)),this.middlewares=[ui(t)]}};var hn={dateIn:kr,dateOut:jr,form:Mr,file:ht,upload:Kr,raw:Hr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
package/dist/index.d.cts CHANGED
@@ -354,8 +354,14 @@ declare const arrayResultHandler: ResultHandler<z.ZodArray<z.ZodTypeAny, "many">
354
354
  /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
355
355
  type GetLogger = (request?: Request) => ActualLogger;
356
356
 
357
+ /**
358
+ * @example { v1: { books: { ":bookId": getBookEndpoint } } }
359
+ * @example { "v1/books/:bookId": getBookEndpoint }
360
+ * @example { "get /v1/books/:bookId": getBookEndpoint }
361
+ * @example { v1: { "patch /books/:bookId": changeBookEndpoint } }
362
+ * */
357
363
  interface Routing {
358
- [SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
364
+ [K: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
359
365
  }
360
366
 
361
367
  declare abstract class Routable {
@@ -824,6 +830,11 @@ declare class Documentation extends OpenApiBuilder {
824
830
  /** @desc An error related to the wrong Routing declaration */
825
831
  declare class RoutingError extends Error {
826
832
  name: string;
833
+ readonly cause: {
834
+ method: Method;
835
+ path: string;
836
+ };
837
+ constructor(message: string, method: Method, path: string);
827
838
  }
828
839
  /**
829
840
  * @desc An error related to the generating of the documentation
package/dist/index.d.ts CHANGED
@@ -354,8 +354,14 @@ declare const arrayResultHandler: ResultHandler<z.ZodArray<z.ZodTypeAny, "many">
354
354
  /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
355
355
  type GetLogger = (request?: Request) => ActualLogger;
356
356
 
357
+ /**
358
+ * @example { v1: { books: { ":bookId": getBookEndpoint } } }
359
+ * @example { "v1/books/:bookId": getBookEndpoint }
360
+ * @example { "get /v1/books/:bookId": getBookEndpoint }
361
+ * @example { v1: { "patch /books/:bookId": changeBookEndpoint } }
362
+ * */
357
363
  interface Routing {
358
- [SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
364
+ [K: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
359
365
  }
360
366
 
361
367
  declare abstract class Routable {
@@ -824,6 +830,11 @@ declare class Documentation extends OpenApiBuilder {
824
830
  /** @desc An error related to the wrong Routing declaration */
825
831
  declare class RoutingError extends Error {
826
832
  name: string;
833
+ readonly cause: {
834
+ method: Method;
835
+ path: string;
836
+ };
837
+ constructor(message: string, method: Method, path: string);
827
838
  }
828
839
  /**
829
840
  * @desc An error related to the generating of the documentation
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as H from"ramda";import{z as Ae}from"zod";import*as U from"ramda";import{z as gr}from"zod";var Z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var we=class extends Error{name="RoutingError"},B=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},rt=class extends Error{name="IOSchemaError"},de=class extends rt{constructor(r){super(me(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends rt{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var jt=/:([A-Za-z0-9_]+)/g,ot=e=>e.match(jt)?.map(t=>t.slice(1))||[],Fo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Z.upload);return"files"in e&&r},Nt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},qo=["body","query","params"],Lt=e=>e.method.toLowerCase(),nt=(e,t={})=>{let r=Lt(e);return r==="options"?{}:(t[r]||Nt[r]||qo).filter(o=>o==="files"?Fo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),me=e=>e instanceof gr.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof de?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Bo=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return le(t,(n[y]?.examples||[]).map(U.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof gr.ZodObject&&(n=Bo(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},le=(e,t,r)=>e.length&&t.length?U.xprod(e,t).map(r):e.concat(t),Mt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=U.chain(o=>o.split(/[^A-Z0-9]/gi),e);return U.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Mt).join("")},st=U.tryCatch((e,t)=>typeof e.parse(t),U.always(void 0)),ue=e=>typeof e=="object"&&e!==null,fe=U.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as it from"ramda";var y=Symbol.for("express-zod-api"),Fe=e=>{let t=e.describe(e.description);return t._def[y]=it.clone(t._def[y])||{examples:[]},t},hr=(e,t)=>{if(!(y in e._def))return t;let r=Fe(t);return r._def[y].examples=le(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?it.mergeDeepRight({...o},{...n}):n),r};var $o=function(e){let t=Fe(this);return t._def[y].examples.push(e),t},_o=function(){let e=Fe(this);return e._def[y].isDeprecated=!0,e},Vo=function(e){let t=Fe(this);return t._def[y].defaultLabel=e,t},Go=function(e){return new Ae.ZodBranded({typeName:Ae.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...H.clone(this._def[y]),brand:e}})},Jo=function(e){let t=typeof e=="function"?e:H.pipe(H.toPairs,H.map(([n,s])=>H.pair(e[String(n)]||n,s)),H.fromPairs),r=t(H.clone(this.shape)),o=Ae.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ae.ZodType.prototype,{example:{get(){return $o.bind(this)}},deprecated:{get(){return _o.bind(this)}},brand:{set(){},get(){return Go.bind(this)}}}),Object.defineProperty(Ae.ZodDefault.prototype,"label",{get(){return Vo.bind(this)}}),Object.defineProperty(Ae.ZodObject.prototype,"remap",{get(){return Jo.bind(this)}}));function Wo(e){return e}import{z as Lr}from"zod";import*as ve from"ramda";import{z as Cr}from"zod";import{fail as N}from"node:assert/strict";import{z as qe}from"zod";var at=e=>!isNaN(e.getTime());var ye=Symbol("DateIn"),br=()=>qe.union([qe.string().date(),qe.string().datetime(),qe.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(qe.date().refine(at)).brand(ye);import{z as Yo}from"zod";var ge=Symbol("DateOut"),xr=()=>Yo.date().refine(at).transform(e=>e.toISOString()).brand(ge);import{z as pt}from"zod";var G=Symbol("File"),Sr=pt.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Qo={buffer:()=>Sr.brand(G),string:()=>pt.string().brand(G),binary:()=>Sr.or(pt.string()).brand(G),base64:()=>pt.string().base64().brand(G)};function ct(e){return Qo[e||"string"]()}import{z as Rr}from"zod";var dt=Symbol("Form"),Tr=e=>(e instanceof Rr.ZodObject?e:Rr.object(e)).brand(dt);import{z as Xo}from"zod";var ie=Symbol("Raw"),Or=Xo.object({raw:ct("buffer")});function Pr(e){return(e?Or.extend(e):Or).brand(ie)}import{z as en}from"zod";var Ee=Symbol("Upload"),wr=()=>en.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ee);var Ar=(e,{next:t})=>e.options.some(t),tn=({_def:e},{next:t})=>[e.left,e.right].some(t),mt=(e,{next:t})=>t(e.unwrap()),lt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Ar,ZodDiscriminatedUnion:Ar,ZodIntersection:tn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:mt,ZodNullable:mt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Be=(e,{condition:t,rules:r=lt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Be(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Er=e=>Be(e,{condition:t=>t._def[y]?.brand===Ee,rules:{...lt,[dt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),zr=e=>Be(e,{condition:t=>t._def[y]?.brand===ie,maxDepth:3}),Zr=e=>Be(e,{condition:t=>t._def[y]?.brand===dt,maxDepth:3}),Ir=(e,t)=>{let r=new WeakSet;return Be(e,{maxDepth:300,rules:{...lt,ZodBranded:mt,ZodReadonly:mt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:lt.ZodEffects}[t],ZodNaN:()=>N("z.nan()"),ZodSymbol:()=>N("z.symbol()"),ZodFunction:()=>N("z.function()"),ZodMap:()=>N("z.map()"),ZodSet:()=>N("z.set()"),ZodBigInt:()=>N("z.bigint()"),ZodVoid:()=>N("z.void()"),ZodPromise:()=>N("z.promise()"),ZodNever:()=>N("z.never()"),ZodDate:()=>t==="in"&&N("z.date()"),[ge]:()=>t==="in"&&N("ez.dateOut()"),[ye]:()=>t==="out"&&N("ez.dateIn()"),[ie]:()=>t==="out"&&N("ez.raw()"),[Ee]:()=>t==="out"&&N("ez.upload()"),[G]:()=>!1}})};import nn,{isHttpError as sn}from"http-errors";import vr,{isHttpError as rn}from"http-errors";import{z as on}from"zod";var Ut=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof on.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},$e=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),ze=e=>rn(e)?e:vr(e instanceof ee?400:500,me(e),{cause:e.cause||e}),he=e=>fe()&&!e.expose?vr(e.statusCode).message:e.message;var ut=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=he(nn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:sn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as kr}from"zod";var Ht=class{},J=class extends Ht{#e;#t;#r;constructor({input:t=kr.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 kr.ZodError?new ee(o):o}}},Ze=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends Ie{},ft=class e extends _e{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return Er(this.#e.inputSchema)?"upload":zr(this.#e.inputSchema)?"raw":Zr(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ve.pluck("security",this.#e.middlewares||[]);return ve.reject(ve.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Cr.ZodError?new de(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Ze))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Cr.ZodError?new ee(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){ut({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Lt(t),a={},c=null,m=null,p=nt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import*as jr from"ramda";import{z as be}from"zod";var Nr=(e,t)=>{let r=jr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>hr(s,n),o)},$=e=>e instanceof be.ZodObject?e:e instanceof be.ZodBranded?$(e.unwrap()):e instanceof be.ZodUnion||e instanceof be.ZodDiscriminatedUnion?e.options.map(t=>$(t)).reduce((t,r)=>t.merge(r.partial()),be.object({})):e instanceof be.ZodEffects?$(e._def.schema):e instanceof be.ZodPipeline?$(e._def.in):$(e._def.left).merge($(e._def.right));import{z as W}from"zod";var ke={positive:200,negative:400},Ce=Object.keys(ke);var Dt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},xe=class extends Dt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Ut(this.#e,{variant:"positive",args:[t],statusCodes:[ke.positive],mimeTypes:[Z.json]})}getNegativeResponse(){return Ut(this.#t,{variant:"negative",args:[],statusCodes:[ke.negative],mimeTypes:[Z.json]})}},Se=new xe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=ze(e);return $e(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:he(a)}})}n.status(ke.positive).json({status:"success",data:r})}}),Kt=new xe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>ue(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);return $e(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(he(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(ke.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof J?t:new J(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ze(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new J({handler:t})),this.resultHandler)}build({input:t=Lr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],S=typeof s=="string"?[s]:s||[];return new ft({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:S,methods:l,getOperationId:b,inputSchema:Nr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Lr.object({}),handler:async o=>(await t(o),{})})}},an=new Re(Se),pn=new Re(Kt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as Fr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as Mr from"ramda";var Ft={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},yt={debug:10,info:20,warn:30,error:40},Ur=e=>ue(e)&&Object.keys(yt).some(t=>t in e),Hr=e=>e in yt,Dr=(e,t)=>yt[e]<yt[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),je=Mr.memoizeWith((e,t)=>`${e}${t}`,fn),Kr=e=>e<1e-6?je("nanosecond",3).format(e/1e-6):e<.001?je("nanosecond").format(e/1e-6):e<1?je("microsecond").format(e/.001):e<1e3?je("millisecond").format(e):e<6e4?je("second",2).format(e/1e3):je("minute",2).format(e/6e4);var Ve=class e{config;constructor({color:t=yn.isSupported(),level:r=fe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return gn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Dr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Ft.ctx(s):s),m.push(c?`${Ft[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Fr.now();return()=>{let o=Fr.now()-r,{message:n,severity:s="debug",formatter:a=Kr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as Ne from"ramda";var Ge=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Ne.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Ne.reject(Ne.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import hn from"express";var Je=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import bt from"express";import An from"node:http";import En from"node:https";var Le=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import bn from"http-errors";import*as qr from"ramda";var gt=class{constructor(t){this.logger=t}#e=qr.tryCatch(Ir);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of Ce){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(Z.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=ot(t);if(s.length===0)return;let{shape:a}=n||$(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Br=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new we(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Me=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Br(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof _e){let{methods:a=["get"]}=s;for(let c of a)t(s,n,c)}else if(s instanceof Je)r&&s.apply(n,r);else if(s instanceof Ge)for(let[a,c,m]of s.entries){let{methods:p}=c;if(p&&!p.includes(a))throw new we(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...Br(s,n))}};var xn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=bn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},qt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=fe()?void 0:new gt(t()),a=new Map;if(Me({routing:o,onEndpoint:(m,p,l,b)=>{fe()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],S=async(h,k)=>{let P=t(h);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},z=typeof r.cors=="function"?await r.cors({request:h,endpoint:m,logger:P,defaultHeaders:R}):R;for(let C in z)k.set(C,z[C])}return m.execute({request:h,response:k,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,S),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,S)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,xn(p))};import Rn from"http-errors";import{setInterval as Sn}from"node:timers/promises";var $r=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",_r=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Vr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Gr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Jr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Wr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void($r(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",Gr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Vr(p)||_r(p))&&a(p);for await(let p of Sn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Jr))};return{sockets:n,shutdown:()=>o??=m()}};var Yr=({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(),Qr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Rn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){ut({response:o,logger:s,error:new re(oe(a),n)})}},Tn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},On=e=>({log:e.debug.bind(e)}),Xr=async({getLogger:e,config:t})=>{let r=await Le("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:On(l)})(c,m,p)}),o&&a.push(Tn(o)),a},eo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},to=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},ro=e=>t=>t?.res?.locals[y]?.logger||e,oo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),no=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Wr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as Pn,hex as so,italic as ht,whiteBright as wn}from"ansis";var io=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 Sonia".padEnd(20)),s=so("#F5A9B8"),a=so("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(wn,5,7).fill(s,7,9).fill(a,9,12).fill(Pn,12,13),m=`
1
+ import*as H from"ramda";import{z as Ae}from"zod";import*as U from"ramda";import{z as br}from"zod";var Z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var de=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},B=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},rt=class extends Error{name="IOSchemaError"},me=class extends rt{constructor(r){super(le(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends rt{constructor(r){super(le(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(le(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var jt=/:([A-Za-z0-9_]+)/g,ot=e=>e.match(jt)?.map(t=>t.slice(1))||[],$o=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Z.upload);return"files"in e&&r},Nt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},_o=["body","query","params"],Mt=e=>e.method.toLowerCase(),nt=(e,t={})=>{let r=Mt(e);return r==="options"?{}:(t[r]||Nt[r]||_o).filter(o=>o==="files"?$o(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),le=e=>e instanceof br.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof me?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Vo=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return ue(t,(n[y]?.examples||[]).map(U.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof br.ZodObject&&(n=Vo(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},ue=(e,t,r)=>e.length&&t.length?U.xprod(e,t).map(r):e.concat(t),Lt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=U.chain(o=>o.split(/[^A-Z0-9]/gi),e);return U.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Lt).join("")},st=U.tryCatch((e,t)=>typeof e.parse(t),U.always(void 0)),fe=e=>typeof e=="object"&&e!==null,ye=U.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as it from"ramda";var y=Symbol.for("express-zod-api"),Fe=e=>{let t=e.describe(e.description);return t._def[y]=it.clone(t._def[y])||{examples:[]},t},xr=(e,t)=>{if(!(y in e._def))return t;let r=Fe(t);return r._def[y].examples=ue(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?it.mergeDeepRight({...o},{...n}):n),r};var Go=function(e){let t=Fe(this);return t._def[y].examples.push(e),t},Jo=function(){let e=Fe(this);return e._def[y].isDeprecated=!0,e},Wo=function(e){let t=Fe(this);return t._def[y].defaultLabel=e,t},Yo=function(e){return new Ae.ZodBranded({typeName:Ae.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...H.clone(this._def[y]),brand:e}})},Qo=function(e){let t=typeof e=="function"?e:H.pipe(H.toPairs,H.map(([n,s])=>H.pair(e[String(n)]||n,s)),H.fromPairs),r=t(H.clone(this.shape)),o=Ae.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ae.ZodType.prototype,{example:{get(){return Go.bind(this)}},deprecated:{get(){return Jo.bind(this)}},brand:{set(){},get(){return Yo.bind(this)}}}),Object.defineProperty(Ae.ZodDefault.prototype,"label",{get(){return Wo.bind(this)}}),Object.defineProperty(Ae.ZodObject.prototype,"remap",{get(){return Qo.bind(this)}}));function Xo(e){return e}import{z as Ur}from"zod";import*as ve from"ramda";import{z as Nr}from"zod";import{fail as N}from"node:assert/strict";import{z as qe}from"zod";var at=e=>!isNaN(e.getTime());var ge=Symbol("DateIn"),Sr=()=>qe.union([qe.string().date(),qe.string().datetime(),qe.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(qe.date().refine(at)).brand(ge);import{z as en}from"zod";var he=Symbol("DateOut"),Rr=()=>en.date().refine(at).transform(e=>e.toISOString()).brand(he);import{z as pt}from"zod";var G=Symbol("File"),Tr=pt.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),tn={buffer:()=>Tr.brand(G),string:()=>pt.string().brand(G),binary:()=>Tr.or(pt.string()).brand(G),base64:()=>pt.string().base64().brand(G)};function ct(e){return tn[e||"string"]()}import{z as Or}from"zod";var dt=Symbol("Form"),Pr=e=>(e instanceof Or.ZodObject?e:Or.object(e)).brand(dt);import{z as rn}from"zod";var ie=Symbol("Raw"),wr=rn.object({raw:ct("buffer")});function Ar(e){return(e?wr.extend(e):wr).brand(ie)}import{z as on}from"zod";var Ee=Symbol("Upload"),Er=()=>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",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ee);var zr=(e,{next:t})=>e.options.some(t),nn=({_def:e},{next:t})=>[e.left,e.right].some(t),mt=(e,{next:t})=>t(e.unwrap()),lt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:zr,ZodDiscriminatedUnion:zr,ZodIntersection:nn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:mt,ZodNullable:mt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Be=(e,{condition:t,rules:r=lt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Be(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Zr=e=>Be(e,{condition:t=>t._def[y]?.brand===Ee,rules:{...lt,[dt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),Ir=e=>Be(e,{condition:t=>t._def[y]?.brand===ie,maxDepth:3}),vr=e=>Be(e,{condition:t=>t._def[y]?.brand===dt,maxDepth:3}),kr=(e,t)=>{let r=new WeakSet;return Be(e,{maxDepth:300,rules:{...lt,ZodBranded:mt,ZodReadonly:mt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:lt.ZodEffects}[t],ZodNaN:()=>N("z.nan()"),ZodSymbol:()=>N("z.symbol()"),ZodFunction:()=>N("z.function()"),ZodMap:()=>N("z.map()"),ZodSet:()=>N("z.set()"),ZodBigInt:()=>N("z.bigint()"),ZodVoid:()=>N("z.void()"),ZodPromise:()=>N("z.promise()"),ZodNever:()=>N("z.never()"),ZodDate:()=>t==="in"&&N("z.date()"),[he]:()=>t==="in"&&N("ez.dateOut()"),[ge]:()=>t==="out"&&N("ez.dateIn()"),[ie]:()=>t==="out"&&N("ez.raw()"),[Ee]:()=>t==="out"&&N("ez.upload()"),[G]:()=>!1}})};import pn,{isHttpError as cn}from"http-errors";import Cr,{isHttpError as sn}from"http-errors";import{z as an}from"zod";var Ut=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof an.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},$e=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),ze=e=>sn(e)?e:Cr(e instanceof ee?400:500,le(e),{cause:e.cause||e}),be=e=>ye()&&!e.expose?Cr(e.statusCode).message:e.message;var ut=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=be(pn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:cn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as jr}from"zod";var Ht=class{},J=class extends Ht{#e;#t;#r;constructor({input:t=jr.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 jr.ZodError?new ee(o):o}}},Ze=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends Ie{},ft=class e extends _e{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return Zr(this.#e.inputSchema)?"upload":Ir(this.#e.inputSchema)?"raw":vr(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ve.pluck("security",this.#e.middlewares||[]);return ve.reject(ve.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Nr.ZodError?new me(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Ze))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Nr.ZodError?new ee(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){ut({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Mt(t),a={},c=null,m=null,p=nt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import*as Mr from"ramda";import{z as xe}from"zod";var Lr=(e,t)=>{let r=Mr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>xr(s,n),o)},$=e=>e instanceof xe.ZodObject?e:e instanceof xe.ZodBranded?$(e.unwrap()):e instanceof xe.ZodUnion||e instanceof xe.ZodDiscriminatedUnion?e.options.map(t=>$(t)).reduce((t,r)=>t.merge(r.partial()),xe.object({})):e instanceof xe.ZodEffects?$(e._def.schema):e instanceof xe.ZodPipeline?$(e._def.in):$(e._def.left).merge($(e._def.right));import{z as W}from"zod";var ke={positive:200,negative:400},Ce=Object.keys(ke);var Dt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Se=class extends Dt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Ut(this.#e,{variant:"positive",args:[t],statusCodes:[ke.positive],mimeTypes:[Z.json]})}getNegativeResponse(){return Ut(this.#t,{variant:"negative",args:[],statusCodes:[ke.negative],mimeTypes:[Z.json]})}},Re=new Se({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=ze(e);return $e(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:be(a)}})}n.status(ke.positive).json({status:"success",data:r})}}),Kt=new Se({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>fe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);return $e(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(be(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(ke.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Te=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof J?t:new J(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ze(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new J({handler:t})),this.resultHandler)}build({input:t=Ur.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,h=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],S=typeof s=="string"?[s]:s||[];return new ft({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:S,methods:l,getOperationId:h,inputSchema:Lr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Ur.object({}),handler:async o=>(await t(o),{})})}},dn=new Te(Re),mn=new Te(Kt);import bn from"ansis";import{inspect as xn}from"node:util";import{performance as Br}from"node:perf_hooks";import{blue as ln,green as un,hex as fn,red as yn,cyanBright as gn}from"ansis";import*as Hr from"ramda";var Ft={debug:ln,info:un,warn:fn("#FFA500"),error:yn,ctx:gn},yt={debug:10,info:20,warn:30,error:40},Dr=e=>fe(e)&&Object.keys(yt).some(t=>t in e),Kr=e=>e in yt,Fr=(e,t)=>yt[e]<yt[t],hn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),je=Hr.memoizeWith((e,t)=>`${e}${t}`,hn),qr=e=>e<1e-6?je("nanosecond",3).format(e/1e-6):e<.001?je("nanosecond").format(e/1e-6):e<1?je("microsecond").format(e/.001):e<1e3?je("millisecond").format(e):e<6e4?je("second",2).format(e/1e3):je("minute",2).format(e/6e4);var Ve=class e{config;constructor({color:t=bn.isSupported(),level:r=ye()?"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 xn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Fr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Ft.ctx(s):s),m.push(c?`${Ft[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Br.now();return()=>{let o=Br.now()-r,{message:n,severity:s="debug",formatter:a=qr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as Ne from"ramda";var Ge=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Ne.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Ne.reject(Ne.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import Sn from"express";var Je=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,Sn.static(...this.#e))}};import bt from"express";import kn from"node:http";import Cn from"node:https";var Me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import Pn from"http-errors";import*as $r from"ramda";var gt=class{constructor(t){this.logger=t}#e=$r.tryCatch(kr);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of Ce){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(Z.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=ot(t);if(s.length===0)return;let{shape:a}=n||$(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var qt=["get","post","put","delete","patch"],_r=e=>qt.includes(e);var Rn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&_r(t)?[r,t]:[e]},Tn=e=>e.trim().split("/").filter(Boolean).join("/"),Vr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Rn(r);return[[t||""].concat(Tn(n)||[]).join("/"),o,s]}),On=(e,t)=>{throw new de("Route with explicit method can only be assigned with Endpoint",e,t)},Gr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new de(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Bt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new de("Route has a duplicate",e,t);r.add(o)},Le=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Vr(e),n=new Set;for(;o.length;){let[s,a,c]=o.shift();if(a instanceof _e)if(c)Bt(c,s,n),Gr(c,s,a.methods),t(a,s,c);else{let{methods:m=["get"]}=a;for(let p of m)Bt(p,s,n),t(a,s,p)}else if(c&&On(c,s),a instanceof Je)r&&a.apply(s,r);else if(a instanceof Ge)for(let[m,p,l]of a.entries){let{methods:h}=p;Bt(m,s,n),Gr(m,s,h),t(p,s,m,l)}else o.unshift(...Vr(a,s))}};var wn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=Pn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},$t=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ye()?void 0:new gt(t()),a=new Map;if(Le({routing:o,onEndpoint:(m,p,l,h)=>{ye()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],S=async(b,k)=>{let P=t(b);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...h||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},z=typeof r.cors=="function"?await r.cors({request:b,endpoint:m,logger:P,defaultHeaders:R}):R;for(let C in z)k.set(C,z[C])}return m.execute({request:b,response:k,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,S),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,S)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,wn(p))};import En from"http-errors";import{setInterval as An}from"node:timers/promises";var Jr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Wr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Yr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Qr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Xr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var eo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Jr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",Qr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Yr(p)||Wr(p))&&a(p);for await(let p of An(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Xr))};return{sockets:n,shutdown:()=>o??=m()}};var to=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:oe(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),ro=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=En(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){ut({response:o,logger:s,error:new re(oe(a),n)})}},zn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Zn=e=>({log:e.debug.bind(e)}),oo=async({getLogger:e,config:t})=>{let r=await Me("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Zn(l)})(c,m,p)}),o&&a.push(zn(o)),a},no=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},so=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},io=e=>t=>t?.res?.locals[y]?.logger||e,ao=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),po=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=eo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as In,hex as co,italic as ht,whiteBright as vn}from"ansis";var mo=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 Sonia".padEnd(20)),s=co("#F5A9B8"),a=co("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(vn,5,7).fill(s,7,9).fill(a,9,12).fill(In,12,13),m=`
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(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var ao=e=>{e.startupLogo!==!1&&io(process.stdout);let t=e.errorHandler||Se,r=Ur(e.logger)?e.logger:new Ve(e.logger);r.debug("Running",{build:"v23.3.0 (ESM)",env:process.env.NODE_ENV||"development"}),oo(r);let o=to({logger:r,config:e}),s={getLogger:ro(r),errorHandler:t},a=Qr(s),c=Yr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=ao(e);return qt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=ao(e),c=bt().disable("x-powered-by").use(a);if(e.compression){let g=await Le("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||bt.json()],raw:[e.rawParser||bt.raw(),eo],form:[e.formParser||bt.urlencoded()],upload:e.upload?await Xr({config:e,getLogger:o}):[]};qt({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,S)=>()=>g.listen(S,()=>r.info("Listening",S)),b=[];if(e.http){let g=An.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=En.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&no({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};import{OpenApiBuilder as Os}from"openapi3-ts/oas31";import*as vo from"ramda";import*as T from"ramda";var po=e=>ue(e)&&"or"in e,co=e=>ue(e)&&"and"in e,Bt=e=>!co(e)&&!po(e),mo=e=>{let t=T.filter(Bt,e),r=T.chain(T.prop("and"),T.filter(co,e)),[o,n]=T.partition(Bt,r),s=T.concat(t,o),a=T.filter(po,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>le(m,T.map(l=>Bt(l)?[l]:l.and,p),([l,b])=>T.concat(l,b)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as $t,isSchemaObject as St}from"openapi3-ts/oas31";import*as d from"ramda";import{z as K}from"zod";var Te=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Te(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var lo=["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,yo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",go={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},vn=/^\d{4}-\d{2}-\d{2}$/,kn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Cn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,ho=e=>e.replace(jt,t=>`{${t.slice(1)}}`),jn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Nn=({_def:{innerType:e}},{next:t})=>t(e),Ln=()=>({format:"any"}),Mn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Un=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Hn=({options:e},{next:t})=>({oneOf:e.map(t)}),Dn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Kn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},bo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Kn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>le(e,t,([r,o])=>d.mergeDeepRight(r,o))},Fn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(bo)),d.isEmpty)),qn=d.tryCatch(e=>{let[t,r]=e.filter(St).filter(Fn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,bo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Bn=({_def:{left:e,right:t}},{next:r})=>qn([e,t].map(r)),$n=(e,{next:t})=>t(e.unwrap()),_n=(e,{next:t})=>t(e.unwrap()),Vn=(e,{next:t})=>{let r=t(e.unwrap());return St(r)&&(r.type=So(r)),r},Gn=e=>e in go,xo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":Gn(t)?t:void 0},fo=e=>({type:xo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jn=({value:e})=>({type:xo(e),const:e}),Wn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof K.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=xt(e,r)),s.length&&(a.required=s),a},Yn=()=>({type:"null"}),Qn=({},e)=>{if(e.isResponse)throw new B("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:yo}}},Xn=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:yo}}},es=({},e)=>{throw new B(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},ts=()=>({type:"boolean"}),rs=()=>({type:"integer",format:"bigint"}),os=e=>e.every(t=>t instanceof K.ZodLiteral),ns=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.ZodEnum||e instanceof K.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=xt(K.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.ZodLiteral)return{type:"object",properties:xt(K.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.ZodUnion&&os(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:xt(K.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},ss=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),as=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:S,isBase64:h,isNANOID:k,isBase64url:P,isDuration:V,_def:{checks:L}})=>{let R=L.find(v=>v.kind==="regex"),z=L.find(v=>v.kind==="datetime"),C=L.some(v=>v.kind==="jwt"),M=L.find(v=>v.kind==="length"),O={type:"string"},q={"date-time":l,byte:h,base64url:P,date:g,time:S,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:k,jwt:C,ip:m,cidr:b,emoji:p};for(let v in q)if(q[v]){O.format=v;break}return M&&([O.minLength,O.maxLength]=[M.value,M.value]),r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),g&&(O.pattern=vn.source),S&&(O.pattern=kn.source),l&&(O.pattern=Cn(z?.offset).source),R&&(O.pattern=R.regex.source),O},ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(h=>h.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(h=>h.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,S={type:e?"integer":"number",format:e?"int64":"double"};return p?S.minimum=m:S.exclusiveMinimum=m,g?S.maximum=b:S.exclusiveMaximum=b,S},xt=({shape:e},t)=>d.map(t,e),cs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return go?.[t]},So=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ds=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&St(o)){let s=st(e,cs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.any())}if(!t&&n.type==="preprocess"&&St(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ms=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ls=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),fs=(e,{next:t})=>t(e.unwrap().shape.raw),Ro=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,To=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Ro)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ys=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Ro)({schema:e,variant:"original",validate:!0,pullProps:!0}),gs=(e,t)=>t?.includes(e)||e.startsWith("x-")||lo.includes(e),Oo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=$(r),g=ot(e),S=o.includes("query"),h=o.includes("params"),k=o.includes("headers"),P=R=>h&&g.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),L=R=>k&&(c?.(R,t,e)??gs(R,V));return Object.entries(b.shape).reduce((R,[z,C])=>{let M=P(z)?"path":L(z)?"header":S?"query":void 0;if(!M)return R;let O=Te(C,{rules:{...a,..._t},onEach:Vt,onMissing:Gt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(C,O,se(l,z)):O,{_def:v}=C;return R.concat({name:z,in:M,deprecated:v[y]?.isDeprecated,required:!C.isOptional(),description:O.description||l,schema:q,examples:ys(b,z)})},[])},_t={ZodString:as,ZodNumber:ps,ZodBigInt:rs,ZodBoolean:ts,ZodNull:Yn,ZodArray:ss,ZodTuple:is,ZodRecord:ns,ZodObject:Wn,ZodLiteral:Jn,ZodIntersection:Bn,ZodUnion:Hn,ZodAny:Ln,ZodDefault:jn,ZodEnum:fo,ZodNativeEnum:fo,ZodEffects:ds,ZodOptional:$n,ZodNullable:Vn,ZodDiscriminatedUnion:Dn,ZodBranded:ls,ZodDate:es,ZodCatch:Nn,ZodPipeline:ms,ZodLazy:us,ZodReadonly:_n,[G]:Un,[Ee]:Mn,[ge]:Xn,[ye]:Qn,[ie]:fs},Vt=(e,{isResponse:t,prev:r})=>{if($t(r))return{};let{description:o,_def:n}=e,s=e instanceof K.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[y]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=So(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},Gt=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Po=(e,t)=>{if($t(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Po(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},wo=e=>$t(e)?e:d.omit(["examples"],e),Ao=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Mt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=wo(Te(r,{rules:{...p,..._t},onEach:Vt,onMissing:Gt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),S={schema:a==="components"?s(r,g,se(b)):g,examples:To(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[S]))}},hs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},bs=({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},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),Ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ts=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Eo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?hs(o):o.type==="input"?bs(o,t):o.type==="header"?xs(o):o.type==="cookie"?Ss(o):o.type==="openid"?Rs(o):Ts(o);return e.map(o=>o.map(r))},zo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Zo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Po(Te(r,{rules:{...a,..._t},onEach:Vt,onMissing:Gt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=wo(l),S={schema:s==="components"?n(r,g,se(p)):g,examples:To($(r),!1,c)},h={description:p,content:{[o]:S}};return(b||o===Z.raw)&&(h.required=!0),h},Io=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Jt=e=>e.length<=uo?e:e.slice(0,uo-1)+"\u2026",Rt=e=>e.length?e.slice():void 0;var Wt=class extends Os{#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),typeof r=="function"&&(r=r())),typeof r=="object"&&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 B(`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:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});Me({routing:t,onEndpoint:(h,k,P)=>{let V={path:k,method:P,endpoint:h,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:L,shortDescription:R,scopes:z,inputSchema:C}=h,M=R?Jt(R):b&&L?Jt(L):void 0,O=r.inputSources?.[P]||Nt[P],q=this.#n(k,P,h.getOperationId(P)),v=mo(h.security),pe=Oo({...V,inputSources:O,isHeader:p,security:v,schema:C,description:a?.requestParameter?.call(null,{method:P,path:k,operationId:q})}),Qe={};for(let te of Ce){let ce=h.getResponses(te);for(let{mimeTypes:kt,schema:et,statusCodes:tt}of ce)for(let Ct of tt)Qe[Ct]=Ao({...V,variant:te,schema:et,mimeTypes:kt,statusCode:Ct,hasMultipleStatusCodes:ce.length>1||tt.length>1,description:a?.[`${te}Response`]?.call(null,{method:P,path:k,operationId:q,statusCode:Ct})})}let It=O.includes("body")?Zo({...V,paramNames:vo.pluck("name",pe),schema:C,mimeType:Z[h.requestType],description:a?.requestBody?.call(null,{method:P,path:k,operationId:q})}):void 0,Xe=zo(Eo(v,O),z,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),vt={operationId:q,summary:M,description:L,deprecated:h.isDeprecated||void 0,tags:Rt(h.tags),parameters:Rt(pe),requestBody:It,security:Rt(Xe),responses:Qe};this.addPath(ho(k),{[P]:vt})}}),m&&(this.rootDoc.tags=Io(m))}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var As=e=>Ps({...e,headers:{"content-type":Z.json,...e?.headers}}),Es=e=>ws(e),zs=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)}})},ko=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),s=Es({req:n,...t});s.req=t?.req||n,n.res=s;let a=zs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=ko(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Is=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Se}}=ko(r),m=nt(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import Zt from"typescript";import{z as ni}from"zod";import*as Mo from"ramda";import X from"typescript";var Co=["get","post","put","delete","patch"];import*as Y from"ramda";import u from"typescript";var i=u.factory,Tt=[i.createModifier(u.SyntaxKind.ExportKeyword)],vs=[i.createModifier(u.SyntaxKind.AsyncKeyword)],We={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.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)},ks=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Xt=e=>typeof e=="string"&&ks.test(e)?i.createIdentifier(e):E(e),Ot=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Pt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ue=e=>Object.entries(e).map(([t,r])=>Pt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),er=(e,t=[])=>i.createConstructorDeclaration(We.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,tr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,Xt(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Yt(s,a.join(" ")):s},rr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),or=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Tt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),nr=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(D,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Tt:void 0,e,n&&pr(n),t);return o?Yt(s,o):s},jo=(e,t)=>i.createPropertyDeclaration(We.public,e,void 0,f(t),void 0),sr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(We.public,void 0,e,void 0,o&&pr(o),t,n,i.createBlock(r)),ir=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Tt,e,r&&pr(r),void 0,t),ar=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),wt=e=>f(Promise.name,[e]),At=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Tt:void 0,e,void 0,void 0,t);return o?Yt(n,o):n},pr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Pe=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?vs:void 0,void 0,Array.isArray(e)?Y.map(Pt,e):Ue(e),void 0,void 0,t),w=e=>e,Ye=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),He=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Et=(e,t)=>f("Extract",[e,t]),cr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),No=e=>i.createUnionTypeNode([f(e),wt(e)]),dr=(e,t)=>i.createFunctionTypeNode(void 0,Ue(e),f(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),D=e=>i.createLiteralTypeNode(E(e)),Cs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Lo=e=>Cs.includes(e.kind);var zt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=nr("Method",Co);someOfType=Q("SomeOf",_("T",ar("T")),{params:["T"]});requestType=Q("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=>At(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Xt(t),i.createArrayLiteralExpression(Mo.map(E,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,dr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:tr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},wt(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Pe({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(A(this.#e.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,Pe({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:tr},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([cr(this.#e.pathParameter,A(this.#e.pathParameter,w("replace"))(Ot(":",[this.#e.keyParameter]),Pe([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>sr(this.#e.provideMethod,Ue({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(or(this.#e.methodParameter,this.#e.pathParameter),A(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(A(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(A(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:wt(_(this.interfaces.response,"K"))});makeClientClass=t=>ir(t,[er([Pt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:We.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Ot("?",[He(URLSearchParams.name,t)]);#o=()=>He(URL.name,Ot("",[this.#e.pathParameter],[this.#e.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.#e.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),Ye(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(Z.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(w("body"),Ye(this.#e.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(A(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,Ye(this.#e.hasBodyConst,E(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,A(this.#e.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,A(this.#e.contentTypeConst,w("startsWith"))(E(Z.json))),l=i.createReturnStatement(A(this.#e.responseConst,Ye(this.#e.isJsonConst,E(w("json")),E(w("text"))))());return j(this.#e.defaultImplementationConst,Pe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>er(Ue({request:"K",params:_(this.interfaces.input,"K")}),[j(or(this.#e.pathParameter,this.#e.restConst),A(this.#e.substituteFn)(i.createElementAccessExpression(A(this.#e.parseRequestFn)(this.#e.requestParameter),E(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),cr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),He("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Oe(w("event"),t)]);#i=()=>sr(this.#e.onMethod,Ue({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:dr({[this.#e.dataParameter.text]:_(Et("R",rr(this.#s("E"))),D(w("data")))},No(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,Pe([this.#e.msgParameter],A(this.#e.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",D(w("event")))}});makeSubscriptionClass=t=>ir(t,[jo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Et(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Et(_(this.interfaces.positive,"K"),rr(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,He(t)),A(this.#e.clientConst,this.#e.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(He(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(E("time"),Pe(["time"],i.createBlock([])))]};import*as I from"ramda";import x from"typescript";import{z as lr}from"zod";var{factory:F}=x,js={[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},mr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Ns=({value:e})=>D(e),Ls=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof lr.ZodOptional:a.isOptional();return Oe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return F.createTypeLiteralNode(n)},Ms=({element:e},{next:t})=>F.createArrayTypeNode(t(e)),Us=({options:e})=>F.createUnionTypeNode(e.map(D)),Uo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Lo(n)?n.kind:n,n)}return F.createUnionTypeNode(Array.from(r.values()))},Hs=e=>js?.[e.kind],Ds=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=st(e,Hs(o)),s={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(n&&s[n]||x.SyntaxKind.AnyKeyword)}return o},Ks=e=>F.createUnionTypeNode(Object.values(e.enum).map(D)),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?F.createUnionTypeNode([o,f(x.SyntaxKind.UndefinedKeyword)]):o},qs=(e,{next:t})=>F.createUnionTypeNode([t(e.unwrap()),D(null)]),Bs=({items:e,_def:{rest:t}},{next:r})=>F.createTupleTypeNode(e.map(r).concat(t===null?[]:F.createRestTypeNode(r(t)))),$s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),_s=I.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(mr.name,...o))return!1;if(I.both(I.eqBy(mr.type),I.eqBy(mr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Vs=({_def:{left:e,right:t}},{next:r})=>_s([e,t].map(r)),Gs=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),Js=(e,{next:t})=>t(e.unwrap()),Ws=(e,{next:t})=>t(e.unwrap()),Ys=({_def:e},{next:t})=>t(e.innerType),Qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Xs=()=>D(null),ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ti=e=>{let t=e.unwrap(),r=f(x.SyntaxKind.StringKeyword),o=f("Buffer"),n=F.createUnionTypeNode([r,o]);return t instanceof lr.ZodString?r:t instanceof lr.ZodUnion?n:o},ri=(e,{next:t})=>t(e.unwrap().shape.raw),oi={ZodString:ae(x.SyntaxKind.StringKeyword),ZodNumber:ae(x.SyntaxKind.NumberKeyword),ZodBigInt:ae(x.SyntaxKind.BigIntKeyword),ZodBoolean:ae(x.SyntaxKind.BooleanKeyword),ZodAny:ae(x.SyntaxKind.AnyKeyword),ZodUndefined:ae(x.SyntaxKind.UndefinedKeyword),[ye]:ae(x.SyntaxKind.StringKeyword),[ge]:ae(x.SyntaxKind.StringKeyword),ZodNull:Xs,ZodArray:Ms,ZodTuple:Bs,ZodRecord:$s,ZodObject:Ls,ZodLiteral:Ns,ZodIntersection:Vs,ZodUnion:Uo,ZodDefault:Gs,ZodEnum:Us,ZodNativeEnum:Ks,ZodEffects:Ds,ZodOptional:Fs,ZodNullable:qs,ZodDiscriminatedUnion:Uo,ZodBranded:Js,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:ei,ZodReadonly:Ws,[G]:ti,[ie]:ri},ur=(e,{brandHandling:t,ctx:r})=>Te(e,{rules:{...t,...oi},onMissing:()=>f(x.SyntaxKind.AnyKeyword),ctx:r});var fr=class extends zt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=D(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=ni.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(S,h,k)=>{let P=se.bind(null,k,h),{isDeprecated:V,inputSchema:L,tags:R}=S,z=`${k} ${h}`,C=Q(P("input"),ur(L,l),{comment:z});this.#e.push(C);let M=Ce.reduce((v,pe)=>{let Qe=S.getResponses(pe),It=Ho.chain(([vt,{schema:te,mimeTypes:ce,statusCodes:kt}])=>{let et=Q(P(pe,"variant",`${vt+1}`),ur(ce?te:m,b),{comment:z});return this.#e.push(et),kt.map(tt=>Oe(tt,et.name))},Array.from(Qe.entries())),Xe=At(P(pe,"response","variants"),It,{comment:z});return this.#e.push(Xe),Object.assign(v,{[pe]:Xe})},{});this.paths.add(h);let O=D(z),q={input:f(C.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,O),_(this.interfaces.negative,O)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(z,{isDeprecated:V,store:q}),this.tags.set(z,R)}}),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 lo=e=>{e.startupLogo!==!1&&mo(process.stdout);let t=e.errorHandler||Re,r=Dr(e.logger)?e.logger:new Ve(e.logger);r.debug("Running",{build:"v23.4.0 (ESM)",env:process.env.NODE_ENV||"development"}),ao(r);let o=so({logger:r,config:e}),s={getLogger:io(r),errorHandler:t},a=ro(s),c=to(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},jn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=lo(e);return $t({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Nn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=lo(e),c=bt().disable("x-powered-by").use(a);if(e.compression){let g=await Me("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||bt.json()],raw:[e.rawParser||bt.raw(),no],form:[e.formParser||bt.urlencoded()],upload:e.upload?await oo({config:e,getLogger:o}):[]};$t({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,S)=>()=>g.listen(S,()=>r.info("Listening",S)),h=[];if(e.http){let g=kn.createServer(c);p.push(g),h.push(l(g,e.http.listen))}if(e.https){let g=Cn.createServer(e.https.options,c);p.push(g),h.push(l(g,e.https.listen))}return e.gracefulShutdown&&po({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:h.map(g=>g())}};import{OpenApiBuilder as Zs}from"openapi3-ts/oas31";import*as No from"ramda";import*as T from"ramda";var uo=e=>fe(e)&&"or"in e,fo=e=>fe(e)&&"and"in e,_t=e=>!fo(e)&&!uo(e),yo=e=>{let t=T.filter(_t,e),r=T.chain(T.prop("and"),T.filter(fo,e)),[o,n]=T.partition(_t,r),s=T.concat(t,o),a=T.filter(uo,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>ue(m,T.map(l=>_t(l)?[l]:l.and,p),([l,h])=>T.concat(l,h)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as Vt,isSchemaObject as St}from"openapi3-ts/oas31";import*as d from"ramda";import{z as K}from"zod";var Oe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Oe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var go=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var ho=50,xo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",So={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ln=/^\d{4}-\d{2}-\d{2}$/,Un=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Hn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Ro=e=>e.replace(jt,t=>`{${t.slice(1)}}`),Dn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Kn=({_def:{innerType:e}},{next:t})=>t(e),Fn=()=>({format:"any"}),qn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Bn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},$n=({options:e},{next:t})=>({oneOf:e.map(t)}),_n=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Vn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},To={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Vn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>ue(e,t,([r,o])=>d.mergeDeepRight(r,o))},Gn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(To)),d.isEmpty)),Jn=d.tryCatch(e=>{let[t,r]=e.filter(St).filter(Gn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,To);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Wn=({_def:{left:e,right:t}},{next:r})=>Jn([e,t].map(r)),Yn=(e,{next:t})=>t(e.unwrap()),Qn=(e,{next:t})=>t(e.unwrap()),Xn=(e,{next:t})=>{let r=t(e.unwrap());return St(r)&&(r.type=Po(r)),r},es=e=>e in So,Oo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":es(t)?t:void 0},bo=e=>({type:Oo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ts=({value:e})=>({type:Oo(e),const:e}),rs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof K.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=xt(e,r)),s.length&&(a.required=s),a},os=()=>({type:"null"}),ns=({},e)=>{if(e.isResponse)throw new B("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:xo}}},ss=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:xo}}},is=({},e)=>{throw new B(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},as=()=>({type:"boolean"}),ps=()=>({type:"integer",format:"bigint"}),cs=e=>e.every(t=>t instanceof K.ZodLiteral),ds=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.ZodEnum||e instanceof K.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=xt(K.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.ZodLiteral)return{type:"object",properties:xt(K.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.ZodUnion&&cs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:xt(K.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},ms=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},ls=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),us=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:h,isDate:g,isTime:S,isBase64:b,isNANOID:k,isBase64url:P,isDuration:V,_def:{checks:M}})=>{let R=M.find(v=>v.kind==="regex"),z=M.find(v=>v.kind==="datetime"),C=M.some(v=>v.kind==="jwt"),L=M.find(v=>v.kind==="length"),O={type:"string"},q={"date-time":l,byte:b,base64url:P,date:g,time:S,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:k,jwt:C,ip:m,cidr:h,emoji:p};for(let v in q)if(q[v]){O.format=v;break}return L&&([O.minLength,O.maxLength]=[L.value,L.value]),r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),g&&(O.pattern=Ln.source),S&&(O.pattern=Un.source),l&&(O.pattern=Hn(z?.offset).source),R&&(O.pattern=R.regex.source),O},fs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(b=>b.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(b=>b.kind==="max"),h=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,S={type:e?"integer":"number",format:e?"int64":"double"};return p?S.minimum=m:S.exclusiveMinimum=m,g?S.maximum=h:S.exclusiveMaximum=h,S},xt=({shape:e},t)=>d.map(t,e),ys=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return So?.[t]},Po=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",gs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&St(o)){let s=st(e,ys(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.any())}if(!t&&n.type==="preprocess"&&St(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},hs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ss=(e,{next:t})=>t(e.unwrap().shape.raw),wo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Ao=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),wo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Rs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),wo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ts=(e,t)=>t?.includes(e)||e.startsWith("x-")||go.includes(e),Eo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let h=$(r),g=ot(e),S=o.includes("query"),b=o.includes("params"),k=o.includes("headers"),P=R=>b&&g.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),M=R=>k&&(c?.(R,t,e)??Ts(R,V));return Object.entries(h.shape).reduce((R,[z,C])=>{let L=P(z)?"path":M(z)?"header":S?"query":void 0;if(!L)return R;let O=Oe(C,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(C,O,se(l,z)):O,{_def:v}=C;return R.concat({name:z,in:L,deprecated:v[y]?.isDeprecated,required:!C.isOptional(),description:O.description||l,schema:q,examples:Rs(h,z)})},[])},Gt={ZodString:us,ZodNumber:fs,ZodBigInt:ps,ZodBoolean:as,ZodNull:os,ZodArray:ms,ZodTuple:ls,ZodRecord:ds,ZodObject:rs,ZodLiteral:ts,ZodIntersection:Wn,ZodUnion:$n,ZodAny:Fn,ZodDefault:Dn,ZodEnum:bo,ZodNativeEnum:bo,ZodEffects:gs,ZodOptional:Yn,ZodNullable:Xn,ZodDiscriminatedUnion:_n,ZodBranded:bs,ZodDate:is,ZodCatch:Kn,ZodPipeline:hs,ZodLazy:xs,ZodReadonly:Qn,[G]:Bn,[Ee]:qn,[he]:ss,[ge]:ns,[ie]:Ss},Jt=(e,{isResponse:t,prev:r})=>{if(Vt(r))return{};let{description:o,_def:n}=e,s=e instanceof K.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[y]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=Po(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},Wt=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},zo=(e,t)=>{if(Vt(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=zo(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},Zo=e=>Vt(e)?e:d.omit(["examples"],e),Io=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:h=`${e.toUpperCase()} ${t} ${Lt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:h};let g=Zo(Oe(r,{rules:{...p,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),S={schema:a==="components"?s(r,g,se(h)):g,examples:Ao(r,!0)};return{description:h,content:d.fromPairs(d.xprod(o,[S]))}},Os=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ps=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ws=({name:e})=>({type:"apiKey",in:"header",name:e}),As=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Es=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),zs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),vo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Os(o):o.type==="input"?Ps(o,t):o.type==="header"?ws(o):o.type==="cookie"?As(o):o.type==="openid"?Es(o):zs(o);return e.map(o=>o.map(r))},ko=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Co=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,h]=zo(Oe(r,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=Zo(l),S={schema:s==="components"?n(r,g,se(p)):g,examples:Ao($(r),!1,c)},b={description:p,content:{[o]:S}};return(h||o===Z.raw)&&(b.required=!0),b},jo=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)},[]),Yt=e=>e.length<=ho?e:e.slice(0,ho-1)+"\u2026",Rt=e=>e.length?e.slice():void 0;var Qt=class extends Zs{#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),typeof r=="function"&&(r=r())),typeof r=="object"&&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 B(`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:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:h=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let b of typeof s=="string"?[s]:s)this.addServer({url:b});Le({routing:t,onEndpoint:(b,k,P)=>{let V={path:k,method:P,endpoint:b,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:M,shortDescription:R,scopes:z,inputSchema:C}=b,L=R?Yt(R):h&&M?Yt(M):void 0,O=r.inputSources?.[P]||Nt[P],q=this.#n(k,P,b.getOperationId(P)),v=yo(b.security),pe=Eo({...V,inputSources:O,isHeader:p,security:v,schema:C,description:a?.requestParameter?.call(null,{method:P,path:k,operationId:q})}),Qe={};for(let te of Ce){let ce=b.getResponses(te);for(let{mimeTypes:kt,schema:et,statusCodes:tt}of ce)for(let Ct of tt)Qe[Ct]=Io({...V,variant:te,schema:et,mimeTypes:kt,statusCode:Ct,hasMultipleStatusCodes:ce.length>1||tt.length>1,description:a?.[`${te}Response`]?.call(null,{method:P,path:k,operationId:q,statusCode:Ct})})}let It=O.includes("body")?Co({...V,paramNames:No.pluck("name",pe),schema:C,mimeType:Z[b.requestType],description:a?.requestBody?.call(null,{method:P,path:k,operationId:q})}):void 0,Xe=ko(vo(v,O),z,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),vt={operationId:q,summary:L,description:M,deprecated:b.isDeprecated||void 0,tags:Rt(b.tags),parameters:Rt(pe),requestBody:It,security:Rt(Xe),responses:Qe};this.addPath(Ro(k),{[P]:vt})}}),m&&(this.rootDoc.tags=jo(m))}};import{createRequest as Is,createResponse as vs}from"node-mocks-http";var ks=e=>Is({...e,headers:{"content-type":Z.json,...e?.headers}}),Cs=e=>vs(e),js=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Kr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Mo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ks(e),s=Cs({req:n,...t});s.req=t?.req||n,n.res=s;let a=js(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Ns=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Mo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Ms=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Re}}=Mo(r),m=nt(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Fo from"ramda";import Zt from"typescript";import{z as di}from"zod";import*as Do from"ramda";import X from"typescript";import*as Y from"ramda";import u from"typescript";var i=u.factory,Tt=[i.createModifier(u.SyntaxKind.ExportKeyword)],Ls=[i.createModifier(u.SyntaxKind.AsyncKeyword)],We={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Xt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),er=(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)},Us=/^[A-Za-z_$][A-Za-z0-9_$]*$/,tr=e=>typeof e=="string"&&Us.test(e)?i.createIdentifier(e):E(e),Ot=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Pt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ue=e=>Object.entries(e).map(([t,r])=>Pt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),rr=(e,t=[])=>i.createConstructorDeclaration(We.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,or=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Pe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,tr(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Xt(s,a.join(" ")):s},nr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),sr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Tt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),ir=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(D,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Tt:void 0,e,n&&dr(n),t);return o?Xt(s,o):s},Lo=(e,t)=>i.createPropertyDeclaration(We.public,e,void 0,f(t),void 0),ar=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(We.public,void 0,e,void 0,o&&dr(o),t,n,i.createBlock(r)),pr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Tt,e,r&&dr(r),void 0,t),cr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),wt=e=>f(Promise.name,[e]),At=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Tt:void 0,e,void 0,void 0,t);return o?Xt(n,o):n},dr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),we=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ls:void 0,void 0,Array.isArray(e)?Y.map(Pt,e):Ue(e),void 0,void 0,t),w=e=>e,Ye=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),He=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Et=(e,t)=>f("Extract",[e,t]),mr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Uo=e=>i.createUnionTypeNode([f(e),wt(e)]),lr=(e,t)=>i.createFunctionTypeNode(void 0,Ue(e),f(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),D=e=>i.createLiteralTypeNode(E(e)),Hs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Ho=e=>Hs.includes(e.kind);var zt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=ir("Method",qt);someOfType=Q("SomeOf",_("T",cr("T")),{params:["T"]});requestType=Q("Request",cr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>ir(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>At(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Pe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(tr(t),i.createArrayLiteralExpression(Do.map(E,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,lr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},wt(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,we({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(A(this.#e.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,we({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([mr(this.#e.pathParameter,A(this.#e.pathParameter,w("replace"))(Ot(":",[this.#e.keyParameter]),we([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ar(this.#e.provideMethod,Ue({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(sr(this.#e.methodParameter,this.#e.pathParameter),A(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(A(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(A(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:wt(_(this.interfaces.response,"K"))});makeClientClass=t=>pr(t,[rr([Pt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:We.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Ot("?",[He(URLSearchParams.name,t)]);#o=()=>He(URL.name,Ot("",[this.#e.pathParameter],[this.#e.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.#e.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),Ye(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(Z.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(w("body"),Ye(this.#e.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(A(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,Ye(this.#e.hasBodyConst,E(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,A(this.#e.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,A(this.#e.contentTypeConst,w("startsWith"))(E(Z.json))),l=i.createReturnStatement(A(this.#e.responseConst,Ye(this.#e.isJsonConst,E(w("json")),E(w("text"))))());return j(this.#e.defaultImplementationConst,we([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>rr(Ue({request:"K",params:_(this.interfaces.input,"K")}),[j(sr(this.#e.pathParameter,this.#e.restConst),A(this.#e.substituteFn)(i.createElementAccessExpression(A(this.#e.parseRequestFn)(this.#e.requestParameter),E(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),mr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),He("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Pe(w("event"),t)]);#i=()=>ar(this.#e.onMethod,Ue({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:lr({[this.#e.dataParameter.text]:_(Et("R",nr(this.#s("E"))),D(w("data")))},Uo(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,we([this.#e.msgParameter],A(this.#e.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",D(w("event")))}});makeSubscriptionClass=t=>pr(t,[Lo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Et(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Et(_(this.interfaces.positive,"K"),nr(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,He(t)),A(this.#e.clientConst,this.#e.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(He(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(E("time"),we(["time"],i.createBlock([])))]};import*as I from"ramda";import x from"typescript";import{z as fr}from"zod";var{factory:F}=x,Ds={[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},ur={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Ks=({value:e})=>D(e),Fs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof fr.ZodOptional:a.isOptional();return Pe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return F.createTypeLiteralNode(n)},qs=({element:e},{next:t})=>F.createArrayTypeNode(t(e)),Bs=({options:e})=>F.createUnionTypeNode(e.map(D)),Ko=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Ho(n)?n.kind:n,n)}return F.createUnionTypeNode(Array.from(r.values()))},$s=e=>Ds?.[e.kind],_s=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=st(e,$s(o)),s={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(n&&s[n]||x.SyntaxKind.AnyKeyword)}return o},Vs=e=>F.createUnionTypeNode(Object.values(e.enum).map(D)),Gs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?F.createUnionTypeNode([o,f(x.SyntaxKind.UndefinedKeyword)]):o},Js=(e,{next:t})=>F.createUnionTypeNode([t(e.unwrap()),D(null)]),Ws=({items:e,_def:{rest:t}},{next:r})=>F.createTupleTypeNode(e.map(r).concat(t===null?[]:F.createRestTypeNode(r(t)))),Ys=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Qs=I.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(ur.name,...o))return!1;if(I.both(I.eqBy(ur.type),I.eqBy(ur.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Xs=({_def:{left:e,right:t}},{next:r})=>Qs([e,t].map(r)),ei=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),ti=(e,{next:t})=>t(e.unwrap()),ri=(e,{next:t})=>t(e.unwrap()),oi=({_def:e},{next:t})=>t(e.innerType),ni=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),si=()=>D(null),ii=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ai=e=>{let t=e.unwrap(),r=f(x.SyntaxKind.StringKeyword),o=f("Buffer"),n=F.createUnionTypeNode([r,o]);return t instanceof fr.ZodString?r:t instanceof fr.ZodUnion?n:o},pi=(e,{next:t})=>t(e.unwrap().shape.raw),ci={ZodString:ae(x.SyntaxKind.StringKeyword),ZodNumber:ae(x.SyntaxKind.NumberKeyword),ZodBigInt:ae(x.SyntaxKind.BigIntKeyword),ZodBoolean:ae(x.SyntaxKind.BooleanKeyword),ZodAny:ae(x.SyntaxKind.AnyKeyword),ZodUndefined:ae(x.SyntaxKind.UndefinedKeyword),[ge]:ae(x.SyntaxKind.StringKeyword),[he]:ae(x.SyntaxKind.StringKeyword),ZodNull:si,ZodArray:qs,ZodTuple:Ws,ZodRecord:Ys,ZodObject:Fs,ZodLiteral:Ks,ZodIntersection:Xs,ZodUnion:Ko,ZodDefault:ei,ZodEnum:Bs,ZodNativeEnum:Vs,ZodEffects:_s,ZodOptional:Gs,ZodNullable:Js,ZodDiscriminatedUnion:Ko,ZodBranded:ti,ZodCatch:oi,ZodPipeline:ni,ZodLazy:ii,ZodReadonly:ri,[G]:ai,[ie]:pi},yr=(e,{brandHandling:t,ctx:r})=>Oe(e,{rules:{...t,...ci},onMissing:()=>f(x.SyntaxKind.AnyKeyword),ctx:r});var gr=class extends zt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=D(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=di.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},h={brandHandling:r,ctx:{...p,isResponse:!0}};Le({routing:t,onEndpoint:(S,b,k)=>{let P=se.bind(null,k,b),{isDeprecated:V,inputSchema:M,tags:R}=S,z=`${k} ${b}`,C=Q(P("input"),yr(M,l),{comment:z});this.#e.push(C);let L=Ce.reduce((v,pe)=>{let Qe=S.getResponses(pe),It=Fo.chain(([vt,{schema:te,mimeTypes:ce,statusCodes:kt}])=>{let et=Q(P(pe,"variant",`${vt+1}`),yr(ce?te:m,h),{comment:z});return this.#e.push(et),kt.map(tt=>Pe(tt,et.name))},Array.from(Qe.entries())),Xe=At(P(pe,"response","variants"),It,{comment:z});return this.#e.push(Xe),Object.assign(v,{[pe]:Xe})},{});this.paths.add(b);let O=D(z),q={input:f(C.name),positive:this.someOf(L.positive),negative:this.someOf(L.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,O),_(this.interfaces.negative,O)]),encoded:i.createIntersectionTypeNode([f(L.positive.name),f(L.negative.name)])};this.registry.set(z,{isDeprecated:V,store:q}),this.tags.set(z,R)}}),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:er(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&Zt.addSyntheticLeadingComment(Zt.addSyntheticLeadingComment(i.createEmptyStatement(),Zt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Zt.SyntaxKind.MultiLineCommentTrivia,`
20
- ${r}`);return this.#e.concat(o||[]).map((n,s)=>Qt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
20
+ ${r}`);return this.#e.concat(o||[]).map((n,s)=>er(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 a=(await Le("prettier")).format;o=c=>a(c,{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 De}from"zod";var Ko=(e,t)=>De.object({data:t,event:De.literal(e),id:De.string().optional(),retry:De.number().int().positive().optional()}),si=(e,t,r)=>Ko(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),ii=1e4,Do=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":Z.sse,"cache-control":"no-cache"}),ai=e=>new J({handler:async({response:t})=>setTimeout(()=>Do(t),ii)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Do(t),t.write(si(e,r,o),"utf-8"),t.flush?.()}}}),pi=e=>new xe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Ko(o,n));return{mimeType:Z.sse,schema:r.length?De.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:De.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);$e(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(he(a),"utf-8")}t.end()}}),yr=class extends Re{constructor(t){super(pi(t)),this.middlewares=[ai(t)]}};var ci={dateIn:br,dateOut:xr,form:Tr,file:ct,upload:wr,raw:Pr};export{Ve as BuiltinLogger,Ge as DependsOnMethod,Wt as Documentation,B as DocumentationError,Re as EndpointsFactory,yr as EventStreamFactory,ee as InputValidationError,fr as Integration,J as Middleware,Ke as MissingPeerError,de as OutputValidationError,xe as ResultHandler,we as RoutingError,Je as ServeStatic,pn as arrayEndpointsFactory,Kt as arrayResultHandler,zn as attachRouting,Wo as createConfig,Zn as createServer,an as defaultEndpointsFactory,Se as defaultResultHandler,ze as ensureHttpError,ci as ez,ne as getExamples,me as getMessageFromError,Zs as testEndpoint,Is as testMiddleware};
22
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Me("prettier")).format;o=c=>a(c,{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 De}from"zod";var Bo=(e,t)=>De.object({data:t,event:De.literal(e),id:De.string().optional(),retry:De.number().int().positive().optional()}),mi=(e,t,r)=>Bo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),li=1e4,qo=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":Z.sse,"cache-control":"no-cache"}),ui=e=>new J({handler:async({response:t})=>setTimeout(()=>qo(t),li)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{qo(t),t.write(mi(e,r,o),"utf-8"),t.flush?.()}}}),fi=e=>new Se({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Bo(o,n));return{mimeType:Z.sse,schema:r.length?De.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:De.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);$e(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(be(a),"utf-8")}t.end()}}),hr=class extends Te{constructor(t){super(fi(t)),this.middlewares=[ui(t)]}};var yi={dateIn:Sr,dateOut:Rr,form:Pr,file:ct,upload:Er,raw:Ar};export{Ve as BuiltinLogger,Ge as DependsOnMethod,Qt as Documentation,B as DocumentationError,Te as EndpointsFactory,hr as EventStreamFactory,ee as InputValidationError,gr as Integration,J as Middleware,Ke as MissingPeerError,me as OutputValidationError,Se as ResultHandler,de as RoutingError,Je as ServeStatic,mn as arrayEndpointsFactory,Kt as arrayResultHandler,jn as attachRouting,Xo as createConfig,Nn as createServer,dn as defaultEndpointsFactory,Re as defaultResultHandler,ze as ensureHttpError,yi as ez,ne as getExamples,le as getMessageFromError,Ns as testEndpoint,Ms as testMiddleware};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "23.3.0",
3
+ "version": "23.4.0",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -99,8 +99,8 @@
99
99
  }
100
100
  },
101
101
  "devDependencies": {
102
- "@arethetypeswrong/cli": "^0.18.0",
103
- "@types/cors": "^2.8.14",
102
+ "@arethetypeswrong/cli": "^0.18.1",
103
+ "@types/cors": "^2.8.18",
104
104
  "@types/depd": "^1.1.36",
105
105
  "@types/node-forge": "^1.3.11",
106
106
  "@types/ramda": "^0.30.0",
@@ -135,6 +135,5 @@
135
135
  "swagger-documentation",
136
136
  "zod",
137
137
  "validation"
138
- ],
139
- "packageManager": "yarn@1.22.22+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610"
138
+ ]
140
139
  }