express-zod-api 22.12.0-beta.1 → 22.13.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,58 @@
2
2
 
3
3
  ## Version 22
4
4
 
5
+ ### v22.13.0
6
+
7
+ - Ability to configure and disable access logging:
8
+ - New config option: `accessLogger` — the function for producing access logs;
9
+ - The default value is the function writing messages similar to `GET: /v1/path` having `debug` severity;
10
+ - The option can be assigned with `null` to disable writing of access logs;
11
+ - Thanks to the contributions of [@gmorgen1](https://github.com/gmorgen1) and [@crgeary](https://github.com/crgeary);
12
+ - [@danmichaelo](https://github.com/danmichaelo) fixed a broken link in the Security policy;
13
+ - Added JSDoc for several types involved into creating Middlewares and producing Endpoints.
14
+
15
+ ```ts
16
+ import { createConfig } from "express-zod-api";
17
+
18
+ const config = createConfig({
19
+ accessLogger: (request, logger) => logger.info(request.path), // or null to disable
20
+ });
21
+ ```
22
+
23
+ ### v22.12.0
24
+
25
+ - Featuring HTML forms support (URL Encoded request body):
26
+ - Introducing the new proprietary schema `ez.form()` accepting an object shape or a custom `z.object()` schema;
27
+ - Introducing the new config option `formParser` having `express.urlencoded()` as the default value;
28
+ - Requests to Endpoints having `input` schema assigned with `ez.form()` are parsed using `formParser`;
29
+ - Exception: requests to Endpoints having `ez.upload()` within `ez.form()` are still parsed by `express-fileupload`;
30
+ - The lack of this feature was reported by [@james10424](https://github.com/james10424).
31
+
32
+ ```ts
33
+ import { defaultEndpointsFactory, ez } from "express-zod-api";
34
+ import { z } from "zod";
35
+
36
+ // The request content type should be "application/x-www-form-urlencoded"
37
+ export const submitFeedbackEndpoint = defaultEndpointsFactory.build({
38
+ method: "post",
39
+ input: ez.form({
40
+ name: z.string().min(1),
41
+ email: z.string().email(),
42
+ message: z.string().min(1),
43
+ }),
44
+ });
45
+ ```
46
+
47
+ ### v22.11.2
48
+
49
+ - Fixed: allow future versions of Express 5:
50
+ - Incorrect condition for the peer dependency was introduced in v21.0.0.
51
+
52
+ ```diff
53
+ - "express": "^4.21.1 || 5.0.1",
54
+ + "express": "^4.21.1 || ^5.0.1",
55
+ ```
56
+
5
57
  ### v22.11.1
6
58
 
7
59
  - Simplified the type of `requestMock` returned from `testEndpoint` and `testMiddleware`.
@@ -714,7 +766,7 @@ const after: Routing = {
714
766
  - Introducing `errorHandler` option for `testMiddleware()` method:
715
767
  - If your middleware throws an error there was no ability to make assertions other than the thrown error;
716
768
  - New option can be assigned with a function for transforming the error into response, so that `testMiddlware` itself
717
- would not throw, enabling usage of all returned entities for mutiple assertions in test;
769
+ would not throw, enabling usage of all returned entities for multiple assertions in test;
718
770
  - The feature suggested by [@williamgcampbell](https://github.com/williamgcampbell).
719
771
 
720
772
  ```ts
@@ -1361,7 +1413,7 @@ new Integration({
1361
1413
  - This makes all requests eligible for the assigned parsers and reverts changes made in [v18.5.2](#v1852);
1362
1414
  - Specifying `rawParser` in config is no longer needed to enable the feature.
1363
1415
  - Non-breaking significant changes:
1364
- - Request logging reflects the actual path instead of the configured route, and it's placed in front of parsing:
1416
+ - Access logging reflects the actual path instead of the configured route, and it's placed in front of parsing:
1365
1417
  - The severity of those messaged reduced from `info` to `debug`;
1366
1418
  - The debug messages from uploader are enabled by default when the logger level is set to `debug`;
1367
1419
  - How to migrate confidently:
package/CONTRIBUTING.md CHANGED
@@ -20,11 +20,11 @@ Which is highly appreciated as well. Consider these steps:
20
20
 
21
21
  - Fork the repo,
22
22
  - Create a new branch in your fork of the repo (don't change `master`),
23
- - Install the dependencies using `pnpm i`,
24
- - Install the pre-commit hooks using `pnpm install_hooks`,
23
+ - Install the dependencies using `yarn`,
24
+ - Install the pre-commit hooks using `yarn install_hooks`,
25
25
  - Make changes,
26
- - Run the tests using `pnpm test`,
27
- - In case you wanna run tests from `example` and `*-test` workspaces, run `pnpm build` first.
26
+ - Run the tests using `yarn test`,
27
+ - In case you wanna run tests from `example` and `*-test` workspaces, run `yarn build` first.
28
28
  - Commit everything,
29
29
  - Push your branch into your fork,
30
30
  - Create a PR between the forks:
package/README.md CHANGED
@@ -41,11 +41,12 @@ Start your API server with I/O schema validation and custom middlewares in minut
41
41
  8. [Error handling](#error-handling)
42
42
  9. [Production mode](#production-mode)
43
43
  10. [Non-object response](#non-object-response) including file downloads
44
- 11. [File uploads](#file-uploads)
45
- 12. [Serving static files](#serving-static-files)
46
- 13. [Connect to your own express app](#connect-to-your-own-express-app)
47
- 14. [Testing endpoints](#testing-endpoints)
48
- 15. [Testing middlewares](#testing-middlewares)
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)
49
50
  6. [Special needs](#special-needs)
50
51
  1. [Different responses for different status codes](#different-responses-for-different-status-codes)
51
52
  2. [Array response](#array-response) for migrating legacy APIs
@@ -87,6 +88,10 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
87
88
 
88
89
  These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
89
90
 
91
+ [<img src="https://github.com/gmorgen1.png" alt="@gmorgen1" width="50px" />](https://github.com/gmorgen1)
92
+ [<img src="https://github.com/crgeary.png" alt="@crgeary" width="50px" />](https://github.com/crgeary)
93
+ [<img src="https://github.com/danmichaelo.png" alt="@danmichaelo" width="50px" />](https://github.com/danmichaelo)
94
+ [<img src="https://github.com/james10424.png" alt="@james10424" width="50px" />](https://github.com/james10424)
90
95
  [<img src="https://github.com/APTy.png" alt="@APTy" width="50px" />](https://github.com/APTy)
91
96
  [<img src="https://github.com/LufyCZ.png" alt="@LufyCZ" width="50px" />](https://github.com/LufyCZ)
92
97
  [<img src="https://github.com/mlms13.png" alt="@mlms13" width="50px" />](https://github.com/mlms13)
@@ -166,8 +171,8 @@ Install the framework, its peer dependencies and type assistance packages using
166
171
 
167
172
  ```shell
168
173
  # example for yarn and express 5 (recommended):
169
- yarn add express-zod-api express@^5 zod typescript http-errors
170
- yarn add -D @types/express@^5 @types/node @types/http-errors
174
+ yarn add express-zod-api express zod typescript http-errors
175
+ yarn add -D @types/express @types/node @types/http-errors
171
176
  ```
172
177
 
173
178
  Ensure having the following options in your `tsconfig.json` file in order to make it work as expected:
@@ -964,43 +969,53 @@ const fileStreamingEndpointsFactory = new EndpointsFactory(
964
969
  );
965
970
  ```
966
971
 
967
- ## File uploads
972
+ ## HTML Forms (URL encoded)
968
973
 
969
- Install the following additional packages: `express-fileupload` and `@types/express-fileupload`, and enable or
970
- configure file uploads:
974
+ Use the proprietary schema `ez.form()` with an object shape or a custom `z.object()` with form fields in order to
975
+ describe the `input` schema of an Endpoint. Requests to the Endpoint are parsed using the `formParser` config option,
976
+ which is `express.urlencoded()` by default. The request content type should be `application/x-www-form-urlencoded`
977
+ (default for HTML forms without uploads).
971
978
 
972
- ```typescript
973
- import { createConfig } from "express-zod-api";
979
+ ```ts
980
+ import { defaultEndpointsFactory, ez } from "express-zod-api";
981
+ import { z } from "zod";
974
982
 
975
- const config = createConfig({
976
- upload: true, // or options
983
+ export const submitFeedbackEndpoint = defaultEndpointsFactory.build({
984
+ method: "post",
985
+ input: ez.form({
986
+ name: z.string().min(1),
987
+ email: z.string().email(),
988
+ message: z.string().min(1),
989
+ }),
977
990
  });
978
991
  ```
979
992
 
980
- Refer to [documentation](https://www.npmjs.com/package/express-fileupload#available-options) on available options.
981
- Some options are forced in order to ensure the correct workflow: `abortOnLimit: false`, `parseNested: true`, `logger`
982
- is assigned with `.debug()` method of the configured logger, and `debug` is enabled by default.
983
- The `limitHandler` option is replaced by the `limitError` one. You can also connect an additional middleware for
984
- restricting the ability to upload using the `beforeUpload` option. So the configuration for the limited and restricted
985
- upload might look this way:
993
+ _Hint: for unlisted extra fields use the following syntax: `ez.form( z.object({}).passthrough() )`._
994
+
995
+ ## File uploads
996
+
997
+ Install the following additional packages: `express-fileupload` and `@types/express-fileupload`, and enable or
998
+ configure file uploads. Refer to [documentation](https://www.npmjs.com/package/express-fileupload#available-options) on
999
+ available options. The `limitHandler` option is replaced by the `limitError` one. You can also connect an additional
1000
+ middleware for restricting the ability to upload using the `beforeUpload` option. So the configuration for the limited
1001
+ and restricted upload might look this way:
986
1002
 
987
1003
  ```typescript
988
1004
  import createHttpError from "http-errors";
989
1005
 
990
1006
  const config = createConfig({
991
- upload: {
1007
+ upload: /* true or options: */ {
992
1008
  limits: { fileSize: 51200 }, // 50 KB
993
1009
  limitError: createHttpError(413, "The file is too large"), // handled by errorHandler in config
994
1010
  beforeUpload: ({ request, logger }) => {
995
1011
  if (!canUpload(request)) throw createHttpError(403, "Not authorized");
996
1012
  },
1013
+ debug: true, // default
997
1014
  },
998
1015
  });
999
1016
  ```
1000
1017
 
1001
- Then you can change the `Endpoint` to handle requests having the `multipart/form-data` content type instead of JSON by
1002
- using `ez.upload()` schema. Together with a corresponding configuration option, this makes it possible to handle file
1003
- uploads. Here is a simplified example:
1018
+ Then use `ez.upload()` schema for a corresponding property. The request content type must be `multipart/form-data`:
1004
1019
 
1005
1020
  ```typescript
1006
1021
  import { z } from "zod";
package/SECURITY.md CHANGED
@@ -8,7 +8,7 @@
8
8
  | 21.x.x | Kesaria | 11.2024 | :white_check_mark: |
9
9
  | 20.x.x | Zoey | 06.2024 | :white_check_mark: |
10
10
  | 19.x.x | Dime | 05.2024 | :white_check_mark: |
11
- | 18.x.x | Victoria | 04.2024 | :white_check_mark: |
11
+ | 18.x.x | Victoria | 04.2024 | :x: |
12
12
  | 17.x.x | Tonya | 02.2024 | :x: |
13
13
  | 16.x.x | Nina | 12.2023 | :x: |
14
14
  | 15.x.x | Vika | 12.2023 | :x: |
@@ -32,6 +32,6 @@
32
32
  Found a vulnerability or other security issue?
33
33
 
34
34
  Please urgently inform me privately by
35
- [email](https://github.com/RobinTail/express-zod-api/blob/master/package.json#L14).
35
+ [email](https://github.com/RobinTail/express-zod-api/blob/master/express-zod-api/package.json#L14).
36
36
 
37
37
  I will try to fix it as soon as possible.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var sn=Object.create;var at=Object.defineProperty;var an=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var cn=Object.getPrototypeOf,dn=Object.prototype.hasOwnProperty;var mn=(e,t)=>{for(var r in t)at(e,r,{get:t[r],enumerable:!0})},wr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pn(t))!dn.call(e,n)&&n!==r&&at(e,n,{get:()=>t[n],enumerable:!(o=an(t,n))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?sn(cn(e)):{},wr(t||!e||!e.__esModule?at(r,"default",{value:e,enumerable:!0}):r,e)),ln=e=>wr(at({},"__esModule",{value:!0}),e);var ei={};mn(ei,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>Et,DocumentationError:()=>B,EndpointsFactory:()=>ye,EventStreamFactory:()=>Ut,InputValidationError:()=>X,Integration:()=>Mt,Middleware:()=>V,MissingPeerError:()=>ve,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>be,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Fr,arrayResultHandler:()=>Rt,attachRouting:()=>So,createConfig:()=>Er,createServer:()=>Ro,defaultEndpointsFactory:()=>Kr,defaultResultHandler:()=>Ue,ensureHttpError:()=>we,ez:()=>nn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>_o,testMiddleware:()=>Vo});module.exports=ln(ei);var H=S(require("ramda"),1),Te=require("zod");var D=S(require("ramda"),1),qt=require("zod");var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var be=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.`}},pt=class extends Error{name="IOSchemaError"},ae=class extends pt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends pt{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"},ve=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Bt=/:([A-Za-z0-9_]+)/g,ct=e=>e.match(Bt)?.map(t=>t.slice(1))||[],un=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},$t={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},fn=["body","query","params"],_t=e=>e.method.toLowerCase(),dt=(e,t={})=>{let r=_t(e);return r==="options"?{}:(t[r]||$t[r]||fn).filter(o=>o==="files"?un(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof qt.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,yn=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return xe(t,(n[h]?.examples||[]).map(D.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[h]?.examples||[];if(!n.length&&o&&e instanceof qt.z.ZodObject&&(n=yn(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},xe=(e,t,r)=>e.length&&t.length?D.xprod(e,t).map(r):e.concat(t),Ge=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Vt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=D.chain(o=>o.split(/[^A-Z0-9]/gi),e);return D.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Vt).join("")},mt=D.tryCatch((e,t)=>typeof e.parse(t),D.always(void 0)),Se=e=>typeof e=="object"&&e!==null,Re=D.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var lt=S(require("ramda"),1),h=Symbol.for("express-zod-api"),Je=e=>{let t=e.describe(e.description);return t._def[h]=lt.clone(t._def[h])||{examples:[]},t},Ar=(e,t)=>{if(!(h in e._def))return t;let r=Je(t);return r._def[h].examples=xe(r._def[h].examples,e._def[h].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?lt.mergeDeepRight({...o},{...n}):n),r};var gn=function(e){let t=Je(this);return t._def[h].examples.push(e),t},hn=function(){let e=Je(this);return e._def[h].isDeprecated=!0,e},bn=function(e){let t=Je(this);return t._def[h].defaultLabel=e,t},xn=function(e){return new Te.z.ZodBranded({typeName:Te.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[h]:{examples:[],...H.clone(this._def[h]),brand:e}})},Sn=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=Te.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};h in globalThis||(globalThis[h]=!0,Object.defineProperties(Te.z.ZodType.prototype,{example:{get(){return gn.bind(this)}},deprecated:{get(){return hn.bind(this)}},brand:{set(){},get(){return xn.bind(this)}}}),Object.defineProperty(Te.z.ZodDefault.prototype,"label",{get(){return bn.bind(this)}}),Object.defineProperty(Te.z.ZodObject.prototype,"remap",{get(){return Sn.bind(this)}}));function Er(e){return e}var er=require("zod");var Qt=require("zod");var L=require("node:assert/strict");var ke=require("zod");var ut=e=>!isNaN(e.getTime());var Oe=Symbol("DateIn"),zr=()=>ke.z.union([ke.z.string().date(),ke.z.string().datetime(),ke.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ke.z.date().refine(ut)).brand(Oe);var Ir=require("zod");var Pe=Symbol("DateOut"),Zr=()=>Ir.z.date().refine(ut).transform(e=>e.toISOString()).brand(Pe);var We=require("zod"),ee=Symbol("File"),vr=We.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Rn={buffer:()=>vr.brand(ee),string:()=>We.z.string().brand(ee),binary:()=>vr.or(We.z.string()).brand(ee),base64:()=>We.z.string().base64().brand(ee)};function ft(e){return Rn[e||"string"]()}var kr=require("zod");var le=Symbol("Raw"),Cr=(e={})=>kr.z.object({raw:ft("buffer")}).extend(e).brand(le);var jr=require("zod"),Ce=Symbol("Upload"),Nr=()=>jr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ce);var Lr=(e,{next:t})=>e.options.some(t),Tn=({_def:e},{next:t})=>[e.left,e.right].some(t),yt=(e,{next:t})=>t(e.unwrap()),Gt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Lr,ZodDiscriminatedUnion:Lr,ZodIntersection:Tn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:yt,ZodNullable:yt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=Gt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[h]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Mr=e=>gt(e,{condition:t=>t._def[h]?.brand===Ce}),ht=e=>gt(e,{condition:t=>t._def[h]?.brand===le,maxDepth:3}),Ur=(e,t)=>{let r=new WeakSet;return gt(e,{maxDepth:300,rules:{...Gt,ZodBranded:yt,ZodReadonly:yt,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:Gt.ZodEffects}[t],ZodNaN:()=>(0,L.fail)("z.nan()"),ZodSymbol:()=>(0,L.fail)("z.symbol()"),ZodFunction:()=>(0,L.fail)("z.function()"),ZodMap:()=>(0,L.fail)("z.map()"),ZodSet:()=>(0,L.fail)("z.set()"),ZodBigInt:()=>(0,L.fail)("z.bigint()"),ZodVoid:()=>(0,L.fail)("z.void()"),ZodPromise:()=>(0,L.fail)("z.promise()"),ZodNever:()=>(0,L.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,L.fail)("z.date()"),[Pe]:()=>t==="in"&&(0,L.fail)("ez.dateOut()"),[Oe]:()=>t==="out"&&(0,L.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,L.fail)("ez.raw()"),[Ce]:()=>t==="out"&&(0,L.fail)("ez.upload()"),[ee]:()=>!1}})};var bt=S(require("http-errors"),1);var Ye=S(require("http-errors"),1),Dr=require("zod");var Jt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Dr.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}))},Qe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>(0,Ye.isHttpError)(e)?e:(0,Ye.default)(e instanceof X?400:500,ce(e),{cause:e.cause||e}),Ae=e=>Re()&&!e.expose?(0,Ye.default)(e.statusCode).message:e.message;var xt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ae((0,bt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:(0,bt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Wt=require("zod");var Yt=class{},V=class extends Yt{#e;#t;#r;constructor({input:t=Wt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){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 Wt.z.ZodError?new X(o):o}}},je=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 Ne=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends Ne{},St=class e extends Xe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Mr(this.#e.inputSchema)?"upload":ht(this.#e.inputSchema)?"raw":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){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 Qt.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 je))&&(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 Qt.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){xt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=_t(t),a={},c=null,m=null,p=dt(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 ue=require("zod");var Hr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ar(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 Le={positive:200,negative:400},Me=Object.keys(Le);var Xt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends Xt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Jt(this.#e,{variant:"positive",args:[t],statusCodes:[Le.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Jt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[C.json]})}},Ue=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=we(e);return Qe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.positive).json({status:"success",data:r})}}),Rt=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)=>Se(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=we(r);return Qe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=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 je(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=er.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||[],x=typeof s=="string"?[s]:s||[];return new St({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:x,methods:l,getOperationId:b,inputSchema:Hr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:er.z.object({}),handler:async o=>(await t(o),{})})}},Kr=new ye(Ue),Fr=new ye(Rt);var Gr=S(require("ansis"),1),Jr=require("node:util"),rr=require("node:perf_hooks");var te=require("ansis"),qr=S(require("ramda"),1);var tr={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},Tt={debug:10,info:20,warn:30,error:40},Br=e=>Se(e)&&Object.keys(Tt).some(t=>t in e),$r=e=>e in Tt,_r=(e,t)=>Tt[e]<Tt[t],On=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=qr.memoizeWith((e,t)=>`${e}${t}`,On),Vr=e=>e<1e-6?De("nanosecond",3).format(e/1e-6):e<.001?De("nanosecond").format(e/1e-6):e<1?De("microsecond").format(e/.001):e<1e3?De("millisecond").format(e):e<6e4?De("second",2).format(e/1e3):De("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=Gr.default.isSupported(),level:r=Re()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return(0,Jr.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"||_r(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?tr.ctx(s):s),m.push(c?`${tr[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.prettyPrint(o)),Object.keys(a).length>0&&m.push(this.prettyPrint(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=rr.performance.now();return()=>{let o=rr.performance.now()-r,{message:n,severity:s="debug",formatter:a=Vr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Fe=S(require("ramda"),1);var Ke=class e extends Ne{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Fe.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Fe.reject(Fe.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 Wr=S(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Wr.default.static(...this.params))}};var Pt=S(require("express"),1),ho=S(require("node:http"),1),bo=S(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ve(e)};var Xr=S(require("http-errors"),1);var Yr=S(require("ramda"),1);var Ot=class{constructor(t){this.logger=t}#e=Yr.tryCatch(Ur);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="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.getSchema("input"),"in");for(let o of Me){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(C.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=ct(t);if(s.length===0)return;let a=n?.shape||G(r.getSchema("input")).shape;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 Qr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new be(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),$e=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Qr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Xe){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof qe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new be(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...Qr(s,n))}};var Pn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,Xr.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},or=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new Ot(t()),a=new Map;if($e({routing:o,onEndpoint:(m,p,l,b)=>{Re()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.getRequestType()]||[],x=async(y,j)=>{let P=t(y);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:P,defaultHeaders:T}):T;for(let N in v)j.set(N,v[N])}return m.execute({request:y,response:j,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,Pn(p))};var et=S(require("http-errors"),1);var so=require("node:timers/promises");var eo=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",to=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",ro=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,oo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),no=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var io=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(eo(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",oo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(ro(p)||to(p))&&a(p);for await(let p of(0,so.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(no))};return{sockets:n,shutdown:()=>o??=m()}};var ao=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,et.isHttpError)(r)?r:(0,et.default)(400,de(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),po=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,et.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){xt({response:o,logger:s,error:new pe(de(a),n)})}},wn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},An=e=>({log:e.debug.bind(e)}),co=async({getLogger:e,config:t})=>{let r=await Be("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);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:An(l)})(c,m,p)}),o&&a.push(wn(o)),a},mo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},lo=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[h]={logger:s}),n()},uo=e=>t=>t?.res?.locals[h]?.logger||e,fo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),yo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=io(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var $=require("ansis"),go=e=>{if(e.columns<132)return;let t=(0,$.italic)("Proudly supports transgender community.".padStart(109)),r=(0,$.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,$.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,$.italic)("for Tai".padEnd(20)),s=(0,$.hex)("#F5A9B8"),a=(0,$.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill($.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill($.gray,12,13),m=`
1
+ "use strict";var dn=Object.create;var ct=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var ln=Object.getOwnPropertyNames;var un=Object.getPrototypeOf,fn=Object.prototype.hasOwnProperty;var yn=(e,t)=>{for(var r in t)ct(e,r,{get:t[r],enumerable:!0})},Er=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ln(t))!fn.call(e,n)&&n!==r&&ct(e,n,{get:()=>t[n],enumerable:!(o=mn(t,n))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?dn(un(e)):{},Er(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),gn=e=>Er(ct({},"__esModule",{value:!0}),e);var ni={};yn(ni,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>It,DocumentationError:()=>B,EndpointsFactory:()=>ye,EventStreamFactory:()=>Ht,InputValidationError:()=>X,Integration:()=>Dt,Middleware:()=>V,MissingPeerError:()=>ve,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>be,ServeStatic:()=>qe,arrayEndpointsFactory:()=>_r,arrayResultHandler:()=>Pt,attachRouting:()=>Po,createConfig:()=>Ir,createServer:()=>wo,defaultEndpointsFactory:()=>$r,defaultResultHandler:()=>Ue,ensureHttpError:()=>we,ez:()=>cn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>Wo,testMiddleware:()=>Yo});module.exports=gn(ni);var H=S(require("ramda"),1),Te=require("zod");var D=S(require("ramda"),1),$t=require("zod");var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var be=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.`}},dt=class extends Error{name="IOSchemaError"},ae=class extends dt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends dt{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"},ve=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,mt=e=>e.match(_t)?.map(t=>t.slice(1))||[],hn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},Vt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},bn=["body","query","params"],Gt=e=>e.method.toLowerCase(),lt=(e,t={})=>{let r=Gt(e);return r==="options"?{}:(t[r]||Vt[r]||bn).filter(o=>o==="files"?hn(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,xn=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return xe(t,(n[g]?.examples||[]).map(D.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[g]?.examples||[];if(!n.length&&o&&e instanceof $t.z.ZodObject&&(n=xn(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},xe=(e,t,r)=>e.length&&t.length?D.xprod(e,t).map(r):e.concat(t),Ge=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=D.chain(o=>o.split(/[^A-Z0-9]/gi),e);return D.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Jt).join("")},ut=D.tryCatch((e,t)=>typeof e.parse(t),D.always(void 0)),Se=e=>typeof e=="object"&&e!==null,Re=D.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ft=S(require("ramda"),1),g=Symbol.for("express-zod-api"),Je=e=>{let t=e.describe(e.description);return t._def[g]=ft.clone(t._def[g])||{examples:[]},t},zr=(e,t)=>{if(!(g in e._def))return t;let r=Je(t);return r._def[g].examples=xe(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?ft.mergeDeepRight({...o},{...n}):n),r};var Sn=function(e){let t=Je(this);return t._def[g].examples.push(e),t},Rn=function(){let e=Je(this);return e._def[g].isDeprecated=!0,e},Tn=function(e){let t=Je(this);return t._def[g].defaultLabel=e,t},On=function(e){return new Te.z.ZodBranded({typeName:Te.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...H.clone(this._def[g]),brand:e}})},Pn=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=Te.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Te.z.ZodType.prototype,{example:{get(){return Sn.bind(this)}},deprecated:{get(){return Rn.bind(this)}},brand:{set(){},get(){return On.bind(this)}}}),Object.defineProperty(Te.z.ZodDefault.prototype,"label",{get(){return Tn.bind(this)}}),Object.defineProperty(Te.z.ZodObject.prototype,"remap",{get(){return Pn.bind(this)}}));function Ir(e){return e}var rr=require("zod");var er=require("zod");var L=require("node:assert/strict");var ke=require("zod");var yt=e=>!isNaN(e.getTime());var Oe=Symbol("DateIn"),Zr=()=>ke.z.union([ke.z.string().date(),ke.z.string().datetime(),ke.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ke.z.date().refine(yt)).brand(Oe);var vr=require("zod");var Pe=Symbol("DateOut"),kr=()=>vr.z.date().refine(yt).transform(e=>e.toISOString()).brand(Pe);var We=require("zod"),ee=Symbol("File"),Cr=We.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),wn={buffer:()=>Cr.brand(ee),string:()=>We.z.string().brand(ee),binary:()=>Cr.or(We.z.string()).brand(ee),base64:()=>We.z.string().base64().brand(ee)};function gt(e){return wn[e||"string"]()}var Wt=require("zod"),ht=Symbol("Form"),jr=e=>(e instanceof Wt.z.ZodObject?e:Wt.z.object(e)).brand(ht);var Nr=require("zod");var le=Symbol("Raw"),Lr=(e={})=>Nr.z.object({raw:gt("buffer")}).extend(e).brand(le);var Mr=require("zod"),Ce=Symbol("Upload"),Ur=()=>Mr.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(Ce);var Dr=(e,{next:t})=>e.options.some(t),An=({_def:e},{next:t})=>[e.left,e.right].some(t),bt=(e,{next:t})=>t(e.unwrap()),xt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Dr,ZodDiscriminatedUnion:Dr,ZodIntersection:An,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:bt,ZodNullable:bt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Ye=(e,{condition:t,rules:r=xt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Ye(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Hr=e=>Ye(e,{condition:t=>t._def[g]?.brand===Ce,rules:{...xt,[ht]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),St=e=>Ye(e,{condition:t=>t._def[g]?.brand===le,maxDepth:3}),Kr=e=>Ye(e,{condition:t=>t._def[g]?.brand===ht,maxDepth:3}),Fr=(e,t)=>{let r=new WeakSet;return Ye(e,{maxDepth:300,rules:{...xt,ZodBranded:bt,ZodReadonly:bt,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:xt.ZodEffects}[t],ZodNaN:()=>(0,L.fail)("z.nan()"),ZodSymbol:()=>(0,L.fail)("z.symbol()"),ZodFunction:()=>(0,L.fail)("z.function()"),ZodMap:()=>(0,L.fail)("z.map()"),ZodSet:()=>(0,L.fail)("z.set()"),ZodBigInt:()=>(0,L.fail)("z.bigint()"),ZodVoid:()=>(0,L.fail)("z.void()"),ZodPromise:()=>(0,L.fail)("z.promise()"),ZodNever:()=>(0,L.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,L.fail)("z.date()"),[Pe]:()=>t==="in"&&(0,L.fail)("ez.dateOut()"),[Oe]:()=>t==="out"&&(0,L.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,L.fail)("ez.raw()"),[Ce]:()=>t==="out"&&(0,L.fail)("ez.upload()"),[ee]:()=>!1}})};var Rt=S(require("http-errors"),1);var Qe=S(require("http-errors"),1),qr=require("zod");var Yt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof qr.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}))},Xe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>(0,Qe.isHttpError)(e)?e:(0,Qe.default)(e instanceof X?400:500,ce(e),{cause:e.cause||e}),Ae=e=>Re()&&!e.expose?(0,Qe.default)(e.statusCode).message:e.message;var Tt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ae((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}getSecurity(){return this.#t}getSchema(){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}}},je=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 Ne=class{nest(t){return Object.assign(t,{"":this})}};var et=class extends Ne{},Ot=class e extends et{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Hr(this.#e.inputSchema)?"upload":St(this.#e.inputSchema)?"raw":Kr(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){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 je))&&(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=lt(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 ue=require("zod");var Br=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),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 Le={positive:200,negative:400},Me=Object.keys(Le);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:[Le.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[C.json]})}},Ue=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=we(e);return Xe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.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)=>Se(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=we(r);return Xe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=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 je(...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,h=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new Ot({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:h,tags:x,methods:l,getOperationId:b,inputSchema:Br(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:rr.z.object({}),handler:async o=>(await t(o),{})})}},$r=new ye(Ue),_r=new ye(Pt);var Qr=S(require("ansis"),1),Xr=require("node:util"),nr=require("node:perf_hooks");var te=require("ansis"),Vr=S(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},Gr=e=>Se(e)&&Object.keys(wt).some(t=>t in e),Jr=e=>e in wt,Wr=(e,t)=>wt[e]<wt[t],En=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=Vr.memoizeWith((e,t)=>`${e}${t}`,En),Yr=e=>e<1e-6?De("nanosecond",3).format(e/1e-6):e<.001?De("nanosecond").format(e/1e-6):e<1?De("microsecond").format(e/.001):e<1e3?De("millisecond").format(e):e<6e4?De("second",2).format(e/1e3):De("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=Qr.default.isSupported(),level:r=Re()?"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,Xr.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"||Wr(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=Yr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Fe=S(require("ramda"),1);var Ke=class e extends Ne{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Fe.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Fe.reject(Fe.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 eo=S(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,eo.default.static(...this.params))}};var rt=S(require("express"),1),Ro=S(require("node:http"),1),To=S(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ve(e)};var oo=S(require("http-errors"),1);var to=S(require("ramda"),1);var At=class{constructor(t){this.logger=t}#e=to.tryCatch(Fr);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="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.getSchema("input"),"in");for(let o of Me){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(C.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=mt(t);if(s.length===0)return;let a=n?.shape||G(r.getSchema("input")).shape;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 ro=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new be(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),$e=({routing:e,onEndpoint:t,onStatic:r})=>{let o=ro(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof et){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof qe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new be(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...ro(s,n))}};var zn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,oo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},sr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new At(t()),a=new Map;if($e({routing:o,onEndpoint:(m,p,l,b)=>{Re()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let h=n?.[m.getRequestType()]||[],x=async(y,j)=>{let P=t(y);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:P,defaultHeaders:T}):T;for(let N in v)j.set(N,v[N])}return m.execute({request:y,response:j,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...h,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...h,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,zn(p))};var tt=S(require("http-errors"),1);var co=require("node:timers/promises");var no=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",so=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",io=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ao=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),po=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var mo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(no(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",ao);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(io(p)||so(p))&&a(p);for await(let p of(0,co.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(po))};return{sockets:n,shutdown:()=>o??=m()}};var lo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,tt.isHttpError)(r)?r:(0,tt.default)(400,de(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),uo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,tt.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)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Zn=e=>({log:e.debug.bind(e)}),fo=async({getLogger:e,config:t})=>{let r=await Be("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);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Zn(l)})(c,m,p)}),o&&a.push(In(o)),a},yo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},go=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{try{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[g]={logger:a}),s()}catch(a){s(a)}},ho=e=>t=>t?.res?.locals[g]?.logger||e,bo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),xo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=mo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var $=require("ansis"),So=e=>{if(e.columns<132)return;let t=(0,$.italic)("Proudly supports transgender community.".padStart(109)),r=(0,$.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,$.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,$.italic)("for Tai".padEnd(20)),s=(0,$.hex)("#F5A9B8"),a=(0,$.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill($.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill($.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 xo=e=>{e.startupLogo!==!1&&go(process.stdout);let t=e.errorHandler||Ue,r=Br(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.12.0-beta.1 (CJS)",env:process.env.NODE_ENV||"development"}),fo(r);let o=lo({logger:r,config:e}),s={getLogger:uo(r),errorHandler:t},a=po(s),c=ao(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},So=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=xo(e);return or({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Ro=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=xo(e),c=(0,Pt.default)().disable("x-powered-by").use(a);if(e.compression){let g=await Be("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}let m={json:[e.jsonParser||Pt.default.json()],raw:[e.rawParser||Pt.default.raw(),mo],upload:e.upload?await co({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),or({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,x)=>()=>g.listen(x,()=>r.info("Listening",x)),b=[];if(e.http){let g=ho.default.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=bo.default.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&yo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};var qo=require("openapi3-ts/oas31"),Bo=S(require("ramda"),1);var O=S(require("ramda"),1);var To=e=>Se(e)&&"or"in e,Oo=e=>Se(e)&&"and"in e,nr=e=>!Oo(e)&&!To(e),Po=e=>{let t=O.filter(nr,e),r=O.chain(O.prop("and"),O.filter(Oo,e)),[o,n]=O.partition(nr,r),s=O.concat(t,o),a=O.filter(To,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>xe(m,O.map(l=>nr(l)?[l]:l.and,p),([l,b])=>O.concat(l,b)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=S(require("ramda"),1),K=require("zod");var Ee=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[h]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ee(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 wo=["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","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 Ao=50,zo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},In=/^\d{4}-\d{2}-\d{2}$/,Zn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,vn=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$/,Io=e=>e.replace(Bt,t=>`{${t.slice(1)}}`),kn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),Cn=({_def:{innerType:e}},{next:t})=>t(e),jn=()=>({format:"any"}),Nn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Ln=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"}},Mn=({options:e},{next:t})=>({oneOf:e.map(t)}),Un=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Dn=(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")},Zo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Dn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>xe(e,t,([r,o])=>d.mergeDeepRight(r,o))},Hn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Zo)),d.isEmpty)),Kn=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Hn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Zo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Fn=({_def:{left:e,right:t}},{next:r})=>Kn([e,t].map(r)),qn=(e,{next:t})=>t(e.unwrap()),Bn=(e,{next:t})=>t(e.unwrap()),$n=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=ko(r)),r},vo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Eo=e=>({type:vo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),_n=({value:e})=>({type:vo(e),const:e}),Vn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ge(c)?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=wt(e,r)),s.length&&(a.required=s),a},Gn=()=>({type:"null"}),Jn=({},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:zo}}},Wn=({},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:zo}}},Yn=({},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)},Qn=()=>({type:"boolean"}),Xn=()=>({type:"integer",format:"bigint"}),es=e=>e.every(t=>t instanceof K.z.ZodLiteral),ts=({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=wt(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:wt(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&es(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:wt(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},rs=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},os=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ns=({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:x,isBase64:y,isNANOID:j,isBase64url:P,isDuration:Q,_def:{checks:Z}})=>{let T=Z.find(k=>k.kind==="regex"),v=Z.find(k=>k.kind==="datetime"),N=Z.some(k=>k.kind==="jwt"),U=Z.find(k=>k.kind==="length"),z={type:"string"},q={"date-time":l,byte:y,base64url:P,date:g,time:x,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:j,jwt:N,ip:m,cidr:b,emoji:p};for(let k in q)if(q[k]){z.format=k;break}return U&&([z.minLength,z.maxLength]=[U.value,U.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),g&&(z.pattern=In.source),x&&(z.pattern=Zn.source),l&&(z.pattern=vn(v?.offset).source),T&&(z.pattern=T.regex.source),z},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(y=>y.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(y=>y.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,x={type:e?"integer":"number",format:e?"int64":"double"};return p?x.minimum=m:x.exclusiveMinimum=m,g?x.maximum=b:x.exclusiveMaximum=b,x},wt=({shape:e},t)=>d.map(t,e),is=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return zn?.[t]},ko=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",as=(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=mt(e,is(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},ps=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),cs=(e,{next:t})=>t(e.unwrap()),ds=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ms=(e,{next:t})=>t(e.unwrap().shape.raw),Co=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,jo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Co)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ls=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Co)({schema:e,variant:"original",validate:!0,pullProps:!0}),us=(e,t)=>t?.includes(e)||e.startsWith("x-")||wo.includes(e),No=({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=ct(e),x=o.includes("query"),y=o.includes("params"),j=o.includes("headers"),P=T=>y&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),Z=T=>j&&(c?.(T,t,e)??us(T,Q));return Object.entries(b.shape).reduce((T,[v,N])=>{let U=P(v)?"path":Z(v)?"header":x?"query":void 0;if(!U)return T;let z=Ee(N,{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(N,z,me(l,v)):z,{_def:k}=N;return T.concat({name:v,in:U,deprecated:k[h]?.isDeprecated,required:!N.isOptional(),description:z.description||l,schema:q,examples:ls(b,v)})},[])},sr={ZodString:ns,ZodNumber:ss,ZodBigInt:Xn,ZodBoolean:Qn,ZodNull:Gn,ZodArray:rs,ZodTuple:os,ZodRecord:ts,ZodObject:Vn,ZodLiteral:_n,ZodIntersection:Fn,ZodUnion:Mn,ZodAny:jn,ZodDefault:kn,ZodEnum:Eo,ZodNativeEnum:Eo,ZodEffects:as,ZodOptional:qn,ZodNullable:$n,ZodDiscriminatedUnion:Un,ZodBranded:cs,ZodDate:Yn,ZodCatch:Cn,ZodPipeline:ps,ZodLazy:ds,ZodReadonly:Bn,[ee]:Ln,[Ce]:Nn,[Pe]:Wn,[Oe]:Jn,[le]:ms},ir=(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&&Ge(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[h]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=ko(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},ar=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Lo=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Lo(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]},Mo=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Uo=({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} ${Vt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=Mo(Ee(r,{rules:{...p,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,g,me(b)):g,examples:jo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},fs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ys=({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},gs=({name:e})=>({type:"apiKey",in:"header",name:e}),hs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),bs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),xs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Do=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?fs(o):o.type==="input"?ys(o,t):o.type==="header"?gs(o):o.type==="cookie"?hs(o):o.type==="openid"?bs(o):xs(o);return e.map(o=>o.map(r))},Ho=(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:[]})},{})),Ko=({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]=Lo(Ee(r,{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=Mo(l),x={schema:s==="components"?n(r,g,me(p)):g,examples:jo(G(r),!1,c)},y={description:p,content:{[o]:x}};return(b||ht(r))&&(y.required=!0),y},Fo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),pr=e=>e.length<=Ao?e:e.slice(0,Ao-1)+"\u2026",At=e=>e.length?e.slice():void 0;var Et=class extends qo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||me(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(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.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.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 y of typeof s=="string"?[s]:s)this.addServer({url:y});$e({routing:t,onEndpoint:(y,j,P)=>{let Q={path:j,method:P,endpoint:y,composition:g,brandHandling:c,numericRange:l,makeRef:this.makeRef.bind(this)},[Z,T]=["short","long"].map(y.getDescription.bind(y)),v=Z?pr(Z):b&&T?pr(T):void 0,N=r.inputSources?.[P]||$t[P],U=this.ensureUniqOperationId(j,P,y.getOperationId(P)),z=Po(y.getSecurity()),q=No({...Q,inputSources:N,isHeader:p,security:z,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:P,path:j,operationId:U})}),k={};for(let ie of Me){let he=y.getResponses(ie);for(let{mimeTypes:Kt,schema:st,statusCodes:it}of he)for(let Ft of it)k[Ft]=Uo({...Q,variant:ie,schema:st,mimeTypes:Kt,statusCode:Ft,hasMultipleStatusCodes:he.length>1||it.length>1,description:a?.[`${ie}Response`]?.call(null,{method:P,path:j,operationId:U,statusCode:Ft})})}let Dt=N.includes("body")?Ko({...Q,paramNames:Bo.pluck("name",q),schema:y.getSchema("input"),mimeType:C[y.getRequestType()],description:a?.requestBody?.call(null,{method:P,path:j,operationId:U})}):void 0,nt=Ho(Do(z,N),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),Ht={operationId:U,summary:v,description:T,deprecated:y.isDeprecated||void 0,tags:At(y.getTags()),parameters:At(q),requestBody:Dt,security:At(nt),responses:k};this.addPath(Io(j),{[P]:Ht})}}),m&&(this.rootDoc.tags=Fo(m))}};var zt=require("node-mocks-http"),Ss=e=>(0,zt.createRequest)({...e,headers:{"content-type":C.json,...e?.headers}}),Rs=e=>(0,zt.createResponse)(e),Ts=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:$r(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},$o=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ss(e),s=Rs({req:n,...t});s.req=t?.req||n,n.res=s;let a=Ts(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},_o=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=$o(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Vo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=$o(o),m=dt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:m,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(de(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var en=S(require("ramda"),1),ot=S(require("typescript"),1),tn=require("zod");var Qo=S(require("ramda"),1),Y=S(require("typescript"),1);var Go=["get","post","put","delete","patch"];var re=S(require("ramda"),1),u=S(require("typescript"),1),i=u.default.factory,It=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Os=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],tt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),dr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Ps=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mr=e=>typeof e=="string"&&Ps.test(e)?i.createIdentifier(e):E(e),Zt=(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)))),vt=(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),_e=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),lr=(e,t=[])=>i.createConstructorDeclaration(tt.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,ur=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),ze=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,mr(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?cr(s,a.join(" ")):s},fr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),yr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&It,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),gr=(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?It:void 0,e,n&&Sr(n),t);return o?cr(s,o):s},Jo=(e,t)=>i.createPropertyDeclaration(tt.public,e,void 0,f(t),void 0),hr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(tt.public,void 0,e,void 0,o&&Sr(o),t,n,i.createBlock(r)),br=(e,t,{typeParams:r}={})=>i.createClassDeclaration(It,e,r&&Sr(r),void 0,t),xr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),kt=e=>f(Promise.name,[e]),Ct=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?It:void 0,e,void 0,void 0,t);return o?cr(n,o):n},Sr=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)}),Ie=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Os:void 0,void 0,Array.isArray(e)?re.map(vt,e):_e(e),void 0,void 0,t),w=e=>e,rt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),A=(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),Ve=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),jt=(e,t)=>f("Extract",[e,t]),Rr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Wo=e=>i.createUnionTypeNode([f(e),kt(e)]),Tr=(e,t)=>i.createFunctionTypeNode(void 0,_e(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),F=e=>i.createLiteralTypeNode(E(e)),ws=[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],Yo=e=>ws.includes(e.kind);var Nt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={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=gr("Method",Go);someOfType=oe("SomeOf",W("T",xr("T")),{params:["T"]});requestType=oe("Request",xr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>gr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ct(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>ze(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(mr(t),i.createArrayLiteralExpression(Qo.map(E,r))))),{expose:!0});makeImplementationType=()=>oe(this.ids.implementationType,Tr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:ur,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},kt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.ids.parseRequestFn,Ie({[this.ids.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(A(this.ids.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>M(this.ids.substituteFn,Ie({[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:ur},i.createBlock([M(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],Y.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([Rr(this.ids.pathParameter,A(this.ids.pathParameter,w("replace"))(Zt(":",[this.ids.keyParameter]),Ie([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),f("const")))])));makeProvider=()=>hr(this.ids.provideMethod,_e({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:W(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[M(yr(this.ids.methodParameter,this.ids.pathParameter),A(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(A(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(A(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:kt(W(this.interfaces.response,"K"))});makeClientClass=t=>br(t,[lr([vt(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:tt.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>Zt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,Zt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.ids.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),rt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(C.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(w("body"),rt(this.ids.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=M(this.ids.responseConst,i.createAwaitExpression(A(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=M(this.ids.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.ids.methodParameter))),a=M(this.ids.searchParamsConst,rt(this.ids.hasBodyConst,E(""),this.makeSearchParams(this.ids.paramsArgument))),c=M(this.ids.contentTypeConst,A(this.ids.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=M(this.ids.isJsonConst,A(this.ids.contentTypeConst,w("startsWith"))(E(C.json))),l=i.createReturnStatement(A(this.ids.responseConst,rt(this.ids.isJsonConst,E(w("json")),E(w("text"))))());return M(this.ids.defaultImplementationConst,Ie([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>lr(_e({request:"K",params:W(this.interfaces.input,"K")}),[M(yr(this.ids.pathParameter,this.ids.restConst),A(this.ids.substituteFn)(i.createElementAccessExpression(A(this.ids.parseRequestFn)(this.ids.requestParameter),E(1)),this.ids.paramsArgument)),M(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),Rr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ze(w("event"),t)]);makeOnMethod=()=>hr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Tr({[this.ids.dataParameter.text]:W(jt("R",fr(this.makeEventNarrow("E"))),F(w("data")))},Wo(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.ids.sourceProp,w("addEventListener"))(this.ids.eventParameter,Ie([this.ids.msgParameter],A(this.ids.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(w("event")))}});makeSubscriptionClass=t=>br(t,[Jo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:jt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:jt(W(this.interfaces.positive,"K"),fr(this.makeEventNarrow(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.ids.clientConst,Ve(t)),A(this.ids.clientConst,this.ids.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(Ve(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(E("time"),Ie(["time"],i.createBlock([])))]};var I=S(require("ramda"),1),R=S(require("typescript"),1),Lt=require("zod");var{factory:_}=R.default,As={[R.default.SyntaxKind.AnyKeyword]:"",[R.default.SyntaxKind.BigIntKeyword]:BigInt(0),[R.default.SyntaxKind.BooleanKeyword]:!1,[R.default.SyntaxKind.NumberKeyword]:0,[R.default.SyntaxKind.ObjectKeyword]:{},[R.default.SyntaxKind.StringKeyword]:"",[R.default.SyntaxKind.UndefinedKeyword]:void 0},Or={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Es=({value:e})=>F(e),zs=({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&&Ge(a)?a instanceof Lt.z.ZodOptional:a.isOptional();return ze(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[h]?.isDeprecated})});return _.createTypeLiteralNode(n)},Is=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),Zs=({options:e})=>_.createUnionTypeNode(e.map(F)),Xo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Yo(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},vs=e=>As?.[e.kind],ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=mt(e,vs(o)),s={number:R.default.SyntaxKind.NumberKeyword,bigint:R.default.SyntaxKind.BigIntKeyword,boolean:R.default.SyntaxKind.BooleanKeyword,string:R.default.SyntaxKind.StringKeyword,undefined:R.default.SyntaxKind.UndefinedKeyword,object:R.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||R.default.SyntaxKind.AnyKeyword)}return o},Cs=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(R.default.SyntaxKind.UndefinedKeyword)]):o},Ns=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),F(null)]),Ls=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),Ms=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Us=I.tryCatch(e=>{if(!e.every(R.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(Or.name,...o))return!1;if(I.both(I.eqBy(Or.type),I.eqBy(Or.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),Ds=({_def:{left:e,right:t}},{next:r})=>Us([e,t].map(r)),Hs=({_def:e},{next:t})=>t(e.innerType),ge=e=>()=>f(e),Ks=(e,{next:t})=>t(e.unwrap()),Fs=(e,{next:t})=>t(e.unwrap()),qs=({_def:e},{next:t})=>t(e.innerType),Bs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),$s=()=>F(null),_s=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Vs=e=>{let t=e.unwrap(),r=f(R.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Lt.z.ZodString?r:t instanceof Lt.z.ZodUnion?n:o},Gs=(e,{next:t})=>t(e.unwrap().shape.raw),Js={ZodString:ge(R.default.SyntaxKind.StringKeyword),ZodNumber:ge(R.default.SyntaxKind.NumberKeyword),ZodBigInt:ge(R.default.SyntaxKind.BigIntKeyword),ZodBoolean:ge(R.default.SyntaxKind.BooleanKeyword),ZodAny:ge(R.default.SyntaxKind.AnyKeyword),ZodUndefined:ge(R.default.SyntaxKind.UndefinedKeyword),[Oe]:ge(R.default.SyntaxKind.StringKeyword),[Pe]:ge(R.default.SyntaxKind.StringKeyword),ZodNull:$s,ZodArray:Is,ZodTuple:Ls,ZodRecord:Ms,ZodObject:zs,ZodLiteral:Es,ZodIntersection:Ds,ZodUnion:Xo,ZodDefault:Hs,ZodEnum:Zs,ZodNativeEnum:Cs,ZodEffects:ks,ZodOptional:js,ZodNullable:Ns,ZodDiscriminatedUnion:Xo,ZodBranded:Ks,ZodCatch:qs,ZodPipeline:Bs,ZodLazy:_s,ZodReadonly:Fs,[ee]:Vs,[le]:Gs},Pr=(e,{brandHandling:t,ctx:r})=>Ee(e,{rules:{...t,...Js},onMissing:()=>f(R.default.SyntaxKind.AnyKeyword),ctx:r});var Mt=class extends Nt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=F(null);this.aliases.set(t,oe(o,n)),this.aliases.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=tn.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};$e({routing:t,onEndpoint:(x,y,j)=>{let P=me.bind(null,j,y),{isDeprecated:Q}=x,Z=`${j} ${y}`,T=oe(P("input"),Pr(x.getSchema("input"),l),{comment:Z});this.program.push(T);let v=Me.reduce((z,q)=>{let k=x.getResponses(q),Dt=en.chain(([Ht,{schema:ie,mimeTypes:he,statusCodes:Kt}])=>{let st=oe(P(q,"variant",`${Ht+1}`),Pr(he?ie:m,b),{comment:Z});return this.program.push(st),Kt.map(it=>ze(it,st.name))},Array.from(k.entries())),nt=Ct(P(q,"response","variants"),Dt,{comment:Z});return this.program.push(nt),Object.assign(z,{[q]:nt})},{});this.paths.add(y);let N=F(Z),U={input:f(T.name),positive:this.someOf(v.positive),negative:this.someOf(v.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,N),W(this.interfaces.negative,N)]),encoded:i.createIntersectionTypeNode([f(v.positive.name),f(v.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:U}),this.tags.set(Z,x.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:dr(r,t)).join(`
19
- `):void 0}print(t){let r=this.printUsage(t),o=r&&ot.default.addSyntheticLeadingComment(ot.default.addSyntheticLeadingComment(i.createEmptyStatement(),ot.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),ot.default.SyntaxKind.MultiLineCommentTrivia,`
20
- ${r}`);return this.program.concat(o||[]).map((n,s)=>dr(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
18
+ `))};var Oo=e=>{e.startupLogo!==!1&&So(process.stdout);let t=e.errorHandler||Ue,r=Gr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.13.0 (CJS)",env:process.env.NODE_ENV||"development"}),bo(r);let o=go({logger:r,config:e}),s={getLogger:ho(r),errorHandler:t},a=uo(s),c=lo(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Po=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Oo(e);return sr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},wo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Oo(e),c=(0,rt.default)().disable("x-powered-by").use(a);if(e.compression){let h=await Be("compression");c.use(h(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(),yo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await fo({config:e,getLogger:o}):[]};sr({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(h,x)=>()=>h.listen(x,()=>r.info("Listening",x)),b=[];if(e.http){let h=Ro.default.createServer(c);p.push(h),b.push(l(h,e.http.listen))}if(e.https){let h=To.default.createServer(e.https.options,c);p.push(h),b.push(l(h,e.https.listen))}return e.gracefulShutdown&&xo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(h=>h())}};var Vo=require("openapi3-ts/oas31"),Go=S(require("ramda"),1);var O=S(require("ramda"),1);var Ao=e=>Se(e)&&"or"in e,Eo=e=>Se(e)&&"and"in e,ir=e=>!Eo(e)&&!Ao(e),zo=e=>{let t=O.filter(ir,e),r=O.chain(O.prop("and"),O.filter(Eo,e)),[o,n]=O.partition(ir,r),s=O.concat(t,o),a=O.filter(Ao,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>xe(m,O.map(l=>ir(l)?[l]:l.and,p),([l,b])=>O.concat(l,b)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=S(require("ramda"),1),K=require("zod");var Ee=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ee(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 Io=["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 Zo=50,ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",kn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Cn=/^\d{4}-\d{2}-\d{2}$/,jn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Nn=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$/,Co=e=>e.replace(_t,t=>`{${t.slice(1)}}`),Ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Mn=({_def:{innerType:e}},{next:t})=>t(e),Un=()=>({format:"any"}),Dn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=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"}},Kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Fn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),qn=(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")},jo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(qn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>xe(e,t,([r,o])=>d.mergeDeepRight(r,o))},Bn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(jo)),d.isEmpty)),$n=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Bn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,jo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),_n=({_def:{left:e,right:t}},{next:r})=>$n([e,t].map(r)),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>t(e.unwrap()),Jn=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Lo(r)),r},No=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},vo=e=>({type:No(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Wn=({value:e})=>({type:No(e),const:e}),Yn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ge(c)?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},Qn=()=>({type:"null"}),Xn=({},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:ko}}},es=({},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:ko}}},ts=({},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)},rs=()=>({type:"boolean"}),os=()=>({type:"integer",format:"bigint"}),ns=e=>e.every(t=>t instanceof K.z.ZodLiteral),ss=({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&&ns(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",additionalProperties:r(t)}},is=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},as=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ps=({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:h,isTime:x,isBase64:y,isNANOID:j,isBase64url:P,isDuration:Q,_def:{checks:Z}})=>{let T=Z.find(k=>k.kind==="regex"),v=Z.find(k=>k.kind==="datetime"),N=Z.some(k=>k.kind==="jwt"),U=Z.find(k=>k.kind==="length"),z={type:"string"},q={"date-time":l,byte:y,base64url:P,date:h,time:x,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:j,jwt:N,ip:m,cidr:b,emoji:p};for(let k in q)if(q[k]){z.format=k;break}return U&&([z.minLength,z.maxLength]=[U.value,U.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),h&&(z.pattern=Cn.source),x&&(z.pattern=jn.source),l&&(z.pattern=Nn(v?.offset).source),T&&(z.pattern=T.regex.source),z},cs=({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(y=>y.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(y=>y.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,h=l?l.inclusive:!0,x={type:e?"integer":"number",format:e?"int64":"double"};return p?x.minimum=m:x.exclusiveMinimum=m,h?x.maximum=b:x.exclusiveMaximum=b,x},Et=({shape:e},t)=>d.map(t,e),ds=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return kn?.[t]},Lo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ms=(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=ut(e,ds(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},ls=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),us=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ys=(e,{next:t})=>t(e.unwrap().shape.raw),Mo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Uo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Mo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),gs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Mo)({schema:e,variant:"original",validate:!0,pullProps:!0}),hs=(e,t)=>t?.includes(e)||e.startsWith("x-")||Io.includes(e),Do=({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),h=mt(e),x=o.includes("query"),y=o.includes("params"),j=o.includes("headers"),P=T=>y&&h.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),Z=T=>j&&(c?.(T,t,e)??hs(T,Q));return Object.entries(b.shape).reduce((T,[v,N])=>{let U=P(v)?"path":Z(v)?"header":x?"query":void 0;if(!U)return T;let z=Ee(N,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(N,z,me(l,v)):z,{_def:k}=N;return T.concat({name:v,in:U,deprecated:k[g]?.isDeprecated,required:!N.isOptional(),description:z.description||l,schema:q,examples:gs(b,v)})},[])},ar={ZodString:ps,ZodNumber:cs,ZodBigInt:os,ZodBoolean:rs,ZodNull:Qn,ZodArray:is,ZodTuple:as,ZodRecord:ss,ZodObject:Yn,ZodLiteral:Wn,ZodIntersection:_n,ZodUnion:Kn,ZodAny:Un,ZodDefault:Ln,ZodEnum:vo,ZodNativeEnum:vo,ZodEffects:ms,ZodOptional:Vn,ZodNullable:Jn,ZodDiscriminatedUnion:Fn,ZodBranded:us,ZodDate:ts,ZodCatch:Mn,ZodPipeline:ls,ZodLazy:fs,ZodReadonly:Gn,[ee]:Hn,[Ce]:Dn,[Pe]:es,[Oe]:Xn,[le]:ys},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&&Ge(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[g]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=Lo(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},cr=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Ho=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Ho(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]},Ko=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Fo=({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 h=Ko(Ee(r,{rules:{...p,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,h,me(b)):h,examples:Uo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},bs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},xs=({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},Ss=({name:e})=>({type:"apiKey",in:"header",name:e}),Rs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ts=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Os=({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"?bs(o):o.type==="input"?xs(o,t):o.type==="header"?Ss(o):o.type==="cookie"?Rs(o):o.type==="openid"?Ts(o):Os(o);return e.map(o=>o.map(r))},Bo=(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:[]})},{})),$o=({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]=Ho(Ee(r,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),h=Ko(l),x={schema:s==="components"?n(r,h,me(p)):h,examples:Uo(G(r),!1,c)},y={description:p,content:{[o]:x}};return(b||St(r))&&(y.required=!0),y},_o=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<=Zo?e:e.slice(0,Zo-1)+"\u2026",zt=e=>e.length?e.slice():void 0;var It=class extends Vo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||me(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(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.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.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:h="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});$e({routing:t,onEndpoint:(y,j,P)=>{let Q={path:j,method:P,endpoint:y,composition:h,brandHandling:c,numericRange:l,makeRef:this.makeRef.bind(this)},[Z,T]=["short","long"].map(y.getDescription.bind(y)),v=Z?dr(Z):b&&T?dr(T):void 0,N=r.inputSources?.[P]||Vt[P],U=this.ensureUniqOperationId(j,P,y.getOperationId(P)),z=zo(y.getSecurity()),q=Do({...Q,inputSources:N,isHeader:p,security:z,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:P,path:j,operationId:U})}),k={};for(let ie of Me){let he=y.getResponses(ie);for(let{mimeTypes:qt,schema:at,statusCodes:pt}of he)for(let Bt of pt)k[Bt]=Fo({...Q,variant:ie,schema:at,mimeTypes:qt,statusCode:Bt,hasMultipleStatusCodes:he.length>1||pt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:P,path:j,operationId:U,statusCode:Bt})})}let Kt=N.includes("body")?$o({...Q,paramNames:Go.pluck("name",q),schema:y.getSchema("input"),mimeType:C[y.getRequestType()],description:a?.requestBody?.call(null,{method:P,path:j,operationId:U})}):void 0,it=Bo(qo(z,N),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),Ft={operationId:U,summary:v,description:T,deprecated:y.isDeprecated||void 0,tags:zt(y.getTags()),parameters:zt(q),requestBody:Kt,security:zt(it),responses:k};this.addPath(Co(j),{[P]:Ft})}}),m&&(this.rootDoc.tags=_o(m))}};var Zt=require("node-mocks-http"),Ps=e=>(0,Zt.createRequest)({...e,headers:{"content-type":C.json,...e?.headers}}),ws=e=>(0,Zt.createResponse)(e),As=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Jr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ps(e),s=ws({req:n,...t});s.req=t?.req||n,n.res=s;let a=As(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Wo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Yo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Jo(o),m=lt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:m,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(de(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var nn=S(require("ramda"),1),st=S(require("typescript"),1),sn=require("zod");var rn=S(require("ramda"),1),Y=S(require("typescript"),1);var Qo=["get","post","put","delete","patch"];var re=S(require("ramda"),1),u=S(require("typescript"),1),i=u.default.factory,vt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Es=[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)},zs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ur=e=>typeof e=="string"&&zs.test(e)?i.createIdentifier(e):E(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),_e=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]),ze=(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))),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)),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},Xo=(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)}),Ie=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Es:void 0,void 0,Array.isArray(e)?re.map(Ct,e):_e(e),void 0,void 0,t),w=e=>e,nt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),A=(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),Ve=(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)),en=e=>i.createUnionTypeNode([f(e),jt(e)]),Pr=(e,t)=>i.createFunctionTypeNode(void 0,_e(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),F=e=>i.createLiteralTypeNode(E(e)),Is=[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],tn=e=>Is.includes(e.kind);var Mt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={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",Qo);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.ids.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}])=>ze(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(ur(t),i.createArrayLiteralExpression(rn.map(E,r))))),{expose:!0});makeImplementationType=()=>oe(this.ids.implementationType,Pr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:yr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},jt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.ids.parseRequestFn,Ie({[this.ids.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(A(this.ids.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>M(this.ids.substituteFn,Ie({[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:yr},i.createBlock([M(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],Y.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([Or(this.ids.pathParameter,A(this.ids.pathParameter,w("replace"))(kt(":",[this.ids.keyParameter]),Ie([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),f("const")))])));makeProvider=()=>xr(this.ids.provideMethod,_e({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:W(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[M(hr(this.ids.methodParameter,this.ids.pathParameter),A(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(A(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(A(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:jt(W(this.interfaces.response,"K"))});makeClientClass=t=>Sr(t,[fr([Ct(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:ot.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>kt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,kt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.ids.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),nt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(C.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(w("body"),nt(this.ids.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=M(this.ids.responseConst,i.createAwaitExpression(A(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=M(this.ids.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.ids.methodParameter))),a=M(this.ids.searchParamsConst,nt(this.ids.hasBodyConst,E(""),this.makeSearchParams(this.ids.paramsArgument))),c=M(this.ids.contentTypeConst,A(this.ids.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=M(this.ids.isJsonConst,A(this.ids.contentTypeConst,w("startsWith"))(E(C.json))),l=i.createReturnStatement(A(this.ids.responseConst,nt(this.ids.isJsonConst,E(w("json")),E(w("text"))))());return M(this.ids.defaultImplementationConst,Ie([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>fr(_e({request:"K",params:W(this.interfaces.input,"K")}),[M(hr(this.ids.pathParameter,this.ids.restConst),A(this.ids.substituteFn)(i.createElementAccessExpression(A(this.ids.parseRequestFn)(this.ids.requestParameter),E(1)),this.ids.paramsArgument)),M(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),Or(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ze(w("event"),t)]);makeOnMethod=()=>xr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Pr({[this.ids.dataParameter.text]:W(Lt("R",gr(this.makeEventNarrow("E"))),F(w("data")))},en(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.ids.sourceProp,w("addEventListener"))(this.ids.eventParameter,Ie([this.ids.msgParameter],A(this.ids.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(w("event")))}});makeSubscriptionClass=t=>Sr(t,[Xo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{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.makeEventNarrow(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.ids.clientConst,Ve(t)),A(this.ids.clientConst,this.ids.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(Ve(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(E("time"),Ie(["time"],i.createBlock([])))]};var I=S(require("ramda"),1),R=S(require("typescript"),1),Ut=require("zod");var{factory:_}=R.default,Zs={[R.default.SyntaxKind.AnyKeyword]:"",[R.default.SyntaxKind.BigIntKeyword]:BigInt(0),[R.default.SyntaxKind.BooleanKeyword]:!1,[R.default.SyntaxKind.NumberKeyword]:0,[R.default.SyntaxKind.ObjectKeyword]:{},[R.default.SyntaxKind.StringKeyword]:"",[R.default.SyntaxKind.UndefinedKeyword]:void 0},wr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},vs=({value:e})=>F(e),ks=({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&&Ge(a)?a instanceof Ut.z.ZodOptional:a.isOptional();return ze(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return _.createTypeLiteralNode(n)},Cs=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),js=({options:e})=>_.createUnionTypeNode(e.map(F)),on=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(tn(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},Ns=e=>Zs?.[e.kind],Ls=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ut(e,Ns(o)),s={number:R.default.SyntaxKind.NumberKeyword,bigint:R.default.SyntaxKind.BigIntKeyword,boolean:R.default.SyntaxKind.BooleanKeyword,string:R.default.SyntaxKind.StringKeyword,undefined:R.default.SyntaxKind.UndefinedKeyword,object:R.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||R.default.SyntaxKind.AnyKeyword)}return o},Ms=e=>_.createUnionTypeNode(Object.values(e.enum).map(F)),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(R.default.SyntaxKind.UndefinedKeyword)]):o},Ds=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),F(null)]),Hs=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),Ks=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Fs=I.tryCatch(e=>{if(!e.every(R.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(wr.name,...o))return!1;if(I.both(I.eqBy(wr.type),I.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),qs=({_def:{left:e,right:t}},{next:r})=>Fs([e,t].map(r)),Bs=({_def:e},{next:t})=>t(e.innerType),ge=e=>()=>f(e),$s=(e,{next:t})=>t(e.unwrap()),_s=(e,{next:t})=>t(e.unwrap()),Vs=({_def:e},{next:t})=>t(e.innerType),Gs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Js=()=>F(null),Ws=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ys=e=>{let t=e.unwrap(),r=f(R.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Ut.z.ZodString?r:t instanceof Ut.z.ZodUnion?n:o},Qs=(e,{next:t})=>t(e.unwrap().shape.raw),Xs={ZodString:ge(R.default.SyntaxKind.StringKeyword),ZodNumber:ge(R.default.SyntaxKind.NumberKeyword),ZodBigInt:ge(R.default.SyntaxKind.BigIntKeyword),ZodBoolean:ge(R.default.SyntaxKind.BooleanKeyword),ZodAny:ge(R.default.SyntaxKind.AnyKeyword),ZodUndefined:ge(R.default.SyntaxKind.UndefinedKeyword),[Oe]:ge(R.default.SyntaxKind.StringKeyword),[Pe]:ge(R.default.SyntaxKind.StringKeyword),ZodNull:Js,ZodArray:Cs,ZodTuple:Hs,ZodRecord:Ks,ZodObject:ks,ZodLiteral:vs,ZodIntersection:qs,ZodUnion:on,ZodDefault:Bs,ZodEnum:js,ZodNativeEnum:Ms,ZodEffects:Ls,ZodOptional:Us,ZodNullable:Ds,ZodDiscriminatedUnion:on,ZodBranded:$s,ZodCatch:Vs,ZodPipeline:Gs,ZodLazy:Ws,ZodReadonly:_s,[ee]:Ys,[le]:Qs},Ar=(e,{brandHandling:t,ctx:r})=>Ee(e,{rules:{...t,...Xs},onMissing:()=>f(R.default.SyntaxKind.AnyKeyword),ctx:r});var Dt=class extends Mt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=F(null);this.aliases.set(t,oe(o,n)),this.aliases.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=sn.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};$e({routing:t,onEndpoint:(x,y,j)=>{let P=me.bind(null,j,y),{isDeprecated:Q}=x,Z=`${j} ${y}`,T=oe(P("input"),Ar(x.getSchema("input"),l),{comment:Z});this.program.push(T);let v=Me.reduce((z,q)=>{let k=x.getResponses(q),Kt=nn.chain(([Ft,{schema:ie,mimeTypes:he,statusCodes:qt}])=>{let at=oe(P(q,"variant",`${Ft+1}`),Ar(he?ie:m,b),{comment:Z});return this.program.push(at),qt.map(pt=>ze(pt,at.name))},Array.from(k.entries())),it=Nt(P(q,"response","variants"),Kt,{comment:Z});return this.program.push(it),Object.assign(z,{[q]:it})},{});this.paths.add(y);let N=F(Z),U={input:f(T.name),positive:this.someOf(v.positive),negative:this.someOf(v.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,N),W(this.interfaces.negative,N)]),encoded:i.createIntersectionTypeNode([f(v.positive.name),f(v.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:U}),this.tags.set(Z,x.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:lr(r,t)).join(`
19
+ `):void 0}print(t){let r=this.printUsage(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.program.concat(o||[]).map((n,s)=>lr(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
22
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Be("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};var Ze=require("zod");var on=(e,t)=>Ze.z.object({data:t,event:Ze.z.literal(e),id:Ze.z.string().optional(),retry:Ze.z.number().int().positive().optional()}),Ws=(e,t,r)=>on(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),Ys=1e4,rn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":C.sse,"cache-control":"no-cache"}),Qs=e=>new V({handler:async({response:t})=>setTimeout(()=>rn(t),Ys)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{rn(t),t.write(Ws(e,r,o),"utf-8"),t.flush?.()}}}),Xs=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>on(o,n));return{mimeType:C.sse,schema:r.length?Ze.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=we(r);Qe(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(Ae(a),"utf-8")}t.end()}}),Ut=class extends ye{constructor(t){super(Xs(t)),this.middlewares=[Qs(t)]}};var nn={dateIn:zr,dateOut:Zr,file:ft,upload:Nr,raw:Cr};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 Be("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};var Ze=require("zod");var pn=(e,t)=>Ze.z.object({data:t,event:Ze.z.literal(e),id:Ze.z.string().optional(),retry:Ze.z.number().int().positive().optional()}),ei=(e,t,r)=>pn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),ti=1e4,an=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":C.sse,"cache-control":"no-cache"}),ri=e=>new V({handler:async({response:t})=>setTimeout(()=>an(t),ti)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{an(t),t.write(ei(e,r,o),"utf-8"),t.flush?.()}}}),oi=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>pn(o,n));return{mimeType:C.sse,schema:r.length?Ze.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=we(r);Xe(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(Ae(a),"utf-8")}t.end()}}),Ht=class extends ye{constructor(t){super(oi(t)),this.middlewares=[ri(t)]}};var cn={dateIn:Zr,dateOut:kr,form:jr,file:gt,upload:Ur,raw:Lr};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});