express-zod-api 25.3.1 → 25.4.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,6 +2,33 @@
2
2
 
3
3
  ## Version 25
4
4
 
5
+ ### v25.4.1
6
+
7
+ - This patch fixes the issue for users facing `TypeError: .example is not a function`, but not using that method:
8
+ - Some environments fail to load Zod plugin properly so that the usage of `ZodType::example()` (plugin method)
9
+ internally by the framework itself could cause that error;
10
+ - This version fixes the problem by replacing the usage of `.example()` with `globalRegistry.add()`;
11
+ - The issue was found and reported by [@misha-z1nchuk](https://github.com/misha-z1nchuk).
12
+
13
+ ### v25.4.0
14
+
15
+ - Feat: configurable query parser:
16
+ - In Express 5 the default query parser was changed from "extended" to "simple";
17
+ - The "extended" parser is the `qs` module, while the "simple" parser is the `node:querystring` module;
18
+ - This version introduces the new config option `queryParser` having the default value "simple" for compatibility;
19
+ - The "extended" parser supports nested objects and arrays with optional indexes in square brackets;
20
+ - You can now choose between "simple" and "extended" parsers as well as configure a custom implementation.
21
+
22
+ ```ts
23
+ import { createConfig } from "express-zod-api";
24
+ import qs from "qs";
25
+
26
+ const config = createConfig({
27
+ // for comma-separated arrays: ?values=1,2,3
28
+ queryParser: (query) => qs.parse(query, { comma: true }),
29
+ });
30
+ ```
31
+
5
32
  ### v25.3.1
6
33
 
7
34
  - Small optimization for running diagnostics (non-production mode);
package/README.md CHANGED
@@ -22,14 +22,15 @@ Start your API server with I/O schema validation and custom middlewares in minut
22
22
  3. [Options](#options)
23
23
  4. [Using native express middlewares](#using-native-express-middlewares)
24
24
  5. [Refinements](#refinements)
25
- 6. [Transformations](#transformations)
26
- 7. [Top level transformations and mapping](#top-level-transformations-and-mapping)
27
- 8. [Dealing with dates](#dealing-with-dates)
28
- 9. [Cross-Origin Resource Sharing](#cross-origin-resource-sharing) (CORS)
29
- 10. [Enabling HTTPS](#enabling-https)
30
- 11. [Enabling compression](#enabling-compression)
31
- 12. [Customizing logger](#customizing-logger)
32
- 13. [Child logger](#child-logger)
25
+ 6. [Query string parser](#query-string-parser)
26
+ 7. [Transformations](#transformations)
27
+ 8. [Top level transformations and mapping](#top-level-transformations-and-mapping)
28
+ 9. [Dealing with dates](#dealing-with-dates)
29
+ 10. [Cross-Origin Resource Sharing](#cross-origin-resource-sharing) (CORS)
30
+ 11. [Enabling HTTPS](#enabling-https)
31
+ 12. [Enabling compression](#enabling-compression)
32
+ 13. [Customizing logger](#customizing-logger)
33
+ 14. [Child logger](#child-logger)
33
34
  5. [Advanced features](#advanced-features)
34
35
  1. [Customizing input sources](#customizing-input-sources)
35
36
  2. [Headers as input source](#headers-as-input-source)
@@ -84,6 +85,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
84
85
 
85
86
  These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
86
87
 
88
+ [<img src="https://github.com/misha-z1nchuk.png" alt="@misha-z1nchuk" width="50px" />](https://github.com/misha-z1nchuk)
87
89
  [<img src="https://github.com/GreaterTamarack.png" alt="@GreaterTamarack" width="50px" />](https://github.com/GreaterTamarack)
88
90
  [<img src="https://github.com/pepegc.png" alt="@pepegc" width="50px" />](https://github.com/pepegc)
89
91
  [<img src="https://github.com/MichaelHindley.png" alt="@MichaelHindley" width="50px" />](https://github.com/MichaelHindley)
@@ -491,24 +493,31 @@ const endpoint = endpointsFactory.build({
491
493
  });
492
494
  ```
493
495
 
496
+ ## Query string parser
497
+
498
+ In Express 5 the default query string parser was changed from "extended" (which is the `qs` module) to "simple" (which
499
+ is the `node:querystring` module). The "extended" parser supports nested objects and arrays with optional indexes in
500
+ square brackets. You can choose between those parsers as well as configure a custom implementation:
501
+
502
+ | `queryParser` value | Query string example for arrays |
503
+ | -------------------------------------- | ------------------------------------------------ |
504
+ | simple | `?values=1&values=2&values=3` |
505
+ | extended | as simple or `?values[]=1&values[]=2&values[]=3` |
506
+ | `(str) => qs.parse(str, {comma:true})` | as extended or `?values=1,2,3` |
507
+
494
508
  ## Transformations
495
509
 
496
- Since parameters of GET requests come in the form of strings, there is often a need to transform them into numbers or
497
- arrays of numbers.
510
+ Since parameters of GET requests come in the form of strings, there is often a need to transform them into numbers.
498
511
 
499
512
  ```typescript
500
513
  import { z } from "zod";
501
514
 
502
- const getUserEndpoint = endpointsFactory.build({
515
+ const getUserEndpoint = endpointsFactory.buildVoid({
503
516
  input: z.object({
504
517
  id: z.string().transform((id) => parseInt(id, 10)),
505
- ids: z
506
- .string()
507
- .transform((ids) => ids.split(",").map((id) => parseInt(id, 10))),
508
518
  }),
509
- handler: async ({ input: { id, ids }, logger }) => {
510
- logger.debug("id", id); // type: number
511
- logger.debug("ids", ids); // type: number[]
519
+ handler: async ({ input: { id }, logger }) => {
520
+ logger.debug("id", typeof id); // number
512
521
  },
513
522
  });
514
523
  ```
package/dist/index.d.ts CHANGED
@@ -34,12 +34,6 @@ type Method = (typeof methods)[number];
34
34
  * @example Method | "head"
35
35
  * */
36
36
  type ClientMethod = (typeof clientMethods)[number];
37
- /**
38
- * @desc Methods supported in CORS headers
39
- * @see makeCorsHeaders
40
- * @see createWrongMethodHandler
41
- * @example ClientMethod | "options"
42
- * */
43
37
  //#endregion
44
38
  //#region src/api-response.d.ts
45
39
  /** @public this is the user facing configuration */
@@ -53,10 +47,6 @@ interface ApiResponse<S extends z.ZodType> {
53
47
  * */
54
48
  mimeType?: string | [string, ...string[]] | null;
55
49
  }
56
- /**
57
- * @private This is what the framework entities operate
58
- * @see normalize
59
- * */
60
50
  //#endregion
61
51
  //#region src/common-helpers.d.ts
62
52
  /** @since zod 3.25.61 output type fixed */
@@ -74,10 +64,7 @@ type NoNever<T, F> = [T] extends [never] ? F : T;
74
64
  * */
75
65
  interface TagOverrides {}
76
66
  type Tag = NoNever<keyof TagOverrides, string>;
77
- /** @see https://expressjs.com/en/guide/routing.html */
78
-
79
67
  declare const getMessageFromError: (error: Error) => string;
80
- /** Faster replacement to instanceof for code operating core types (traversing schemas) */
81
68
  //#endregion
82
69
  //#region src/logger-helpers.d.ts
83
70
  declare const severity: {
@@ -163,11 +150,8 @@ type Base$1 = object & {
163
150
  type IOSchema = z.ZodType<Base$1>;
164
151
  /** EndpointsFactory schema extended type when adding a Middleware */
165
152
  type Extension<Current extends IOSchema | undefined, Inc extends IOSchema | undefined> = Current extends IOSchema ? Inc extends IOSchema ? z.ZodIntersection<Current, Inc> : Current : Inc;
166
- /** Makes a schema for EndpointsFactory extended with a Middleware */
167
-
168
153
  /** The Endpoint input schema type, condition wrapped into schema to make it z.output-compatible */
169
154
  type FinalInputSchema<FIN extends IOSchema | undefined, BIN extends IOSchema> = z.ZodIntersection<FIN extends IOSchema ? FIN : BIN, BIN>;
170
- /** Makes the Endpoint input schema */
171
155
  //#endregion
172
156
  //#region src/logical-container.d.ts
173
157
  type LogicalOr<T> = {
@@ -340,8 +324,6 @@ type DiscriminatedResult = {
340
324
  output: null;
341
325
  error: Error;
342
326
  };
343
- /** @throws ResultHandlerError when Result is an empty array */
344
-
345
327
  /**
346
328
  * @example InputValidationError —> BadRequest(400)
347
329
  * @example Error —> InternalServerError(500)
@@ -599,6 +581,15 @@ interface ServerConfig extends CommonConfig {
599
581
  * @requires compression
600
582
  */
601
583
  compression?: boolean | CompressionOptions;
584
+ /**
585
+ * @desc Configure or customize the parser for request query string
586
+ * @example "simple" // for "node:querystring" module, array elements must be repeated: ?a=1&a=2
587
+ * @example "extended" // for "qs" module, supports nested objects and arrays with brackets: ?a[]=1&a[]=2
588
+ * @example (query) => qs.parse(query, {comma: true}) // for comma-separated arrays: ?a=1,2,3
589
+ * @default "simple"
590
+ * @link https://expressjs.com/en/5x/api.html#req.query
591
+ */
592
+ queryParser?: "simple" | "extended" | ((query: string) => object);
602
593
  /**
603
594
  * @desc Custom raw parser (assigns Buffer to request body)
604
595
  * @default express.raw()
@@ -839,8 +830,6 @@ declare class InputValidationError extends IOSchemaError {
839
830
  name: string;
840
831
  constructor(cause: z.ZodError);
841
832
  }
842
- /** @desc An error related to the execution or incorrect configuration of ResultHandler */
843
-
844
833
  declare class MissingPeerError extends Error {
845
834
  name: string;
846
835
  constructor(module: string);
@@ -918,7 +907,6 @@ type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends
918
907
  // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
919
908
  ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Variant extends "each" ? PrevInc<U> : Context)) => U;
920
909
  type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
921
- /** @since 10.1.1 calling onEach _after_ handler and giving it the previously achieved result */
922
910
  //#endregion
923
911
  //#region src/zts-helpers.d.ts
924
912
  interface ZTSContext extends FlatObject {
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`)||``,n=t.toLowerCase().startsWith(y.upload);return`files`in e&&n},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,r=n?t[n]||he[n]:void 0;return r||ge},ye=(e,t={})=>{let n=_e(e);return ve(n,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})=>{let n=e.length?`${r.core.toDotPath(e)}: `:``;return`${n}${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),r=t.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),n);return r.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`,Te=Symbol(`Buffer`),Ee=()=>r.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).brand(Te),De=Symbol(`DateIn`),Oe=({examples:e,...t}={})=>{let n=r.union([r.iso.date(),r.iso.datetime(),r.iso.datetime({local:!0})]);return n.meta({examples:e}).transform(e=>new Date(e)).pipe(r.date()).brand(De).meta(t)},ke=Symbol(`DateOut`),Ae=(e={})=>r.date().transform(e=>e.toISOString()).brand(ke).meta(e);var je=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},E=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.`}},Me=class extends Error{name=`IOSchemaError`},Ne=class extends Me{name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},Pe=class extends Me{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}},D=class extends Me{name=`InputValidationError`;constructor(e){super(S(e),{cause:e}),this.cause=e}},Fe=class extends Error{name=`ResultHandlerError`;constructor(e,t){super(S(e),{cause:e}),this.cause=e,this.handled=t}},Ie=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const Le=Symbol(`Form`),Re=e=>(e instanceof r.ZodObject?e:r.object(e)).brand(Le),O=Symbol(`Upload`),ze=()=>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(O),k=Symbol(`Raw`),Be=r.object({raw:Ee()}),Ve=e=>Be.extend(e).brand(k);function He(e){return e?Ve(e):Be.brand(k)}const Ue=(e,{io:n,condition:i})=>t.tryCatch(()=>{r.toJSONSchema(e,{io:n,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new Ne(e)}})},e=>e.cause)(),We=(e,{io:n})=>{let i=r.toJSONSchema(e,{io:n,unrepresentable:`any`}),a=[i];for(;a.length;){let e=a.shift();if(t.is(Object,e)){if(e.$ref===`#`)return!0;a.push(...t.values(e))}t.is(Array,e)&&a.push(...t.values(e))}return!1},Ge=t=>Ue(t,{condition:t=>{let n=e(t);return typeof n==`symbol`&&[O,k,Le].includes(n)},io:`input`}),Ke=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`],qe=(t,n)=>Ue(t,{io:n,condition:t=>{let r=e(t),{type:i}=t._zod.def;return!!(Ke.includes(i)||r===Te||n===`input`&&(i===`date`||r===ke)||n===`output`&&(r===De||r===k||r===O))}}),Je=(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){let e=Error(`At least one ${t} response schema required.`);throw new Fe(e)}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}))},Ye=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),A=e=>a(e)?e:i(e instanceof D?400:500,S(e),{cause:e.cause||e}),j=e=>Ce()&&!e.expose?i(e.statusCode).message:e.message,Xe=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}))},[]),Ze=({error:e,logger:t,response:n})=>{t.error(`Result handler failure`,e);let r=j(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 Qe=class{},M=class extends Qe{#schema;#security;#handler;constructor({input:e,security:t,handler:n}){super(),this.#schema=e,this.#security=t,this.#handler=n}get security(){return this.#security}get schema(){return this.#schema}async execute({input:e,...t}){try{let n=await(this.#schema||de).parseAsync(e);return this.#handler({...t,input:n})}catch(e){throw e instanceof r.ZodError?new D(e):e}}},$e=class extends M{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)})})}},et=class{nest(e){return Object.assign(e,{"":this})}},tt=class extends et{},nt=class i extends tt{#def;#ensureOutputExamples=t.once(()=>{if(n.get(this.#def.outputSchema)?.examples?.length||!C(this.#def.outputSchema,`object`))return;let e=Xe(this.#def.outputSchema);if(!e.length)return;let t=this.#def.outputSchema.meta();n.remove(this.#def.outputSchema).add(this.#def.outputSchema,{...t,examples:e})});constructor(e){super(),this.#def=e}#clone(e){return new i({...this.#def,...e})}deprecated(){return this.#clone({deprecated:!0})}get isDeprecated(){return this.#def.deprecated||!1}get description(){return this.#def.description}get shortDescription(){return this.#def.shortDescription}get methods(){return Object.freeze(this.#def.methods)}get inputSchema(){return this.#def.inputSchema}get outputSchema(){return this.#ensureOutputExamples(),this.#def.outputSchema}get requestType(){let t=Ge(this.#def.inputSchema);if(t){let n=e(t);if(n===O)return`upload`;if(n===k)return`raw`;if(n===Le)return`form`}return`json`}getResponses(e){return e===`positive`&&this.#ensureOutputExamples(),Object.freeze(e===`negative`?this.#def.resultHandler.getNegativeResponse():this.#def.resultHandler.getPositiveResponse(this.#def.outputSchema))}get security(){let e=t.pluck(`security`,this.#def.middlewares||[]);return t.reject(t.isNil,e)}get scopes(){return Object.freeze(this.#def.scopes||[])}get tags(){return Object.freeze(this.#def.tags||[])}getOperationId(e){return this.#def.getOperationId?.(e)}async#parseOutput(e){try{return await this.#def.outputSchema.parseAsync(e)}catch(e){throw e instanceof r.ZodError?new Pe(e):e}}async#runMiddlewares({method:e,logger:t,options:n,response:r,...i}){for(let a of this.#def.middlewares||[]){if(e===`options`&&!(a instanceof $e))continue;if(Object.assign(n,await a.execute({...i,options:n,response:r,logger:t})),r.writableEnded){t.warn(`A middleware has closed the stream. Accumulated options:`,n);break}}}async#parseAndRunHandler({input:e,...t}){let n;try{n=await this.#def.inputSchema.parseAsync(e)}catch(e){throw e instanceof r.ZodError?new D(e):e}return this.#def.handler({...t,input:n})}async#handleResult(e){try{await this.#def.resultHandler.execute(e)}catch(t){Ze({...e,error:new Fe(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.#runMiddlewares({method:i,input:s,request:e,response:t,logger:n,options:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();o={output:await this.#parseOutput(await this.#parseAndRunHandler({input:s,logger:n,options:a})),error:null}}catch(e){o={output:null,error:x(e)}}await this.#handleResult({...o,input:s,request:e,response:t,logger:n,options:a})}};const rt=(e,t)=>e&&t?e.and(t):e||t,it=(e,t)=>e?e.and(t):t,N={positive:200,negative:400},at=Object.keys(N);var ot=class{#handler;constructor(e){this.#handler=e}execute(...e){return this.#handler(...e)}},P=class extends ot{#positive;#negative;constructor(e){super(e.handler),this.#positive=e.positive,this.#negative=e.negative}getPositiveResponse(e){return Je(this.#positive,{variant:`positive`,args:[e],statusCodes:[N.positive],mimeTypes:[y.json]})}getNegativeResponse(){return Je(this.#negative,{variant:`negative`,args:[],statusCodes:[N.negative],mimeTypes:[y.json]})}};const F=new P({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:r.object({status:r.literal(`error`),error:r.object({message:r.string()})}).example({status:`error`,error:{message:`Sample error message`}}),handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=A(e);return Ye(n,a,r,t),void i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:j(n)}})}i.status(N.positive).json({status:`success`,data:n})}}),st=new P({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:r.string().example(`Sample error message`),mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=A(n);return Ye(t,r,i,a),void e.status(t.statusCode).type(`text/plain`).send(j(t))}if(`items`in t&&Array.isArray(t.items))return void e.status(N.positive).json(t.items);throw Error(`Property 'items' is missing in the endpoint output`)}});var ct=class e{schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#extend(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=rt(this.schema,t.schema),n}addMiddleware(e){return this.#extend(e instanceof M?e:new M(e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#extend(new $e(...e))}addOptions(e){return this.#extend(new M({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 nt({...o,middlewares:s,outputSchema:t,resultHandler:c,scopes:d,tags:f,methods:l,getOperationId:u,inputSchema:it(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:de,handler:async t=>(await e(t),{})})}};const lt=new ct(F),ut=new ct(st),dt={debug:s,info:u,warn:d(`#FFA500`),error:p,ctx:c},ft={debug:10,info:20,warn:30,error:40},pt=e=>T(e)&&Object.keys(ft).some(t=>t in e),mt=e=>e in ft,ht=(e,t)=>ft[e]<ft[t],gt=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:`unit`,unitDisplay:`long`,unit:e}),I=t.memoizeWith((e,t)=>`${e}${t}`,gt),_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`||ht(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?dt.ctx(i):i),s.push(o?`${dt[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 extends et{#endpoints;constructor(e){super(),this.#endpoints=e}get entries(){let e=t.filter(e=>!!e[1],Object.entries(this.#endpoints));return Object.freeze(e)}deprecated(){let t=Object.entries(this.#endpoints).reduce((e,[t,n])=>Object.assign(e,{[t]:n.deprecated()}),{});return new e(t)}},bt=class{#params;constructor(...e){this.#params=e}apply(e,t){return t(e,g.static(...this.#params))}};const xt=async(e,t=`default`)=>{try{return(await import(e))[t]}catch{}throw new Ie(e)},St=e=>e.type===`object`,Ct=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}})}),wt=t.pipe(Object.keys,t.without([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),t.isEmpty),Tt=t.pair(!0),Et=(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`&&wt(r)))throw Error(`Can not merge`);return t.pair(e,r)})),o.anyOf&&r.push(...t.map(Tt,o.anyOf)),o.oneOf&&r.push(...t.map(Tt,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))),St(o)&&(r.push([e,{examples:Dt(o)}]),o.properties&&(i.properties=(n===`throw`?Ct: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},Dt=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 Ot=class{#verifiedEndpoints=new WeakSet;#verifiedPaths=new WeakMap;constructor(e){this.logger=e}checkSchema(e,t){if(!this.#verifiedEndpoints.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=qe(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 at)for(let{mimeTypes:r,schema:i}of e.getResponses(n)){if(!r?.includes(y.json))continue;let e=qe(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.#verifiedEndpoints.add(e)}}checkPathParams(e,t,n){let i=this.#verifiedPaths.get(t);if(i?.paths.includes(e))return;let a=pe(e);if(a.length===0)return;let o=i?.flat||Et(r.toJSONSchema(t.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of a){if(t in o.properties)continue;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.#verifiedPaths.set(t,{flat:o,paths:[e]})}};const kt=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},At=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&b(t)?[n,t]:[e]},jt=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Mt=(e,t)=>Object.entries(e).map(([e,n])=>{let[r,i]=At(e),a=[t||``].concat(jt(r)||[]).join(`/`);return[a,n,i]}),Nt=(e,t)=>{throw new je(`Route with explicit method can only be assigned with Endpoint`,e,t)},Pt=(e,t,n)=>{if(!(!n||n.includes(e)))throw new je(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ft=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new je(`Route has a duplicate`,e,t);n.add(r)},It=({routing:e,onEndpoint:t,onStatic:n})=>{let r=Mt(e),i=new Set;for(;r.length;){let[e,a,o]=r.shift();if(a instanceof tt)if(o)Ft(o,e,i),Pt(o,e,a.methods),t(o,e,a);else{let{methods:n=[`get`]}=a;for(let r of n)Ft(r,e,i),t(r,e,a)}else if(o&&Nt(o,e),a instanceof bt)n&&a.apply(e,n);else if(a instanceof yt)for(let[n,r]of a.entries){let{methods:a}=r;Ft(n,e,i),Pt(n,e,a),t(n,e,r)}else r.unshift(...Mt(a,e))}},Lt=e=>e.sort((e,t)=>b(t)-+b(e)||e.localeCompare(t)).join(`, `).toUpperCase(),Rt=e=>({method:t},n,r)=>{let a=Lt(e);n.set({Allow:a});let o=i(405,`${t} is not allowed`,{headers:{Allow:a}});r(o)},zt=e=>({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":Lt(e),"Access-Control-Allow-Headers":`content-type`}),Bt=({app:e,getLogger:n,config:r,routing:i,parsers:a})=>{let o=Ce()?void 0:new Ot(n()),s=new Map,c=(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)};return It({routing:i,onEndpoint:c,onStatic:e.use.bind(e)}),s},Vt=({app:e,config:t,getLogger:n,...r})=>{let i=Bt({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=zt(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)}if(t.wrongMethodBehavior===404)continue;a.set(r,Rt(i))}for(let[t,n]of a)e.all(t,n)},Ht=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`,Ut=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,Wt=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,Gt=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),Kt=e=>new Promise((t,n)=>void e.close(e=>e?n(e):t())),qt=(e,{timeout:t=1e3,logger:n}={})=>{let r,i=new Set,a=e=>void i.delete(e.destroy()),o=e=>void(Ht(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`,Gt);n?.info(`Graceful shutdown`,{sockets:i.size,timeout:t});for(let e of i)(Wt(e)||Ut(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(Kt))};return{sockets:i,shutdown:()=>r??=c()}};var Jt=`express-zod-api`;const Yt=Symbol.for(Jt),Xt=({errorHandler:e,getLogger:t})=>async(n,r,i,a)=>n?e.execute({error:x(n),request:r,response:i,input:null,output:null,options:{},logger:t(r)}):a(),Zt=({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,options:{}})}catch(e){Ze({response:r,logger:o,error:new Fe(x(e),a)})}},Qt=e=>(t,{},n)=>{let r=Object.values(t?.files||[]).flat().find(({truncated:e})=>e);if(r)return n(e);n()},$t=e=>({log:e.debug.bind(e)}),en=async({getLogger:e,config:t})=>{let n=await xt(`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:$t(s)})(t,r,o)}),r&&o.push(Qt(r)),o},tn=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},nn=({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[Yt]={logger:o}),a()},rn=e=>t=>t?.res?.locals[Yt]?.logger||e,an=e=>process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
2
- `).slice(1))),on=({servers:e,logger:t,options:{timeout:n,beforeExit:r,events:i=[`SIGINT`,`SIGTERM`]}})=>{let a=qt(e,{logger:t,timeout:n}),o=async()=>{await a.shutdown(),await r?.(),process.exit()};for(let e of i)process.on(e,o)},sn=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 Sara`.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{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={})=>{let n=_e(e);return ve(n,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`,Te=Symbol(`Buffer`),Ee=()=>r.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).brand(Te),De=Symbol(`DateIn`),Oe=({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(De).meta(t),ke=Symbol(`DateOut`),Ae=(e={})=>r.date().transform(e=>e.toISOString()).brand(ke).meta(e);var je=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},E=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.`}},Me=class extends Error{name=`IOSchemaError`},Ne=class extends Me{name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},Pe=class extends Me{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}},D=class extends Me{name=`InputValidationError`;constructor(e){super(S(e),{cause:e}),this.cause=e}},Fe=class extends Error{name=`ResultHandlerError`;constructor(e,t){super(S(e),{cause:e}),this.cause=e,this.handled=t}},Ie=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const Le=Symbol(`Form`),Re=e=>(e instanceof r.ZodObject?e:r.object(e)).brand(Le),O=Symbol(`Upload`),ze=()=>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(O),k=Symbol(`Raw`),Be=r.object({raw:Ee()}),Ve=e=>Be.extend(e).brand(k);function He(e){return e?Ve(e):Be.brand(k)}const Ue=(e,{io:n,condition:i})=>t.tryCatch(()=>{r.toJSONSchema(e,{io:n,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new Ne(e)}})},e=>e.cause)(),We=(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},Ge=t=>Ue(t,{condition:t=>{let n=e(t);return typeof n==`symbol`&&[O,k,Le].includes(n)},io:`input`}),Ke=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`],qe=(t,n)=>Ue(t,{io:n,condition:t=>{let r=e(t),{type:i}=t._zod.def;return!!(Ke.includes(i)||r===Te||n===`input`&&(i===`date`||r===ke)||n===`output`&&(r===De||r===k||r===O))}}),Je=(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){let e=Error(`At least one ${t} response schema required.`);throw new Fe(e)}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}))},Ye=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),A=e=>a(e)?e:i(e instanceof D?400:500,S(e),{cause:e.cause||e}),j=e=>Ce()&&!e.expose?i(e.statusCode).message:e.message,Xe=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}))},[]),Ze=({error:e,logger:t,response:n})=>{t.error(`Result handler failure`,e);let r=j(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 Qe=class{},M=class extends Qe{#schema;#security;#handler;constructor({input:e,security:t,handler:n}){super(),this.#schema=e,this.#security=t,this.#handler=n}get security(){return this.#security}get schema(){return this.#schema}async execute({input:e,...t}){try{let n=await(this.#schema||de).parseAsync(e);return this.#handler({...t,input:n})}catch(e){throw e instanceof r.ZodError?new D(e):e}}},$e=class extends M{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)})})}},et=class{nest(e){return Object.assign(e,{"":this})}},tt=class extends et{},nt=class i extends tt{#def;#ensureOutputExamples=t.once(()=>{if(n.get(this.#def.outputSchema)?.examples?.length||!C(this.#def.outputSchema,`object`))return;let e=Xe(this.#def.outputSchema);if(!e.length)return;let t=this.#def.outputSchema.meta();n.remove(this.#def.outputSchema).add(this.#def.outputSchema,{...t,examples:e})});constructor(e){super(),this.#def=e}#clone(e){return new i({...this.#def,...e})}deprecated(){return this.#clone({deprecated:!0})}get isDeprecated(){return this.#def.deprecated||!1}get description(){return this.#def.description}get shortDescription(){return this.#def.shortDescription}get methods(){return Object.freeze(this.#def.methods)}get inputSchema(){return this.#def.inputSchema}get outputSchema(){return this.#ensureOutputExamples(),this.#def.outputSchema}get requestType(){let t=Ge(this.#def.inputSchema);if(t){let n=e(t);if(n===O)return`upload`;if(n===k)return`raw`;if(n===Le)return`form`}return`json`}getResponses(e){return e===`positive`&&this.#ensureOutputExamples(),Object.freeze(e===`negative`?this.#def.resultHandler.getNegativeResponse():this.#def.resultHandler.getPositiveResponse(this.#def.outputSchema))}get security(){let e=t.pluck(`security`,this.#def.middlewares||[]);return t.reject(t.isNil,e)}get scopes(){return Object.freeze(this.#def.scopes||[])}get tags(){return Object.freeze(this.#def.tags||[])}getOperationId(e){return this.#def.getOperationId?.(e)}async#parseOutput(e){try{return await this.#def.outputSchema.parseAsync(e)}catch(e){throw e instanceof r.ZodError?new Pe(e):e}}async#runMiddlewares({method:e,logger:t,options:n,response:r,...i}){for(let a of this.#def.middlewares||[]){if(e===`options`&&!(a instanceof $e))continue;if(Object.assign(n,await a.execute({...i,options:n,response:r,logger:t})),r.writableEnded){t.warn(`A middleware has closed the stream. Accumulated options:`,n);break}}}async#parseAndRunHandler({input:e,...t}){let n;try{n=await this.#def.inputSchema.parseAsync(e)}catch(e){throw e instanceof r.ZodError?new D(e):e}return this.#def.handler({...t,input:n})}async#handleResult(e){try{await this.#def.resultHandler.execute(e)}catch(t){Ze({...e,error:new Fe(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.#runMiddlewares({method:i,input:s,request:e,response:t,logger:n,options:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();o={output:await this.#parseOutput(await this.#parseAndRunHandler({input:s,logger:n,options:a})),error:null}}catch(e){o={output:null,error:x(e)}}await this.#handleResult({...o,input:s,request:e,response:t,logger:n,options:a})}};const rt=(e,t)=>e&&t?e.and(t):e||t,it=(e,t)=>e?e.and(t):t,N={positive:200,negative:400},at=Object.keys(N);var ot=class{#handler;constructor(e){this.#handler=e}execute(...e){return this.#handler(...e)}},P=class extends ot{#positive;#negative;constructor(e){super(e.handler),this.#positive=e.positive,this.#negative=e.negative}getPositiveResponse(e){return Je(this.#positive,{variant:`positive`,args:[e],statusCodes:[N.positive],mimeTypes:[y.json]})}getNegativeResponse(){return Je(this.#negative,{variant:`negative`,args:[],statusCodes:[N.negative],mimeTypes:[y.json]})}};const st=r.object({status:r.literal(`error`),error:r.object({message:r.string()})});n.add(st,{examples:[{status:`error`,error:{message:`Sample error message`}}]});const F=new P({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:st,handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=A(e);Ye(n,a,r,t),i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:j(n)}});return}i.status(N.positive).json({status:`success`,data:n})}}),ct=r.string();n.add(ct,{examples:[`Sample error message`]});const lt=new P({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:ct,mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=A(n);Ye(t,r,i,a),e.status(t.statusCode).type(`text/plain`).send(j(t));return}if(`items`in t&&Array.isArray(t.items)){e.status(N.positive).json(t.items);return}throw Error(`Property 'items' is missing in the endpoint output`)}});var ut=class e{schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#extend(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=rt(this.schema,t.schema),n}addMiddleware(e){return this.#extend(e instanceof M?e:new M(e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#extend(new $e(...e))}addOptions(e){return this.#extend(new M({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 nt({...o,middlewares:s,outputSchema:t,resultHandler:c,scopes:d,tags:f,methods:l,getOperationId:u,inputSchema:it(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:de,handler:async t=>(await e(t),{})})}};const dt=new ut(F),ft=new ut(lt),pt={debug:s,info:u,warn:d(`#FFA500`),error:p,ctx:c},mt={debug:10,info:20,warn:30,error:40},ht=e=>T(e)&&Object.keys(mt).some(t=>t in e),gt=e=>e in mt,_t=(e,t)=>mt[e]<mt[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})),vt=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 yt=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`||_t(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?pt.ctx(i):i),s.push(o?`${pt[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=vt}=typeof e==`object`?e:{message:e};this.print(typeof i==`function`?i(n):i,r,a(n))}}},bt=class e extends et{#endpoints;constructor(e){super(),this.#endpoints=e}get entries(){let e=t.filter(e=>!!e[1],Object.entries(this.#endpoints));return Object.freeze(e)}deprecated(){let t=Object.entries(this.#endpoints).reduce((e,[t,n])=>Object.assign(e,{[t]:n.deprecated()}),{});return new e(t)}},xt=class{#params;constructor(...e){this.#params=e}apply(e,t){return t(e,g.static(...this.#params))}};const St=async(e,t=`default`)=>{try{return(await import(e))[t]}catch{}throw new Ie(e)},Ct=e=>e.type===`object`,wt=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}})}),Tt=t.pipe(Object.keys,t.without([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),t.isEmpty),Et=t.pair(!0),Dt=(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`&&Tt(r)))throw Error(`Can not merge`);return t.pair(e,r)})),o.anyOf&&r.push(...t.map(Et,o.anyOf)),o.oneOf&&r.push(...t.map(Et,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))),Ct(o)&&(r.push([e,{examples:Ot(o)}]),o.properties&&(i.properties=(n===`throw`?wt: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},Ot=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 kt=class{#verifiedEndpoints=new WeakSet;#verifiedPaths=new WeakMap;constructor(e){this.logger=e}checkSchema(e,t){if(!this.#verifiedEndpoints.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=qe(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 at)for(let{mimeTypes:r,schema:i}of e.getResponses(n)){if(!r?.includes(y.json))continue;let e=qe(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.#verifiedEndpoints.add(e)}}checkPathParams(e,t,n){let i=this.#verifiedPaths.get(t);if(i?.paths.includes(e))return;let a=pe(e);if(a.length===0)return;let o=i?.flat||Dt(r.toJSONSchema(t.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of a){if(t in o.properties)continue;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.#verifiedPaths.set(t,{flat:o,paths:[e]})}};const At=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},jt=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&b(t)?[n,t]:[e]},Mt=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Nt=(e,t)=>Object.entries(e).map(([e,n])=>{let[r,i]=jt(e);return[[t||``].concat(Mt(r)||[]).join(`/`),n,i]}),Pt=(e,t)=>{throw new je(`Route with explicit method can only be assigned with Endpoint`,e,t)},Ft=(e,t,n)=>{if(!(!n||n.includes(e)))throw new je(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},It=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new je(`Route has a duplicate`,e,t);n.add(r)},Lt=({routing:e,onEndpoint:t,onStatic:n})=>{let r=Nt(e),i=new Set;for(;r.length;){let[e,a,o]=r.shift();if(a instanceof tt)if(o)It(o,e,i),Ft(o,e,a.methods),t(o,e,a);else{let{methods:n=[`get`]}=a;for(let r of n)It(r,e,i),t(r,e,a)}else if(o&&Pt(o,e),a instanceof xt)n&&a.apply(e,n);else if(a instanceof bt)for(let[n,r]of a.entries){let{methods:a}=r;It(n,e,i),Ft(n,e,a),t(n,e,r)}else r.unshift(...Nt(a,e))}},Rt=e=>e.sort((e,t)=>b(t)-+b(e)||e.localeCompare(t)).join(`, `).toUpperCase(),zt=e=>({method:t},n,r)=>{let a=Rt(e);n.set({Allow:a});let o=i(405,`${t} is not allowed`,{headers:{Allow:a}});r(o)},Bt=e=>({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":Rt(e),"Access-Control-Allow-Headers":`content-type`}),Vt=({app:e,getLogger:n,config:r,routing:i,parsers:a})=>{let o=Ce()?void 0:new kt(n()),s=new Map;return Lt({routing:i,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},Ht=({app:e,config:t,getLogger:n,...r})=>{let i=Vt({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=Bt(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)}if(t.wrongMethodBehavior===404)continue;a.set(r,zt(i))}for(let[t,n]of a)e.all(t,n)},Ut=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`,Wt=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,Gt=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,Kt=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),qt=e=>new Promise((t,n)=>void e.close(e=>e?n(e):t())),Jt=(e,{timeout:t=1e3,logger:n}={})=>{let r,i=new Set,a=e=>void i.delete(e.destroy()),o=e=>void(Ut(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`,Kt);n?.info(`Graceful shutdown`,{sockets:i.size,timeout:t});for(let e of i)(Gt(e)||Wt(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(qt))};return{sockets:i,shutdown:()=>r??=c()}},Yt=Symbol.for(`express-zod-api`),Xt=({errorHandler:e,getLogger:t})=>async(n,r,i,a)=>n?e.execute({error:x(n),request:r,response:i,input:null,output:null,options:{},logger:t(r)}):a(),Zt=({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,options:{}})}catch(e){Ze({response:r,logger:o,error:new Fe(x(e),a)})}},Qt=e=>(t,{},n)=>{if(Object.values(t?.files||[]).flat().find(({truncated:e})=>e))return n(e);n()},$t=e=>({log:e.debug.bind(e)}),en=async({getLogger:e,config:t})=>{let n=await St(`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:$t(s)})(t,r,o)}),r&&o.push(Qt(r)),o},tn=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},nn=({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[Yt]={logger:o}),a()},rn=e=>t=>t?.res?.locals[Yt]?.logger||e,an=e=>process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
2
+ `).slice(1))),on=({servers:e,logger:t,options:{timeout:n,beforeExit:r,events:i=[`SIGINT`,`SIGTERM`]}})=>{let a=Jt(e,{logger:t,timeout:n}),o=async()=>{await a.shutdown(),await r?.(),process.exit()};for(let e of i)process.on(e,o)},sn=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 Sara`.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=`
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
- `))},cn=e=>{e.startupLogo!==!1&&sn(process.stdout);let t=e.errorHandler||F,n=pt(e.logger)?e.logger:new vt(e.logger);n.debug(`Running`,{build:`v25.3.1`,env:process.env.NODE_ENV||`development`}),an(n);let r=nn({logger:n,config:e}),i=rn(n),a={getLogger:i,errorHandler:t},o=Zt(a),s=Xt(a);return{...a,logger:n,notFoundHandler:o,catcher:s,loggingMiddleware:r}},ln=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=cn(e);return Vt({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},un=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=cn(e),s=g().disable(`x-powered-by`).use(o);if(e.compression){let t=await xt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r});let c={json:[e.jsonParser||g.json()],raw:[e.rawParser||g.raw(),tn],form:[e.formParser||g.urlencoded()],upload:e.upload?await en({config:e,getLogger:r}):[]};Vt({app:s,routing:t,getLogger:r,config:e,parsers:c}),s.use(a,i);let l=[],u=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),d=[];if(e.http){let t=te.createServer(s);l.push(t),d.push(u(t,e.http.listen))}if(e.https){let t=ne.createServer(e.https.options,s);l.push(t),d.push(u(t,e.https.listen))}return l.length||n.warn(`No servers configured.`),e.gracefulShutdown&&on({logger:n,servers:l,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:d.map(e=>e())}},dn=e=>T(e)&&`or`in e,fn=e=>T(e)&&`and`in e,pn=e=>!fn(e)&&!dn(e),mn=e=>{let n=t.filter(pn,e),r=t.chain(t.prop(`and`),t.filter(fn,e)),[i,a]=t.partition(pn,r),o=t.concat(n,i),s=t.filter(dn,e),c=t.map(t.prop(`or`),t.concat(s,a));return c.reduce((e,n)=>be(e,t.map(e=>pn(e)?[e]:e.and,n),([e,n])=>t.concat(e,n)),t.reject(t.isEmpty,[o]))};var hn=`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 gn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,_n={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},vn=e=>e.replace(fe,e=>`{${e.slice(1)}}`),yn=({},e)=>{if(e.isResponse)throw new E(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},bn=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),xn=({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}}},Sn=t.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return Et(e,`throw`)},(e,{jsonSchema:t})=>t),Cn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:kn(t.type)})},L=e=>e,wn=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new E(`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?$/.source,externalDocs:{url:gn}};return e?.length&&(r.examples=e),r},Tn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new E(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:gn}};return e?.length&&(r.examples=e),r},En=()=>({type:`string`,format:`bigint`,pattern:/^-?\d+$/.source}),Dn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,On=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return _n?.[t]},kn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],An=({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(Ln(i,{ctx:n}));if(_(a))if(n.isResponse){let e=Se(r,On(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},jn=({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},Mn=e=>e.length?t.fromPairs(t.zip(t.times(e=>`example${e+1}`,e.length),t.map(t.objOf(`value`),e))):void 0,Nn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||hn.includes(e),Pn=({path:e,method:n,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${n.toUpperCase()} ${e} Parameter`})=>{let u=Et(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)??Nn(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:Mn(_(s)&&s.examples?.length?s.examples:t.pluck(n,u.examples?.filter(t.both(T,t.has(n)))||[]))})},[])},Fn={nullable:Cn,union:xn,bigint:En,intersection:Sn,tuple:Dn,pipe:An,[De]:wn,[ke]:Tn,[O]:yn,[k]:jn,[Te]:bn},In=(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=e.$ref.split(`/`).pop(),i=n[t];i&&(e.$ref=r.makeRef(i.id||i,L(i)).$ref);continue}i.push(...t.values(e))}t.is(Array,e)&&i.push(...t.values(e))}return e},Ln=(t,{ctx:n,rules:i=Fn})=>{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 In(T(o.subject)?o.subject:{},a,n)},Rn=(e,n)=>{if(ae(e))return[e,!1];let r=!1,i=t.map(e=>{let[t,i]=Rn(e,n);return r=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]},zn=({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(Ln(r,{rules:{...u,...Fn},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:Mn(p)};return{description:d,content:t.fromPairs(t.xprod(i,[m]))}},Bn=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Vn=({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},Hn=({name:e})=>({type:`apiKey`,in:`header`,name:e}),Un=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),Wn=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),Gn=({flows:e={}})=>({type:`oauth2`,flows:t.map(e=>({...e,scopes:e.scopes||{}}),t.reject(t.isNil,e))}),Kn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?Bn(e):e.type===`input`?Vn(e,t):e.type===`header`?Hn(e):e.type===`cookie`?Un(e):e.type===`openid`?Wn(e):Gn(e);return e.map(e=>e.map(n))},qn=(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:[]})},{})),Jn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Ln(e,{rules:{...t,...Fn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Yn=({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]=Rn(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:Mn(f.length?f:Et(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},Xn=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)},[]),Zn=e=>e.length<=50?e:e.slice(0,49)+`…`,Qn=e=>e.length?e.slice():void 0;var $n=class extends ie{#lastSecuritySchemaIds=new Map;#lastOperationIdSuffixes=new Map;#references=new Map;#makeRef(e,t,n=this.#references.get(e)){return n||(n=`Schema${this.#references.size+1}`,this.#references.set(e,n)),this.addSchema(n,t),{$ref:`#/components/schemas/${n}`}}#ensureUniqOperationId(e,t,n){let r=n||w(t,e),i=this.#lastOperationIdSuffixes.get(r);if(i===void 0)return this.#lastOperationIdSuffixes.set(r,1),r;if(n)throw new E(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#lastOperationIdSuffixes.set(r,i),`${r}${i}`}#ensureUniqSecuritySchemaName(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.#lastSecuritySchemaIds.get(e.type)||0)+1;return this.#lastSecuritySchemaIds.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.#makeRef.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,ee=d?Zn(d):u&&c?Zn(c):void 0,h=ve(e,n.inputSources),g=this.#ensureUniqOperationId(r,e,i.getOperationId(e)),te=Jn({...a,schema:m}),ne=mn(i.security),re=Pn({...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 at){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)ie[l]=zn({...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`)?Yn({...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,_=qn(Kn(ne,h),p,e=>{let t=this.#ensureUniqSecuritySchemaName(e);return this.addSecurityScheme(t,e),t}),oe={operationId:g,summary:ee,description:c,deprecated:i.isDeprecated||void 0,tags:Qn(i.tags),parameters:Qn(re),requestBody:ae,security:Qn(_),responses:ie};this.addPath(vn(r),{[e]:oe})};It({routing:e,onEndpoint:d?kt(p):p}),c&&(this.rootDoc.tags=Xn(c))}};const er=e=>oe({...e,headers:{"content-type":y.json,...e?.headers}}),tr=e=>se(e),nr=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:mt(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},rr=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=er(e),a=tr({req:i,...t});a.req=t?.req||i,i.res=a;let o=nr(r),s={cors:!1,logger:o,...n};return{requestMock:i,responseMock:a,loggerMock:o,configMock:s}},ir=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=rr(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},ar=async({middleware:e,options:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=F}}=rr(n),c=ye(r,o),l={request:r,response:i,logger:a,input:c,options:t};try{let t=await e.execute(l);return{requestMock:r,responseMock:i,loggerMock:a,output:t}}catch(e){return await s.execute({...l,error:x(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}},R=v.factory,or=[R.createModifier(v.SyntaxKind.ExportKeyword)],sr=[R.createModifier(v.SyntaxKind.AsyncKeyword)],cr={public:[R.createModifier(v.SyntaxKind.PublicKeyword)],protectedReadonly:[R.createModifier(v.SyntaxKind.ProtectedKeyword),R.createModifier(v.SyntaxKind.ReadonlyKeyword)]},lr=(e,t)=>v.addSyntheticLeadingComment(e,v.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),ur=(e,t)=>{let n=v.createSourceFile(`print.ts`,``,v.ScriptTarget.Latest,!1,v.ScriptKind.TS),r=v.createPrinter(t);return r.printNode(v.EmitHint.Unspecified,e,n)},dr=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fr=e=>typeof e==`string`&&dr.test(e)?R.createIdentifier(e):Y(e),pr=(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)))),mr=(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])=>mr(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t)),hr=(e,t=[])=>R.createConstructorDeclaration(cr.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,gr=B(`Record`,[v.SyntaxKind.StringKeyword,v.SyntaxKind.AnyKeyword]),V=e=>{let t=new Map;for(let n of e)t.set(Pr(n)?n.kind:n,n);return R.createUnionTypeNode(Array.from(t.values()))},_r=(e,n,{isOptional:r,isDeprecated:i,comment:a}={})=>{let o=B(n),s=R.createPropertySignature(void 0,fr(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?lr(s,c.join(` `)):s},vr=e=>v.setEmitFlags(e,v.EmitFlags.SingleLine),yr=(...e)=>R.createArrayBindingPattern(e.map(e=>R.createBindingElement(void 0,void 0,e))),H=(e,t,{type:n,expose:r}={})=>R.createVariableStatement(r&&or,R.createVariableDeclarationList([R.createVariableDeclaration(e,void 0,n?B(n):void 0,t)],v.NodeFlags.Const)),br=(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?or:void 0,e,i&&Dr(i),t);return r?lr(a,r):a},xr=(e,t)=>R.createPropertyDeclaration(cr.public,e,void 0,B(t),void 0),Sr=(e,t,n,{typeParams:r,returns:i}={})=>R.createMethodDeclaration(cr.public,void 0,e,void 0,r&&Dr(r),t,i,R.createBlock(n)),Cr=(e,t,{typeParams:n}={})=>R.createClassDeclaration(or,e,n&&Dr(n),void 0,t),wr=e=>R.createTypeOperatorNode(v.SyntaxKind.KeyOfKeyword,B(e)),Tr=e=>B(Promise.name,[e]),Er=(e,t,{expose:n,comment:r}={})=>{let i=R.createInterfaceDeclaration(n?or:void 0,e,void 0,void 0,t);return r?lr(i,r):i},Dr=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?sr:void 0,void 0,Array.isArray(e)?t.map(mr,e):z(e),void 0,void 0,n),G=e=>e,Or=(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),kr=(e,t)=>B(`Extract`,[e,t]),Ar=(e,t)=>R.createExpressionStatement(R.createBinaryExpression(e,R.createToken(v.SyntaxKind.EqualsToken),t)),J=(e,t)=>R.createIndexedAccessTypeNode(B(e),B(t)),jr=e=>V([B(e),Tr(e)]),Mr=(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)),Nr=[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],Pr=e=>Nr.includes(e.kind);var Fr=class{paths=new Set;tags=new Map;registry=new Map;#ids={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=br(`Method`,ue);someOfType=U(`SomeOf`,J(`T`,wr(`T`)),{params:[`T`]});requestType=U(`Request`,wr(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>B(this.someOfType.name,[e]);makePathType=()=>br(this.#ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>Er(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>_r(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>H(`endpointTags`,R.createObjectLiteralExpression(Array.from(this.tags).map(([e,n])=>R.createPropertyAssignment(fr(e),R.createArrayLiteralExpression(t.map(Y,n))))),{expose:!0});makeImplementationType=()=>U(this.#ids.implementationType,Mr({[this.#ids.methodParameter.text]:this.methodType.name,[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:gr,[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}},Tr(v.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:v.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>H(this.#ids.parseRequestFn,W({[this.#ids.requestParameter.text]:v.SyntaxKind.StringKeyword},R.createAsExpression(K(this.#ids.requestParameter,G(`split`))(R.createRegularExpressionLiteral(`/ (.+)/`),Y(2)),R.createTupleTypeNode([B(this.methodType.name),B(this.#ids.pathType)]))));makeSubstituteFn=()=>H(this.#ids.substituteFn,W({[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:gr},R.createBlock([H(this.#ids.restConst,R.createObjectLiteralExpression([R.createSpreadAssignment(this.#ids.paramsArgument)])),R.createForInStatement(R.createVariableDeclarationList([R.createVariableDeclaration(this.#ids.keyParameter)],v.NodeFlags.Const),this.#ids.paramsArgument,R.createBlock([Ar(this.#ids.pathParameter,K(this.#ids.pathParameter,G(`replace`))(pr(`:`,[this.#ids.keyParameter]),W([],R.createBlock([R.createExpressionStatement(R.createDeleteExpression(R.createElementAccessExpression(this.#ids.restConst,this.#ids.keyParameter))),R.createReturnStatement(R.createElementAccessExpression(this.#ids.paramsArgument,this.#ids.keyParameter))]))))])),R.createReturnStatement(R.createAsExpression(R.createArrayLiteralExpression([this.#ids.pathParameter,this.#ids.restConst]),B(`const`)))])));#makeProvider=()=>Sr(this.#ids.provideMethod,z({[this.#ids.requestParameter.text]:`K`,[this.#ids.paramsArgument.text]:J(this.interfaces.input,`K`),[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}}),[H(yr(this.#ids.methodParameter,this.#ids.pathParameter),K(this.#ids.parseRequestFn)(this.#ids.requestParameter)),R.createReturnStatement(K(R.createThis(),this.#ids.implementationArgument)(this.#ids.methodParameter,R.createSpreadElement(K(this.#ids.substituteFn)(this.#ids.pathParameter,this.#ids.paramsArgument)),this.#ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Tr(J(this.interfaces.response,`K`))});makeClientClass=e=>Cr(e,[hr([mr(this.#ids.implementationArgument,{type:B(this.#ids.implementationType,[`T`]),mod:cr.protectedReadonly,init:this.#ids.defaultImplementationConst})]),this.#makeProvider()],{typeParams:[`T`]});#makeSearchParams=e=>pr(`?`,[q(URLSearchParams.name,e)]);#makeFetchURL=()=>q(URL.name,pr(``,[this.#ids.pathParameter],[this.#ids.searchParamsConst]),Y(this.serverUrl));makeDefaultImplementation=()=>{let e=R.createPropertyAssignment(G(`method`),K(this.#ids.methodParameter,G(`toUpperCase`))()),t=R.createPropertyAssignment(G(`headers`),Or(this.#ids.hasBodyConst,R.createObjectLiteralExpression([R.createPropertyAssignment(Y(`Content-Type`),Y(y.json))]),this.#ids.undefinedValue)),n=R.createPropertyAssignment(G(`body`),Or(this.#ids.hasBodyConst,K(JSON[Symbol.toStringTag],G(`stringify`))(this.#ids.paramsArgument),this.#ids.undefinedValue)),r=H(this.#ids.responseConst,R.createAwaitExpression(K(fetch.name)(this.#makeFetchURL(),R.createObjectLiteralExpression([e,t,n])))),i=H(this.#ids.hasBodyConst,R.createLogicalNot(K(R.createArrayLiteralExpression([Y(`get`),Y(`head`),Y(`delete`)]),G(`includes`))(this.#ids.methodParameter))),a=H(this.#ids.searchParamsConst,Or(this.#ids.hasBodyConst,Y(``),this.#makeSearchParams(this.#ids.paramsArgument))),o=H(this.#ids.contentTypeConst,K(this.#ids.responseConst,G(`headers`),G(`get`))(Y(`content-type`))),s=R.createIfStatement(R.createPrefixUnaryExpression(v.SyntaxKind.ExclamationToken,this.#ids.contentTypeConst),R.createReturnStatement()),c=H(this.#ids.isJsonConst,K(this.#ids.contentTypeConst,G(`startsWith`))(Y(y.json))),l=R.createReturnStatement(K(this.#ids.responseConst,Or(this.#ids.isJsonConst,Y(G(`json`)),Y(G(`text`))))());return H(this.#ids.defaultImplementationConst,W([this.#ids.methodParameter,this.#ids.pathParameter,this.#ids.paramsArgument],R.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#ids.implementationType})};#makeSubscriptionConstructor=()=>hr(z({request:`K`,params:J(this.interfaces.input,`K`)}),[H(yr(this.#ids.pathParameter,this.#ids.restConst),K(this.#ids.substituteFn)(R.createElementAccessExpression(K(this.#ids.parseRequestFn)(this.#ids.requestParameter),Y(1)),this.#ids.paramsArgument)),H(this.#ids.searchParamsConst,this.#makeSearchParams(this.#ids.restConst)),Ar(R.createPropertyAccessExpression(R.createThis(),this.#ids.sourceProp),q(`EventSource`,this.#makeFetchURL()))]);#makeEventNarrow=e=>R.createTypeLiteralNode([_r(G(`event`),e)]);#makeOnMethod=()=>Sr(this.#ids.onMethod,z({[this.#ids.eventParameter.text]:`E`,[this.#ids.handlerParameter.text]:Mr({[this.#ids.dataParameter.text]:J(kr(`R`,vr(this.#makeEventNarrow(`E`))),X(G(`data`)))},jr(v.SyntaxKind.VoidKeyword))}),[R.createExpressionStatement(K(R.createThis(),this.#ids.sourceProp,G(`addEventListener`))(this.#ids.eventParameter,W([this.#ids.msgParameter],K(this.#ids.handlerParameter)(K(JSON[Symbol.toStringTag],G(`parse`))(R.createPropertyAccessExpression(R.createParenthesizedExpression(R.createAsExpression(this.#ids.msgParameter,B(MessageEvent.name))),G(`data`))))))),R.createReturnStatement(R.createThis())],{typeParams:{E:J(`R`,X(G(`event`)))}});makeSubscriptionClass=e=>Cr(e,[xr(this.#ids.sourceProp,`EventSource`),this.#makeSubscriptionConstructor(),this.#makeOnMethod()],{typeParams:{K:kr(this.requestType.name,R.createTemplateLiteralType(R.createTemplateHead(`get `),[R.createTemplateLiteralTypeSpan(B(v.SyntaxKind.StringKeyword),R.createTemplateTail(``))])),R:kr(J(this.interfaces.positive,`K`),vr(this.#makeEventNarrow(v.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[H(this.#ids.clientConst,q(e)),K(this.#ids.clientConst,this.#ids.provideMethod)(Y(`get /v1/user/retrieve`),R.createObjectLiteralExpression([R.createPropertyAssignment(`id`,Y(`10`))])),K(q(t,Y(`get /v1/events/stream`),R.createObjectLiteralExpression()),this.#ids.onMethod)(Y(`time`),W([`time`],R.createBlock([])))]};const Ir=(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=>Ir(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,Lr={[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},Rr={name:t.path([`name`,`text`]),type:t.path([`type`]),optional:t.path([`questionToken`])},zr=({_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)},Br=({_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)},Vr=(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 _r(e,r(i),{comment:a,isDeprecated:o,isOptional:(t?i._zod.optout:i._zod.optin)===`optional`})});return Z.createTypeLiteralNode(i)};return We(e,{io:t?`output`:`input`})?i(e,a):a()},Hr=({_zod:{def:e}},{next:t})=>Z.createArrayTypeNode(t(e.element)),Ur=({_zod:{def:e}})=>V(Object.values(e.entries).map(X)),Wr=({_zod:{def:e}},{next:t})=>V(e.options.map(t)),Gr=e=>Lr?.[e.kind],Kr=({_zod:{def:e}},{next:t})=>V([t(e.innerType),X(null)]),qr=({_zod:{def:e}},{next:t})=>Z.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:Z.createRestTypeNode(t(e.rest)))),Jr=({_zod:{def:e}},{next:t})=>B(`Record`,[e.keyType,e.valueType].map(t)),Yr=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(Rr.name,...e))return!1;if(t.both(t.eqBy(Rr.type),t.eqBy(Rr.optional))(...e))return!0;throw Error(`Has conflicting prop`)},n);return Z.createTypeLiteralNode(r)},(e,t)=>Z.createIntersectionTypeNode(t)),Xr=({_zod:{def:e}},{next:t})=>Yr([e.left,e.right].map(t)),Q=e=>()=>B(e),$=({_zod:{def:e}},{next:t})=>t(e.innerType),Zr=e=>B(e?v.SyntaxKind.UnknownKeyword:v.SyntaxKind.AnyKeyword),Qr=({_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=t(i),o=Se(r,Gr(a)),s={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(o&&s[o]||Zr(n))},$r=()=>X(null),ei=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ti=()=>B(`Buffer`),ni=(e,{next:t})=>t(e._zod.def.shape.raw),ri={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),[De]:Q(v.SyntaxKind.StringKeyword),[ke]:Q(v.SyntaxKind.StringKeyword),never:Q(v.SyntaxKind.NeverKeyword),void:Q(v.SyntaxKind.UndefinedKeyword),unknown:Q(v.SyntaxKind.UnknownKeyword),null:$r,array:Hr,tuple:qr,record:Jr,object:Vr,literal:zr,template_literal:Br,intersection:Xr,union:Wr,default:$,enum:Ur,optional:$,nonoptional:$,nullable:Kr,catch:$,pipe:Qr,lazy:ei,readonly:$,[Te]:ti,[k]:ni},ii=(e,{brandHandling:t,ctx:n})=>Ir(e,{rules:{...t,...ri},onMissing:({},{isResponse:e})=>Zr(e),ctx:n});var ai=class extends Fr{#program=[this.someOfType];#aliases=new Map;#usage=[];#makeAlias(e,t){let n=this.#aliases.get(e)?.name?.text;if(!n){n=`Type${this.#aliases.size+1}`;let r=X(null);this.#aliases.set(e,U(n,r)),this.#aliases.set(e,U(n,t()))}return B(n)}constructor({routing:e,brandHandling:n,variant:i=`client`,clientClassName:a=`Client`,subscriptionClassName:o=`Subscription`,serverUrl:s=`https://example.com`,noContent:c=r.undefined(),hasHeadMethod:l=!0}){super(s);let u={makeAlias:this.#makeAlias.bind(this)},d={brandHandling:n,ctx:{...u,isResponse:!1}},f={brandHandling:n,ctx:{...u,isResponse:!0}},p=(e,n,r)=>{let i=w.bind(null,e,n),{isDeprecated:a,inputSchema:o,tags:s}=r,l=`${e} ${n}`,u=U(i(`input`),ii(o,d),{comment:l});this.#program.push(u);let p=at.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}`),ii(s?n:c,f),{comment:l});return this.#program.push(u),o.map(e=>_r(e,u.name))},Array.from(o.entries())),u=Er(i(a,`response`,`variants`),s,{comment:l});return this.#program.push(u),Object.assign(n,{[a]:u})},{});this.paths.add(n);let m=X(l),ee={input:B(u.name),positive:this.someOf(p.positive),negative:this.someOf(p.negative),response:V([J(this.interfaces.positive,m),J(this.interfaces.negative,m)]),encoded:R.createIntersectionTypeNode([B(p.positive.name),B(p.negative.name)])};this.registry.set(l,{isDeprecated:a,store:ee}),this.tags.set(l,s)};It({routing:e,onEndpoint:l?kt(p):p}),this.#program.unshift(...this.#aliases.values()),this.#program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),i!==`types`&&(this.#program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(a),this.makeSubscriptionClass(o)),this.#usage.push(...this.makeUsageStatements(a,o)))}#printUsage(e){return this.#usage.length?this.#usage.map(t=>typeof t==`string`?t:ur(t,e)).join(`
17
+ `))},cn=e=>{e.startupLogo!==!1&&sn(process.stdout);let t=e.errorHandler||F,n=ht(e.logger)?e.logger:new yt(e.logger);n.debug(`Running`,{build:`v25.4.1`,env:process.env.NODE_ENV||`development`}),an(n);let r=nn({logger:n,config:e}),i={getLogger:rn(n),errorHandler:t},a=Zt(i),o=Xt(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},ln=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=cn(e);return Ht({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},un=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=cn(e),s=g().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.compression){let t=await St(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r});let c={json:[e.jsonParser||g.json()],raw:[e.rawParser||g.raw(),tn],form:[e.formParser||g.urlencoded()],upload:e.upload?await en({config:e,getLogger:r}):[]};Ht({app:s,routing:t,getLogger:r,config:e,parsers:c}),s.use(a,i);let l=[],u=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),d=[];if(e.http){let t=te.createServer(s);l.push(t),d.push(u(t,e.http.listen))}if(e.https){let t=ne.createServer(e.https.options,s);l.push(t),d.push(u(t,e.https.listen))}return l.length||n.warn(`No servers configured.`),e.gracefulShutdown&&on({logger:n,servers:l,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:d.map(e=>e())}},dn=e=>T(e)&&`or`in e,fn=e=>T(e)&&`and`in e,pn=e=>!fn(e)&&!dn(e),mn=e=>{let n=t.filter(pn,e),r=t.chain(t.prop(`and`),t.filter(fn,e)),[i,a]=t.partition(pn,r),o=t.concat(n,i),s=t.filter(dn,e);return t.map(t.prop(`or`),t.concat(s,a)).reduce((e,n)=>be(e,t.map(e=>pn(e)?[e]:e.and,n),([e,n])=>t.concat(e,n)),t.reject(t.isEmpty,[o]))};var hn=`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 gn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,_n={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},vn=e=>e.replace(fe,e=>`{${e.slice(1)}}`),yn=({},e)=>{if(e.isResponse)throw new E(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},bn=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),xn=({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}}},Sn=t.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return Dt(e,`throw`)},(e,{jsonSchema:t})=>t),Cn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:kn(t.type)})},L=e=>e,wn=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new E(`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:gn}};return e?.length&&(r.examples=e),r},Tn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new E(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:gn}};return e?.length&&(r.examples=e),r},En=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),Dn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,On=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return _n?.[t]},kn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],An=({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(Ln(i,{ctx:n}));if(_(a))if(n.isResponse){let e=Se(r,On(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},jn=({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},Mn=e=>e.length?t.fromPairs(t.zip(t.times(e=>`example${e+1}`,e.length),t.map(t.objOf(`value`),e))):void 0,Nn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||hn.includes(e),Pn=({path:e,method:n,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${n.toUpperCase()} ${e} Parameter`})=>{let u=Dt(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)??Nn(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:Mn(_(s)&&s.examples?.length?s.examples:t.pluck(n,u.examples?.filter(t.both(T,t.has(n)))||[]))})},[])},Fn={nullable:Cn,union:xn,bigint:En,intersection:Sn,tuple:Dn,pipe:An,[De]:wn,[ke]:Tn,[O]:yn,[k]:jn,[Te]:bn},In=(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=e.$ref.split(`/`).pop(),i=n[t];i&&(e.$ref=r.makeRef(i.id||i,L(i)).$ref);continue}i.push(...t.values(e))}t.is(Array,e)&&i.push(...t.values(e))}return e},Ln=(t,{ctx:n,rules:i=Fn})=>{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 In(T(o.subject)?o.subject:{},a,n)},Rn=(e,n)=>{if(ae(e))return[e,!1];let r=!1,i=t.map(e=>{let[t,i]=Rn(e,n);return r=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]},zn=({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(Ln(r,{rules:{...u,...Fn},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:Mn(p)};return{description:d,content:t.fromPairs(t.xprod(i,[m]))}},Bn=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Vn=({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},Hn=({name:e})=>({type:`apiKey`,in:`header`,name:e}),Un=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),Wn=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),Gn=({flows:e={}})=>({type:`oauth2`,flows:t.map(e=>({...e,scopes:e.scopes||{}}),t.reject(t.isNil,e))}),Kn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?Bn(e):e.type===`input`?Vn(e,t):e.type===`header`?Hn(e):e.type===`cookie`?Un(e):e.type===`openid`?Wn(e):Gn(e);return e.map(e=>e.map(n))},qn=(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:[]})},{})),Jn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Ln(e,{rules:{...t,...Fn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Yn=({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]=Rn(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:Mn(f.length?f:Dt(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},Xn=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)},[]),Zn=e=>e.length<=50?e:e.slice(0,49)+`…`,Qn=e=>e.length?e.slice():void 0;var $n=class extends ie{#lastSecuritySchemaIds=new Map;#lastOperationIdSuffixes=new Map;#references=new Map;#makeRef(e,t,n=this.#references.get(e)){return n||(n=`Schema${this.#references.size+1}`,this.#references.set(e,n)),this.addSchema(n,t),{$ref:`#/components/schemas/${n}`}}#ensureUniqOperationId(e,t,n){let r=n||w(t,e),i=this.#lastOperationIdSuffixes.get(r);if(i===void 0)return this.#lastOperationIdSuffixes.set(r,1),r;if(n)throw new E(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#lastOperationIdSuffixes.set(r,i),`${r}${i}`}#ensureUniqSecuritySchemaName(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.#lastSecuritySchemaIds.get(e.type)||0)+1;return this.#lastSecuritySchemaIds.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.#makeRef.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,ee=d?Zn(d):u&&c?Zn(c):void 0,h=ve(e,n.inputSources),g=this.#ensureUniqOperationId(r,e,i.getOperationId(e)),te=Jn({...a,schema:m}),ne=mn(i.security),re=Pn({...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 at){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)ie[l]=zn({...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`)?Yn({...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,_=qn(Kn(ne,h),p,e=>{let t=this.#ensureUniqSecuritySchemaName(e);return this.addSecurityScheme(t,e),t}),oe={operationId:g,summary:ee,description:c,deprecated:i.isDeprecated||void 0,tags:Qn(i.tags),parameters:Qn(re),requestBody:ae,security:Qn(_),responses:ie};this.addPath(vn(r),{[e]:oe})};Lt({routing:e,onEndpoint:d?At(p):p}),c&&(this.rootDoc.tags=Xn(c))}};const er=e=>oe({...e,headers:{"content-type":y.json,...e?.headers}}),tr=e=>se(e),nr=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:gt(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},rr=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=er(e),a=tr({req:i,...t});a.req=t?.req||i,i.res=a;let o=nr(r),s={cors:!1,logger:o,...n};return{requestMock:i,responseMock:a,loggerMock:o,configMock:s}},ir=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=rr(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},ar=async({middleware:e,options:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=F}}=rr(n),c=ye(r,o),l={request:r,response:i,logger:a,input:c,options:t};try{let t=await e.execute(l);return{requestMock:r,responseMock:i,loggerMock:a,output:t}}catch(e){return await s.execute({...l,error:x(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}},R=v.factory,or=[R.createModifier(v.SyntaxKind.ExportKeyword)],sr=[R.createModifier(v.SyntaxKind.AsyncKeyword)],cr={public:[R.createModifier(v.SyntaxKind.PublicKeyword)],protectedReadonly:[R.createModifier(v.SyntaxKind.ProtectedKeyword),R.createModifier(v.SyntaxKind.ReadonlyKeyword)]},lr=(e,t)=>v.addSyntheticLeadingComment(e,v.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),ur=(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)},dr=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fr=e=>typeof e==`string`&&dr.test(e)?R.createIdentifier(e):Y(e),pr=(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)))),mr=(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])=>mr(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t)),hr=(e,t=[])=>R.createConstructorDeclaration(cr.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,gr=B(`Record`,[v.SyntaxKind.StringKeyword,v.SyntaxKind.AnyKeyword]),V=e=>{let t=new Map;for(let n of e)t.set(Pr(n)?n.kind:n,n);return R.createUnionTypeNode(Array.from(t.values()))},_r=(e,n,{isOptional:r,isDeprecated:i,comment:a}={})=>{let o=B(n),s=R.createPropertySignature(void 0,fr(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?lr(s,c.join(` `)):s},vr=e=>v.setEmitFlags(e,v.EmitFlags.SingleLine),yr=(...e)=>R.createArrayBindingPattern(e.map(e=>R.createBindingElement(void 0,void 0,e))),H=(e,t,{type:n,expose:r}={})=>R.createVariableStatement(r&&or,R.createVariableDeclarationList([R.createVariableDeclaration(e,void 0,n?B(n):void 0,t)],v.NodeFlags.Const)),br=(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?or:void 0,e,i&&Dr(i),t);return r?lr(a,r):a},xr=(e,t)=>R.createPropertyDeclaration(cr.public,e,void 0,B(t),void 0),Sr=(e,t,n,{typeParams:r,returns:i}={})=>R.createMethodDeclaration(cr.public,void 0,e,void 0,r&&Dr(r),t,i,R.createBlock(n)),Cr=(e,t,{typeParams:n}={})=>R.createClassDeclaration(or,e,n&&Dr(n),void 0,t),wr=e=>R.createTypeOperatorNode(v.SyntaxKind.KeyOfKeyword,B(e)),Tr=e=>B(Promise.name,[e]),Er=(e,t,{expose:n,comment:r}={})=>{let i=R.createInterfaceDeclaration(n?or:void 0,e,void 0,void 0,t);return r?lr(i,r):i},Dr=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?sr:void 0,void 0,Array.isArray(e)?t.map(mr,e):z(e),void 0,void 0,n),G=e=>e,Or=(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),kr=(e,t)=>B(`Extract`,[e,t]),Ar=(e,t)=>R.createExpressionStatement(R.createBinaryExpression(e,R.createToken(v.SyntaxKind.EqualsToken),t)),J=(e,t)=>R.createIndexedAccessTypeNode(B(e),B(t)),jr=e=>V([B(e),Tr(e)]),Mr=(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)),Nr=[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],Pr=e=>Nr.includes(e.kind);var Fr=class{paths=new Set;tags=new Map;registry=new Map;#ids={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=br(`Method`,ue);someOfType=U(`SomeOf`,J(`T`,wr(`T`)),{params:[`T`]});requestType=U(`Request`,wr(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>B(this.someOfType.name,[e]);makePathType=()=>br(this.#ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>Er(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>_r(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>H(`endpointTags`,R.createObjectLiteralExpression(Array.from(this.tags).map(([e,n])=>R.createPropertyAssignment(fr(e),R.createArrayLiteralExpression(t.map(Y,n))))),{expose:!0});makeImplementationType=()=>U(this.#ids.implementationType,Mr({[this.#ids.methodParameter.text]:this.methodType.name,[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:gr,[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}},Tr(v.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:v.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>H(this.#ids.parseRequestFn,W({[this.#ids.requestParameter.text]:v.SyntaxKind.StringKeyword},R.createAsExpression(K(this.#ids.requestParameter,G(`split`))(R.createRegularExpressionLiteral(`/ (.+)/`),Y(2)),R.createTupleTypeNode([B(this.methodType.name),B(this.#ids.pathType)]))));makeSubstituteFn=()=>H(this.#ids.substituteFn,W({[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:gr},R.createBlock([H(this.#ids.restConst,R.createObjectLiteralExpression([R.createSpreadAssignment(this.#ids.paramsArgument)])),R.createForInStatement(R.createVariableDeclarationList([R.createVariableDeclaration(this.#ids.keyParameter)],v.NodeFlags.Const),this.#ids.paramsArgument,R.createBlock([Ar(this.#ids.pathParameter,K(this.#ids.pathParameter,G(`replace`))(pr(`:`,[this.#ids.keyParameter]),W([],R.createBlock([R.createExpressionStatement(R.createDeleteExpression(R.createElementAccessExpression(this.#ids.restConst,this.#ids.keyParameter))),R.createReturnStatement(R.createElementAccessExpression(this.#ids.paramsArgument,this.#ids.keyParameter))]))))])),R.createReturnStatement(R.createAsExpression(R.createArrayLiteralExpression([this.#ids.pathParameter,this.#ids.restConst]),B(`const`)))])));#makeProvider=()=>Sr(this.#ids.provideMethod,z({[this.#ids.requestParameter.text]:`K`,[this.#ids.paramsArgument.text]:J(this.interfaces.input,`K`),[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}}),[H(yr(this.#ids.methodParameter,this.#ids.pathParameter),K(this.#ids.parseRequestFn)(this.#ids.requestParameter)),R.createReturnStatement(K(R.createThis(),this.#ids.implementationArgument)(this.#ids.methodParameter,R.createSpreadElement(K(this.#ids.substituteFn)(this.#ids.pathParameter,this.#ids.paramsArgument)),this.#ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Tr(J(this.interfaces.response,`K`))});makeClientClass=e=>Cr(e,[hr([mr(this.#ids.implementationArgument,{type:B(this.#ids.implementationType,[`T`]),mod:cr.protectedReadonly,init:this.#ids.defaultImplementationConst})]),this.#makeProvider()],{typeParams:[`T`]});#makeSearchParams=e=>pr(`?`,[q(URLSearchParams.name,e)]);#makeFetchURL=()=>q(URL.name,pr(``,[this.#ids.pathParameter],[this.#ids.searchParamsConst]),Y(this.serverUrl));makeDefaultImplementation=()=>{let e=R.createPropertyAssignment(G(`method`),K(this.#ids.methodParameter,G(`toUpperCase`))()),t=R.createPropertyAssignment(G(`headers`),Or(this.#ids.hasBodyConst,R.createObjectLiteralExpression([R.createPropertyAssignment(Y(`Content-Type`),Y(y.json))]),this.#ids.undefinedValue)),n=R.createPropertyAssignment(G(`body`),Or(this.#ids.hasBodyConst,K(JSON[Symbol.toStringTag],G(`stringify`))(this.#ids.paramsArgument),this.#ids.undefinedValue)),r=H(this.#ids.responseConst,R.createAwaitExpression(K(fetch.name)(this.#makeFetchURL(),R.createObjectLiteralExpression([e,t,n])))),i=H(this.#ids.hasBodyConst,R.createLogicalNot(K(R.createArrayLiteralExpression([Y(`get`),Y(`head`),Y(`delete`)]),G(`includes`))(this.#ids.methodParameter))),a=H(this.#ids.searchParamsConst,Or(this.#ids.hasBodyConst,Y(``),this.#makeSearchParams(this.#ids.paramsArgument))),o=H(this.#ids.contentTypeConst,K(this.#ids.responseConst,G(`headers`),G(`get`))(Y(`content-type`))),s=R.createIfStatement(R.createPrefixUnaryExpression(v.SyntaxKind.ExclamationToken,this.#ids.contentTypeConst),R.createReturnStatement()),c=H(this.#ids.isJsonConst,K(this.#ids.contentTypeConst,G(`startsWith`))(Y(y.json))),l=R.createReturnStatement(K(this.#ids.responseConst,Or(this.#ids.isJsonConst,Y(G(`json`)),Y(G(`text`))))());return H(this.#ids.defaultImplementationConst,W([this.#ids.methodParameter,this.#ids.pathParameter,this.#ids.paramsArgument],R.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#ids.implementationType})};#makeSubscriptionConstructor=()=>hr(z({request:`K`,params:J(this.interfaces.input,`K`)}),[H(yr(this.#ids.pathParameter,this.#ids.restConst),K(this.#ids.substituteFn)(R.createElementAccessExpression(K(this.#ids.parseRequestFn)(this.#ids.requestParameter),Y(1)),this.#ids.paramsArgument)),H(this.#ids.searchParamsConst,this.#makeSearchParams(this.#ids.restConst)),Ar(R.createPropertyAccessExpression(R.createThis(),this.#ids.sourceProp),q(`EventSource`,this.#makeFetchURL()))]);#makeEventNarrow=e=>R.createTypeLiteralNode([_r(G(`event`),e)]);#makeOnMethod=()=>Sr(this.#ids.onMethod,z({[this.#ids.eventParameter.text]:`E`,[this.#ids.handlerParameter.text]:Mr({[this.#ids.dataParameter.text]:J(kr(`R`,vr(this.#makeEventNarrow(`E`))),X(G(`data`)))},jr(v.SyntaxKind.VoidKeyword))}),[R.createExpressionStatement(K(R.createThis(),this.#ids.sourceProp,G(`addEventListener`))(this.#ids.eventParameter,W([this.#ids.msgParameter],K(this.#ids.handlerParameter)(K(JSON[Symbol.toStringTag],G(`parse`))(R.createPropertyAccessExpression(R.createParenthesizedExpression(R.createAsExpression(this.#ids.msgParameter,B(MessageEvent.name))),G(`data`))))))),R.createReturnStatement(R.createThis())],{typeParams:{E:J(`R`,X(G(`event`)))}});makeSubscriptionClass=e=>Cr(e,[xr(this.#ids.sourceProp,`EventSource`),this.#makeSubscriptionConstructor(),this.#makeOnMethod()],{typeParams:{K:kr(this.requestType.name,R.createTemplateLiteralType(R.createTemplateHead(`get `),[R.createTemplateLiteralTypeSpan(B(v.SyntaxKind.StringKeyword),R.createTemplateTail(``))])),R:kr(J(this.interfaces.positive,`K`),vr(this.#makeEventNarrow(v.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[H(this.#ids.clientConst,q(e)),K(this.#ids.clientConst,this.#ids.provideMethod)(Y(`get /v1/user/retrieve`),R.createObjectLiteralExpression([R.createPropertyAssignment(`id`,Y(`10`))])),K(q(t,Y(`get /v1/events/stream`),R.createObjectLiteralExpression()),this.#ids.onMethod)(Y(`time`),W([`time`],R.createBlock([])))]};const Ir=(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=>Ir(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,Lr={[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},Rr={name:t.path([`name`,`text`]),type:t.path([`type`]),optional:t.path([`questionToken`])},zr=({_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)},Br=({_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)},Vr=(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 _r(e,r(i),{comment:a,isDeprecated:o,isOptional:(t?i._zod.optout:i._zod.optin)===`optional`})});return Z.createTypeLiteralNode(i)};return We(e,{io:t?`output`:`input`})?i(e,a):a()},Hr=({_zod:{def:e}},{next:t})=>Z.createArrayTypeNode(t(e.element)),Ur=({_zod:{def:e}})=>V(Object.values(e.entries).map(X)),Wr=({_zod:{def:e}},{next:t})=>V(e.options.map(t)),Gr=e=>Lr?.[e.kind],Kr=({_zod:{def:e}},{next:t})=>V([t(e.innerType),X(null)]),qr=({_zod:{def:e}},{next:t})=>Z.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:Z.createRestTypeNode(t(e.rest)))),Jr=({_zod:{def:e}},{next:t})=>B(`Record`,[e.keyType,e.valueType].map(t)),Yr=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(Rr.name,...e))return!1;if(t.both(t.eqBy(Rr.type),t.eqBy(Rr.optional))(...e))return!0;throw Error(`Has conflicting prop`)},n);return Z.createTypeLiteralNode(r)},(e,t)=>Z.createIntersectionTypeNode(t)),Xr=({_zod:{def:e}},{next:t})=>Yr([e.left,e.right].map(t)),Q=e=>()=>B(e),$=({_zod:{def:e}},{next:t})=>t(e.innerType),Zr=e=>B(e?v.SyntaxKind.UnknownKeyword:v.SyntaxKind.AnyKeyword),Qr=({_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=t(i),o=Se(r,Gr(a)),s={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(o&&s[o]||Zr(n))},$r=()=>X(null),ei=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ti=()=>B(`Buffer`),ni=(e,{next:t})=>t(e._zod.def.shape.raw),ri={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),[De]:Q(v.SyntaxKind.StringKeyword),[ke]:Q(v.SyntaxKind.StringKeyword),never:Q(v.SyntaxKind.NeverKeyword),void:Q(v.SyntaxKind.UndefinedKeyword),unknown:Q(v.SyntaxKind.UnknownKeyword),null:$r,array:Hr,tuple:qr,record:Jr,object:Vr,literal:zr,template_literal:Br,intersection:Xr,union:Wr,default:$,enum:Ur,optional:$,nonoptional:$,nullable:Kr,catch:$,pipe:Qr,lazy:ei,readonly:$,[Te]:ti,[k]:ni},ii=(e,{brandHandling:t,ctx:n})=>Ir(e,{rules:{...t,...ri},onMissing:({},{isResponse:e})=>Zr(e),ctx:n});var ai=class extends Fr{#program=[this.someOfType];#aliases=new Map;#usage=[];#makeAlias(e,t){let n=this.#aliases.get(e)?.name?.text;if(!n){n=`Type${this.#aliases.size+1}`;let r=X(null);this.#aliases.set(e,U(n,r)),this.#aliases.set(e,U(n,t()))}return B(n)}constructor({routing:e,brandHandling:n,variant:i=`client`,clientClassName:a=`Client`,subscriptionClassName:o=`Subscription`,serverUrl:s=`https://example.com`,noContent:c=r.undefined(),hasHeadMethod:l=!0}){super(s);let u={makeAlias:this.#makeAlias.bind(this)},d={brandHandling:n,ctx:{...u,isResponse:!1}},f={brandHandling:n,ctx:{...u,isResponse:!0}},p=(e,n,r)=>{let i=w.bind(null,e,n),{isDeprecated:a,inputSchema:o,tags:s}=r,l=`${e} ${n}`,u=U(i(`input`),ii(o,d),{comment:l});this.#program.push(u);let p=at.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}`),ii(s?n:c,f),{comment:l});return this.#program.push(u),o.map(e=>_r(e,u.name))},Array.from(o.entries())),u=Er(i(a,`response`,`variants`),s,{comment:l});return this.#program.push(u),Object.assign(n,{[a]:u})},{});this.paths.add(n);let m=X(l),ee={input:B(u.name),positive:this.someOf(p.positive),negative:this.someOf(p.negative),response:V([J(this.interfaces.positive,m),J(this.interfaces.negative,m)]),encoded:R.createIntersectionTypeNode([B(p.positive.name),B(p.negative.name)])};this.registry.set(l,{isDeprecated:a,store:ee}),this.tags.set(l,s)};Lt({routing:e,onEndpoint:l?At(p):p}),this.#program.unshift(...this.#aliases.values()),this.#program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),i!==`types`&&(this.#program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(a),this.makeSubscriptionClass(o)),this.#usage.push(...this.makeUsageStatements(a,o)))}#printUsage(e){return this.#usage.length?this.#usage.map(t=>typeof t==`string`?t:ur(t,e)).join(`
18
18
  `):void 0}print(e){let t=this.#printUsage(e),n=t&&v.addSyntheticLeadingComment(v.addSyntheticLeadingComment(R.createEmptyStatement(),v.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),v.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#program.concat(n||[]).map((t,n)=>ur(t,n<this.#program.length?e:{...e,omitTrailingSemicolon:!0})).join(`
19
19
 
20
- `)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=(await xt(`prettier`)).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#printUsage(e);this.#usage=r&&n?[await n(r)]:this.#usage;let i=this.print(e);return n?n(i):i}};const oi=(e,t)=>r.object({data:t,event:r.literal(e),id:r.string().optional(),retry:r.int().positive().optional()}),si=(e,t,n)=>oi(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
21
- `)).parse({event:t,data:n}),ci=e=>e.headersSent||e.writeHead(200,{connection:`keep-alive`,"content-type":y.sse,"cache-control":`no-cache`}),li=e=>new M({handler:async({response:t})=>setTimeout(()=>ci(t),1e4)&&{isClosed:()=>t.writableEnded||t.closed,emit:(n,r)=>{ci(t),t.write(si(e,n,r),`utf-8`),t.flush?.()}}}),ui=e=>new P({positive:()=>{let[t,...n]=Object.entries(e).map(([e,t])=>oi(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=A(t);Ye(a,n,r,i),e.headersSent||e.status(a.statusCode).type(`text/plain`).write(j(a),`utf-8`)}e.end()}});var di=class extends ct{constructor(e){super(ui(e)),this.middlewares=[li(e)]}};const fi={dateIn:Oe,dateOut:Ae,form:Re,upload:ze,raw:He,buffer:Ee};export{vt as BuiltinLogger,yt as DependsOnMethod,$n as Documentation,E as DocumentationError,ct as EndpointsFactory,di as EventStreamFactory,D as InputValidationError,ai as Integration,M as Middleware,Ie as MissingPeerError,Pe as OutputValidationError,P as ResultHandler,je as RoutingError,bt as ServeStatic,ut as arrayEndpointsFactory,st as arrayResultHandler,ln as attachRouting,ce as createConfig,un as createServer,lt as defaultEndpointsFactory,F as defaultResultHandler,A as ensureHttpError,fi as ez,S as getMessageFromError,ir as testEndpoint,ar as testMiddleware};
20
+ `)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=(await St(`prettier`)).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#printUsage(e);this.#usage=r&&n?[await n(r)]:this.#usage;let i=this.print(e);return n?n(i):i}};const oi=(e,t)=>r.object({data:t,event:r.literal(e),id:r.string().optional(),retry:r.int().positive().optional()}),si=(e,t,n)=>oi(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
21
+ `)).parse({event:t,data:n}),ci=e=>e.headersSent||e.writeHead(200,{connection:`keep-alive`,"content-type":y.sse,"cache-control":`no-cache`}),li=e=>new M({handler:async({response:t})=>setTimeout(()=>ci(t),1e4)&&{isClosed:()=>t.writableEnded||t.closed,emit:(n,r)=>{ci(t),t.write(si(e,n,r),`utf-8`),t.flush?.()}}}),ui=e=>new P({positive:()=>{let[t,...n]=Object.entries(e).map(([e,t])=>oi(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=A(t);Ye(a,n,r,i),e.headersSent||e.status(a.statusCode).type(`text/plain`).write(j(a),`utf-8`)}e.end()}});var di=class extends ut{constructor(e){super(ui(e)),this.middlewares=[li(e)]}};const fi={dateIn:Oe,dateOut:Ae,form:Re,upload:ze,raw:He,buffer:Ee};export{yt as BuiltinLogger,bt as DependsOnMethod,$n as Documentation,E as DocumentationError,ut as EndpointsFactory,di as EventStreamFactory,D as InputValidationError,ai as Integration,M as Middleware,Ie as MissingPeerError,Pe as OutputValidationError,P as ResultHandler,je as RoutingError,xt as ServeStatic,ft as arrayEndpointsFactory,lt as arrayResultHandler,ln as attachRouting,ce as createConfig,un as createServer,dt as defaultEndpointsFactory,F as defaultResultHandler,A as ensureHttpError,fi as ez,S as getMessageFromError,ir as testEndpoint,ar as testMiddleware};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "25.3.1",
3
+ "version": "25.4.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": {