express-zod-api 26.0.0-beta.2 → 26.1.0-beta.1

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,30 +2,40 @@
2
2
 
3
3
  ## Version 26
4
4
 
5
+ ### v26.1.0
6
+
7
+ - Optimization to the memory consumption for your API:
8
+ - It has been discovered that static import of `typescript` within the framework consumes memory unnecessarily;
9
+ - Importing `typescript` is only necessary to generate an Integration;
10
+ - This version avoids static importing, but the solution is temporary in order to avoid breaking changes;
11
+ - The issue was found, investigated and reported by [@NicolasMahe](https://github.com/NicolasMahe).
12
+
5
13
  ### v26.0.0
6
14
 
15
+ - Supported `http-errors` versions: `^2.0.1`;
7
16
  - Supported `zod` versions: `^4.1.13`:
8
17
  - This Zod patch contains an [important fix](https://github.com/colinhacks/zod/pull/5452) that makes the
9
- `globalRegistry` really global across both CJS and ESM bundles of Zod distribution;
18
+ `globalRegistry` truly global across both CJS and ESM bundles of the Zod distribution;
10
19
  - The issue was found and reported by [@shadone](https://github.com/shadone);
11
- - New version of Zod plugin now also extends the CJS exports of Zod:
12
- - This fixes the "TypeError: example is not a function" in CJS and removes the requirement to use ESM environment;
13
- - The issue reported by [@squishykid](https://github.com/squishykid), and addressed earlier in [v25.5.3](#v2553);
20
+ - The new version of the Zod plugin now also extends the CJS exports of Zod:
21
+ - This fixes the "TypeError: example is not a function" in CJS and removes the requirement to use an ESM environment;
22
+ - The issue was reported by [@squishykid](https://github.com/squishykid) and addressed earlier in [v25.5.3](#v2553);
14
23
  - `DependsOnMethod` removed:
15
24
  - You can now specify methods as direct keys of an assigned object in `Routing`;
16
25
  - That object can still contain nested paths as before;
17
- - The keys matching lowercase HTTP methods are treated according to the new config setting `methodLikeRouteBehavior`:
18
- - `method` — when assigned with an Endpoint the key is treated as method of its parent path (default);
26
+ - Keys matching lowercase HTTP methods are treated according to the new config setting `methodLikeRouteBehavior`:
27
+ - `method` — when assigned with an Endpoint, the key is treated as a method of its parent path (default);
19
28
  - `path` — the key is always treated as a nested path segment;
20
- - `options` property renamed to `ctx` in argument of:
29
+ - The `options` property has been renamed to `ctx` in the argument of:
21
30
  - `Middleware::handler()`,
22
31
  - `ResultHandler::handler()`,
23
- - `handler` of `EndpointsFactory::build()` argument,
32
+ - The `handler` of the `EndpointsFactory::build()` argument,
24
33
  - `testMiddleware()`;
25
34
  - `EndpointsFactory::addOptions()` renamed to `addContext()`;
26
- - The `Integration::constructor()` argument object now requires `config` property, similar to `Documentation`;
35
+ - The `Integration::constructor()` argument object now requires a `config` property, similar to `Documentation`;
36
+ - Consider [the automated migration](https://www.npmjs.com/package/@express-zod-api/migration).
27
37
 
28
- ```patch
38
+ ```diff
29
39
  const routing: Routing = {
30
40
  - "/v1/users": new DependsOnMethod({
31
41
  + "/v1/users": {
@@ -39,6 +49,10 @@
39
49
 
40
50
  ## Version 25
41
51
 
52
+ ### v25.6.1
53
+
54
+ - Technical update before v26: no significant changes.
55
+
42
56
  ### v25.6.0
43
57
 
44
58
  - Added `afterRouting` hook to server configuration:
package/README.md CHANGED
@@ -59,8 +59,7 @@ Start your API server with I/O schema validation and custom middlewares in minut
59
59
  5. [Graceful shutdown](#graceful-shutdown)
60
60
  6. [Subscriptions](#subscriptions)
61
61
  8. [Caveats](#caveats)
62
- 1. [TypeError: example is not a function](#typeerror-example-is-not-a-function)
63
- 2. [Excessive properties in endpoint output](#excessive-properties-in-endpoint-output)
62
+ 1. [Excessive properties in endpoint output](#excessive-properties-in-endpoint-output)
64
63
  9. [Your input to my output](#your-input-to-my-output)
65
64
 
66
65
  See also [Changelog](CHANGELOG.md) and [automated migration](https://www.npmjs.com/package/@express-zod-api/migration).
@@ -86,6 +85,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
86
85
 
87
86
  These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
88
87
 
88
+ [<img src="https://github.com/NicolasMahe.png" alt="@NicolasMahe" width="50" />](https://github.com/NicolasMahe)
89
89
  [<img src="https://github.com/shadone.png" alt="@shadone" width="50" />](https://github.com/shadone)
90
90
  [<img src="https://github.com/squishykid.png" alt="@squishykid" width="50" />](https://github.com/squishykid)
91
91
  [<img src="https://github.com/jakub-msqt.png" alt="@jakub-msqt" width="50" />](https://github.com/jakub-msqt)
package/SECURITY.md CHANGED
@@ -4,11 +4,12 @@
4
4
 
5
5
  | Version | Code name | Release | Supported |
6
6
  | ------: | :------------ | :------ | :----------------: |
7
+ | 26.x.x | Lia | 12.2025 | :white_check_mark: |
7
8
  | 25.x.x | Sara | 08.2025 | :white_check_mark: |
8
9
  | 24.x.x | Ashley | 06.2025 | :white_check_mark: |
9
10
  | 23.x.x | Sonia | 04.2025 | :white_check_mark: |
10
11
  | 22.x.x | Tai | 01.2025 | :white_check_mark: |
11
- | 21.x.x | Kesaria | 11.2024 | :white_check_mark: |
12
+ | 21.x.x | Kesaria | 11.2024 | :x: |
12
13
  | 20.x.x | Zoey | 06.2024 | :x: |
13
14
  | 19.x.x | Dime | 05.2024 | :x: |
14
15
  | 18.x.x | Victoria | 04.2024 | :x: |
package/dist/index.d.ts CHANGED
@@ -37,8 +37,8 @@ type ClientMethod = (typeof clientMethods)[number];
37
37
  //#endregion
38
38
  //#region src/api-response.d.ts
39
39
  /** @public this is the user facing configuration */
40
- interface ApiResponse<S$1 extends z.ZodType> {
41
- schema: S$1;
40
+ interface ApiResponse<S extends z.ZodType> {
41
+ schema: S;
42
42
  /** @default 200 for a positive and 400 for a negative response */
43
43
  statusCode?: number | [number, ...number[]];
44
44
  /**
@@ -209,24 +209,24 @@ interface Scopes<K$1 extends string> {
209
209
  /** @desc The available scopes for the OAuth2 security and their short descriptions. Optional. */
210
210
  scopes?: Record<K$1, string>;
211
211
  }
212
- type AuthCodeFlow<S$1 extends string> = AuthUrl & TokenUrl & RefreshUrl & Scopes<S$1>;
213
- type ImplicitFlow<S$1 extends string> = AuthUrl & RefreshUrl & Scopes<S$1>;
214
- type PasswordFlow<S$1 extends string> = TokenUrl & RefreshUrl & Scopes<S$1>;
215
- type ClientCredFlow<S$1 extends string> = TokenUrl & RefreshUrl & Scopes<S$1>;
212
+ type AuthCodeFlow<S extends string> = AuthUrl & TokenUrl & RefreshUrl & Scopes<S>;
213
+ type ImplicitFlow<S extends string> = AuthUrl & RefreshUrl & Scopes<S>;
214
+ type PasswordFlow<S extends string> = TokenUrl & RefreshUrl & Scopes<S>;
215
+ type ClientCredFlow<S extends string> = TokenUrl & RefreshUrl & Scopes<S>;
216
216
  /**
217
217
  * @see https://swagger.io/docs/specification/authentication/oauth2/
218
218
  */
219
- interface OAuth2Security<S$1 extends string> {
219
+ interface OAuth2Security<S extends string> {
220
220
  type: "oauth2";
221
221
  flows?: {
222
222
  /** @desc Authorization Code flow (previously called accessCode in OpenAPI 2.0) */
223
- authorizationCode?: AuthCodeFlow<S$1>;
223
+ authorizationCode?: AuthCodeFlow<S>;
224
224
  /** @desc Implicit flow */
225
- implicit?: ImplicitFlow<S$1>;
225
+ implicit?: ImplicitFlow<S>;
226
226
  /** @desc Resource Owner Password flow */
227
- password?: PasswordFlow<S$1>;
227
+ password?: PasswordFlow<S>;
228
228
  /** @desc Client Credentials flow (previously called application in OpenAPI 2.0) */
229
- clientCredentials?: ClientCredFlow<S$1>;
229
+ clientCredentials?: ClientCredFlow<S>;
230
230
  };
231
231
  }
232
232
  /**
@@ -234,7 +234,7 @@ interface OAuth2Security<S$1 extends string> {
234
234
  * @param K is an optional input field used by InputSecurity
235
235
  * @param S is an optional union of scopes used by OAuth2Security
236
236
  * */
237
- type Security<K$1 extends string = string, S$1 extends string = string> = BasicSecurity | BearerSecurity | InputSecurity<K$1> | HeaderSecurity | CookieSecurity | OpenIdSecurity | OAuth2Security<S$1>;
237
+ type Security<K$1 extends string = string, S extends string = string> = BasicSecurity | BearerSecurity | InputSecurity<K$1> | HeaderSecurity | CookieSecurity | OpenIdSecurity | OAuth2Security<S>;
238
238
  //#endregion
239
239
  //#region src/middleware.d.ts
240
240
  type Handler$2<IN, CTX, RET> = (params: {
@@ -291,12 +291,12 @@ declare class Middleware<CTX extends FlatObject, RET extends FlatObject, SCO ext
291
291
  logger: ActualLogger;
292
292
  }): Promise<RET>;
293
293
  }
294
- declare class ExpressMiddleware<R extends Request, S$1 extends Response, RET extends FlatObject> extends Middleware<FlatObject, RET, string> {
295
- constructor(nativeMw: (request: R, response: S$1, next: NextFunction) => any, {
294
+ declare class ExpressMiddleware<R extends Request, S extends Response, RET extends FlatObject> extends Middleware<FlatObject, RET, string> {
295
+ constructor(nativeMw: (request: R, response: S, next: NextFunction) => any, {
296
296
  provider,
297
297
  transformer
298
298
  }?: {
299
- provider?: (request: R, response: S$1) => RET | Promise<RET>;
299
+ provider?: (request: R, response: S) => RET | Promise<RET>;
300
300
  transformer?: (err: Error) => Error;
301
301
  });
302
302
  }
@@ -326,7 +326,7 @@ type Handler$1<RES = unknown> = (params: DiscriminatedResult & {
326
326
  response: Response<RES>;
327
327
  logger: ActualLogger;
328
328
  }) => void | Promise<void>;
329
- type Result<S$1 extends z.ZodType = z.ZodType> = S$1 | ApiResponse<S$1> | ApiResponse<S$1>[];
329
+ type Result<S extends z.ZodType = z.ZodType> = S | ApiResponse<S> | ApiResponse<S>[];
330
330
  type LazyResult<R extends Result, A extends unknown[] = []> = (...args: A) => R;
331
331
  declare abstract class AbstractResultHandler {
332
332
  #private;
@@ -668,11 +668,11 @@ declare class EndpointsFactory<IN extends IOSchema | undefined = undefined, CTX
668
668
  protected middlewares: AbstractMiddleware[];
669
669
  constructor(resultHandler: AbstractResultHandler);
670
670
  addMiddleware<RET extends FlatObject, ASCO extends string, AIN extends IOSchema | undefined = undefined>(subject: Middleware<CTX, RET, ASCO, AIN> | ConstructorParameters<typeof Middleware<CTX, RET, ASCO, AIN>>[0]): EndpointsFactory<Extension<IN, AIN>, CTX & RET, SCO & ASCO>;
671
- use: <R extends Request, S$1 extends Response, AOUT extends FlatObject = Record<string, never>>(nativeMw: (request: R, response: S$1, next: express0.NextFunction) => any, params_1?: {
672
- provider?: ((request: R, response: S$1) => AOUT | Promise<AOUT>) | undefined;
671
+ use: <R extends Request, S extends Response, AOUT extends FlatObject = Record<string, never>>(nativeMw: (request: R, response: S, next: express0.NextFunction) => any, params_1?: {
672
+ provider?: ((request: R, response: S) => AOUT | Promise<AOUT>) | undefined;
673
673
  transformer?: (err: Error) => Error;
674
674
  } | undefined) => EndpointsFactory<Extension<IN, undefined>, CTX & AOUT, SCO>;
675
- addExpressMiddleware<R extends Request, S$1 extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S$1, AOUT>>): EndpointsFactory<Extension<IN, undefined>, CTX & AOUT, SCO>;
675
+ addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<Extension<IN, undefined>, CTX & AOUT, SCO>;
676
676
  addContext<RET extends FlatObject>(getContext: () => Promise<RET>): EndpointsFactory<Extension<IN, undefined>, CTX & RET, SCO>;
677
677
  build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({
678
678
  input,
@@ -752,7 +752,6 @@ interface DocumentationParams {
752
752
  /**
753
753
  * @desc Depict the HEAD method for each Endpoint supporting the GET method (feature of Express)
754
754
  * @default true
755
- * @todo move to config
756
755
  * */
757
756
  hasHeadMethod?: boolean;
758
757
  /** @default inline */
@@ -893,8 +892,14 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
893
892
  output: FlatObject;
894
893
  }>;
895
894
  //#endregion
895
+ //#region src/typescript-api.d.ts
896
+ declare class TypescriptAPI {
897
+ #private;
898
+ constructor();
899
+ }
900
+ //#endregion
896
901
  //#region src/integration-base.d.ts
897
- declare abstract class IntegrationBase {
902
+ declare abstract class IntegrationBase extends TypescriptAPI {
898
903
  #private;
899
904
  private readonly serverUrl;
900
905
  protected constructor(serverUrl: string);
@@ -916,6 +921,7 @@ type HandlingRules<U, Context$1 extends FlatObject = EmptyObject, K$1 extends st
916
921
  interface ZTSContext extends FlatObject {
917
922
  isResponse: boolean;
918
923
  makeAlias: (key: object, produce: () => ts.TypeNode) => ts.TypeNode;
924
+ api: TypescriptAPI;
919
925
  }
920
926
  type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
921
927
  //#endregion
@@ -947,7 +953,6 @@ interface IntegrationParams {
947
953
  /**
948
954
  * @desc Depict the HEAD method for each Endpoint supporting the GET method (feature of Express)
949
955
  * @default true
950
- * @todo move to config
951
956
  * */
952
957
  hasHeadMethod?: boolean;
953
958
  /**
@@ -1016,13 +1021,13 @@ declare const base: z.ZodObject<{
1016
1021
  raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
1017
1022
  }, z.core.$strip>;
1018
1023
  type Base = ReturnType<typeof base.brand<symbol>>;
1019
- declare const extended: <S$1 extends z.core.$ZodShape>(extra: S$1) => z.core.$ZodBranded<z.ZodObject<("raw" & keyof S$1 extends never ? {
1024
+ declare const extended: <S extends z.core.$ZodShape>(extra: S) => z.core.$ZodBranded<z.ZodObject<("raw" & keyof S extends never ? {
1020
1025
  raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
1021
- } & S$1 : ({
1026
+ } & S : ({
1022
1027
  raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
1023
- } extends infer T_1 extends z.core.util.SomeObject ? { [K in keyof T_1 as K extends keyof S$1 ? never : K]: T_1[K] } : never) & { [K_1 in keyof S$1]: S$1[K_1] }) extends infer T ? { [k in keyof T]: T[k] } : never, z.core.$strip>, symbol>;
1028
+ } extends infer T_1 extends z.core.util.SomeObject ? { [K in keyof T_1 as K extends keyof S ? never : K]: T_1[K] } : never) & { [K_1 in keyof S]: S[K_1] }) extends infer T ? { [k in keyof T]: T[k] } : never, z.core.$strip>, symbol>;
1024
1029
  declare function raw(): Base;
1025
- declare function raw<S$1 extends z.core.$ZodShape>(extra: S$1): ReturnType<typeof extended<S$1>>;
1030
+ declare function raw<S extends z.core.$ZodShape>(extra: S): ReturnType<typeof extended<S>>;
1026
1031
  //#endregion
1027
1032
  //#region src/proprietary-schemas.d.ts
1028
1033
  declare const ez: {
@@ -1031,7 +1036,7 @@ declare const ez: {
1031
1036
  ...rest
1032
1037
  }?: DateInParams) => zod_v4_core0.$ZodBranded<zod0.ZodPipe<zod0.ZodPipe<zod0.ZodUnion<readonly [zod0.ZodISODate, zod0.ZodISODateTime, zod0.ZodISODateTime]>, zod0.ZodTransform<Date, string>>, zod0.ZodDate>, symbol>;
1033
1038
  dateOut: (meta?: DateOutParams) => zod_v4_core0.$ZodBranded<zod0.ZodPipe<zod0.ZodDate, zod0.ZodTransform<string, Date>>, symbol>;
1034
- form: <S$1 extends zod_v4_core0.$ZodShape>(base: S$1 | zod0.ZodObject<S$1>) => zod_v4_core0.$ZodBranded<zod0.ZodObject<S$1, zod_v4_core0.$strip>, symbol>;
1039
+ form: <S extends zod_v4_core0.$ZodShape>(base: S | zod0.ZodObject<S>) => zod_v4_core0.$ZodBranded<zod0.ZodObject<S, zod_v4_core0.$strip>, symbol>;
1035
1040
  upload: () => zod_v4_core0.$ZodBranded<zod0.ZodCustom<express_fileupload0.UploadedFile, express_fileupload0.UploadedFile>, symbol>;
1036
1041
  raw: typeof raw;
1037
1042
  buffer: () => zod_v4_core0.$ZodBranded<zod0.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import{getBrand as e}from"@express-zod-api/zod-plugin";import*as t from"ramda";import{globalRegistry as n,z as r}from"zod";import i,{isHttpError as a}from"http-errors";import o,{blue as s,cyanBright as c,gray as l,green as u,hex as d,italic as f,red as p,whiteBright as m}from"ansis";import{inspect as ee}from"node:util";import{performance as h}from"node:perf_hooks";import g from"express";import te from"node:http";import ne from"node:https";import{setInterval as re}from"node:timers/promises";import{OpenApiBuilder as ie,isReferenceObject as ae,isSchemaObject as _}from"openapi3-ts/oas31";import{createRequest as oe,createResponse as se}from"node-mocks-http";import v from"typescript";function ce(e){return e}const y={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},le=[`get`,`post`,`put`,`delete`,`patch`],ue=[...le,`head`],b=e=>le.includes(e),de=r.object({}),fe=/:([A-Za-z0-9_]+)/g,pe=e=>e.match(fe)?.map(e=>e.slice(1))||[],me=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(y.upload);return`files`in e&&t},he={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`]},ge=[`body`,`query`,`params`],_e=e=>e.method.toLowerCase(),ve=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:b(e)?e:void 0;return(n?t[n]||he[n]:void 0)||ge},ye=(e,t={})=>ve(_e(e),t).filter(t=>t===`files`?me(e):!0).reduce((t,n)=>Object.assign(t,e[n]),{}),x=e=>e instanceof Error?e:e instanceof r.ZodError?new r.ZodRealError(e.issues):Error(String(e)),S=e=>e instanceof r.ZodError?e.issues.map(({path:e,message:t})=>`${e.length?`${r.core.toDotPath(e)}: `:``}${t}`).join(`; `):e.message,C=(e,n)=>T(e)&&`_zod`in e&&(n?t.path([`_zod`,`def`,`type`],e)===n:!0),be=(e,n,r)=>e.length&&n.length?t.xprod(e,n).map(r):e.concat(n),xe=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),w=(...e)=>{let n=t.chain(e=>e.split(/[^A-Z0-9]/gi),e);return t.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),n).map(xe).join(``)},Se=t.tryCatch((e,t)=>typeof r.parse(e,t),t.always(void 0)),T=e=>typeof e==`object`&&!!e,Ce=t.memoizeWith(()=>`static`,()=>process.env.NODE_ENV===`production`),we=(e,t)=>!!t&&e!==`head`,E=Symbol(`Buffer`),Te=()=>r.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).brand(E),D=Symbol(`DateIn`),Ee=({examples:e,...t}={})=>r.union([r.iso.date(),r.iso.datetime(),r.iso.datetime({local:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(r.date()).brand(D).meta(t),O=Symbol(`DateOut`),De=(e={})=>r.date().transform(e=>e.toISOString()).brand(O).meta(e);var k=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},A=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},Oe=class extends Error{name=`IOSchemaError`},ke=class extends Oe{name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},Ae=class extends Oe{name=`OutputValidationError`;constructor(e){let t=new r.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(S(t),{cause:e}),this.cause=e}},j=class extends Oe{name=`InputValidationError`;constructor(e){super(S(e),{cause:e}),this.cause=e}},je=class extends Error{name=`ResultHandlerError`;constructor(e,t){super(S(e),{cause:e}),this.cause=e,this.handled=t}},Me=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const Ne=Symbol(`Form`),Pe=e=>(e instanceof r.ZodObject?e:r.object(e)).brand(Ne),M=Symbol(`Upload`),Fe=()=>r.custom(e=>typeof e==`object`&&!!e&&`name`in e&&`encoding`in e&&`mimetype`in e&&`data`in e&&`tempFilePath`in e&&`truncated`in e&&`size`in e&&`md5`in e&&`mv`in e&&typeof e.name==`string`&&typeof e.encoding==`string`&&typeof e.mimetype==`string`&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath==`string`&&typeof e.truncated==`boolean`&&typeof e.size==`number`&&typeof e.md5==`string`&&typeof e.mv==`function`,{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(M),N=Symbol(`Raw`),Ie=r.object({raw:Te()}),Le=e=>Ie.extend(e).brand(N);function Re(e){return e?Le(e):Ie.brand(N)}const ze=(e,{io:n,condition:i})=>t.tryCatch(()=>void r.toJSONSchema(e,{io:n,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new ke(e)}}),e=>e.cause)(),Be=(e,{io:n})=>{let i=[r.toJSONSchema(e,{io:n,unrepresentable:`any`})];for(;i.length;){let e=i.shift();if(t.is(Object,e)){if(e.$ref===`#`)return!0;i.push(...t.values(e))}t.is(Array,e)&&i.push(...t.values(e))}return!1},Ve=t=>ze(t,{condition:t=>{let n=e(t);return typeof n==`symbol`&&[M,N,Ne].includes(n)},io:`input`}),He=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`],Ue=(t,n)=>ze(t,{io:n,condition:t=>{let r=e(t),{type:i}=t._zod.def;return!!(He.includes(i)||r===E||n===`input`&&(i===`date`||r===O)||n===`output`&&(r===D||r===N||r===M))}}),We=(e,{variant:t,args:n,...i})=>{if(typeof e==`function`&&(e=e(...n)),e instanceof r.ZodType)return[{schema:e,...i}];if(Array.isArray(e)&&!e.length)throw new je(Error(`At least one ${t} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||i.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?i.mimeTypes:n}))},Ge=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),Ke=e=>a(e)?e:i(e instanceof j?400:500,S(e),{cause:e.cause||e}),qe=e=>Ce()&&!e.expose?i(e.statusCode).message:e.message,Je=e=>Object.entries(e._zod.def.shape).reduce((e,[r,i])=>{let{examples:a=[]}=n.get(i)||{};return be(e,a.map(t.objOf(r)),([e,t])=>({...e,...t}))},[]),Ye=({error:e,logger:t,response:n})=>{t.error(`Result handler failure`,e);let r=qe(i(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`\nOriginal error: ${e.handled.message}.`:``),{expose:a(e.cause)?e.cause.expose:!1}));n.status(500).type(`text/plain`).end(r)};var Xe=class{},P=class extends Xe{#e;#t;#n;constructor({input:e,security:t,handler:n}){super(),this.#e=e,this.#t=t,this.#n=n}get security(){return this.#t}get schema(){return this.#e}async execute({input:e,...t}){try{let n=await(this.#e||de).parseAsync(e);return this.#n({...t,input:n})}catch(e){throw e instanceof r.ZodError?new j(e):e}}},Ze=class extends P{constructor(e,{provider:t=()=>({}),transformer:n=e=>e}={}){super({handler:async({request:r,response:i})=>new Promise((a,o)=>{let s=e=>{if(e&&e instanceof Error)return o(n(e));a(t(r,i))};e(r,i,s)?.catch(s)})})}},Qe=class{nest(e){return{...e,"":this}}},$e=class i extends Qe{#e;#t=t.once(()=>{if(n.get(this.#e.outputSchema)?.examples?.length||!C(this.#e.outputSchema,`object`))return;let e=Je(this.#e.outputSchema);if(!e.length)return;let t=this.#e.outputSchema.meta();n.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...t,examples:e})});constructor(e){super(),this.#e=e}#n(e){return new i({...this.#e,...e})}deprecated(){return this.#n({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Ve(this.#e.inputSchema);if(t){let n=e(t);if(n===M)return`upload`;if(n===N)return`raw`;if(n===Ne)return`form`}return`json`}getResponses(e){return e===`positive`&&this.#t(),Object.freeze(e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let e=t.pluck(`security`,this.#e.middlewares||[]);return t.reject(t.isNil,e)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(e){return this.#e.getOperationId?.(e)}async#r(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof r.ZodError?new Ae(e):e}}async#i({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof Ze))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#a({input:e,...t}){let n;try{n=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof r.ZodError?new j(e):e}return this.#e.handler({...t,input:n})}async#o(e){try{await this.#e.resultHandler.execute(e)}catch(t){Ye({...e,error:new je(x(t),e.error||void 0)})}}async execute({request:e,response:t,logger:n,config:r}){let i=_e(e),a={},o={output:{},error:null},s=ye(e,r.inputSources);try{if(await this.#i({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();o={output:await this.#r(await this.#a({input:s,logger:n,ctx:a})),error:null}}catch(e){o={output:null,error:x(e)}}await this.#o({...o,input:s,request:e,response:t,logger:n,ctx:a})}};const et=(e,t)=>e&&t?e.and(t):e||t,tt=(e,t)=>e?e.and(t):t,F={positive:200,negative:400},nt=Object.keys(F);var rt=class{#e;constructor(e){this.#e=e}execute(...e){return this.#e(...e)}},it=class extends rt{#e;#t;constructor(e){super(e.handler),this.#e=e.positive,this.#t=e.negative}getPositiveResponse(e){return We(this.#e,{variant:`positive`,args:[e],statusCodes:[F.positive],mimeTypes:[y.json]})}getNegativeResponse(){return We(this.#t,{variant:`negative`,args:[],statusCodes:[F.negative],mimeTypes:[y.json]})}};const at=r.object({status:r.literal(`error`),error:r.object({message:r.string()})});n.add(at,{examples:[{status:`error`,error:{message:`Sample error message`}}]});const ot=new it({positive:e=>{let t=r.object({status:r.literal(`success`),data:e}),{examples:i}=n.get(e)||{};return i?.length&&n.add(t,{examples:i.map(e=>({status:`success`,data:e}))}),t},negative:at,handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=Ke(e);Ge(n,a,r,t),i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:qe(n)}});return}i.status(F.positive).json({status:`success`,data:n})}}),st=r.string();n.add(st,{examples:[`Sample error message`]});const ct=new it({positive:e=>{let t=e instanceof r.ZodObject&&`items`in e.shape&&e.shape.items instanceof r.ZodArray?e.shape.items:r.array(r.any());if(n.get(t)?.examples?.length)return t;let i=n.get(e)?.examples?.filter(e=>T(e)&&`items`in e&&Array.isArray(e.items)).map(e=>e.items);if(i?.length){let e=t.meta();n.remove(t).add(t,{...e,examples:i})}return t},negative:{schema:st,mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=Ke(n);Ge(t,r,i,a),e.status(t.statusCode).type(`text/plain`).send(qe(t));return}if(`items`in t&&Array.isArray(t.items)){e.status(F.positive).json(t.items);return}throw Error(`Property 'items' is missing in the endpoint output`)}});var lt=class e{schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#e(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=et(this.schema,t.schema),n}addMiddleware(e){return this.#e(e instanceof P?e:new P(e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#e(new Ze(...e))}addContext(e){return this.#e(new P({handler:e}))}build({input:e=de,output:t,operationId:n,scope:r,tag:i,method:a,...o}){let{middlewares:s,resultHandler:c}=this,l=typeof a==`string`?[a]:a,u=typeof n==`function`?n:e=>n&&`${n}${e===`head`?`__HEAD`:``}`,d=typeof r==`string`?[r]:r||[],f=typeof i==`string`?[i]:i||[];return new $e({...o,middlewares:s,outputSchema:t,resultHandler:c,scopes:d,tags:f,methods:l,getOperationId:u,inputSchema:tt(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:de,handler:async t=>(await e(t),{})})}};const ut=new lt(ot),dt=new lt(ct),ft={debug:s,info:u,warn:d(`#FFA500`),error:p,ctx:c},pt={debug:10,info:20,warn:30,error:40},mt=e=>T(e)&&Object.keys(pt).some(t=>t in e),ht=e=>e in pt,gt=(e,t)=>pt[e]<pt[t],I=t.memoizeWith((e,t)=>`${e}${t}`,(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:`unit`,unitDisplay:`long`,unit:e})),_t=e=>e<1e-6?I(`nanosecond`,3).format(e/1e-6):e<.001?I(`nanosecond`).format(e/1e-6):e<1?I(`microsecond`).format(e/.001):e<1e3?I(`millisecond`).format(e):e<6e4?I(`second`,2).format(e/1e3):I(`minute`,2).format(e/6e4);var vt=class e{config;constructor({color:e=o.isSupported(),level:t=Ce()?`warn`:`debug`,depth:n=2,ctx:r={}}={}){this.config={color:e,level:t,depth:n,ctx:r}}format(e){let{depth:t,color:n,level:r}=this.config;return ee(e,{depth:t,colors:n,breakLength:r===`debug`?80:1/0,compact:r===`debug`?3:!0})}print(e,t,n){let{level:r,ctx:{requestId:i,...a},color:o}=this.config;if(r===`silent`||gt(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?ft.ctx(i):i),s.push(o?`${ft[e](e)}:`:`${e}:`,t),n!==void 0&&s.push(this.format(n)),Object.keys(a).length>0&&s.push(this.format(a)),console.log(s.join(` `))}debug(e,t){this.print(`debug`,e,t)}info(e,t){this.print(`info`,e,t)}warn(e,t){this.print(`warn`,e,t)}error(e,t){this.print(`error`,e,t)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(e){let t=h.now();return()=>{let n=h.now()-t,{message:r,severity:i=`debug`,formatter:a=_t}=typeof e==`object`?e:{message:e};this.print(typeof i==`function`?i(n):i,r,a(n))}}},yt=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,g.static(...this.#e))}};const bt=async(e,t=`default`)=>{try{return(await import(e))[t]}catch{}throw new Me(e)},xt=e=>e.type===`object`,St=t.mergeDeepWith((e,n)=>{if(Array.isArray(e)&&Array.isArray(n))return t.concat(e,n);if(e===n)return n;throw Error(`Can not flatten properties`,{cause:{a:e,b:n}})}),Ct=t.pipe(Object.keys,t.without([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),t.isEmpty),wt=t.pair(!0),Tt=(e,n=`coerce`)=>{let r=[t.pair(!1,e)],i={type:`object`,properties:{}},a=[];for(;r.length;){let[e,o]=r.shift();if(o.description&&(i.description??=o.description),o.allOf&&r.push(...o.allOf.map(r=>{if(n===`throw`&&!(r.type===`object`&&Ct(r)))throw Error(`Can not merge`);return t.pair(e,r)})),o.anyOf&&r.push(...t.map(wt,o.anyOf)),o.oneOf&&r.push(...t.map(wt,o.oneOf)),o.examples?.length&&(e?i.examples=t.concat(i.examples||[],o.examples):i.examples=be(i.examples?.filter(T)||[],o.examples.filter(T),([e,n])=>t.mergeDeepRight(e,n))),xt(o)&&(r.push([e,{examples:Et(o)}]),o.properties&&(i.properties=(n===`throw`?St:t.mergeDeepRight)(i.properties,o.properties),!e&&o.required&&a.push(...o.required)),T(o.propertyNames))){let t=[];typeof o.propertyNames.const==`string`&&t.push(o.propertyNames.const),o.propertyNames.enum&&t.push(...o.propertyNames.enum.filter(e=>typeof e==`string`));let n={...Object(o.additionalProperties)};for(let e of t)i.properties[e]??=n;e||a.push(...t)}}return a.length&&(i.required=[...new Set(a)]),i},Et=e=>Object.entries(e.properties||{}).reduce((e,[n,r])=>{let{examples:i=[]}=T(r)?r:{};return be(e,i.map(t.objOf(n)),([e,t])=>({...e,...t}))},[]);var Dt=class{#e=new WeakSet;#t=new WeakMap;constructor(e){this.logger=e}checkSchema(e,t){if(!this.#e.has(e)){for(let n of[`input`,`output`]){let i=[r.toJSONSchema(e[`${n}Schema`],{unrepresentable:`any`})];for(;i.length>0;){let e=i.shift();e.type&&e.type!==`object`&&this.logger.warn(`Endpoint ${n} schema is not object-based`,t);for(let t of[`allOf`,`oneOf`,`anyOf`])e[t]&&i.push(...e[t])}}if(e.requestType===`json`){let n=Ue(e.inputSchema,`input`);n&&this.logger.warn(`The final input schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(t,{reason:n}))}for(let n of nt)for(let{mimeTypes:r,schema:i}of e.getResponses(n)){if(!r?.includes(y.json))continue;let e=Ue(i,`output`);e&&this.logger.warn(`The final ${n} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(t,{reason:e}))}this.#e.add(e)}}checkPathParams(e,t,n){let i=this.#t.get(t);if(i?.paths.includes(e))return;let a=pe(e);if(a.length===0)return;let o=i?.flat||Tt(r.toJSONSchema(t.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of a)t in o.properties||this.logger.warn(`The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.`,Object.assign(n,{path:e,param:t}));i?i.paths.push(e):this.#t.set(t,{flat:o,paths:[e]})}};const Ot=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},kt=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&b(t)?[n,t]:[e]},At=e=>e.trim().split(`/`).filter(Boolean).join(`/`),jt=({methodLikeRouteBehavior:e=`method`},t,n)=>{let r=e===`method`;return Object.entries(t).map(([e,t])=>{let[i,a]=b(e)&&r&&t instanceof Qe?[`/`,e]:kt(e);return[[n||``].concat(At(i)||[]).join(`/`),t,a]})},Mt=(e,t)=>{throw new k(`Route with explicit method can only be assigned with Endpoint`,e,t)},Nt=(e,t,n)=>{if(!(!n||n.includes(e)))throw new k(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Pt=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new k(`Route has a duplicate`,e,t);n.add(r)},Ft=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=jt(t,e),a=new Set;for(;i.length;){let[e,o,s]=i.shift();if(o instanceof Qe)if(s)Pt(s,e,a),Nt(s,e,o.methods),n(s,e,o);else{let{methods:t=[`get`]}=o;for(let r of t)Pt(r,e,a),n(r,e,o)}else s&&Mt(s,e),o instanceof yt?r&&o.apply(e,r):i.unshift(...jt(t,o,e))}},It=e=>e.sort((e,t)=>b(t)-+b(e)||e.localeCompare(t)).join(`, `).toUpperCase(),Lt=e=>({method:t},n,r)=>{let a=It(e);n.set({Allow:a}),r(i(405,`${t} is not allowed`,{headers:{Allow:a}}))},Rt=e=>({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":It(e),"Access-Control-Allow-Headers":`content-type`}),zt=({app:e,getLogger:n,config:r,routing:i,parsers:a})=>{let o=Ce()?void 0:new Dt(n()),s=new Map;return Ft({routing:i,config:r,onEndpoint:(e,n,i)=>{o?.checkSchema(i,{path:n,method:e}),o?.checkPathParams(n,i,{method:e});let c=a?.[i.requestType]||[],l=t.pair(c,i);s.has(n)||s.set(n,new Map(r.cors?[[`options`,l]]:[])),s.get(n)?.set(e,l)},onStatic:e.use.bind(e)}),s},Bt=({app:e,config:t,getLogger:n,...r})=>{let i=zt({app:e,getLogger:n,config:t,...r}),a=new Map;for(let[r,o]of i){let i=Array.from(o.keys());i.includes(`get`)&&i.push(`head`);for(let[a,[s,c]]of o){let o=s.slice().concat(async(e,r)=>{let i=n(e);return c.execute({request:e,response:r,logger:i,config:t})});t.cors&&o.unshift(async(e,r,a)=>{let o=n(e),s=Rt(i),l=typeof t.cors==`function`?await t.cors({request:e,endpoint:c,logger:o,defaultHeaders:s}):s;r.set(l),a()}),e[a](r,...o)}t.wrongMethodBehavior!==404&&a.set(r,Lt(i))}for(let[t,n]of a)e.all(t,n)},Vt=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`,Ht=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,Ut=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,Wt=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),Gt=e=>new Promise((t,n)=>void e.close(e=>e?n(e):t())),Kt=(e,{timeout:t=1e3,logger:n}={})=>{let r,i=new Set,a=e=>void i.delete(e.destroy()),o=e=>void(Vt(e)?!e._httpMessage.headersSent&&e._httpMessage.setHeader(`connection`,`close`):a(e)),s=e=>void(r?e.destroy():i.add(e.once(`close`,()=>void i.delete(e))));for(let t of e)for(let e of[`connection`,`secureConnection`])t.on(e,s);let c=async()=>{for(let t of e)t.on(`request`,Wt);n?.info(`Graceful shutdown`,{sockets:i.size,timeout:t});for(let e of i)(Ut(e)||Ht(e))&&o(e);for await(let e of re(10,Date.now()))if(i.size===0||Date.now()-e>=t)break;for(let e of i)a(e);return Promise.allSettled(e.map(Gt))};return{sockets:i,shutdown:()=>r??=c()}},qt=Symbol.for(`express-zod-api`),Jt=({errorHandler:e,getLogger:t})=>async(n,r,i,a)=>n?e.execute({error:x(n),request:r,response:i,input:null,output:null,ctx:{},logger:t(r)}):a(),Yt=({errorHandler:e,getLogger:t})=>async(n,r)=>{let a=i(404,`Can not ${n.method} ${n.path}`),o=t(n);try{await e.execute({request:n,response:r,logger:o,error:a,input:null,output:null,ctx:{}})}catch(e){Ye({response:r,logger:o,error:new je(x(e),a)})}},Xt=e=>(t,{},n)=>{if(Object.values(t?.files||[]).flat().find(({truncated:e})=>e))return n(e);n()},Zt=e=>({log:e.debug.bind(e)}),Qt=async({getLogger:e,config:t})=>{let n=await bt(`express-fileupload`),{limitError:r,beforeUpload:i,...a}={...typeof t.upload==`object`&&t.upload},o=[];return o.push(async(t,r,o)=>{let s=e(t);return await i?.({request:t,logger:s}),n({debug:!0,...a,abortOnLimit:!1,parseNested:!0,logger:Zt(s)})(t,r,o)}),r&&o.push(Xt(r)),o},$t=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},en=({logger:e,config:{childLoggerProvider:t,accessLogger:n=({method:e,path:t},n)=>n.debug(`${e}: ${t}`)}})=>async(r,i,a)=>{let o=await t?.({request:r,parent:e})||e;n?.(r,o),r.res&&(r.res.locals[qt]={logger:o}),a()},tn=e=>t=>t?.res?.locals[qt]?.logger||e,nn=e=>process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
2
- `).slice(1))),rn=({servers:e,logger:t,options:{timeout:n,beforeExit:r,events:i=[`SIGINT`,`SIGTERM`]}})=>{let a=Kt(e,{logger:t,timeout:n}),o=async()=>{await a.shutdown(),await r?.(),process.exit()};for(let e of i)process.on(e,o)},an=e=>{if(e.columns<132)return;let t=f(`Proudly supports transgender community.`.padStart(109)),n=f(`Start your API server with I/O schema validation and custom middlewares in minutes.`.padStart(109)),r=f(`Thank you for choosing Express Zod API for your project.`.padStart(132)),i=f(`for Lia`.padEnd(20)),a=d(`#F5A9B8`),o=d(`#5BCEFA`),s=Array(14).fill(o,1,3).fill(a,3,5).fill(m,5,7).fill(a,7,9).fill(o,9,12).fill(l,12,13),c=`
1
+ import{createRequire as e}from"node:module";import{getBrand as t}from"@express-zod-api/zod-plugin";import*as n from"ramda";import{globalRegistry as r,z as i}from"zod";import a,{isHttpError as o}from"http-errors";import s,{blue as c,cyanBright as l,gray as u,green as d,hex as f,italic as p,red as m,whiteBright as h}from"ansis";import{inspect as g}from"node:util";import{performance as _}from"node:perf_hooks";import v from"express";import ee from"node:http";import te from"node:https";import{setInterval as ne}from"node:timers/promises";import{OpenApiBuilder as re,isReferenceObject as ie,isSchemaObject as y}from"openapi3-ts/oas31";import{createRequest as ae,createResponse as oe}from"node-mocks-http";import b from"typescript";function se(e){return e}const x={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},ce=[`get`,`post`,`put`,`delete`,`patch`],le=[...ce,`head`],S=e=>ce.includes(e),ue=i.object({}),de=/:([A-Za-z0-9_]+)/g,fe=e=>e.match(de)?.map(e=>e.slice(1))||[],pe=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(x.upload);return`files`in e&&t},me={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`]},he=[`body`,`query`,`params`],ge=e=>e.method.toLowerCase(),_e=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:S(e)?e:void 0;return(n?t[n]||me[n]:void 0)||he},ve=(e,t={})=>_e(ge(e),t).filter(t=>t===`files`?pe(e):!0).reduce((t,n)=>Object.assign(t,e[n]),{}),C=e=>e instanceof Error?e:e instanceof i.ZodError?new i.ZodRealError(e.issues):Error(String(e)),w=e=>e instanceof i.ZodError?e.issues.map(({path:e,message:t})=>`${e.length?`${i.core.toDotPath(e)}: `:``}${t}`).join(`; `):e.message,T=(e,t)=>O(e)&&`_zod`in e&&(t?n.path([`_zod`,`def`,`type`],e)===t:!0),E=(e,t,r)=>e.length&&t.length?n.xprod(e,t).map(r):e.concat(t),ye=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),D=(...e)=>{let t=n.chain(e=>e.split(/[^A-Z0-9]/gi),e);return n.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),t).map(ye).join(``)},be=n.tryCatch((e,t)=>typeof i.parse(e,t),n.always(void 0)),O=e=>typeof e==`object`&&!!e,xe=n.memoizeWith(()=>`static`,()=>process.env.NODE_ENV===`production`),Se=(e,t)=>!!t&&e!==`head`,k=Symbol(`Buffer`),Ce=()=>i.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).brand(k),A=Symbol(`DateIn`),we=({examples:e,...t}={})=>i.union([i.iso.date(),i.iso.datetime(),i.iso.datetime({local:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(i.date()).brand(A).meta(t),j=Symbol(`DateOut`),Te=(e={})=>i.date().transform(e=>e.toISOString()).brand(j).meta(e);var M=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},N=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},P=class extends Error{name=`IOSchemaError`},Ee=class extends P{name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},De=class extends P{name=`OutputValidationError`;constructor(e){let t=new i.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(w(t),{cause:e}),this.cause=e}},F=class extends P{name=`InputValidationError`;constructor(e){super(w(e),{cause:e}),this.cause=e}},Oe=class extends Error{name=`ResultHandlerError`;constructor(e,t){super(w(e),{cause:e}),this.cause=e,this.handled=t}},ke=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const I=Symbol(`Form`),Ae=e=>(e instanceof i.ZodObject?e:i.object(e)).brand(I),L=Symbol(`Upload`),je=()=>i.custom(e=>typeof e==`object`&&!!e&&`name`in e&&`encoding`in e&&`mimetype`in e&&`data`in e&&`tempFilePath`in e&&`truncated`in e&&`size`in e&&`md5`in e&&`mv`in e&&typeof e.name==`string`&&typeof e.encoding==`string`&&typeof e.mimetype==`string`&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath==`string`&&typeof e.truncated==`boolean`&&typeof e.size==`number`&&typeof e.md5==`string`&&typeof e.mv==`function`,{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(L),R=Symbol(`Raw`),Me=i.object({raw:Ce()}),Ne=e=>Me.extend(e).brand(R);function Pe(e){return e?Ne(e):Me.brand(R)}const Fe=(e,{io:t,condition:r})=>n.tryCatch(()=>void i.toJSONSchema(e,{io:t,unrepresentable:`any`,override:({zodSchema:e})=>{if(r(e))throw new Ee(e)}}),e=>e.cause)(),Ie=(e,{io:t})=>{let r=[i.toJSONSchema(e,{io:t,unrepresentable:`any`})];for(;r.length;){let e=r.shift();if(n.is(Object,e)){if(e.$ref===`#`)return!0;r.push(...n.values(e))}n.is(Array,e)&&r.push(...n.values(e))}return!1},Le=e=>Fe(e,{condition:e=>{let n=t(e);return typeof n==`symbol`&&[L,R,I].includes(n)},io:`input`}),Re=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`],ze=(e,n)=>Fe(e,{io:n,condition:e=>{let r=t(e),{type:i}=e._zod.def;return!!(Re.includes(i)||r===k||n===`input`&&(i===`date`||r===j)||n===`output`&&(r===A||r===R||r===L))}}),Be=(e,{variant:t,args:n,...r})=>{if(typeof e==`function`&&(e=e(...n)),e instanceof i.ZodType)return[{schema:e,...r}];if(Array.isArray(e)&&!e.length)throw new Oe(Error(`At least one ${t} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||r.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?r.mimeTypes:n}))},z=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),B=e=>o(e)?e:a(e instanceof F?400:500,w(e),{cause:e.cause||e}),V=e=>xe()&&!e.expose?a(e.statusCode).message:e.message,Ve=e=>Object.entries(e._zod.def.shape).reduce((e,[t,i])=>{let{examples:a=[]}=r.get(i)||{};return E(e,a.map(n.objOf(t)),([e,t])=>({...e,...t}))},[]),He=({error:e,logger:t,response:n})=>{t.error(`Result handler failure`,e);let r=V(a(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`\nOriginal error: ${e.handled.message}.`:``),{expose:o(e.cause)?e.cause.expose:!1}));n.status(500).type(`text/plain`).end(r)};var Ue=class{},H=class extends Ue{#e;#t;#n;constructor({input:e,security:t,handler:n}){super(),this.#e=e,this.#t=t,this.#n=n}get security(){return this.#t}get schema(){return this.#e}async execute({input:e,...t}){try{let n=await(this.#e||ue).parseAsync(e);return this.#n({...t,input:n})}catch(e){throw e instanceof i.ZodError?new F(e):e}}},We=class extends H{constructor(e,{provider:t=()=>({}),transformer:n=e=>e}={}){super({handler:async({request:r,response:i})=>new Promise((a,o)=>{let s=e=>{if(e&&e instanceof Error)return o(n(e));a(t(r,i))};e(r,i,s)?.catch(s)})})}},Ge=class{nest(e){return{...e,"":this}}},Ke=class e extends Ge{#e;#t=n.once(()=>{if(r.get(this.#e.outputSchema)?.examples?.length||!T(this.#e.outputSchema,`object`))return;let e=Ve(this.#e.outputSchema);if(!e.length)return;let t=this.#e.outputSchema.meta();r.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...t,examples:e})});constructor(e){super(),this.#e=e}#n(t){return new e({...this.#e,...t})}deprecated(){return this.#n({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let e=Le(this.#e.inputSchema);if(e){let n=t(e);if(n===L)return`upload`;if(n===R)return`raw`;if(n===I)return`form`}return`json`}getResponses(e){return e===`positive`&&this.#t(),Object.freeze(e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let e=n.pluck(`security`,this.#e.middlewares||[]);return n.reject(n.isNil,e)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(e){return this.#e.getOperationId?.(e)}async#r(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof i.ZodError?new De(e):e}}async#i({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof We))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#a({input:e,...t}){let n;try{n=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof i.ZodError?new F(e):e}return this.#e.handler({...t,input:n})}async#o(e){try{await this.#e.resultHandler.execute(e)}catch(t){He({...e,error:new Oe(C(t),e.error||void 0)})}}async execute({request:e,response:t,logger:n,config:r}){let i=ge(e),a={},o={output:{},error:null},s=ve(e,r.inputSources);try{if(await this.#i({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();o={output:await this.#r(await this.#a({input:s,logger:n,ctx:a})),error:null}}catch(e){o={output:null,error:C(e)}}await this.#o({...o,input:s,request:e,response:t,logger:n,ctx:a})}};const qe=(e,t)=>e&&t?e.and(t):e||t,Je=(e,t)=>e?e.and(t):t,U={positive:200,negative:400},Ye=Object.keys(U);var Xe=class{#e;constructor(e){this.#e=e}execute(...e){return this.#e(...e)}},W=class extends Xe{#e;#t;constructor(e){super(e.handler),this.#e=e.positive,this.#t=e.negative}getPositiveResponse(e){return Be(this.#e,{variant:`positive`,args:[e],statusCodes:[U.positive],mimeTypes:[x.json]})}getNegativeResponse(){return Be(this.#t,{variant:`negative`,args:[],statusCodes:[U.negative],mimeTypes:[x.json]})}};const Ze=i.object({status:i.literal(`error`),error:i.object({message:i.string()})});r.add(Ze,{examples:[{status:`error`,error:{message:`Sample error message`}}]});const G=new W({positive:e=>{let t=i.object({status:i.literal(`success`),data:e}),{examples:n}=r.get(e)||{};return n?.length&&r.add(t,{examples:n.map(e=>({status:`success`,data:e}))}),t},negative:Ze,handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=B(e);z(n,a,r,t),i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:V(n)}});return}i.status(U.positive).json({status:`success`,data:n})}}),Qe=i.string();r.add(Qe,{examples:[`Sample error message`]});const $e=new W({positive:e=>{let t=e instanceof i.ZodObject&&`items`in e.shape&&e.shape.items instanceof i.ZodArray?e.shape.items:i.array(i.any());if(r.get(t)?.examples?.length)return t;let n=r.get(e)?.examples?.filter(e=>O(e)&&`items`in e&&Array.isArray(e.items)).map(e=>e.items);if(n?.length){let e=t.meta();r.remove(t).add(t,{...e,examples:n})}return t},negative:{schema:Qe,mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=B(n);z(t,r,i,a),e.status(t.statusCode).type(`text/plain`).send(V(t));return}if(`items`in t&&Array.isArray(t.items)){e.status(U.positive).json(t.items);return}throw Error(`Property 'items' is missing in the endpoint output`)}});var K=class e{schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#e(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=qe(this.schema,t.schema),n}addMiddleware(e){return this.#e(e instanceof H?e:new H(e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#e(new We(...e))}addContext(e){return this.#e(new H({handler:e}))}build({input:e=ue,output:t,operationId:n,scope:r,tag:i,method:a,...o}){let{middlewares:s,resultHandler:c}=this,l=typeof a==`string`?[a]:a,u=typeof n==`function`?n:e=>n&&`${n}${e===`head`?`__HEAD`:``}`,d=typeof r==`string`?[r]:r||[],f=typeof i==`string`?[i]:i||[];return new Ke({...o,middlewares:s,outputSchema:t,resultHandler:c,scopes:d,tags:f,methods:l,getOperationId:u,inputSchema:Je(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:ue,handler:async t=>(await e(t),{})})}};const et=new K(G),tt=new K($e),nt={debug:c,info:d,warn:f(`#FFA500`),error:m,ctx:l},q={debug:10,info:20,warn:30,error:40},rt=e=>O(e)&&Object.keys(q).some(t=>t in e),it=e=>e in q,at=(e,t)=>q[e]<q[t],J=n.memoizeWith((e,t)=>`${e}${t}`,(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:`unit`,unitDisplay:`long`,unit:e})),ot=e=>e<1e-6?J(`nanosecond`,3).format(e/1e-6):e<.001?J(`nanosecond`).format(e/1e-6):e<1?J(`microsecond`).format(e/.001):e<1e3?J(`millisecond`).format(e):e<6e4?J(`second`,2).format(e/1e3):J(`minute`,2).format(e/6e4);var st=class e{config;constructor({color:e=s.isSupported(),level:t=xe()?`warn`:`debug`,depth:n=2,ctx:r={}}={}){this.config={color:e,level:t,depth:n,ctx:r}}format(e){let{depth:t,color:n,level:r}=this.config;return g(e,{depth:t,colors:n,breakLength:r===`debug`?80:1/0,compact:r===`debug`?3:!0})}print(e,t,n){let{level:r,ctx:{requestId:i,...a},color:o}=this.config;if(r===`silent`||at(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?nt.ctx(i):i),s.push(o?`${nt[e](e)}:`:`${e}:`,t),n!==void 0&&s.push(this.format(n)),Object.keys(a).length>0&&s.push(this.format(a)),console.log(s.join(` `))}debug(e,t){this.print(`debug`,e,t)}info(e,t){this.print(`info`,e,t)}warn(e,t){this.print(`warn`,e,t)}error(e,t){this.print(`error`,e,t)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(e){let t=_.now();return()=>{let n=_.now()-t,{message:r,severity:i=`debug`,formatter:a=ot}=typeof e==`object`?e:{message:e};this.print(typeof i==`function`?i(n):i,r,a(n))}}},ct=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,v.static(...this.#e))}};const lt=async(e,t=`default`)=>{try{return(await import(e))[t]}catch{}throw new ke(e)},ut=e=>e.type===`object`,dt=n.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return n.concat(e,t);if(e===t)return t;throw Error(`Can not flatten properties`,{cause:{a:e,b:t}})}),ft=n.pipe(Object.keys,n.without([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),n.isEmpty),pt=n.pair(!0),Y=(e,t=`coerce`)=>{let r=[n.pair(!1,e)],i={type:`object`,properties:{}},a=[];for(;r.length;){let[e,o]=r.shift();if(o.description&&(i.description??=o.description),o.allOf&&r.push(...o.allOf.map(r=>{if(t===`throw`&&!(r.type===`object`&&ft(r)))throw Error(`Can not merge`);return n.pair(e,r)})),o.anyOf&&r.push(...n.map(pt,o.anyOf)),o.oneOf&&r.push(...n.map(pt,o.oneOf)),o.examples?.length&&(e?i.examples=n.concat(i.examples||[],o.examples):i.examples=E(i.examples?.filter(O)||[],o.examples.filter(O),([e,t])=>n.mergeDeepRight(e,t))),ut(o)&&(r.push([e,{examples:mt(o)}]),o.properties&&(i.properties=(t===`throw`?dt:n.mergeDeepRight)(i.properties,o.properties),!e&&o.required&&a.push(...o.required)),O(o.propertyNames))){let t=[];typeof o.propertyNames.const==`string`&&t.push(o.propertyNames.const),o.propertyNames.enum&&t.push(...o.propertyNames.enum.filter(e=>typeof e==`string`));let n={...Object(o.additionalProperties)};for(let e of t)i.properties[e]??=n;e||a.push(...t)}}return a.length&&(i.required=[...new Set(a)]),i},mt=e=>Object.entries(e.properties||{}).reduce((e,[t,r])=>{let{examples:i=[]}=O(r)?r:{};return E(e,i.map(n.objOf(t)),([e,t])=>({...e,...t}))},[]);var ht=class{#e=new WeakMap;constructor(e){this.logger=e}#t(e,t,n){if(!e.isSchemaChecked){for(let e of[`input`,`output`]){let r=[i.toJSONSchema(t[`${e}Schema`],{unrepresentable:`any`})];for(;r.length>0;){let t=r.shift();t.type&&t.type!==`object`&&this.logger.warn(`Endpoint ${e} schema is not object-based`,n);for(let e of[`allOf`,`oneOf`,`anyOf`])t[e]&&r.push(...t[e])}}if(t.requestType===`json`){let e=ze(t.inputSchema,`input`);e&&this.logger.warn(`The final input schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:e})}for(let e of Ye)for(let{mimeTypes:r,schema:i}of t.getResponses(e)){if(!r?.includes(x.json))continue;let t=ze(i,`output`);t&&this.logger.warn(`The final ${e} response schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:t})}e.isSchemaChecked=!0}}#n(e,t,n,r){if(e.paths.has(n))return;let a=fe(n);if(a.length!==0){e.flat??=Y(i.toJSONSchema(t.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of a)t in e.flat.properties||this.logger.warn(`The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.`,{...r,path:n,param:t});e.paths.add(n)}}check=(e,t,n)=>{let r=this.#e.get(n);r||(r={isSchemaChecked:!1,paths:new Set},this.#e.set(n,r)),this.#t(r,n,{method:e,path:t}),this.#n(r,n,t,{method:e})}};const gt=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},_t=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&S(t)?[n,t]:[e]},vt=e=>e.trim().split(`/`).filter(Boolean).join(`/`),yt=({methodLikeRouteBehavior:e=`method`},t,n)=>{let r=e===`method`;return Object.entries(t).map(([e,t])=>{let[i,a]=r&&S(e)&&t instanceof Ge?[`/`,e]:_t(e);return[[n||``].concat(vt(i)||[]).join(`/`),t,a]})},bt=(e,t)=>{throw new M(`Route with explicit method can only be assigned with Endpoint`,e,t)},xt=(e,t,n)=>{if(!(!n||n.includes(e)))throw new M(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},St=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new M(`Route has a duplicate`,e,t);n.add(r)},Ct=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=yt(t,e),a=new Set;for(;i.length;){let[e,o,s]=i.shift();if(o instanceof Ge)if(s)St(s,e,a),xt(s,e,o.methods),n(s,e,o);else{let{methods:t=[`get`]}=o;for(let r of t)St(r,e,a),n(r,e,o)}else s&&bt(s,e),o instanceof ct?r&&o.apply(e,r):i.unshift(...yt(t,o,e))}},wt=e=>e.sort((e,t)=>S(t)-+S(e)||e.localeCompare(t)).join(`, `).toUpperCase(),Tt=e=>({method:t},n,r)=>{let i=wt(e);n.set({Allow:i}),r(a(405,`${t} is not allowed`,{headers:{Allow:i}}))},Et=e=>({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":wt(e),"Access-Control-Allow-Headers":`content-type`}),Dt=({app:e,getLogger:t,config:r,routing:i,parsers:a})=>{let o=xe()?void 0:new ht(t()),s=new Map;return Ct({routing:i,config:r,onEndpoint:(e,t,i)=>{o?.check(e,t,i);let c=a?.[i.requestType]||[],l=n.pair(c,i);s.has(t)||s.set(t,new Map(r.cors?[[`options`,l]]:[])),s.get(t)?.set(e,l)},onStatic:e.use.bind(e)}),s},Ot=({app:e,config:t,getLogger:n,...r})=>{let i=Dt({app:e,getLogger:n,config:t,...r}),a=new Map;for(let[r,o]of i){let i=Array.from(o.keys());i.includes(`get`)&&i.push(`head`);for(let[a,[s,c]]of o){let o=s.slice().concat(async(e,r)=>{let i=n(e);return c.execute({request:e,response:r,logger:i,config:t})});t.cors&&o.unshift(async(e,r,a)=>{let o=n(e),s=Et(i),l=typeof t.cors==`function`?await t.cors({request:e,endpoint:c,logger:o,defaultHeaders:s}):s;r.set(l),a()}),e[a](r,...o)}t.wrongMethodBehavior!==404&&a.set(r,Tt(i))}for(let[t,n]of a)e.all(t,n)},kt=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`,At=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,jt=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,Mt=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),Nt=e=>new Promise((t,n)=>void e.close(e=>e?n(e):t())),Pt=(e,{timeout:t=1e3,logger:n}={})=>{let r,i=new Set,a=e=>void i.delete(e.destroy()),o=e=>void(kt(e)?!e._httpMessage.headersSent&&e._httpMessage.setHeader(`connection`,`close`):a(e)),s=e=>void(r?e.destroy():i.add(e.once(`close`,()=>void i.delete(e))));for(let t of e)for(let e of[`connection`,`secureConnection`])t.on(e,s);let c=async()=>{for(let t of e)t.on(`request`,Mt);n?.info(`Graceful shutdown`,{sockets:i.size,timeout:t});for(let e of i)(jt(e)||At(e))&&o(e);for await(let e of ne(10,Date.now()))if(i.size===0||Date.now()-e>=t)break;for(let e of i)a(e);return Promise.allSettled(e.map(Nt))};return{sockets:i,shutdown:()=>r??=c()}},Ft=Symbol.for(`express-zod-api`),It=({errorHandler:e,getLogger:t})=>async(n,r,i,a)=>n?e.execute({error:C(n),request:r,response:i,input:null,output:null,ctx:{},logger:t(r)}):a(),Lt=({errorHandler:e,getLogger:t})=>async(n,r)=>{let i=a(404,`Can not ${n.method} ${n.path}`),o=t(n);try{await e.execute({request:n,response:r,logger:o,error:i,input:null,output:null,ctx:{}})}catch(e){He({response:r,logger:o,error:new Oe(C(e),i)})}},Rt=e=>(t,{},n)=>{if(Object.values(t?.files||[]).flat().find(({truncated:e})=>e))return n(e);n()},zt=e=>({log:e.debug.bind(e)}),Bt=async({getLogger:e,config:t})=>{let n=await lt(`express-fileupload`),{limitError:r,beforeUpload:i,...a}={...typeof t.upload==`object`&&t.upload},o=[];return o.push(async(t,r,o)=>{let s=e(t);return await i?.({request:t,logger:s}),n({debug:!0,...a,abortOnLimit:!1,parseNested:!0,logger:zt(s)})(t,r,o)}),r&&o.push(Rt(r)),o},Vt=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Ht=({logger:e,config:{childLoggerProvider:t,accessLogger:n=({method:e,path:t},n)=>n.debug(`${e}: ${t}`)}})=>async(r,i,a)=>{let o=await t?.({request:r,parent:e})||e;n?.(r,o),r.res&&(r.res.locals[Ft]={logger:o}),a()},Ut=e=>t=>t?.res?.locals[Ft]?.logger||e,Wt=e=>process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
2
+ `).slice(1))),Gt=({servers:e,logger:t,options:{timeout:n,beforeExit:r,events:i=[`SIGINT`,`SIGTERM`]}})=>{let a=Pt(e,{logger:t,timeout:n}),o=async()=>{await a.shutdown(),await r?.(),process.exit()};for(let e of i)process.on(e,o)},Kt=e=>{if(e.columns<132)return;let t=p(`Proudly supports transgender community.`.padStart(109)),n=p(`Start your API server with I/O schema validation and custom middlewares in minutes.`.padStart(109)),r=p(`Thank you for choosing Express Zod API for your project.`.padStart(132)),i=p(`for Lia`.padEnd(20)),a=f(`#F5A9B8`),o=f(`#5BCEFA`),s=Array(14).fill(o,1,3).fill(a,3,5).fill(h,5,7).fill(a,7,9).fill(o,9,12).fill(u,12,13),c=`
3
3
  8888888888 8888888888P 888 d8888 8888888b. 8888888
4
4
  888 d88P 888 d88888 888 Y88b 888
5
5
  888 d88P 888 d88P888 888 888 888
@@ -14,8 +14,8 @@ ${i}888${n}
14
14
  ${r}
15
15
  `;e.write(c.split(`
16
16
  `).map((e,t)=>s[t]?s[t](e):e).join(`
17
- `))},on=e=>{e.startupLogo!==!1&&an(process.stdout);let t=e.errorHandler||ot,n=mt(e.logger)?e.logger:new vt(e.logger);n.debug(`Running`,{build:`v26.0.0-beta.2`,env:process.env.NODE_ENV||`development`}),nn(n);let r=en({logger:n,config:e}),i={getLogger:tn(n),errorHandler:t},a=Yt(i),o=Jt(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},sn=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=on(e);return Bt({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},cn=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=on(e),s=g().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.compression){let t=await bt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r}),Bt({app:s,routing:t,getLogger:r,config:e,parsers:{json:[e.jsonParser||g.json()],raw:[e.rawParser||g.raw(),$t],form:[e.formParser||g.urlencoded()],upload:e.upload?await Qt({config:e,getLogger:r}):[]}}),await e.afterRouting?.({app:s,getLogger:r}),s.use(a,i);let c=[],l=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),u=[];if(e.http){let t=te.createServer(s);c.push(t),u.push(l(t,e.http.listen))}if(e.https){let t=ne.createServer(e.https.options,s);c.push(t),u.push(l(t,e.https.listen))}return c.length||n.warn(`No servers configured.`),e.gracefulShutdown&&rn({logger:n,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:u.map(e=>e())}},ln=e=>T(e)&&`or`in e,un=e=>T(e)&&`and`in e,dn=e=>!un(e)&&!ln(e),fn=e=>{let n=t.filter(dn,e),r=t.chain(t.prop(`and`),t.filter(un,e)),[i,a]=t.partition(dn,r),o=t.concat(n,i),s=t.filter(ln,e);return t.map(t.prop(`or`),t.concat(s,a)).reduce((e,n)=>be(e,t.map(e=>dn(e)?[e]:e.and,n),([e,n])=>t.concat(e,n)),t.reject(t.isEmpty,[o]))};var pn=`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`.split(`.`);const mn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,hn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},gn=e=>e.replace(fe,e=>`{${e.slice(1)}}`),_n=({},e)=>{if(e.isResponse)throw new A(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},vn=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),yn=({zodSchema:e,jsonSchema:t})=>{if(!C(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},bn=t.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return Tt(e,`throw`)},(e,{jsonSchema:t})=>t),xn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Dn(t.type)})},L=e=>e,Sn=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new A(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:`^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?)?Z?$`,externalDocs:{url:mn}};return e?.length&&(r.examples=e),r},Cn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new A(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:mn}};return e?.length&&(r.examples=e),r},wn=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),Tn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,En=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return hn?.[t]},Dn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],On=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!C(r,`transform`))return t;let a=L(Fn(i,{ctx:n}));if(_(a))if(n.isResponse){let e=Se(r,En(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},kn=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!T(t.properties.raw)?e:t.properties.raw},An=e=>e.length?t.fromPairs(t.zip(t.times(e=>`example${e+1}`,e.length),t.map(t.objOf(`value`),e))):void 0,jn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||pn.includes(e),Mn=({path:e,method:n,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${n.toUpperCase()} ${e} Parameter`})=>{let u=Tt(r),d=pe(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),ee=e=>p&&d.includes(e),h=t.chain(t.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),g=t=>m&&(s?.(t,n,e)??jn(t,h));return Object.entries(u.properties).reduce((e,[n,r])=>{if(!T(r))return e;let i=ee(n)?`path`:g(n)?`header`:f?`query`:void 0;if(!i)return e;let s=L(r),c=o===`components`?a(r.id||JSON.stringify(r),s,w(l,n)):s;return e.concat({name:n,in:i,deprecated:r.deprecated,required:u.required?.includes(n)||!1,description:s.description||l,schema:c,examples:An(_(s)&&s.examples?.length?s.examples:t.pluck(n,u.examples?.filter(t.both(T,t.has(n)))||[]))})},[])},Nn={nullable:xn,union:yn,bigint:wn,intersection:bn,tuple:Tn,pipe:On,[D]:Sn,[O]:Cn,[M]:_n,[N]:kn,[E]:vn},Pn=(e,n,r)=>{let i=[e,n];for(;i.length;){let e=i.shift();if(t.is(Object,e)){if(ae(e)&&!e.$ref.startsWith(`#/components`)){let t=n[e.$ref.split(`/`).pop()];t&&(e.$ref=r.makeRef(t.id||t,L(t)).$ref);continue}i.push(...t.values(e))}t.is(Array,e)&&i.push(...t.values(e))}return e},Fn=(t,{ctx:n,rules:i=Nn})=>{let{$defs:a={},properties:o={}}=r.toJSONSchema(r.object({subject:t}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:t=>{let r=e(t.zodSchema),a=i[r&&r in i?r:t.zodSchema._zod.def.type];if(a){let e={...a(t,n)};for(let e in t.jsonSchema)delete t.jsonSchema[e];Object.assign(t.jsonSchema,e)}}});return Pn(T(o.subject)?o.subject:{},a,n)},In=(e,n)=>{if(ae(e))return[e,!1];let r=!1,i=t.map(e=>{let[t,i]=In(e,n);return r||=i,t}),a=t.omit(n),o={properties:a,examples:t.map(a),required:t.without(n),allOf:i,oneOf:i,anyOf:i},s=t.evolve(o,e);return[s,r||!!s.required?.length]},Ln=({method:e,path:n,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${n} ${xe(a)} response ${c?l:``}`.trim()})=>{if(!we(e,i))return{description:d};let f=L(Fn(r,{rules:{...u,...Nn},ctx:{isResponse:!0,makeRef:o,path:n,method:e}})),p=[];_(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,w(d)):f,examples:An(p)};return{description:d,content:t.fromPairs(t.xprod(i,[m]))}},Rn=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},zn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},Bn=({name:e})=>({type:`apiKey`,in:`header`,name:e}),Vn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),Hn=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),Un=({flows:e={}})=>({type:`oauth2`,flows:t.map(e=>({...e,scopes:e.scopes||{}}),t.reject(t.isNil,e))}),Wn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?Rn(e):e.type===`input`?zn(e,t):e.type===`header`?Bn(e):e.type===`cookie`?Vn(e):e.type===`openid`?Hn(e):Un(e);return e.map(e=>e.map(n))},Gn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Kn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Fn(e,{rules:{...t,...Nn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),qn=({method:e,path:n,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${n} Request body`})=>{let[u,d]=In(L(i),c),f=[];_(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,w(l)):u,examples:An(f.length?f:Tt(i).examples?.filter(e=>T(e)&&!Array.isArray(e)).map(t.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===y.raw)&&(m.required=!0),m},Jn=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Yn=e=>e.length<=50?e:e.slice(0,49)+`…`,Xn=e=>e.length?e.slice():void 0;var Zn=class extends ie{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n=this.#n.get(e)){return n||(n=`Schema${this.#n.size+1}`,this.#n.set(e,n)),this.addSchema(n,t),{$ref:`#/components/schemas/${n}`}}#i(e,t,n){let r=n||w(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new A(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:n,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#r.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,ee=d?Yn(d):u&&c?Yn(c):void 0,h=ve(e,n.inputSources),g=this.#i(r,e,i.getOperationId(e)),te=Kn({...a,schema:m}),ne=fn(i.security),re=Mn({...a,inputSources:h,isHeader:l,security:ne,request:te,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:g})}),ie={};for(let t of nt){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)ie[l]=Ln({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:g,statusCode:l})})}let ae=h.includes(`body`)?qn({...a,request:te,paramNames:t.pluck(`name`,re),schema:m,mimeType:y[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:g})}):void 0,_=Gn(Wn(ne,h),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),oe={operationId:g,summary:ee,description:c,deprecated:i.isDeprecated||void 0,tags:Xn(i.tags),parameters:Xn(re),requestBody:ae,security:Xn(_),responses:ie};this.addPath(gn(r),{[e]:oe})};Ft({routing:e,config:n,onEndpoint:d?Ot(p):p}),c&&(this.rootDoc.tags=Jn(c))}};const Qn=e=>oe({...e,headers:{"content-type":y.json,...e?.headers}}),$n=e=>se(e),er=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:ht(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},tr=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=Qn(e),a=$n({req:i,...t});a.req=t?.req||i,i.res=a;let o=er(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},nr=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=tr(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},rr=async({middleware:e,ctx:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=ot}}=tr(n),c={request:r,response:i,logger:a,input:ye(r,o),ctx:t};try{return{requestMock:r,responseMock:i,loggerMock:a,output:await e.execute(c)}}catch(e){return await s.execute({...c,error:x(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}},R=v.factory,ir=[R.createModifier(v.SyntaxKind.ExportKeyword)],ar=[R.createModifier(v.SyntaxKind.AsyncKeyword)],or={public:[R.createModifier(v.SyntaxKind.PublicKeyword)],protectedReadonly:[R.createModifier(v.SyntaxKind.ProtectedKeyword),R.createModifier(v.SyntaxKind.ReadonlyKeyword)]},sr=(e,t)=>v.addSyntheticLeadingComment(e,v.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let n=v.createSourceFile(`print.ts`,``,v.ScriptTarget.Latest,!1,v.ScriptKind.TS);return v.createPrinter(t).printNode(v.EmitHint.Unspecified,e,n)},lr=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ur=e=>typeof e==`string`&&lr.test(e)?R.createIdentifier(e):Y(e),dr=(e,...t)=>R.createTemplateExpression(R.createTemplateHead(e),t.map(([e,n=``],r)=>R.createTemplateSpan(e,r===t.length-1?R.createTemplateTail(n):R.createTemplateMiddle(n)))),fr=(e,{type:t,mod:n,init:r,optional:i}={})=>R.createParameterDeclaration(n,void 0,e,i?R.createToken(v.SyntaxKind.QuestionToken):void 0,t?B(t):void 0,r),z=e=>Object.entries(e).map(([e,t])=>fr(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t)),pr=(e,t=[])=>R.createConstructorDeclaration(or.public,e,R.createBlock(t)),B=(e,n)=>typeof e==`number`?R.createKeywordTypeNode(e):typeof e==`string`||v.isIdentifier(e)?R.createTypeReferenceNode(e,n&&t.map(B,n)):e,mr=B(`Record`,[v.SyntaxKind.StringKeyword,v.SyntaxKind.AnyKeyword]),V=e=>{let t=new Map;for(let n of e)t.set(Mr(n)?n.kind:n,n);return R.createUnionTypeNode(Array.from(t.values()))},hr=(e,n,{isOptional:r,isDeprecated:i,comment:a}={})=>{let o=B(n),s=R.createPropertySignature(void 0,ur(e),r?R.createToken(v.SyntaxKind.QuestionToken):void 0,r?V([o,B(v.SyntaxKind.UndefinedKeyword)]):o),c=t.reject(t.isNil,[i?`@deprecated`:void 0,a]);return c.length?sr(s,c.join(` `)):s},gr=e=>v.setEmitFlags(e,v.EmitFlags.SingleLine),_r=(...e)=>R.createArrayBindingPattern(e.map(e=>R.createBindingElement(void 0,void 0,e))),H=(e,t,{type:n,expose:r}={})=>R.createVariableStatement(r&&ir,R.createVariableDeclarationList([R.createVariableDeclaration(e,void 0,n?B(n):void 0,t)],v.NodeFlags.Const)),vr=(e,n)=>U(e,V(t.map(X,n)),{expose:!0}),U=(e,t,{expose:n,comment:r,params:i}={})=>{let a=R.createTypeAliasDeclaration(n?ir:void 0,e,i&&Tr(i),t);return r?sr(a,r):a},yr=(e,t)=>R.createPropertyDeclaration(or.public,e,void 0,B(t),void 0),br=(e,t,n,{typeParams:r,returns:i}={})=>R.createMethodDeclaration(or.public,void 0,e,void 0,r&&Tr(r),t,i,R.createBlock(n)),xr=(e,t,{typeParams:n}={})=>R.createClassDeclaration(ir,e,n&&Tr(n),void 0,t),Sr=e=>R.createTypeOperatorNode(v.SyntaxKind.KeyOfKeyword,B(e)),Cr=e=>B(Promise.name,[e]),wr=(e,t,{expose:n,comment:r}={})=>{let i=R.createInterfaceDeclaration(n?ir:void 0,e,void 0,void 0,t);return r?sr(i,r):i},Tr=e=>(Array.isArray(e)?e.map(e=>t.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return R.createTypeParameterDeclaration([],e,n?B(n):void 0,r?B(r):void 0)}),W=(e,n,{isAsync:r}={})=>R.createArrowFunction(r?ar:void 0,void 0,Array.isArray(e)?t.map(fr,e):z(e),void 0,void 0,n),G=e=>e,Er=(e,t,n)=>R.createConditionalExpression(e,R.createToken(v.SyntaxKind.QuestionToken),t,R.createToken(v.SyntaxKind.ColonToken),n),K=(e,...t)=>(...n)=>R.createCallExpression(t.reduce((e,t)=>typeof t==`string`||v.isIdentifier(t)?R.createPropertyAccessExpression(e,t):R.createElementAccessExpression(e,t),typeof e==`string`?R.createIdentifier(e):e),void 0,n),q=(e,...t)=>R.createNewExpression(R.createIdentifier(e),void 0,t),Dr=(e,t)=>B(`Extract`,[e,t]),Or=(e,t)=>R.createExpressionStatement(R.createBinaryExpression(e,R.createToken(v.SyntaxKind.EqualsToken),t)),J=(e,t)=>R.createIndexedAccessTypeNode(B(e),B(t)),kr=e=>V([B(e),Cr(e)]),Ar=(e,t)=>R.createFunctionTypeNode(void 0,z(e),B(t)),Y=e=>typeof e==`number`?R.createNumericLiteral(e):typeof e==`bigint`?R.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?R.createTrue():R.createFalse():e===null?R.createNull():R.createStringLiteral(e),X=e=>R.createLiteralTypeNode(Y(e)),jr=[v.SyntaxKind.AnyKeyword,v.SyntaxKind.BigIntKeyword,v.SyntaxKind.BooleanKeyword,v.SyntaxKind.NeverKeyword,v.SyntaxKind.NumberKeyword,v.SyntaxKind.ObjectKeyword,v.SyntaxKind.StringKeyword,v.SyntaxKind.SymbolKeyword,v.SyntaxKind.UndefinedKeyword,v.SyntaxKind.UnknownKeyword,v.SyntaxKind.VoidKeyword],Mr=e=>jr.includes(e.kind);var Nr=class{paths=new Set;tags=new Map;registry=new Map;#e={pathType:R.createIdentifier(`Path`),implementationType:R.createIdentifier(`Implementation`),keyParameter:R.createIdentifier(`key`),pathParameter:R.createIdentifier(`path`),paramsArgument:R.createIdentifier(`params`),ctxArgument:R.createIdentifier(`ctx`),methodParameter:R.createIdentifier(`method`),requestParameter:R.createIdentifier(`request`),eventParameter:R.createIdentifier(`event`),dataParameter:R.createIdentifier(`data`),handlerParameter:R.createIdentifier(`handler`),msgParameter:R.createIdentifier(`msg`),parseRequestFn:R.createIdentifier(`parseRequest`),substituteFn:R.createIdentifier(`substitute`),provideMethod:R.createIdentifier(`provide`),onMethod:R.createIdentifier(`on`),implementationArgument:R.createIdentifier(`implementation`),hasBodyConst:R.createIdentifier(`hasBody`),undefinedValue:R.createIdentifier(`undefined`),responseConst:R.createIdentifier(`response`),restConst:R.createIdentifier(`rest`),searchParamsConst:R.createIdentifier(`searchParams`),defaultImplementationConst:R.createIdentifier(`defaultImplementation`),clientConst:R.createIdentifier(`client`),contentTypeConst:R.createIdentifier(`contentType`),isJsonConst:R.createIdentifier(`isJSON`),sourceProp:R.createIdentifier(`source`)};interfaces={input:R.createIdentifier(`Input`),positive:R.createIdentifier(`PositiveResponse`),negative:R.createIdentifier(`NegativeResponse`),encoded:R.createIdentifier(`EncodedResponse`),response:R.createIdentifier(`Response`)};methodType=vr(`Method`,ue);someOfType=U(`SomeOf`,J(`T`,Sr(`T`)),{params:[`T`]});requestType=U(`Request`,Sr(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>B(this.someOfType.name,[e]);makePathType=()=>vr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>wr(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>hr(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>H(`endpointTags`,R.createObjectLiteralExpression(Array.from(this.tags).map(([e,n])=>R.createPropertyAssignment(ur(e),R.createArrayLiteralExpression(t.map(Y,n))))),{expose:!0});makeImplementationType=()=>U(this.#e.implementationType,Ar({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:mr,[this.#e.ctxArgument.text]:{optional:!0,type:`T`}},Cr(v.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:v.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>H(this.#e.parseRequestFn,W({[this.#e.requestParameter.text]:v.SyntaxKind.StringKeyword},R.createAsExpression(K(this.#e.requestParameter,G(`split`))(R.createRegularExpressionLiteral(`/ (.+)/`),Y(2)),R.createTupleTypeNode([B(this.methodType.name),B(this.#e.pathType)]))));makeSubstituteFn=()=>H(this.#e.substituteFn,W({[this.#e.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:mr},R.createBlock([H(this.#e.restConst,R.createObjectLiteralExpression([R.createSpreadAssignment(this.#e.paramsArgument)])),R.createForInStatement(R.createVariableDeclarationList([R.createVariableDeclaration(this.#e.keyParameter)],v.NodeFlags.Const),this.#e.paramsArgument,R.createBlock([Or(this.#e.pathParameter,K(this.#e.pathParameter,G(`replace`))(dr(`:`,[this.#e.keyParameter]),W([],R.createBlock([R.createExpressionStatement(R.createDeleteExpression(R.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),R.createReturnStatement(R.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),R.createReturnStatement(R.createAsExpression(R.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),B(`const`)))])));#t=()=>br(this.#e.provideMethod,z({[this.#e.requestParameter.text]:`K`,[this.#e.paramsArgument.text]:J(this.interfaces.input,`K`),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}}),[H(_r(this.#e.methodParameter,this.#e.pathParameter),K(this.#e.parseRequestFn)(this.#e.requestParameter)),R.createReturnStatement(K(R.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,R.createSpreadElement(K(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Cr(J(this.interfaces.response,`K`))});makeClientClass=e=>xr(e,[pr([fr(this.#e.implementationArgument,{type:B(this.#e.implementationType,[`T`]),mod:or.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:[`T`]});#n=e=>dr(`?`,[q(URLSearchParams.name,e)]);#r=()=>q(URL.name,dr(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),Y(this.serverUrl));makeDefaultImplementation=()=>{let e=R.createPropertyAssignment(G(`method`),K(this.#e.methodParameter,G(`toUpperCase`))()),t=R.createPropertyAssignment(G(`headers`),Er(this.#e.hasBodyConst,R.createObjectLiteralExpression([R.createPropertyAssignment(Y(`Content-Type`),Y(y.json))]),this.#e.undefinedValue)),n=R.createPropertyAssignment(G(`body`),Er(this.#e.hasBodyConst,K(JSON[Symbol.toStringTag],G(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=H(this.#e.responseConst,R.createAwaitExpression(K(fetch.name)(this.#r(),R.createObjectLiteralExpression([e,t,n])))),i=H(this.#e.hasBodyConst,R.createLogicalNot(K(R.createArrayLiteralExpression([Y(`get`),Y(`head`),Y(`delete`)]),G(`includes`))(this.#e.methodParameter))),a=H(this.#e.searchParamsConst,Er(this.#e.hasBodyConst,Y(``),this.#n(this.#e.paramsArgument))),o=H(this.#e.contentTypeConst,K(this.#e.responseConst,G(`headers`),G(`get`))(Y(`content-type`))),s=R.createIfStatement(R.createPrefixUnaryExpression(v.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),R.createReturnStatement()),c=H(this.#e.isJsonConst,K(this.#e.contentTypeConst,G(`startsWith`))(Y(y.json))),l=R.createReturnStatement(K(this.#e.responseConst,Er(this.#e.isJsonConst,Y(G(`json`)),Y(G(`text`))))());return H(this.#e.defaultImplementationConst,W([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],R.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#e.implementationType})};#i=()=>pr(z({request:`K`,params:J(this.interfaces.input,`K`)}),[H(_r(this.#e.pathParameter,this.#e.restConst),K(this.#e.substituteFn)(R.createElementAccessExpression(K(this.#e.parseRequestFn)(this.#e.requestParameter),Y(1)),this.#e.paramsArgument)),H(this.#e.searchParamsConst,this.#n(this.#e.restConst)),Or(R.createPropertyAccessExpression(R.createThis(),this.#e.sourceProp),q(`EventSource`,this.#r()))]);#a=e=>R.createTypeLiteralNode([hr(G(`event`),e)]);#o=()=>br(this.#e.onMethod,z({[this.#e.eventParameter.text]:`E`,[this.#e.handlerParameter.text]:Ar({[this.#e.dataParameter.text]:J(Dr(`R`,gr(this.#a(`E`))),X(G(`data`)))},kr(v.SyntaxKind.VoidKeyword))}),[R.createExpressionStatement(K(R.createThis(),this.#e.sourceProp,G(`addEventListener`))(this.#e.eventParameter,W([this.#e.msgParameter],K(this.#e.handlerParameter)(K(JSON[Symbol.toStringTag],G(`parse`))(R.createPropertyAccessExpression(R.createParenthesizedExpression(R.createAsExpression(this.#e.msgParameter,B(MessageEvent.name))),G(`data`))))))),R.createReturnStatement(R.createThis())],{typeParams:{E:J(`R`,X(G(`event`)))}});makeSubscriptionClass=e=>xr(e,[yr(this.#e.sourceProp,`EventSource`),this.#i(),this.#o()],{typeParams:{K:Dr(this.requestType.name,R.createTemplateLiteralType(R.createTemplateHead(`get `),[R.createTemplateLiteralTypeSpan(B(v.SyntaxKind.StringKeyword),R.createTemplateTail(``))])),R:Dr(J(this.interfaces.positive,`K`),gr(this.#a(v.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[H(this.#e.clientConst,q(e)),K(this.#e.clientConst,this.#e.provideMethod)(Y(`get /v1/user/retrieve`),R.createObjectLiteralExpression([R.createPropertyAssignment(`id`,Y(`10`))])),K(q(t,Y(`get /v1/events/stream`),R.createObjectLiteralExpression()),this.#e.onMethod)(Y(`time`),W([`time`],R.createBlock([])))]};const Pr=(t,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=e(t),s=o&&o in r?r[o]:r[t._zod.def.type],c=e=>Pr(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(t,{...a,next:c}):i(t,a),u=n&&n(t,{prev:l,...a});return u?{...l,...u}:l},{factory:Z}=v,Fr={[v.SyntaxKind.AnyKeyword]:``,[v.SyntaxKind.BigIntKeyword]:BigInt(0),[v.SyntaxKind.BooleanKeyword]:!1,[v.SyntaxKind.NumberKeyword]:0,[v.SyntaxKind.ObjectKeyword]:{},[v.SyntaxKind.StringKeyword]:``,[v.SyntaxKind.UndefinedKeyword]:void 0},Ir={name:t.path([`name`,`text`]),type:t.path([`type`]),optional:t.path([`questionToken`])},Lr=({_zod:{def:e}})=>{let t=e.values.map(e=>e===void 0?B(v.SyntaxKind.UndefinedKeyword):X(e));return t.length===1?t[0]:V(t)},Rr=({_zod:{def:e}},{next:t})=>{let n=[...e.parts],r=()=>{let e=``;for(;n.length;){let t=n.shift();if(C(t)){n.unshift(t);break}e+=t??``}return e},i=Z.createTemplateHead(r()),a=[];for(;n.length;){let e=t(n.shift()),i=r(),o=n.length?Z.createTemplateMiddle:Z.createTemplateTail;a.push(Z.createTemplateLiteralTypeSpan(e,o(i)))}return a.length?Z.createTemplateLiteralType(i,a):X(i.text)},zr=(e,{isResponse:t,next:r,makeAlias:i})=>{let a=()=>{let i=Object.entries(e._zod.def.shape).map(([e,i])=>{let{description:a,deprecated:o}=n.get(i)||{};return hr(e,r(i),{comment:a,isDeprecated:o,isOptional:(t?i._zod.optout:i._zod.optin)===`optional`})});return Z.createTypeLiteralNode(i)};return Be(e,{io:t?`output`:`input`})?i(e,a):a()},Br=({_zod:{def:e}},{next:t})=>Z.createArrayTypeNode(t(e.element)),Vr=({_zod:{def:e}})=>V(Object.values(e.entries).map(X)),Hr=({_zod:{def:e}},{next:t})=>V(e.options.map(t)),Ur=e=>Fr?.[e.kind],Wr=({_zod:{def:e}},{next:t})=>V([t(e.innerType),X(null)]),Gr=({_zod:{def:e}},{next:t})=>Z.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:Z.createRestTypeNode(t(e.rest)))),Kr=({_zod:{def:e}},{next:t})=>B(`Record`,[e.keyType,e.valueType].map(t)),qr=t.tryCatch(e=>{if(!e.every(v.isTypeLiteralNode))throw Error(`Not objects`);let n=t.chain(t.prop(`members`),e),r=t.uniqWith((...e)=>{if(!t.eqBy(Ir.name,...e))return!1;if(t.both(t.eqBy(Ir.type),t.eqBy(Ir.optional))(...e))return!0;throw Error(`Has conflicting prop`)},n);return Z.createTypeLiteralNode(r)},(e,t)=>Z.createIntersectionTypeNode(t)),Jr=({_zod:{def:e}},{next:t})=>qr([e.left,e.right].map(t)),Q=e=>()=>B(e),$=({_zod:{def:e}},{next:t})=>t(e.innerType),Yr=e=>B(e?v.SyntaxKind.UnknownKeyword:v.SyntaxKind.AnyKeyword),Xr=({_zod:{def:e}},{next:t,isResponse:n})=>{let r=e[n?`out`:`in`],i=e[n?`in`:`out`];if(!C(r,`transform`))return t(r);let a=Se(r,Ur(t(i))),o={number:v.SyntaxKind.NumberKeyword,bigint:v.SyntaxKind.BigIntKeyword,boolean:v.SyntaxKind.BooleanKeyword,string:v.SyntaxKind.StringKeyword,undefined:v.SyntaxKind.UndefinedKeyword,object:v.SyntaxKind.ObjectKeyword};return B(a&&o[a]||Yr(n))},Zr=()=>X(null),Qr=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),$r=()=>B(`Buffer`),ei=(e,{next:t})=>t(e._zod.def.shape.raw),ti={string:Q(v.SyntaxKind.StringKeyword),number:Q(v.SyntaxKind.NumberKeyword),bigint:Q(v.SyntaxKind.BigIntKeyword),boolean:Q(v.SyntaxKind.BooleanKeyword),any:Q(v.SyntaxKind.AnyKeyword),undefined:Q(v.SyntaxKind.UndefinedKeyword),[D]:Q(v.SyntaxKind.StringKeyword),[O]:Q(v.SyntaxKind.StringKeyword),never:Q(v.SyntaxKind.NeverKeyword),void:Q(v.SyntaxKind.UndefinedKeyword),unknown:Q(v.SyntaxKind.UnknownKeyword),null:Zr,array:Br,tuple:Gr,record:Kr,object:zr,literal:Lr,template_literal:Rr,intersection:Jr,union:Hr,default:$,enum:Vr,optional:$,nonoptional:$,nullable:Wr,catch:$,pipe:Xr,lazy:Qr,readonly:$,[E]:$r,[N]:ei},ni=(e,{brandHandling:t,ctx:n})=>Pr(e,{rules:{...t,...ti},onMissing:({},{isResponse:e})=>Yr(e),ctx:n});var ri=class extends Nr{#e=[this.someOfType];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=X(null);this.#t.set(e,U(n,r)),this.#t.set(e,U(n,t()))}return B(n)}constructor({routing:e,config:n,brandHandling:i,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noContent:l=r.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this)},f={brandHandling:i,ctx:{...d,isResponse:!1}},p={brandHandling:i,ctx:{...d,isResponse:!0}},m=(e,n,r)=>{let i=w.bind(null,e,n),{isDeprecated:a,inputSchema:o,tags:s}=r,c=`${e} ${n}`,u=U(i(`input`),ni(o,f),{comment:c});this.#e.push(u);let d=nt.reduce((n,a)=>{let o=r.getResponses(a),s=t.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=we(e,r),u=U(i(a,`variant`,`${t+1}`),ni(s?n:l,p),{comment:c});return this.#e.push(u),o.map(e=>hr(e,u.name))},Array.from(o.entries())),u=wr(i(a,`response`,`variants`),s,{comment:c});return this.#e.push(u),Object.assign(n,{[a]:u})},{});this.paths.add(n);let m=X(c),ee={input:B(u.name),positive:this.someOf(d.positive),negative:this.someOf(d.negative),response:V([J(this.interfaces.positive,m),J(this.interfaces.negative,m)]),encoded:R.createIntersectionTypeNode([B(d.positive.name),B(d.negative.name)])};this.registry.set(c,{isDeprecated:a,store:ee}),this.tags.set(c,s)};Ft({routing:e,config:n,onEndpoint:u?Ot(m):m}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n.push(...this.makeUsageStatements(o,s)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:cr(t,e)).join(`
18
- `):void 0}print(e){let t=this.#i(e),n=t&&v.addSyntheticLeadingComment(v.addSyntheticLeadingComment(R.createEmptyStatement(),v.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),v.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#e.concat(n||[]).map((t,n)=>cr(t,n<this.#e.length?e:{...e,omitTrailingSemicolon:!0})).join(`
17
+ `))},qt=e=>{e.startupLogo!==!1&&Kt(process.stdout);let t=e.errorHandler||G,n=rt(e.logger)?e.logger:new st(e.logger);n.debug(`Running`,{build:`v26.1.0-beta.1`,env:process.env.NODE_ENV||`development`}),Wt(n);let r=Ht({logger:n,config:e}),i={getLogger:Ut(n),errorHandler:t},a=Lt(i),o=It(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},Jt=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=qt(e);return Ot({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},Yt=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=qt(e),s=v().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.compression){let t=await lt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r}),Ot({app:s,routing:t,getLogger:r,config:e,parsers:{json:[e.jsonParser||v.json()],raw:[e.rawParser||v.raw(),Vt],form:[e.formParser||v.urlencoded()],upload:e.upload?await Bt({config:e,getLogger:r}):[]}}),await e.afterRouting?.({app:s,getLogger:r}),s.use(a,i);let c=[],l=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),u=[];if(e.http){let t=ee.createServer(s);c.push(t),u.push(l(t,e.http.listen))}if(e.https){let t=te.createServer(e.https.options,s);c.push(t),u.push(l(t,e.https.listen))}return c.length||n.warn(`No servers configured.`),e.gracefulShutdown&&Gt({logger:n,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:u.map(e=>e())}},Xt=e=>O(e)&&`or`in e,Zt=e=>O(e)&&`and`in e,Qt=e=>!Zt(e)&&!Xt(e),$t=e=>{let t=n.filter(Qt,e),r=n.chain(n.prop(`and`),n.filter(Zt,e)),[i,a]=n.partition(Qt,r),o=n.concat(t,i),s=n.filter(Xt,e);return n.map(n.prop(`or`),n.concat(s,a)).reduce((e,t)=>E(e,n.map(e=>Qt(e)?[e]:e.and,t),([e,t])=>n.concat(e,t)),n.reject(n.isEmpty,[o]))};var en=`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`.split(`.`);const tn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,nn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},rn=e=>e.replace(de,e=>`{${e.slice(1)}}`),an=({},e)=>{if(e.isResponse)throw new N(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},on=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),sn=({zodSchema:e,jsonSchema:t})=>{if(!T(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},cn=n.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return Y(e,`throw`)},(e,{jsonSchema:t})=>t),ln=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:hn(t.type)})},X=e=>e,un=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new N(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:`^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?)?Z?$`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},dn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new N(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},fn=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),pn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,mn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return nn?.[t]},hn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],gn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!T(r,`transform`))return t;let a=X(Cn(i,{ctx:n}));if(y(a))if(n.isResponse){let e=be(r,mn(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},_n=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!O(t.properties.raw)?e:t.properties.raw},vn=e=>e.length?n.fromPairs(n.zip(n.times(e=>`example${e+1}`,e.length),n.map(n.objOf(`value`),e))):void 0,yn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||en.includes(e),bn=({path:e,method:t,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let u=Y(r),d=fe(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),h=e=>p&&d.includes(e),g=n.chain(n.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),_=n=>m&&(s?.(n,t,e)??yn(n,g));return Object.entries(u.properties).reduce((e,[t,r])=>{if(!O(r))return e;let i=h(t)?`path`:_(t)?`header`:f?`query`:void 0;if(!i)return e;let s=X(r),c=o===`components`?a(r.id||JSON.stringify(r),s,D(l,t)):s;return e.concat({name:t,in:i,deprecated:r.deprecated,required:u.required?.includes(t)||!1,description:s.description||l,schema:c,examples:vn(y(s)&&s.examples?.length?s.examples:n.pluck(t,u.examples?.filter(n.both(O,n.has(t)))||[]))})},[])},xn={nullable:ln,union:sn,bigint:fn,intersection:cn,tuple:pn,pipe:gn,[A]:un,[j]:dn,[L]:an,[R]:_n,[k]:on},Sn=(e,t,r)=>{let i=[e,t];for(;i.length;){let e=i.shift();if(n.is(Object,e)){if(ie(e)&&!e.$ref.startsWith(`#/components`)){let n=t[e.$ref.split(`/`).pop()];n&&(e.$ref=r.makeRef(n.id||n,X(n)).$ref);continue}i.push(...n.values(e))}n.is(Array,e)&&i.push(...n.values(e))}return e},Cn=(e,{ctx:n,rules:r=xn})=>{let{$defs:a={},properties:o={}}=i.toJSONSchema(i.object({subject:e}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:e=>{let i=t(e.zodSchema),a=r[i&&i in r?i:e.zodSchema._zod.def.type];if(a){let t={...a(e,n)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,t)}}});return Sn(O(o.subject)?o.subject:{},a,n)},wn=(e,t)=>{if(ie(e))return[e,!1];let r=!1,i=n.map(e=>{let[n,i]=wn(e,t);return r||=i,n}),a=n.omit(t),o={properties:a,examples:n.map(a),required:n.without(t),allOf:i,oneOf:i,anyOf:i},s=n.evolve(o,e);return[s,r||!!s.required?.length]},Tn=({method:e,path:t,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${t} ${ye(a)} response ${c?l:``}`.trim()})=>{if(!Se(e,i))return{description:d};let f=X(Cn(r,{rules:{...u,...xn},ctx:{isResponse:!0,makeRef:o,path:t,method:e}})),p=[];y(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,D(d)):f,examples:vn(p)};return{description:d,content:n.fromPairs(n.xprod(i,[m]))}},En=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Dn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},On=({name:e})=>({type:`apiKey`,in:`header`,name:e}),kn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),An=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),jn=({flows:e={}})=>({type:`oauth2`,flows:n.map(e=>({...e,scopes:e.scopes||{}}),n.reject(n.isNil,e))}),Mn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?En(e):e.type===`input`?Dn(e,t):e.type===`header`?On(e):e.type===`cookie`?kn(e):e.type===`openid`?An(e):jn(e);return e.map(e=>e.map(n))},Nn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Pn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Cn(e,{rules:{...t,...xn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Fn=({method:e,path:t,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let[u,d]=wn(X(i),c),f=[];y(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,D(l)):u,examples:vn(f.length?f:Y(i).examples?.filter(e=>O(e)&&!Array.isArray(e)).map(n.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===x.raw)&&(m.required=!0),m},In=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Ln=e=>e.length<=50?e:e.slice(0,49)+`…`,Rn=e=>e.length?e.slice():void 0;var zn=class extends re{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n=this.#n.get(e)){return n||(n=`Schema${this.#n.size+1}`,this.#n.set(e,n)),this.addSchema(n,t),{$ref:`#/components/schemas/${n}`}}#i(e,t,n){let r=n||D(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new N(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:t,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#r.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,h=d?Ln(d):u&&c?Ln(c):void 0,g=_e(e,t.inputSources),_=this.#i(r,e,i.getOperationId(e)),v=Pn({...a,schema:m}),ee=$t(i.security),te=bn({...a,inputSources:g,isHeader:l,security:ee,request:v,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:_})}),ne={};for(let t of Ye){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)ne[l]=Tn({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:_,statusCode:l})})}let re=g.includes(`body`)?Fn({...a,request:v,paramNames:n.pluck(`name`,te),schema:m,mimeType:x[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:_})}):void 0,ie=Nn(Mn(ee,g),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),y={operationId:_,summary:h,description:c,deprecated:i.isDeprecated||void 0,tags:Rn(i.tags),parameters:Rn(te),requestBody:re,security:Rn(ie),responses:ne};this.addPath(rn(r),{[e]:y})};Ct({routing:e,config:t,onEndpoint:d?gt(p):p}),c&&(this.rootDoc.tags=In(c))}};const Bn=e=>ae({...e,headers:{"content-type":x.json,...e?.headers}}),Vn=e=>oe(e),Hn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:it(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},Un=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=Bn(e),a=Vn({req:i,...t});a.req=t?.req||i,i.res=a;let o=Hn(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},Wn=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=Un(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},Gn=async({middleware:e,ctx:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=G}}=Un(n),c={request:r,response:i,logger:a,input:ve(r,o),ctx:t};try{return{requestMock:r,responseMock:i,loggerMock:a,output:await e.execute(c)}}catch(e){return await s.execute({...c,error:C(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}};var Kn=class{ts;f;exportModifier;asyncModifier;accessModifiers;#e;#t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;constructor(){this.ts=e(import.meta.url)(`typescript`),this.f=this.ts.factory,this.exportModifier=[this.f.createModifier(this.ts.SyntaxKind.ExportKeyword)],this.asyncModifier=[this.f.createModifier(this.ts.SyntaxKind.AsyncKeyword)],this.accessModifiers={public:[this.f.createModifier(this.ts.SyntaxKind.PublicKeyword)],protectedReadonly:[this.f.createModifier(this.ts.SyntaxKind.ProtectedKeyword),this.f.createModifier(this.ts.SyntaxKind.ReadonlyKeyword)]},this.#e=[this.ts.SyntaxKind.AnyKeyword,this.ts.SyntaxKind.BigIntKeyword,this.ts.SyntaxKind.BooleanKeyword,this.ts.SyntaxKind.NeverKeyword,this.ts.SyntaxKind.NumberKeyword,this.ts.SyntaxKind.ObjectKeyword,this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.SymbolKeyword,this.ts.SyntaxKind.UndefinedKeyword,this.ts.SyntaxKind.UnknownKeyword,this.ts.SyntaxKind.VoidKeyword]}addJsDoc=(e,t)=>this.ts.addSyntheticLeadingComment(e,this.ts.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0);printNode=(e,t)=>{let n=this.ts.createSourceFile(`print.ts`,``,this.ts.ScriptTarget.Latest,!1,this.ts.ScriptKind.TS);return this.ts.createPrinter(t).printNode(this.ts.EmitHint.Unspecified,e,n)};makePropertyIdentifier=e=>typeof e==`string`&&this.#t.test(e)?this.f.createIdentifier(e):this.literally(e);makeTemplate=(e,...t)=>this.f.createTemplateExpression(this.f.createTemplateHead(e),t.map(([e,n=``],r)=>this.f.createTemplateSpan(e,r===t.length-1?this.f.createTemplateTail(n):this.f.createTemplateMiddle(n))));makeParam=(e,{type:t,mod:n,init:r,optional:i}={})=>this.f.createParameterDeclaration(n,void 0,e,i?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,t?this.ensureTypeNode(t):void 0,r);makeParams=e=>Object.entries(e).map(([e,t])=>this.makeParam(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t));makePublicConstructor=(e,t=[])=>this.f.createConstructorDeclaration(this.accessModifiers.public,e,this.f.createBlock(t));ensureTypeNode=(e,t)=>typeof e==`number`?this.f.createKeywordTypeNode(e):typeof e==`string`||this.ts.isIdentifier(e)?this.f.createTypeReferenceNode(e,t&&n.map(this.ensureTypeNode.bind(this),t)):e;makeRecordStringAny=()=>this.ensureTypeNode(`Record`,[this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.AnyKeyword]);makeUnion=e=>{let t=new Map;for(let n of e)t.set(this.isPrimitive(n)?n.kind:n,n);return this.f.createUnionTypeNode(Array.from(t.values()))};makeInterfaceProp=(e,t,{isOptional:r,isDeprecated:i,comment:a}={})=>{let o=this.ensureTypeNode(t),s=this.f.createPropertySignature(void 0,this.makePropertyIdentifier(e),r?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,r?this.makeUnion([o,this.ensureTypeNode(this.ts.SyntaxKind.UndefinedKeyword)]):o),c=n.reject(n.isNil,[i?`@deprecated`:void 0,a]);return c.length?this.addJsDoc(s,c.join(` `)):s};makeOneLine=e=>this.ts.setEmitFlags(e,this.ts.EmitFlags.SingleLine);makeDeconstruction=(...e)=>this.f.createArrayBindingPattern(e.map(e=>this.f.createBindingElement(void 0,void 0,e)));makeConst=(e,t,{type:n,expose:r}={})=>this.f.createVariableStatement(r&&this.exportModifier,this.f.createVariableDeclarationList([this.f.createVariableDeclaration(e,void 0,n?this.ensureTypeNode(n):void 0,t)],this.ts.NodeFlags.Const));makePublicLiteralType=(e,t)=>this.makeType(e,this.makeUnion(n.map(this.makeLiteralType.bind(this),t)),{expose:!0});makeType=(e,t,{expose:n,comment:r,params:i}={})=>{let a=this.f.createTypeAliasDeclaration(n?this.exportModifier:void 0,e,i&&this.makeTypeParams(i),t);return r?this.addJsDoc(a,r):a};makePublicProperty=(e,t)=>this.f.createPropertyDeclaration(this.accessModifiers.public,e,void 0,this.ensureTypeNode(t),void 0);makePublicMethod=(e,t,n,{typeParams:r,returns:i}={})=>this.f.createMethodDeclaration(this.accessModifiers.public,void 0,e,void 0,r&&this.makeTypeParams(r),t,i,this.f.createBlock(n));makePublicClass=(e,t,{typeParams:n}={})=>this.f.createClassDeclaration(this.exportModifier,e,n&&this.makeTypeParams(n),void 0,t);makeKeyOf=e=>this.f.createTypeOperatorNode(this.ts.SyntaxKind.KeyOfKeyword,this.ensureTypeNode(e));makePromise=e=>this.ensureTypeNode(Promise.name,[e]);makeInterface=(e,t,{expose:n,comment:r}={})=>{let i=this.f.createInterfaceDeclaration(n?this.exportModifier:void 0,e,void 0,void 0,t);return r?this.addJsDoc(i,r):i};makeTypeParams=e=>(Array.isArray(e)?e.map(e=>n.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return this.f.createTypeParameterDeclaration([],e,n?this.ensureTypeNode(n):void 0,r?this.ensureTypeNode(r):void 0)});makeArrowFn=(e,t,{isAsync:r}={})=>this.f.createArrowFunction(r?this.asyncModifier:void 0,void 0,Array.isArray(e)?n.map(this.makeParam.bind(this),e):this.makeParams(e),void 0,void 0,t);makeTernary=(e,t,n)=>this.f.createConditionalExpression(e,this.f.createToken(this.ts.SyntaxKind.QuestionToken),t,this.f.createToken(this.ts.SyntaxKind.ColonToken),n);makeCall=(e,...t)=>(...n)=>this.f.createCallExpression(t.reduce((e,t)=>typeof t==`string`||this.ts.isIdentifier(t)?this.f.createPropertyAccessExpression(e,t):this.f.createElementAccessExpression(e,t),typeof e==`string`?this.f.createIdentifier(e):e),void 0,n);makeNew=(e,...t)=>this.f.createNewExpression(this.f.createIdentifier(e),void 0,t);makeExtract=(e,t)=>this.ensureTypeNode(`Extract`,[e,t]);makeAssignment=(e,t)=>this.f.createExpressionStatement(this.f.createBinaryExpression(e,this.f.createToken(this.ts.SyntaxKind.EqualsToken),t));makeIndexed=(e,t)=>this.f.createIndexedAccessTypeNode(this.ensureTypeNode(e),this.ensureTypeNode(t));makeMaybeAsync=e=>this.makeUnion([this.ensureTypeNode(e),this.makePromise(e)]);makeFnType=(e,t)=>this.f.createFunctionTypeNode(void 0,this.makeParams(e),this.ensureTypeNode(t));literally=e=>typeof e==`number`?this.f.createNumericLiteral(e):typeof e==`bigint`?this.f.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?this.f.createTrue():this.f.createFalse():e===null?this.f.createNull():this.f.createStringLiteral(e);makeLiteralType=e=>this.f.createLiteralTypeNode(this.literally(e));isPrimitive=e=>this.#e.includes(e.kind)};const Z=e=>e;var qn=class extends Kn{paths=new Set;tags=new Map;registry=new Map;#e={pathType:this.f.createIdentifier(`Path`),implementationType:this.f.createIdentifier(`Implementation`),keyParameter:this.f.createIdentifier(`key`),pathParameter:this.f.createIdentifier(`path`),paramsArgument:this.f.createIdentifier(`params`),ctxArgument:this.f.createIdentifier(`ctx`),methodParameter:this.f.createIdentifier(`method`),requestParameter:this.f.createIdentifier(`request`),eventParameter:this.f.createIdentifier(`event`),dataParameter:this.f.createIdentifier(`data`),handlerParameter:this.f.createIdentifier(`handler`),msgParameter:this.f.createIdentifier(`msg`),parseRequestFn:this.f.createIdentifier(`parseRequest`),substituteFn:this.f.createIdentifier(`substitute`),provideMethod:this.f.createIdentifier(`provide`),onMethod:this.f.createIdentifier(`on`),implementationArgument:this.f.createIdentifier(`implementation`),hasBodyConst:this.f.createIdentifier(`hasBody`),undefinedValue:this.f.createIdentifier(`undefined`),responseConst:this.f.createIdentifier(`response`),restConst:this.f.createIdentifier(`rest`),searchParamsConst:this.f.createIdentifier(`searchParams`),defaultImplementationConst:this.f.createIdentifier(`defaultImplementation`),clientConst:this.f.createIdentifier(`client`),contentTypeConst:this.f.createIdentifier(`contentType`),isJsonConst:this.f.createIdentifier(`isJSON`),sourceProp:this.f.createIdentifier(`source`)};interfaces={input:this.f.createIdentifier(`Input`),positive:this.f.createIdentifier(`PositiveResponse`),negative:this.f.createIdentifier(`NegativeResponse`),encoded:this.f.createIdentifier(`EncodedResponse`),response:this.f.createIdentifier(`Response`)};methodType=this.makePublicLiteralType(`Method`,le);someOfType=this.makeType(`SomeOf`,this.makeIndexed(`T`,this.makeKeyOf(`T`)),{params:[`T`]});requestType=this.makeType(`Request`,this.makeKeyOf(this.interfaces.input),{expose:!0});constructor(e){super(),this.serverUrl=e}someOf=({name:e})=>this.ensureTypeNode(this.someOfType.name,[e]);makePathType=()=>this.makePublicLiteralType(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>this.makeInterface(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>this.makeInterfaceProp(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>this.makeConst(`endpointTags`,this.f.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>this.f.createPropertyAssignment(this.makePropertyIdentifier(e),this.f.createArrayLiteralExpression(n.map(this.literally.bind(this),t))))),{expose:!0});makeImplementationType=()=>this.makeType(this.#e.implementationType,this.makeFnType({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:this.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.makeRecordStringAny(),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}},this.makePromise(this.ts.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:this.ts.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>this.makeConst(this.#e.parseRequestFn,this.makeArrowFn({[this.#e.requestParameter.text]:this.ts.SyntaxKind.StringKeyword},this.f.createAsExpression(this.makeCall(this.#e.requestParameter,Z(`split`))(this.f.createRegularExpressionLiteral(`/ (.+)/`),this.literally(2)),this.f.createTupleTypeNode([this.ensureTypeNode(this.methodType.name),this.ensureTypeNode(this.#e.pathType)]))));makeSubstituteFn=()=>this.makeConst(this.#e.substituteFn,this.makeArrowFn({[this.#e.pathParameter.text]:this.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.makeRecordStringAny()},this.f.createBlock([this.makeConst(this.#e.restConst,this.f.createObjectLiteralExpression([this.f.createSpreadAssignment(this.#e.paramsArgument)])),this.f.createForInStatement(this.f.createVariableDeclarationList([this.f.createVariableDeclaration(this.#e.keyParameter)],this.ts.NodeFlags.Const),this.#e.paramsArgument,this.f.createBlock([this.makeAssignment(this.#e.pathParameter,this.makeCall(this.#e.pathParameter,Z(`replace`))(this.makeTemplate(`:`,[this.#e.keyParameter]),this.makeArrowFn([],this.f.createBlock([this.f.createExpressionStatement(this.f.createDeleteExpression(this.f.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),this.f.createReturnStatement(this.f.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),this.f.createReturnStatement(this.f.createAsExpression(this.f.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),this.ensureTypeNode(`const`)))])));#t=()=>this.makePublicMethod(this.#e.provideMethod,this.makeParams({[this.#e.requestParameter.text]:`K`,[this.#e.paramsArgument.text]:this.makeIndexed(this.interfaces.input,`K`),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}}),[this.makeConst(this.makeDeconstruction(this.#e.methodParameter,this.#e.pathParameter),this.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter)),this.f.createReturnStatement(this.makeCall(this.f.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,this.f.createSpreadElement(this.makeCall(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:this.makePromise(this.makeIndexed(this.interfaces.response,`K`))});makeClientClass=e=>this.makePublicClass(e,[this.makePublicConstructor([this.makeParam(this.#e.implementationArgument,{type:this.ensureTypeNode(this.#e.implementationType,[`T`]),mod:this.accessModifiers.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:[`T`]});#n=e=>this.makeTemplate(`?`,[this.makeNew(URLSearchParams.name,e)]);#r=()=>this.makeNew(URL.name,this.makeTemplate(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),this.literally(this.serverUrl));makeDefaultImplementation=()=>{let e=this.f.createPropertyAssignment(Z(`method`),this.makeCall(this.#e.methodParameter,Z(`toUpperCase`))()),t=this.f.createPropertyAssignment(Z(`headers`),this.makeTernary(this.#e.hasBodyConst,this.f.createObjectLiteralExpression([this.f.createPropertyAssignment(this.literally(`Content-Type`),this.literally(x.json))]),this.#e.undefinedValue)),n=this.f.createPropertyAssignment(Z(`body`),this.makeTernary(this.#e.hasBodyConst,this.makeCall(JSON[Symbol.toStringTag],Z(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=this.makeConst(this.#e.responseConst,this.f.createAwaitExpression(this.makeCall(fetch.name)(this.#r(),this.f.createObjectLiteralExpression([e,t,n])))),i=this.makeConst(this.#e.hasBodyConst,this.f.createLogicalNot(this.makeCall(this.f.createArrayLiteralExpression([this.literally(`get`),this.literally(`head`),this.literally(`delete`)]),Z(`includes`))(this.#e.methodParameter))),a=this.makeConst(this.#e.searchParamsConst,this.makeTernary(this.#e.hasBodyConst,this.literally(``),this.#n(this.#e.paramsArgument))),o=this.makeConst(this.#e.contentTypeConst,this.makeCall(this.#e.responseConst,Z(`headers`),Z(`get`))(this.literally(`content-type`))),s=this.f.createIfStatement(this.f.createPrefixUnaryExpression(this.ts.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),this.f.createReturnStatement()),c=this.makeConst(this.#e.isJsonConst,this.makeCall(this.#e.contentTypeConst,Z(`startsWith`))(this.literally(x.json))),l=this.f.createReturnStatement(this.makeCall(this.#e.responseConst,this.makeTernary(this.#e.isJsonConst,this.literally(Z(`json`)),this.literally(Z(`text`))))());return this.makeConst(this.#e.defaultImplementationConst,this.makeArrowFn([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],this.f.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#e.implementationType})};#i=()=>this.makePublicConstructor(this.makeParams({request:`K`,params:this.makeIndexed(this.interfaces.input,`K`)}),[this.makeConst(this.makeDeconstruction(this.#e.pathParameter,this.#e.restConst),this.makeCall(this.#e.substituteFn)(this.f.createElementAccessExpression(this.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter),this.literally(1)),this.#e.paramsArgument)),this.makeConst(this.#e.searchParamsConst,this.#n(this.#e.restConst)),this.makeAssignment(this.f.createPropertyAccessExpression(this.f.createThis(),this.#e.sourceProp),this.makeNew(`EventSource`,this.#r()))]);#a=e=>this.f.createTypeLiteralNode([this.makeInterfaceProp(Z(`event`),e)]);#o=()=>this.makePublicMethod(this.#e.onMethod,this.makeParams({[this.#e.eventParameter.text]:`E`,[this.#e.handlerParameter.text]:this.makeFnType({[this.#e.dataParameter.text]:this.makeIndexed(this.makeExtract(`R`,this.makeOneLine(this.#a(`E`))),this.makeLiteralType(Z(`data`)))},this.makeMaybeAsync(this.ts.SyntaxKind.VoidKeyword))}),[this.f.createExpressionStatement(this.makeCall(this.f.createThis(),this.#e.sourceProp,Z(`addEventListener`))(this.#e.eventParameter,this.makeArrowFn([this.#e.msgParameter],this.makeCall(this.#e.handlerParameter)(this.makeCall(JSON[Symbol.toStringTag],Z(`parse`))(this.f.createPropertyAccessExpression(this.f.createParenthesizedExpression(this.f.createAsExpression(this.#e.msgParameter,this.ensureTypeNode(MessageEvent.name))),Z(`data`))))))),this.f.createReturnStatement(this.f.createThis())],{typeParams:{E:this.makeIndexed(`R`,this.makeLiteralType(Z(`event`)))}});makeSubscriptionClass=e=>this.makePublicClass(e,[this.makePublicProperty(this.#e.sourceProp,`EventSource`),this.#i(),this.#o()],{typeParams:{K:this.makeExtract(this.requestType.name,this.f.createTemplateLiteralType(this.f.createTemplateHead(`get `),[this.f.createTemplateLiteralTypeSpan(this.ensureTypeNode(this.ts.SyntaxKind.StringKeyword),this.f.createTemplateTail(``))])),R:this.makeExtract(this.makeIndexed(this.interfaces.positive,`K`),this.makeOneLine(this.#a(this.ts.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[this.makeConst(this.#e.clientConst,this.makeNew(e)),this.makeCall(this.#e.clientConst,this.#e.provideMethod)(this.literally(`get /v1/user/retrieve`),this.f.createObjectLiteralExpression([this.f.createPropertyAssignment(`id`,this.literally(`10`))])),this.makeCall(this.makeNew(t,this.literally(`get /v1/events/stream`),this.f.createObjectLiteralExpression()),this.#e.onMethod)(this.literally(`time`),this.makeArrowFn([`time`],this.f.createBlock([])))]};const Jn=(e,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=t(e),s=o&&o in r?r[o]:r[e._zod.def.type],c=e=>Jn(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(e,{...a,next:c}):i(e,a),u=n&&n(e,{prev:l,...a});return u?{...l,...u}:l},Yn={[b.SyntaxKind.AnyKeyword]:``,[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:``,[b.SyntaxKind.UndefinedKeyword]:void 0},Xn={name:n.path([`name`,`text`]),type:n.path([`type`]),optional:n.path([`questionToken`])},Zn=({_zod:{def:e}},{api:t})=>{let n=e.values.map(e=>e===void 0?t.ensureTypeNode(b.SyntaxKind.UndefinedKeyword):t.makeLiteralType(e));return n.length===1?n[0]:t.makeUnion(n)},Qn=({_zod:{def:e}},{next:t,api:n})=>{let r=[...e.parts],i=()=>{let e=``;for(;r.length;){let t=r.shift();if(T(t)){r.unshift(t);break}e+=t??``}return e},a=n.f.createTemplateHead(i()),o=[];for(;r.length;){let e=t(r.shift()),a=i(),s=r.length?n.f.createTemplateMiddle:n.f.createTemplateTail;o.push(n.f.createTemplateLiteralTypeSpan(e,s(a)))}return o.length?n.f.createTemplateLiteralType(a,o):n.makeLiteralType(a.text)},$n=(e,{isResponse:t,next:n,makeAlias:i,api:a})=>{let o=()=>{let i=Object.entries(e._zod.def.shape).map(([e,i])=>{let{description:o,deprecated:s}=r.get(i)||{};return a.makeInterfaceProp(e,n(i),{comment:o,isDeprecated:s,isOptional:(t?i._zod.optout:i._zod.optin)===`optional`})});return a.f.createTypeLiteralNode(i)};return Ie(e,{io:t?`output`:`input`})?i(e,o):o()},er=({_zod:{def:e}},{next:t,api:n})=>n.f.createArrayTypeNode(t(e.element)),tr=({_zod:{def:e}},{api:t})=>t.makeUnion(Object.values(e.entries).map(t.makeLiteralType.bind(t))),nr=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion(e.options.map(t)),rr=e=>Yn?.[e.kind],ir=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion([t(e.innerType),n.makeLiteralType(null)]),ar=({_zod:{def:e}},{next:t,api:n})=>n.f.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:n.f.createRestTypeNode(t(e.rest)))),or=({_zod:{def:e}},{next:t,api:n})=>n.ensureTypeNode(`Record`,[e.keyType,e.valueType].map(t)),sr=n.tryCatch((e,t)=>{if(!t.every(b.isTypeLiteralNode))throw Error(`Not objects`);let r=n.chain(n.prop(`members`),t),i=n.uniqWith((...e)=>{if(!n.eqBy(Xn.name,...e))return!1;if(n.both(n.eqBy(Xn.type),n.eqBy(Xn.optional))(...e))return!0;throw Error(`Has conflicting prop`)},r);return e.f.createTypeLiteralNode(i)},(e,t,n)=>t.f.createIntersectionTypeNode(n)),cr=({_zod:{def:e}},{next:t,api:n})=>sr(n,[e.left,e.right].map(t)),Q=e=>({},{api:t})=>t.ensureTypeNode(e),$=({_zod:{def:e}},{next:t})=>t(e.innerType),lr=(e,t)=>e.ensureTypeNode(t?b.SyntaxKind.UnknownKeyword:b.SyntaxKind.AnyKeyword),ur=({_zod:{def:e}},{next:t,isResponse:n,api:r})=>{let i=e[n?`out`:`in`],a=e[n?`in`:`out`];if(!T(i,`transform`))return t(i);let o=be(i,rr(t(a))),s={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return r.ensureTypeNode(o&&s[o]||lr(r,n))},dr=({},{api:e})=>e.makeLiteralType(null),fr=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),pr=({},{api:e})=>e.ensureTypeNode(`Buffer`),mr=(e,{next:t})=>t(e._zod.def.shape.raw),hr={string:Q(b.SyntaxKind.StringKeyword),number:Q(b.SyntaxKind.NumberKeyword),bigint:Q(b.SyntaxKind.BigIntKeyword),boolean:Q(b.SyntaxKind.BooleanKeyword),any:Q(b.SyntaxKind.AnyKeyword),undefined:Q(b.SyntaxKind.UndefinedKeyword),[A]:Q(b.SyntaxKind.StringKeyword),[j]:Q(b.SyntaxKind.StringKeyword),never:Q(b.SyntaxKind.NeverKeyword),void:Q(b.SyntaxKind.UndefinedKeyword),unknown:Q(b.SyntaxKind.UnknownKeyword),null:dr,array:er,tuple:ar,record:or,object:$n,literal:Zn,template_literal:Qn,intersection:cr,union:nr,default:$,enum:tr,optional:$,nonoptional:$,nullable:ir,catch:$,pipe:ur,lazy:fr,readonly:$,[k]:pr,[R]:mr},gr=(e,{brandHandling:t,ctx:n})=>Jn(e,{rules:{...t,...hr},onMissing:({},{isResponse:e,api:t})=>lr(t,e),ctx:n});var _r=class extends qn{#e=[this.someOfType];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=this.makeLiteralType(null);this.#t.set(e,this.makeType(n,r)),this.#t.set(e,this.makeType(n,t()))}return this.ensureTypeNode(n)}constructor({routing:e,config:t,brandHandling:r,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noContent:l=i.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this),api:this},f={brandHandling:r,ctx:{...d,isResponse:!1}},p={brandHandling:r,ctx:{...d,isResponse:!0}},m=(e,t,r)=>{let i=D.bind(null,e,t),{isDeprecated:a,inputSchema:o,tags:s}=r,c=`${e} ${t}`,u=this.makeType(i(`input`),gr(o,f),{comment:c});this.#e.push(u);let d=Ye.reduce((t,a)=>{let o=r.getResponses(a),s=n.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=Se(e,r),u=this.makeType(i(a,`variant`,`${t+1}`),gr(s?n:l,p),{comment:c});return this.#e.push(u),o.map(e=>this.makeInterfaceProp(e,u.name))},Array.from(o.entries())),u=this.makeInterface(i(a,`response`,`variants`),s,{comment:c});return this.#e.push(u),Object.assign(t,{[a]:u})},{});this.paths.add(t);let m=this.makeLiteralType(c),h={input:this.ensureTypeNode(u.name),positive:this.someOf(d.positive),negative:this.someOf(d.negative),response:this.makeUnion([this.makeIndexed(this.interfaces.positive,m),this.makeIndexed(this.interfaces.negative,m)]),encoded:this.f.createIntersectionTypeNode([this.ensureTypeNode(d.positive.name),this.ensureTypeNode(d.negative.name)])};this.registry.set(c,{isDeprecated:a,store:h}),this.tags.set(c,s)};Ct({routing:e,config:t,onEndpoint:u?gt(m):m}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n.push(...this.makeUsageStatements(o,s)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:this.printNode(t,e)).join(`
18
+ `):void 0}print(e){let t=this.#i(e),n=t&&this.ts.addSyntheticLeadingComment(this.ts.addSyntheticLeadingComment(this.f.createEmptyStatement(),this.ts.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),this.ts.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#e.concat(n||[]).map((t,n)=>this.printNode(t,n<this.#e.length?e:{...e,omitTrailingSemicolon:!0})).join(`
19
19
 
20
- `)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=(await bt(`prettier`)).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#i(e);this.#n=r&&n?[await n(r)]:this.#n;let i=this.print(e);return n?n(i):i}};const ii=(e,t)=>r.object({data:t,event:r.literal(e),id:r.string().optional(),retry:r.int().positive().optional()}),ai=(e,t,n)=>ii(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
21
- `)).parse({event:t,data:n}),oi=e=>e.headersSent||e.writeHead(200,{connection:`keep-alive`,"content-type":y.sse,"cache-control":`no-cache`}),si=e=>new P({handler:async({request:t,response:n})=>{let r=new AbortController;return t.once(`close`,()=>{r.abort()}),setTimeout(()=>oi(n),1e4),{isClosed:()=>n.writableEnded||n.closed,signal:r.signal,emit:(t,r)=>{oi(n),n.write(ai(e,t,r),`utf-8`),n.flush?.()}}}}),ci=e=>new it({positive:()=>{let[t,...n]=Object.entries(e).map(([e,t])=>ii(e,t));return{mimeType:y.sse,schema:n.length?r.discriminatedUnion(`event`,[t,...n]):t}},negative:{mimeType:`text/plain`,schema:r.string()},handler:async({response:e,error:t,logger:n,request:r,input:i})=>{if(t){let a=Ke(t);Ge(a,n,r,i),e.headersSent||e.status(a.statusCode).type(`text/plain`).write(qe(a),`utf-8`)}e.end()}});var li=class extends lt{constructor(e){super(ci(e)),this.middlewares=[si(e)]}};const ui={dateIn:Ee,dateOut:De,form:Pe,upload:Fe,raw:Re,buffer:Te};export{vt as BuiltinLogger,Zn as Documentation,A as DocumentationError,lt as EndpointsFactory,li as EventStreamFactory,j as InputValidationError,ri as Integration,P as Middleware,Me as MissingPeerError,Ae as OutputValidationError,it as ResultHandler,k as RoutingError,yt as ServeStatic,dt as arrayEndpointsFactory,ct as arrayResultHandler,sn as attachRouting,ce as createConfig,cn as createServer,ut as defaultEndpointsFactory,ot as defaultResultHandler,Ke as ensureHttpError,ui as ez,S as getMessageFromError,nr as testEndpoint,rr as testMiddleware};
20
+ `)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=(await lt(`prettier`)).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#i(e);this.#n=r&&n?[await n(r)]:this.#n;let i=this.print(e);return n?n(i):i}};const vr=(e,t)=>i.object({data:t,event:i.literal(e),id:i.string().optional(),retry:i.int().positive().optional()}),yr=(e,t,n)=>vr(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
21
+ `)).parse({event:t,data:n}),br=e=>e.headersSent||e.writeHead(200,{connection:`keep-alive`,"content-type":x.sse,"cache-control":`no-cache`}),xr=e=>new H({handler:async({request:t,response:n})=>{let r=new AbortController;return t.once(`close`,()=>{r.abort()}),setTimeout(()=>br(n),1e4),{isClosed:()=>n.writableEnded||n.closed,signal:r.signal,emit:(t,r)=>{br(n),n.write(yr(e,t,r),`utf-8`),n.flush?.()}}}}),Sr=e=>new W({positive:()=>{let[t,...n]=Object.entries(e).map(([e,t])=>vr(e,t));return{mimeType:x.sse,schema:n.length?i.discriminatedUnion(`event`,[t,...n]):t}},negative:{mimeType:`text/plain`,schema:i.string()},handler:async({response:e,error:t,logger:n,request:r,input:i})=>{if(t){let a=B(t);z(a,n,r,i),e.headersSent||e.status(a.statusCode).type(`text/plain`).write(V(a),`utf-8`)}e.end()}});var Cr=class extends K{constructor(e){super(Sr(e)),this.middlewares=[xr(e)]}};const wr={dateIn:we,dateOut:Te,form:Ae,upload:je,raw:Pe,buffer:Ce};export{st as BuiltinLogger,zn as Documentation,N as DocumentationError,K as EndpointsFactory,Cr as EventStreamFactory,F as InputValidationError,_r as Integration,H as Middleware,ke as MissingPeerError,De as OutputValidationError,W as ResultHandler,M as RoutingError,ct as ServeStatic,tt as arrayEndpointsFactory,$e as arrayResultHandler,Jt as attachRouting,se as createConfig,Yt as createServer,et as defaultEndpointsFactory,G as defaultResultHandler,B as ensureHttpError,wr as ez,w as getMessageFromError,Wn as testEndpoint,Gn as testMiddleware};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "26.0.0-beta.2",
3
+ "version": "26.1.0-beta.1",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  "node-mocks-http": "^1.17.2",
39
39
  "openapi3-ts": "^4.5.0",
40
40
  "ramda": "^0.32.0",
41
- "@express-zod-api/zod-plugin": "^3.0.0-beta.2"
41
+ "@express-zod-api/zod-plugin": "^3.0.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@types/compression": "^1.7.5",
@@ -48,7 +48,7 @@
48
48
  "compression": "^1.8.0",
49
49
  "express": "^5.1.0",
50
50
  "express-fileupload": "^1.5.0",
51
- "http-errors": "^2.0.0",
51
+ "http-errors": "^2.0.1",
52
52
  "typescript": "^5.1.3",
53
53
  "zod": "^4.1.13"
54
54
  },
@@ -85,14 +85,14 @@
85
85
  "compression": "^1.8.0",
86
86
  "cors": "^2.8.5",
87
87
  "depd": "^2.0.0",
88
- "express": "^5.1.0",
88
+ "express": "^5.2.0",
89
89
  "express-fileupload": "^1.5.1",
90
- "http-errors": "^2.0.0",
91
- "node-forge": "^1.3.1",
90
+ "http-errors": "^2.0.1",
91
+ "node-forge": "^1.3.2",
92
92
  "snakify-ts": "^2.3.0",
93
93
  "typescript": "^5.9.2",
94
94
  "undici": "^7.10.0",
95
- "zod": "^4.1.13"
95
+ "zod": "^4.2.0"
96
96
  },
97
97
  "keywords": [
98
98
  "nodejs",