express-zod-api 9.2.1 → 10.0.0-beta2

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.
Files changed (183) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +28 -20
  3. package/SECURITY.md +14 -13
  4. package/dist/esm/index.js +58 -0
  5. package/dist/esm/index.js.map +1 -0
  6. package/dist/esm/package.json +1 -0
  7. package/dist/index.d.ts +776 -21
  8. package/dist/index.js +55 -69
  9. package/dist/index.js.map +1 -1
  10. package/package.json +31 -25
  11. package/dist/api-response.d.ts +0 -16
  12. package/dist/api-response.js +0 -3
  13. package/dist/api-response.js.map +0 -1
  14. package/dist/client-helpers.d.ts +0 -23
  15. package/dist/client-helpers.js +0 -71
  16. package/dist/client-helpers.js.map +0 -1
  17. package/dist/client.d.ts +0 -15
  18. package/dist/client.js +0 -120
  19. package/dist/client.js.map +0 -1
  20. package/dist/common-helpers.d.ts +0 -46
  21. package/dist/common-helpers.js +0 -207
  22. package/dist/common-helpers.js.map +0 -1
  23. package/dist/config-type.d.ts +0 -59
  24. package/dist/config-type.js +0 -11
  25. package/dist/config-type.js.map +0 -1
  26. package/dist/date-in-schema.d.ts +0 -11
  27. package/dist/date-in-schema.js +0 -46
  28. package/dist/date-in-schema.js.map +0 -1
  29. package/dist/date-out-schema.d.ts +0 -10
  30. package/dist/date-out-schema.js +0 -31
  31. package/dist/date-out-schema.js.map +0 -1
  32. package/dist/depends-on-method.d.ts +0 -10
  33. package/dist/depends-on-method.js +0 -32
  34. package/dist/depends-on-method.js.map +0 -1
  35. package/dist/endpoint.d.ts +0 -98
  36. package/dist/endpoint.js +0 -261
  37. package/dist/endpoint.js.map +0 -1
  38. package/dist/endpoints-factory.d.ts +0 -161
  39. package/dist/endpoints-factory.js +0 -68
  40. package/dist/endpoints-factory.js.map +0 -1
  41. package/dist/errors.d.ts +0 -35
  42. package/dist/errors.js +0 -64
  43. package/dist/errors.js.map +0 -1
  44. package/dist/extend-zod.d.ts +0 -22
  45. package/dist/extend-zod.js +0 -33
  46. package/dist/extend-zod.js.map +0 -1
  47. package/dist/file-schema.d.ts +0 -23
  48. package/dist/file-schema.js +0 -55
  49. package/dist/file-schema.js.map +0 -1
  50. package/dist/io-schema.d.ts +0 -16
  51. package/dist/io-schema.js +0 -21
  52. package/dist/io-schema.js.map +0 -1
  53. package/dist/logger.d.ts +0 -3
  54. package/dist/logger.js +0 -54
  55. package/dist/logger.js.map +0 -1
  56. package/dist/logical-container.d.ts +0 -16
  57. package/dist/logical-container.js +0 -85
  58. package/dist/logical-container.js.map +0 -1
  59. package/dist/metadata.d.ts +0 -27
  60. package/dist/metadata.js +0 -58
  61. package/dist/metadata.js.map +0 -1
  62. package/dist/method.d.ts +0 -8
  63. package/dist/method.js +0 -5
  64. package/dist/method.js.map +0 -1
  65. package/dist/middleware.d.ts +0 -32
  66. package/dist/middleware.js +0 -16
  67. package/dist/middleware.js.map +0 -1
  68. package/dist/mime.d.ts +0 -2
  69. package/dist/mime.js +0 -10
  70. package/dist/mime.js.map +0 -1
  71. package/dist/mock.d.ts +0 -38
  72. package/dist/mock.js +0 -66
  73. package/dist/mock.js.map +0 -1
  74. package/dist/open-api-helpers.d.ts +0 -83
  75. package/dist/open-api-helpers.js +0 -621
  76. package/dist/open-api-helpers.js.map +0 -1
  77. package/dist/open-api.d.ts +0 -25
  78. package/dist/open-api.js +0 -98
  79. package/dist/open-api.js.map +0 -1
  80. package/dist/result-handler.d.ts +0 -151
  81. package/dist/result-handler.js +0 -71
  82. package/dist/result-handler.js.map +0 -1
  83. package/dist/routing-walker.d.ts +0 -12
  84. package/dist/routing-walker.js +0 -55
  85. package/dist/routing-walker.js.map +0 -1
  86. package/dist/routing.d.ts +0 -15
  87. package/dist/routing.js +0 -25
  88. package/dist/routing.js.map +0 -1
  89. package/dist/schema-walker.d.ts +0 -23
  90. package/dist/schema-walker.js +0 -26
  91. package/dist/schema-walker.js.map +0 -1
  92. package/dist/security.d.ts +0 -72
  93. package/dist/security.js +0 -3
  94. package/dist/security.js.map +0 -1
  95. package/dist/serve-static.d.ts +0 -9
  96. package/dist/serve-static.js +0 -17
  97. package/dist/serve-static.js.map +0 -1
  98. package/dist/server.d.ts +0 -20
  99. package/dist/server.js +0 -131
  100. package/dist/server.js.map +0 -1
  101. package/dist/startup-logo.d.ts +0 -1
  102. package/dist/startup-logo.js +0 -27
  103. package/dist/startup-logo.js.map +0 -1
  104. package/dist/upload-schema.d.ts +0 -11
  105. package/dist/upload-schema.js +0 -42
  106. package/dist/upload-schema.js.map +0 -1
  107. package/dist/zts-helpers.d.ts +0 -37
  108. package/dist/zts-helpers.js +0 -60
  109. package/dist/zts-helpers.js.map +0 -1
  110. package/dist/zts.d.ts +0 -31
  111. package/dist/zts.js +0 -147
  112. package/dist/zts.js.map +0 -1
  113. package/dist-esm/api-response.js +0 -2
  114. package/dist-esm/api-response.js.map +0 -1
  115. package/dist-esm/client-helpers.js +0 -48
  116. package/dist-esm/client-helpers.js.map +0 -1
  117. package/dist-esm/client.js +0 -113
  118. package/dist-esm/client.js.map +0 -1
  119. package/dist-esm/common-helpers.js +0 -188
  120. package/dist-esm/common-helpers.js.map +0 -1
  121. package/dist-esm/config-type.js +0 -7
  122. package/dist-esm/config-type.js.map +0 -1
  123. package/dist-esm/date-in-schema.js +0 -42
  124. package/dist-esm/date-in-schema.js.map +0 -1
  125. package/dist-esm/date-out-schema.js +0 -27
  126. package/dist-esm/date-out-schema.js.map +0 -1
  127. package/dist-esm/depends-on-method.js +0 -28
  128. package/dist-esm/depends-on-method.js.map +0 -1
  129. package/dist-esm/endpoint.js +0 -256
  130. package/dist-esm/endpoint.js.map +0 -1
  131. package/dist-esm/endpoints-factory.js +0 -64
  132. package/dist-esm/endpoints-factory.js.map +0 -1
  133. package/dist-esm/errors.js +0 -54
  134. package/dist-esm/errors.js.map +0 -1
  135. package/dist-esm/extend-zod.js +0 -16
  136. package/dist-esm/extend-zod.js.map +0 -1
  137. package/dist-esm/file-schema.js +0 -51
  138. package/dist-esm/file-schema.js.map +0 -1
  139. package/dist-esm/index.js +0 -19
  140. package/dist-esm/index.js.map +0 -1
  141. package/dist-esm/io-schema.js +0 -17
  142. package/dist-esm/io-schema.js.map +0 -1
  143. package/dist-esm/logger.js +0 -47
  144. package/dist-esm/logger.js.map +0 -1
  145. package/dist-esm/logical-container.js +0 -78
  146. package/dist-esm/logical-container.js.map +0 -1
  147. package/dist-esm/metadata.js +0 -51
  148. package/dist-esm/metadata.js.map +0 -1
  149. package/dist-esm/method.js +0 -2
  150. package/dist-esm/method.js.map +0 -1
  151. package/dist-esm/middleware.js +0 -12
  152. package/dist-esm/middleware.js.map +0 -1
  153. package/dist-esm/mime.js +0 -4
  154. package/dist-esm/mime.js.map +0 -1
  155. package/dist-esm/mock.js +0 -57
  156. package/dist-esm/mock.js.map +0 -1
  157. package/dist-esm/open-api-helpers.js +0 -575
  158. package/dist-esm/open-api-helpers.js.map +0 -1
  159. package/dist-esm/open-api.js +0 -94
  160. package/dist-esm/open-api.js.map +0 -1
  161. package/dist-esm/package.json +0 -1
  162. package/dist-esm/result-handler.js +0 -66
  163. package/dist-esm/result-handler.js.map +0 -1
  164. package/dist-esm/routing-walker.js +0 -51
  165. package/dist-esm/routing-walker.js.map +0 -1
  166. package/dist-esm/routing.js +0 -21
  167. package/dist-esm/routing.js.map +0 -1
  168. package/dist-esm/schema-walker.js +0 -22
  169. package/dist-esm/schema-walker.js.map +0 -1
  170. package/dist-esm/security.js +0 -2
  171. package/dist-esm/security.js.map +0 -1
  172. package/dist-esm/serve-static.js +0 -10
  173. package/dist-esm/serve-static.js.map +0 -1
  174. package/dist-esm/server.js +0 -98
  175. package/dist-esm/server.js.map +0 -1
  176. package/dist-esm/startup-logo.js +0 -23
  177. package/dist-esm/startup-logo.js.map +0 -1
  178. package/dist-esm/upload-schema.js +0 -38
  179. package/dist-esm/upload-schema.js.map +0 -1
  180. package/dist-esm/zts-helpers.js +0 -50
  181. package/dist-esm/zts-helpers.js.map +0 -1
  182. package/dist-esm/zts.js +0 -140
  183. package/dist-esm/zts.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # Changelog
2
2
 
3
+ ## Version 10
4
+
5
+ ### v10.0.0-beta2
6
+
7
+ - **BREAKING** changes to the behavior of a public method.
8
+ - The feature method `withMeta` _(introduced in v2.1.0)_ used to mutate its argument (`zod` schema) in order to
9
+ extend it with additional methods.
10
+ - If you're using this feature _within_ the call of `EndpointsFactory::build()`, there is no issue.
11
+ - However, if you're using a schema assignment (to some const) along with this method, this might lead to unexpected
12
+ results.
13
+ - The following case is reported by [@McMerph](https://github.com/McMerph) in issue #827.
14
+ - Reusing a schema assigned to a const for its several wrappings by `withMeta` and setting different examples.
15
+ - In this case all examples were set to the original const.
16
+ - This release fixes that behavior by making `withMeta` immutable: it returns a new copy of its argument.
17
+
18
+ ```ts
19
+ // the example case
20
+ const originalSchema = z.string();
21
+ const schemaA = withMeta(originalSchema).example("A");
22
+ const schemaB = withMeta(originalSchema).example("B");
23
+ // BEFORE: all three const have both examples "A" and "B"
24
+ // AFTER:
25
+ // - originalSchema remains intact
26
+ // - schemaA has example "A"
27
+ // - schemaB has example "B"
28
+ ```
29
+
30
+ ### v10.0.0-beta1
31
+
32
+ - **BREAKING** changes to the concept of dependencies.
33
+ - `zod` becomes a peer dependency, fixes issue #822.
34
+ - You need to install it manually and adjust your imports accordingly.
35
+ - `express` becomes a peer dependency as well.
36
+ - You need to install it manually.
37
+ - `typescript` becomes an optional peer dependency.
38
+ - When using a client generator, you need to install it manually.
39
+ - The minimal supported version is 4.9.3.
40
+ - Proprietary schemas are now exported under the namespace `ez`.
41
+ - Imports and utilization should be adjusted accordingly.
42
+ - Affected schemas: `file`, `dateIn`, `dateOut`, `upload`.
43
+ - **BREAKING** changes to the engines.
44
+ - The minimal Node version is now 14.18.0.
45
+ - Due to switching to `tsup` builder, the file structure has changed:
46
+ - `/dist/index.js` — CommonJS bundle;
47
+ - `/dist/esm/index.js` — ESM bundle;
48
+ - `/dist/index.d.ts` — types declaration bundle.
49
+
50
+ ```ts
51
+ // before
52
+ import { z } from "express-zod-api";
53
+ const stringSchema = z.string();
54
+ const uploadSchema = z.upload();
55
+ ```
56
+
57
+ ```ts
58
+ // after
59
+ import { z } from "zod"; // module changed
60
+ import { ez } from "express-zod-api"; // new namespace
61
+ const stringSchema = z.string(); // remains the same
62
+ const uploadSchema = ez.upload(); // namespace changed
63
+ ```
64
+
3
65
  ## Version 9
4
66
 
5
67
  ### v9.2.1
package/README.md CHANGED
@@ -101,10 +101,14 @@ Much can be customized to fit your needs.
101
101
 
102
102
  ## Installation
103
103
 
104
+ Run one of the following commands to install the library and its peer dependencies.
105
+ Typescript is an optional dependency, however, it's required if you're going to
106
+ [generate a frontend client](#generating-a-frontend-client) for your API.
107
+
104
108
  ```shell
105
- yarn add express-zod-api
109
+ yarn add express-zod-api express zod typescript
106
110
  # or
107
- npm install express-zod-api
111
+ npm install express-zod-api express zod typescript
108
112
  ```
109
113
 
110
114
  Add the following option to your `tsconfig.json` file in order to make it work as expected:
@@ -150,7 +154,7 @@ _In case you need to customize the response, see [Response customization](#respo
150
154
  ## Create your first endpoint
151
155
 
152
156
  ```typescript
153
- import { z } from "express-zod-api";
157
+ import { z } from "zod";
154
158
 
155
159
  const helloWorldEndpoint = defaultEndpointsFactory.build({
156
160
  method: "get",
@@ -270,7 +274,8 @@ const yourEndpoint = defaultEndpointsFactory
270
274
  Here is an example of the authentication middleware, that checks a `key` from input and `token` from headers:
271
275
 
272
276
  ```typescript
273
- import { createMiddleware, createHttpError, z } from "express-zod-api";
277
+ import { z } from "zod";
278
+ import { createMiddleware, createHttpError } from "express-zod-api";
274
279
 
275
280
  const authMiddleware = createMiddleware({
276
281
  security: {
@@ -327,7 +332,8 @@ You can implement additional validations within schemas using refinements.
327
332
  Validation errors are reported in a response with a status code `400`.
328
333
 
329
334
  ```typescript
330
- import { createMiddleware, z } from "express-zod-api";
335
+ import { z } from "zod";
336
+ import { createMiddleware } from "express-zod-api";
331
337
 
332
338
  const nicknameConstraintMiddleware = createMiddleware({
333
339
  input: z.object({
@@ -367,7 +373,7 @@ Since parameters of GET requests come in the form of strings, there is often a n
367
373
  arrays of numbers.
368
374
 
369
375
  ```typescript
370
- import { z } from "express-zod-api";
376
+ import { z } from "zod";
371
377
 
372
378
  const getUserEndpoint = endpointsFactory.build({
373
379
  method: "get",
@@ -398,10 +404,10 @@ which in turn calls
398
404
  It is also impossible to transmit the `Date` in its original form to your endpoints within JSON. Therefore, there is
399
405
  confusion with original method ~~z.date()~~ that should not be used within IO schemas of your API.
400
406
 
401
- In order to solve this problem, the library provides two custom methods for dealing with dates: `z.dateIn()` and
402
- `z.dateOut()` for using within input and output schemas accordingly.
407
+ In order to solve this problem, the library provides two custom methods for dealing with dates: `ez.dateIn()` and
408
+ `ez.dateOut()` for using within input and output schemas accordingly.
403
409
 
404
- `z.dateIn()` is a transforming schema that accepts an ISO `string` representation of a `Date`, validates it, and
410
+ `ez.dateIn()` is a transforming schema that accepts an ISO `string` representation of a `Date`, validates it, and
405
411
  provides your endpoint handler or middleware with a `Date`. It supports the following formats:
406
412
 
407
413
  ```text
@@ -411,20 +417,21 @@ provides your endpoint handler or middleware with a `Date`. It supports the foll
411
417
  2021-12-31
412
418
  ```
413
419
 
414
- `z.dateOut()`, on the contrary, accepts a `Date` and provides `ResultHanlder` with a `string` representation in ISO
420
+ `ez.dateOut()`, on the contrary, accepts a `Date` and provides `ResultHanlder` with a `string` representation in ISO
415
421
  format for the response transmission. Consider the following simplified example for better understanding:
416
422
 
417
423
  ```typescript
418
- import { z, defaultEndpointsFactory } from "express-zod-api";
424
+ import { z } from "zod";
425
+ import { ez, defaultEndpointsFactory } from "express-zod-api";
419
426
 
420
427
  const updateUserEndpoint = defaultEndpointsFactory.build({
421
428
  method: "post",
422
429
  input: z.object({
423
430
  userId: z.string(),
424
- birthday: z.dateIn(), // string -> Date
431
+ birthday: ez.dateIn(), // string -> Date
425
432
  }),
426
433
  output: z.object({
427
- createdAt: z.dateOut(), // Date -> string
434
+ createdAt: ez.dateOut(), // Date -> string
428
435
  }),
429
436
  handler: async ({ input }) => {
430
437
  // input.birthday is Date
@@ -499,10 +506,10 @@ type DefaultResponse<OUT> =
499
506
  You can create your own result handler by using this example as a template:
500
507
 
501
508
  ```typescript
509
+ import { z } from "zod";
502
510
  import {
503
511
  createResultHandler,
504
512
  IOSchema,
505
- z,
506
513
  getStatusCodeFromError,
507
514
  getMessageFromError,
508
515
  } from "express-zod-api";
@@ -545,7 +552,7 @@ Thus, you can configure non-object responses too, for example, to send an image
545
552
  You can find two approaches to `EndpointsFactory` and `ResultHandler` implementation
546
553
  [in this example](https://github.com/RobinTail/express-zod-api/blob/master/example/factories.ts).
547
554
  One of them implements file streaming, in this case the endpoint just has to provide the filename.
548
- The response schema generally may be just `z.string()`, but I made more specific `z.file()` that also supports
555
+ The response schema generally may be just `z.string()`, but I made more specific `ez.file()` that also supports
549
556
  `.binary()` and `.base64()` refinements which are reflected in the
550
557
  [generated documentation](#creating-a-documentation).
551
558
 
@@ -553,7 +560,7 @@ The response schema generally may be just `z.string()`, but I made more specific
553
560
  const fileStreamingEndpointsFactory = new EndpointsFactory(
554
561
  createResultHandler({
555
562
  getPositiveResponse: () => ({
556
- schema: z.file().binary(),
563
+ schema: ez.file().binary(),
557
564
  mimeType: "image/*",
558
565
  }),
559
566
  getNegativeResponse: () => ({ schema: z.string(), mimeType: "text/plain" }),
@@ -599,11 +606,12 @@ const advancedUsage = defaultEndpointsFactory.use(auth(), {
599
606
  ## File uploads
600
607
 
601
608
  You can switch the `Endpoint` to handle requests with the `multipart/form-data` content type instead of JSON by using
602
- `z.upload()` schema. Together with a corresponding configuration option, this makes it possible to handle file uploads.
609
+ `ez.upload()` schema. Together with a corresponding configuration option, this makes it possible to handle file uploads.
603
610
  Here is a simplified example:
604
611
 
605
612
  ```typescript
606
- import { createConfig, z, defaultEndpointsFactory } from "express-zod-api";
613
+ import { z } from "zod";
614
+ import { createConfig, ez, defaultEndpointsFactory } from "express-zod-api";
607
615
 
608
616
  const config = createConfig({
609
617
  server: {
@@ -615,7 +623,7 @@ const config = createConfig({
615
623
  const fileUploadEndpoint = defaultEndpointsFactory.build({
616
624
  method: "post",
617
625
  input: z.object({
618
- avatar: z.upload(), // <--
626
+ avatar: ez.upload(), // <--
619
627
  }),
620
628
  output: z.object({
621
629
  /* ... */
@@ -942,7 +950,7 @@ in this case during development. You can achieve this verification by assigning
942
950
  reusing it in forced type of the output:
943
951
 
944
952
  ```typescript
945
- import { z } from "express-zod-api";
953
+ import { z } from "zod";
946
954
 
947
955
  const output = z.object({
948
956
  anything: z.number(),
package/SECURITY.md CHANGED
@@ -2,24 +2,25 @@
2
2
 
3
3
  ## Supported Versions
4
4
 
5
- | Version | Supported |
6
- | ------- | ------------------ |
7
- | 9.x.x | :white_check_mark: |
8
- | 8.x.x | :white_check_mark: |
9
- | 7.x.x | :x: |
10
- | 6.x.x | :x: |
11
- | 5.x.x | :x: |
12
- | 4.x.x | :x: |
13
- | 3.x.x | :x: |
14
- | 2.x.x | :x: |
15
- | 1.x.x | :x: |
16
- | 0.x.x | :x: |
5
+ | Version | Supported |
6
+ | ------: | :----------------: |
7
+ | 10.x.x | :white_check_mark: |
8
+ | 9.x.x | :white_check_mark: |
9
+ | 8.x.x | :white_check_mark: |
10
+ | 7.x.x | :x: |
11
+ | 6.x.x | :x: |
12
+ | 5.x.x | :x: |
13
+ | 4.x.x | :x: |
14
+ | 3.x.x | :x: |
15
+ | 2.x.x | :x: |
16
+ | 1.x.x | :x: |
17
+ | 0.x.x | :x: |
17
18
 
18
19
  ## Reporting a Vulnerability
19
20
 
20
21
  Found a vulnerability or other security issue?
21
22
 
22
23
  Please urgently inform me privately by
23
- [email](https://github.com/RobinTail/express-zod-api/blob/master/package.json#L115).
24
+ [email](https://github.com/RobinTail/express-zod-api/blob/master/package.json#L121).
24
25
 
25
26
  I will try to fix it as soon as possible.
@@ -0,0 +1,58 @@
1
+ var Or=(e,r,t)=>{if(!r.has(e))throw TypeError("Cannot "+t)};var A=(e,r,t)=>{if(r.has(e))throw TypeError("Cannot add the same private member more than once");r instanceof WeakSet?r.add(e):r.set(e,t)};var E=(e,r,t)=>(Or(e,r,"access private method"),t);var Rt={silent:!0,warn:!0,debug:!0},br=e=>e;import{z as N}from"zod";import{HttpError as zr}from"http-errors";import{z as T}from"zod";import{clone as Pr,mergeDeepRight as Er}from"ramda";var O="expressZodApiMeta",Zr=e=>{let r=e.constructor,t=Pr(e._def);return t[O]=t[O]||{examples:[]},new r(t)},$=e=>{let r=Zr(e);return Object.defineProperties(r,{example:{get:()=>t=>{let o=$(r);return o._def[O].examples.push(t),o}}}),r},At=e=>O in e._def?typeof e._def[O]=="object"&&e._def[O]!==null:!1;function Se(e,r){if(!At(e))return;let t=e._def;return r in t[O]?t[O][r]:void 0}var Oe=(e,r)=>{if(!At(e))return r;let t=$(r),o=te(t._def[O].examples,e._def[O].examples);if(t._def[O].examples=[],o.type==="single")t._def[O].examples=o.value;else for(let[n,i]of o.value)t._def[O].examples.push(Er({...n},{...i}));return t};import Rr from"mime";var j=Rr.getType("json")||"application/json",re="multipart/form-data";import{INVALID as Ar,OK as Ir,ZodIssueCode as Cr,ZodParsedType as Mr,ZodType as Nr,addIssueToContext as wr}from"zod";var Dr="ZodUpload",vr=e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.mimetype=="string"&&typeof e.data=="object"&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",Ge=class extends Nr{_parse(r){let{ctx:t}=this._processInputParams(r);return t.parsedType!==Mr.object||!vr(t.data)?(wr(t,{code:Cr.custom,message:`Expected file upload, received ${t.parsedType}`}),Ar):Ir(t.data)}},L=Ge;L.create=()=>new Ge({typeName:Dr});var qe=/:([A-Za-z0-9_]+)/g;function jr(e){let t=(e.header("content-type")||"").slice(0,re.length).toLowerCase()===re;return"files"in e&&t}var be={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Lr=["body","query","params"],Ve=e=>e.method.toLowerCase();function It(e,r){let t=Ve(e);if(t==="options")return{};let o=Lr;return t in be&&(o=be[t]),r&&t in r&&(o=r[t]||o),o.filter(n=>n==="files"?jr(e):!0).reduce((n,i)=>({...n,...e[i]}),{})}function Be(e){return typeof e=="object"&&"level"in e&&"color"in e&&Object.keys(Rt).includes(e.level)&&typeof e.color=="boolean"}function Pe(e){return!isNaN(e.getTime())}function ne(e){return e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`)}function k(e){return e instanceof T.ZodError?e.issues.map(({path:r,message:t})=>(r.length?[r.join("/")]:[]).concat(t).join(": ")).join("; "):e instanceof U?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message}function Ye(e){return e instanceof zr?e.statusCode:e instanceof C?400:500}var Ee=(e,r)=>{let t=Se(e,"examples");return t===void 0?[]:t.reduce((o,n)=>{let i=e.safeParse(n);return o.concat(i.success?r?i.data:n:[])},[])},te=(e,r)=>{if(e.length===0)return{type:"single",value:r};if(r.length===0)return{type:"single",value:e};let t=[];for(let o of e)for(let n of r)t.push([o,n]);return{type:"tuple",value:t}};function Je(e){let r=e.match(qe);return r?r.map(t=>t.slice(1)):[]}var oe=e=>e.reduce((r,t)=>r||t,!1);function I(e){return e instanceof T.ZodEffects&&e._def.effect.type!=="refinement"?!0:e instanceof T.ZodUnion?oe(e.options.map(I)):e instanceof T.ZodIntersection?oe([e._def.left,e._def.right].map(I)):!1}function Z(e){return e instanceof L?!0:e instanceof T.ZodObject?oe(Object.values(e.shape).map(Z)):e instanceof T.ZodUnion?oe(e.options.map(Z)):e instanceof T.ZodIntersection?oe([e._def.left,e._def.right].map(Z)):e instanceof T.ZodOptional||e instanceof T.ZodNullable?Z(e.unwrap()):e instanceof T.ZodEffects||e instanceof T.ZodTransformer?Z(e._def.schema):e instanceof T.ZodRecord?Z(e._def.valueType):e instanceof T.ZodArray?Z(e._def.type):e instanceof T.ZodDefault?Z(e._def.innerType):!1}var ie=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,se=(e,r,t)=>[r].concat(e.split("/")).concat(t||[]).flatMap(o=>o.split(/[^A-Z0-9]/gi)).map(o=>o.slice(0,1).toUpperCase()+o.slice(1).toLowerCase()).join(""),Ze=({effect:e,sample:r})=>{try{return typeof e.transform(r,{addIssue:()=>{},path:[]})}catch{return}},We=e=>typeof e=="string"?{message:e}:e||{};var G=class extends Error{constructor(){super(...arguments);this.name="RoutingError"}},ae=class extends G{constructor(){super(...arguments);this.name="DependsOnMethodError"}},b=class extends Error{constructor(){super(...arguments);this.name="OpenAPIError"}},M=class extends Error{constructor(){super(...arguments);this.name="IOSchemaError"}},U=class extends M{constructor(t){super(k(t));this.name="OutputValidationError";this.originalError=t}},C=class extends M{constructor(t){super(k(t));this.name="InputValidationError";this.originalError=t}},q=class extends Error{constructor(t,o){super(t);this.name="ResultHandlerError";this.originalError=o||void 0}};var R=e=>typeof e=="object"&&e!==null,Re=e=>({and:e.reduce((r,t)=>r.concat(R(t)&&"and"in t?t.and:t),[])}),Ae=(e,r)=>{if(R(e)){if("and"in e)return{and:e.and.map(t=>R(t)&&"or"in t?{or:t.or.map(r)}:r(t))};if("or"in e)return{or:e.or.map(t=>R(t)&&"and"in t?{and:t.and.map(r)}:r(t))}}return r(e)},Qe=e=>e.and.reduce((r,t)=>{let o=te(r.or,R(t)&&"or"in t?t.or:[t]);return o.type==="single"?r.or.push(...o.value):r.or=o.value.map(Re),r},{or:[]}),V=(e,r)=>{if(R(e)){if("and"in e){if(R(r)){if("and"in r)return Re([e,r]);if("or"in r)return V(Qe(e),r)}return Re([e,r])}if("or"in e){if(R(r)){if("and"in r)return V(r,e);if("or"in r){let t=te(e.or,r.or);return{or:t.type==="single"?t.value:t.value.map(Re)}}}return V(e,{and:[r]})}}return R(r)&&("and"in r||"or"in r)?V(r,e):{and:[e,r]}};import{z as B}from"zod";var Y={positive:200,negative:400},Ct=e=>e,J=Ct({getPositiveResponse:e=>{let r=Se(e,"examples")||[],t=$(B.object({status:B.literal("success"),data:e}));return r.reduce((o,n)=>o.example({status:"success",data:n}),t)},getNegativeResponse:()=>$(B.object({status:B.literal("error"),error:B.object({message:B.string()})})).example({status:"error",error:{message:k(new Error("Sample error message"))}}),handler:({error:e,input:r,output:t,request:o,response:n,logger:i})=>{if(!e){n.status(Y.positive).json({status:"success",data:t});return}let a=Ye(e);a===500&&i.error(`Internal server error
2
+ ${e.stack}
3
+ `,{url:o.url,payload:r}),n.status(a).json({status:"error",error:{message:k(e)}})}}),Ie=({error:e,logger:r,response:t})=>{r.error(`Result handler failure: ${e.message}.`),t.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
4
+ Original error: ${e.originalError.message}.`:""))};var Mt=(e,r=[j])=>{if(e instanceof N.ZodType)return r;let{mimeTypes:t,mimeType:o}=e;return o?[o]:t||r},W=class{},Me,Nt,Ne,wt,we,Dt,De,vt,ve,zt,Ce=class extends W{constructor({middlewares:t,inputSchema:o,outputSchema:n,handler:i,resultHandler:a,description:d,shortDescription:l,...c}){super();A(this,Me);A(this,Ne);A(this,we);A(this,De);A(this,ve);this.methods=[];this.siblingMethods=[];this.middlewares=[];this.scopes=[];this.tags=[];[{name:"input schema",schema:o},{name:"output schema",schema:n}].forEach(({name:u,schema:g})=>{if(I(g))throw new M(`Using transformations on the top level of endpoint ${u} is not allowed.`)}),this.middlewares=t;let p={positive:a.getPositiveResponse(n),negative:a.getNegativeResponse()};this.mimeTypes={input:Z(o)?[re]:[j],positive:Mt(p.positive),negative:Mt(p.negative)},this.schemas={input:o,output:n,positive:p.positive instanceof N.ZodType?p.positive:p.positive.schema,negative:p.negative instanceof N.ZodType?p.negative:p.negative.schema},this.statusCodes={positive:p.positive instanceof N.ZodType?Y.positive:p.positive.statusCode||Y.positive,negative:p.negative instanceof N.ZodType?Y.negative:p.negative.statusCode||Y.negative},this.handler=i,this.resultHandler=a,this.descriptions={long:d,short:l},"scopes"in c&&c.scopes&&this.scopes.push(...c.scopes),"scope"in c&&c.scope&&this.scopes.push(c.scope),"tags"in c&&c.tags&&this.tags.push(...c.tags),"tag"in c&&c.tag&&this.tags.push(c.tag),"methods"in c?this.methods=c.methods:this.methods=[c.method]}_setSiblingMethods(t){this.siblingMethods=t}getDescription(t){return this.descriptions[t]}getMethods(){return this.methods}getSchema(t){return this.schemas[t]}getMimeTypes(t){return this.mimeTypes[t]}getStatusCode(t){return this.statusCodes[t]}getSecurity(){return this.middlewares.reduce((t,o)=>o.security?V(t,o.security):t,{and:[]})}getScopes(){return this.scopes}getTags(){return this.tags}async execute({request:t,response:o,logger:n,config:i}){let a=Ve(t),d,l=null;if(i.cors){let p=E(this,Me,Nt).call(this);typeof i.cors=="function"&&(p=await i.cors({request:t,logger:n,endpoint:this,defaultHeaders:p}));for(let u in p)o.set(u,p[u])}let c=It(t,i.inputSources);try{let{options:p,isStreamClosed:u}=await E(this,we,Dt).call(this,{method:a,input:c,request:t,response:o,logger:n});if(u)return;if(a==="options"){o.status(200).end();return}d=await E(this,Ne,wt).call(this,await E(this,De,vt).call(this,{input:c,options:p,logger:n}))}catch(p){l=ne(p)}await E(this,ve,zt).call(this,{input:c,output:d,request:t,response:o,error:l,logger:n})}};Me=new WeakSet,Nt=function(){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.methods.concat(this.siblingMethods).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}},Ne=new WeakSet,wt=async function(t){try{return await this.schemas.output.parseAsync(t)}catch(o){throw o instanceof N.ZodError?new U(o):o}},we=new WeakSet,Dt=async function({method:t,input:o,request:n,response:i,logger:a}){let d={},l=!1;for(let c of this.middlewares){if(t==="options"&&c.type==="proprietary")continue;let p;try{p=await c.input.parseAsync(o)}catch(u){throw u instanceof N.ZodError?new C(u):u}if(Object.assign(d,await c.middleware({input:p,options:d,request:n,response:i,logger:a})),l="writableEnded"in i&&i.writableEnded,l){a.warn(`The middleware ${c.middleware.name} has closed the stream. Accumulated options:`,d);break}}return{options:d,isStreamClosed:l}},De=new WeakSet,vt=async function({input:t,options:o,logger:n}){let i;try{i=await this.schemas.input.parseAsync(t)}catch(a){throw a instanceof N.ZodError?new C(a):a}return this.handler({input:i,options:o,logger:n})},ve=new WeakSet,zt=async function({error:t,request:o,response:n,logger:i,input:a,output:d}){try{await this.resultHandler.handler({error:t,output:d,request:o,response:n,logger:i,input:a})}catch(l){Ie({logger:i,response:n,error:new q(ne(l).message,t)})}};var jt=["get","post","put","delete","patch"];import{z as kt}from"zod";var Lt=(e,r)=>{let t=e.map(({input:n})=>n).concat(r),o=t.reduce((n,i)=>n.and(i));return t.reduce((n,i)=>Oe(i,n),o)};var Xe=e=>{if(I(e.input))throw new M("Using transformations on the top level of middleware input schema is not allowed.");return{...e,type:"proprietary"}};var X,ze,Q=class{constructor(r){this.middlewares=[];this.use=this.addExpressMiddleware;this.resultHandler="resultHandler"in r?r.resultHandler:r}addMiddleware(r){var t;return E(t=Q,X,ze).call(t,this.middlewares.concat(r),this.resultHandler)}addExpressMiddleware(r,t){var a;let o=t?.transformer||(d=>d),n=t?.provider||(()=>({})),i={type:"express",input:kt.object({}),middleware:async({request:d,response:l})=>new Promise((c,p)=>{r(d,l,g=>{if(g&&g instanceof Error)return p(o(g));c(n(d,l))})})};return E(a=Q,X,ze).call(a,this.middlewares.concat(i),this.resultHandler)}addOptions(r){var t;return E(t=Q,X,ze).call(t,this.middlewares.concat(Xe({input:kt.object({}),middleware:async()=>r})),this.resultHandler)}build({input:r,handler:t,output:o,...n}){let{middlewares:i,resultHandler:a}=this;return new Ce({handler:t,middlewares:i,outputSchema:o,resultHandler:a,inputSchema:Lt(i,r),...n})}},de=Q;X=new WeakSet,ze=function(r,t){let o=new Q(t);return o.middlewares=r,o},A(de,X);var kr=new de(J);import{inspect as Ur}from"util";import{LEVEL as Hr,MESSAGE as Kr,SPLAT as Fr}from"triple-beam";import je from"winston";var{combine:_r,colorize:$r,timestamp:Gr,printf:qr}=je.format;function Le(e){let r=i=>{let{[Hr]:a,[Kr]:d,[Fr]:l,...c}=i;return Ur(c,!1,1,e.color)},t=i=>qr(({timestamp:a,message:d,level:l,durationMs:c,...p})=>(typeof d=="object"&&(p={...p,...d},d="[No message]"),`${a} ${l}: ${d}`+(c===void 0?"":` duration: ${c}ms`)+(Object.keys(p).length===0?"":" "+(i?r(p):JSON.stringify(p))))),o=[Gr()],n={handleExceptions:!0};switch(e.color&&o.push($r()),e.level){case"debug":n.level="debug",o.push(t(!0));break;case"silent":case"warn":default:n.level="warn",o.push(t())}return n.format=_r(...o),je.createLogger({silent:e.level==="silent",levels:je.config.npm.levels,transports:[new je.transports.Console(n)],exitOnError:!1})}var pe=class{constructor(r){this.methods=r;Object.keys(r).forEach(t=>{if(t in r&&!(r[t]?.getMethods()||[]).includes(t))throw new ae(`The endpoint assigned to the '${t}' parameter must have at least this method in its specification.
5
+ This error should prevent mistakes during the development process.
6
+ Example:
7
+
8
+ new ${this.constructor.name}({
9
+ ${t}: endpointsFactory.build({
10
+ methods: ['${t}', `+((r[t]?.getMethods()||[]).map(n=>`'${n}'`).join(", ")||"...")+`]
11
+ // or method: '${t}'
12
+ ...
13
+ })
14
+ });
15
+ `)})}};import Vr from"express";var ce=class{constructor(...r){this.params=r}apply(r,t){return t(r,Vr.static(...this.params))}};var H=({routing:e,onEndpoint:r,onStatic:t,parentPath:o,hasCors:n})=>{Object.entries(e).forEach(([i,a])=>{if(i=i.trim(),i.match(/\//))throw new G(`Routing elements should not contain '/' character.
16
+ The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let d=`${o||""}${i?`/${i}`:""}`;if(a instanceof W){let l=a.getMethods().slice();n&&l.push("options"),l.forEach(c=>{r(a,d,c)})}else if(a instanceof ce)t&&a.apply(d,t);else if(a instanceof pe){if(Object.entries(a.methods).forEach(([l,c])=>{r(c,d,l)}),n&&Object.keys(a.methods).length>0){let[l,...c]=Object.keys(a.methods),p=a.methods[l];p._setSiblingMethods(c),r(p,d,"options")}}else H({onEndpoint:r,onStatic:t,hasCors:n,routing:a,parentPath:d})})};var Ut=()=>`
17
+ \x1B[94m\x1B[39m
18
+ \x1B[94m\x1B[39m
19
+ \x1B[94m8888888888 8888888888P 888 d8888 8888888b. 8888888 \x1B[39m
20
+ \x1B[94m888 d88P 888 d88888 888 Y88b 888\x1B[39m\x1B[95m\x1B[39m
21
+ \x1B[95m888 d88P 888 d88P888 888 888 888\x1B[39m
22
+ \x1B[95m8888888 888 888 88888b. 888d888 .d88b. .d8888b .d8888b d88P .d88b. .d88888 d88P 888 888 d88P 888\x1B[39m\x1B[97m\x1B[39m
23
+ \x1B[97m888 \`Y8bd8P' 888 "88b 888P" d8P Y8b 88K 88K d88P d88""88b d88" 888 d88P 888 8888888P" 888 \x1B[39m
24
+ \x1B[97m888 X88K 888 888 888 88888888 "Y8888b. "Y8888b. d88P 888 888 888 888 d88P 888 888 888\x1B[39m\x1B[95m\x1B[39m
25
+ \x1B[95m888 .d8""8b. 888 d88P 888 Y8b. X88 X88 d88P Y88..88P Y88b 888 d8888888888 888 888 \x1B[39m
26
+ \x1B[95m8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P' d8888888888 "Y88P" "Y88888 d88P 888 888 8888888\x1B[39m\x1B[94m\x1B[39m
27
+ \x1B[94m 888\x1B[39m
28
+ \x1B[94m 888\x1B[3m Proudly supports transgender community.\x1B[23m\x1B[39m
29
+ \x1B[94m\x1B[3mfor Gisberta \x1B[23m 888\x1B[3m Start your API server with I/O schema validation and custom middlewares in minutes.\x1B[23m\x1B[39m\x1B[90m\x1B[39m
30
+ \x1B[90m\x1B[3m Thank you for choosing Express Zod API for your project.\x1B[23m\x1B[39m\x1B[0m\x1B[0m
31
+ \x1B[0m\x1B[0m
32
+ \x1B[0m\x1B[0m
33
+ `.trim();var et=({app:e,logger:r,config:t,routing:o})=>{t.startupLogo!==!1&&console.log(Ut()),H({routing:o,hasCors:!!t.cors,onEndpoint:(n,i,a)=>{e[a](i,async(d,l)=>{r.info(`${d.method}: ${i}`),await n.execute({request:d,response:l,logger:r,config:t})})},onStatic:(n,i)=>{e.use(n,i)}})};import Br,{json as Yr}from"express";import Jr from"compression";import Wr from"express-fileupload";import Qr from"https";import Xr from"http-errors";var eo=(e,r)=>(t,o,n,i)=>{if(!t)return i();e.handler({error:t,request:o,response:n,logger:r,input:o.body,output:null})},Ht=(e,r)=>(t,o)=>{let n=Xr(404,`Can not ${t.method} ${t.path}`);try{e.handler({request:t,response:o,logger:r,error:n,input:null,output:null})}catch(i){Ie({response:o,logger:r,error:new q(ne(i).message,n)})}};function to(e,r){let t=Be(e.logger)?Le(e.logger):e.logger;et({app:e.app,routing:r,logger:t,config:e});let o=e.errorHandler||J;return{notFoundHandler:Ht(o,t),logger:t}}function ro(e,r){let t=Be(e.logger)?Le(e.logger):e.logger,o=Br();o.disable("x-powered-by");let n=e.errorHandler||J,i=e.server.compression?Jr({...typeof e.server.compression=="object"?e.server.compression:{}}):void 0,a=e.server.jsonParser||Yr(),d=e.server.upload?Wr({...typeof e.server.upload=="object"?e.server.upload:{},abortOnLimit:!1,parseNested:!0}):void 0,l=[].concat(i||[]).concat(a).concat(d||[]);o.use(l),o.use(eo(n,t)),et({app:o,routing:r,logger:t,config:e}),o.use(Ht(n,t));let c=o.listen(e.server.listen,()=>{t.info(`Listening ${e.server.listen}`)}),p;return e.https&&(p=Qr.createServer(e.https.options,o).listen(e.https.listen,()=>{t.info(`Listening ${e.https.listen}`)})),{app:o,httpServer:c,httpsServer:p,logger:t}}import{OpenApiBuilder as Fo}from"openapi3-ts";import{omit as ue}from"ramda";import{z as x}from"zod";import{INVALID as Kt,ZodIssueCode as tt,ZodParsedType as Ft,ZodType as oo,addIssueToContext as rt}from"zod";var ot=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/,no="ZodDateIn",nt=class extends oo{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);if(o.parsedType!==Ft.string)return rt(o,{code:tt.invalid_type,expected:Ft.string,received:o.parsedType}),Kt;ot.test(o.data)||(rt(o,{code:tt.invalid_string,validation:"regex"}),t.dirty());let n=new Date(o.data);return Pe(n)?{status:t.value,value:n}:(rt(o,{code:tt.invalid_date}),Kt)}},le=nt;le.create=()=>new nt({typeName:no});var K=({schema:e,onEach:r,rules:t,onMissing:o,...n})=>{let i=r&&r({schema:e,...n}),a="typeName"in e._def?t[e._def.typeName]:void 0,l=a?a({schema:e,...n,next:c=>K({...c,...n,onEach:r,rules:t,onMissing:o})}):o(e);return i?{...l,...i}:l};var _t=50,Gt="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",io={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},qt=e=>e.replace(qe,r=>`{${r.slice(1)}}`),so=({schema:{_def:{innerType:e,defaultValue:r}},next:t})=>({...t({schema:e}),default:r()}),ao=({schema:{_def:{innerType:e}},next:r})=>r({schema:e}),po=()=>({format:"any"}),co=({isResponse:e})=>{if(e)throw new b("Please use z.upload() only for input.");return{type:"string",format:"binary"}},lo=({schema:{isBinary:e,isBase64:r},isResponse:t})=>{if(!t)throw new b("Please use z.file() only within ResultHandler.");return{type:"string",format:e?"binary":r?"byte":"file"}},mo=({schema:{options:e},next:r})=>({oneOf:e.map(t=>r({schema:t}))}),uo=({schema:{options:e,discriminator:r},next:t})=>({discriminator:{propertyName:r},oneOf:Array.from(e.values()).map(o=>t({schema:o}))}),fo=({schema:{_def:{left:e,right:r}},next:t})=>({allOf:[e,r].map(o=>t({schema:o}))}),yo=({schema:e,next:r})=>r({schema:e.unwrap()}),go=({schema:e,next:r})=>({nullable:!0,...r({schema:e.unwrap()})}),$t=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),xo=({schema:{value:e}})=>({type:typeof e,enum:[e]}),ho=({schema:e,isResponse:r,next:t})=>{let o=Object.keys(e.shape).filter(n=>{let i=e.shape[n];return!(r&&ie(i)?i instanceof x.ZodOptional:i.isOptional())});return{type:"object",properties:ke({schema:e,isResponse:r,next:t}),...o.length?{required:o}:{}}},To=()=>({type:"string",nullable:!0,format:"null"}),So=({isResponse:e})=>{if(e)throw new b("Please use z.dateOut() for output.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:ot.source,externalDocs:{url:Gt}}},Oo=({isResponse:e})=>{if(!e)throw new b("Please use z.dateIn() for input.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Gt}}},bo=({isResponse:e})=>{throw new b(`Using z.date() within ${e?"output":"input"} schema is forbidden. Please use z.date${e?"Out":"In"}() instead. Check out the documentation for details.`)},Po=()=>({type:"boolean"}),Eo=()=>({type:"integer",format:"bigint"}),Zo=({schema:{keySchema:e,valueSchema:r},isResponse:t,next:o})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let n=Object.values(e.enum),i=n.reduce((a,d)=>({...a,[d]:r}),{});return{type:"object",properties:ke({schema:x.object(i),isResponse:t,next:o}),...n.length?{required:n}:{}}}if(e instanceof x.ZodLiteral)return{type:"object",properties:ke({schema:x.object({[e.value]:r}),isResponse:t,next:o}),required:[e.value]};if(e instanceof x.ZodUnion&&e.options.reduce((i,a)=>i&&a instanceof x.ZodLiteral,!0)){let i=e.options.reduce((a,d)=>({...a,[d.value]:r}),{});return{type:"object",properties:ke({schema:x.object(i),isResponse:t,next:o}),required:e.options.map(a=>a.value)}}return{type:"object",additionalProperties:o({schema:r})}},Ro=({schema:{_def:e,element:r},next:t})=>({type:"array",items:t({schema:r}),...e.minLength!==null&&{minItems:e.minLength.value},...e.maxLength!==null&&{maxItems:e.maxLength.value}}),Ao=({schema:{items:e},next:r})=>{let t=e.map(o=>r({schema:o}));return{type:"array",minItems:t.length,maxItems:t.length,items:{oneOf:t,format:"tuple",...t.length>0&&{description:t.map((o,n)=>`${n}: ${o.type}`).join(", ")}}}},Io=({schema:{isEmail:e,isURL:r,minLength:t,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:d,isIP:l,isEmoji:c,isDatetime:p,_def:{checks:u}}})=>{let g=u.find(S=>S.kind==="regex"),y=u.find(S=>S.kind==="datetime"),h=g?g.regex:y?y.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0;return{type:"string",...p&&{format:"date-time"},...e&&{format:"email"},...r&&{format:"url"},...n&&{format:"uuid"},...i&&{format:"cuid"},...a&&{format:"cuid2"},...d&&{format:"ulid"},...l&&{format:"ip"},...c&&{format:"emoji"},...t!==null&&{minLength:t},...o!==null&&{maxLength:o},...h&&{pattern:`/${h.source}/${h.flags}`}}},Co=({schema:e})=>{let r=e._def.checks.find(({kind:i})=>i==="min"),t=r?r.inclusive:!0,o=e._def.checks.find(({kind:i})=>i==="max"),n=o?o.inclusive:!0;return{type:e.isInt?"integer":"number",format:e.isInt?"int64":"double",minimum:e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:Number.MIN_VALUE:e.minValue,exclusiveMinimum:!t,maximum:e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,exclusiveMaximum:!n}},ke=({schema:{shape:e},next:r})=>Object.keys(e).reduce((t,o)=>({...t,[o]:r({schema:e[o]})}),{}),Mo=e=>{let r=Array.isArray(e.type)?e.type[0]:e.type;return io?.[r]},No=({schema:e,isResponse:r,next:t})=>{let o=t({schema:e.innerType()}),{effect:n}=e._def;if(r&&n.type==="transform"){let i=Ze({effect:n,sample:Mo(o)});return i&&["number","string","boolean"].includes(i)?{type:i}:t({schema:x.any()})}if(!r&&n.type==="preprocess"){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},wo=({schema:e,isResponse:r,next:t})=>t({schema:e._def[r?"out":"in"]}),Do=({schema:e,next:r})=>r({schema:e.unwrap()}),Vt=(e,r,t=[])=>{let o=Ee(e,r);return o.length===0?{}:{examples:o.reduce((n,i,a)=>({...n,[`example${a+1}`]:{value:ue(t,i)}}),{})}},vo=(e,r,t)=>{let o=Ee(e,r);return o.length===0?{}:{examples:o.reduce((n,i,a)=>t in i?{...n,[`example${a+1}`]:{value:i[t]}}:n,{})}};function me(e){if(e instanceof x.ZodObject)return e;let r;if(e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion)r=Array.from(e.options.values()).map(t=>me(t)).reduce((t,o)=>t.merge(o.partial()),x.object({}));else if(e instanceof x.ZodEffects){if(I(e))throw new b("Using transformations on the top level of input schema is not allowed.");r=me(e._def.schema)}else r=me(e._def.left).merge(me(e._def.right));return Oe(e,r)}var Bt=({path:e,method:r,endpoint:t,inputSources:o})=>{let n=t.getSchema("input"),i=me(n).shape,a=Je(e),d=o.includes("query"),l=o.includes("params"),c=p=>l&&a.includes(p);return Object.keys(i).filter(p=>d||c(p)).map(p=>({name:p,in:c(p)?"path":"query",required:!i[p].isOptional(),schema:{description:`${r.toUpperCase()} ${e} parameter`,...K({schema:i[p],isResponse:!1,rules:st,onEach:at,onMissing:dt})},...vo(n,!1,p)}))},st={ZodString:Io,ZodNumber:Co,ZodBigInt:Eo,ZodBoolean:Po,ZodDateIn:So,ZodDateOut:Oo,ZodNull:To,ZodArray:Ro,ZodTuple:Ao,ZodRecord:Zo,ZodObject:ho,ZodLiteral:xo,ZodIntersection:fo,ZodUnion:mo,ZodFile:lo,ZodUpload:co,ZodAny:po,ZodDefault:so,ZodEnum:$t,ZodNativeEnum:$t,ZodEffects:No,ZodOptional:yo,ZodNullable:go,ZodDiscriminatedUnion:uo,ZodBranded:Do,ZodDate:bo,ZodCatch:ao,ZodPipeline:wo},at=({schema:e,isResponse:r})=>{let{description:t}=e,o=Ee(e,r);return{...t&&{description:t},...e.isNullable()&&!(r&&ie(e))&&{nullable:!0},...o.length>0&&{example:o[0]}}},dt=e=>{throw new b(`Zod type ${e.constructor.name} is unsupported`)},it=(e,r)=>{let t=e.properties?ue(r,e.properties):void 0,o=e.example?ue(r,e.example):void 0,n=e.required?e.required.filter(d=>!r.includes(d)):void 0,i=e.allOf?e.allOf.map(d=>it(d,r)):void 0,a=e.oneOf?e.oneOf.map(d=>it(d,r)):void 0;return ue(Object.entries({properties:t,required:n,example:o,allOf:i,oneOf:a}).filter(([{},d])=>d===void 0).map(([d])=>d),{...e,properties:t,required:n,example:o,allOf:i,oneOf:a})},Yt=e=>ue(["example"],e),pt=({method:e,path:r,description:t,endpoint:o,isPositive:n})=>{let i=n?o.getSchema("positive"):o.getSchema("negative"),a=n?o.getMimeTypes("positive"):o.getMimeTypes("negative"),d=Yt(K({schema:i,isResponse:!0,rules:st,onEach:at,onMissing:dt})),l=Vt(i,!0);return{description:`${e.toUpperCase()} ${r} ${t}`,content:a.reduce((c,p)=>({...c,[p]:{schema:d,...l}}),{})}},zo=()=>({type:"http",scheme:"basic"}),jo=({format:e})=>({type:"http",scheme:"bearer",...e&&{bearerFormat:e}}),Lo=({name:e})=>({type:"apiKey",in:"query",name:e}),ko=({name:e})=>({type:"apiKey",in:"header",name:e}),Uo=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ho=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ko=({flows:e={}})=>({type:"oauth2",flows:Object.keys(e).reduce((r,t)=>{let o=e[t];if(!o)return r;let{scopes:n={},...i}=o;return{...r,[t]:{...i,scopes:n}}},{})}),Jt=e=>{let r={basic:zo,bearer:jo,input:Lo,header:ko,cookie:Uo,openid:Ho,oauth2:Ko};return Ae(e,t=>r[t.type](t))},Ue=e=>{if(typeof e=="object"){if("or"in e)return e.or.map(r=>("and"in r?r.and:[r]).reduce((t,{name:o,scopes:n})=>({...t,[o]:n}),{}));if("and"in e)return Ue(Qe(e))}return Ue({or:[e]})},Wt=({method:e,path:r,endpoint:t})=>{let o=Je(r),n=Yt(it(K({schema:t.getSchema("input"),isResponse:!1,rules:st,onEach:at,onMissing:dt}),o)),i=Vt(t.getSchema("input"),!1,o);return{content:t.getMimeTypes("input").reduce((a,d)=>({...a,[d]:{schema:{description:`${e.toUpperCase()} ${r} request body`,...n},...i}}),{})}},Qt=e=>Object.keys(e).map(r=>{let t=e[r];return{name:r,description:typeof t=="string"?t:t.description,...typeof t=="object"&&t.url&&{externalDocs:{url:t.url}}}}),ct=e=>e.length<=_t?e:e.slice(0,_t-1)+"\u2026";var lt=class extends Fo{constructor({routing:t,config:o,title:n,version:i,serverUrl:a,successfulResponseDescription:d="Successful response",errorResponseDescription:l="Error response",hasSummaryFromDescription:c=!0}){super();this.lastSecuritySchemaIds={};this.lastOperationIdSuffixes={};this.addInfo({title:n,version:i}).addServer({url:a}),H({routing:t,onEndpoint:(u,g,y)=>{let h=y,S={path:g,method:h,endpoint:u},[F,_]=["short","long"].map(u.getDescription.bind(u)),xe=o.inputSources?.[h]||be[h],he=Bt({...S,inputSources:xe}),P={operationId:this.ensureUniqOperationId(g,h),responses:{[u.getStatusCode("positive")]:pt({...S,description:d,isPositive:!0}),[u.getStatusCode("negative")]:pt({...S,description:l,isPositive:!1})}};_&&(P.description=_,c&&F===void 0&&(P.summary=ct(_))),F&&(P.summary=ct(F)),u.getTags().length>0&&(P.tags=u.getTags()),he.length>0&&(P.parameters=he),xe.includes("body")&&(P.requestBody=Wt(S));let Te=Ue(Ae(Jt(u.getSecurity()),$e=>{let Zt=this.ensureUniqSecuritySchemaName($e),Sr=["oauth2","openIdConnect"].includes($e.type)?u.getScopes():[];return this.addSecurityScheme(Zt,$e),{name:Zt,scopes:Sr}}));Te.length>0&&(P.security=Te);let Tr=qt(g);this.addPath(Tr,{[h]:P})}}),this.rootDoc.tags=o.tags?Qt(o.tags):[]}ensureUniqOperationId(t,o){let n=se(t,o);return n in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[n]++,`${n}${this.lastOperationIdSuffixes[n]}`):(this.lastOperationIdSuffixes[n]=1,n)}ensureUniqSecuritySchemaName(t){for(let o in this.rootDoc.components?.securitySchemes||{})if(JSON.stringify(t)===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}};import Xt from"http";var _o=e=>({method:"GET",header:jest.fn(()=>j),...e}),$o=e=>{let r={writableEnded:!1,statusCode:200,statusMessage:Xt.STATUS_CODES[200],set:jest.fn(()=>r),status:jest.fn(t=>(r.statusCode=t,r.statusMessage=Xt.STATUS_CODES[t],r)),json:jest.fn(()=>r),end:jest.fn(()=>(r.writableEnded=!0,r)),...e};return r},Go=async({endpoint:e,requestProps:r,responseProps:t,configProps:o,loggerProps:n,__noJest:i})=>{if(!jest||i)throw new Error("You need to install Jest in order to use testEndpoint().");let a=_o(r),d=$o(t),l={info:jest.fn(),warn:jest.fn(),error:jest.fn(),debug:jest.fn(),...n},c={cors:!1,logger:l,...o};return await e.execute({request:a,response:d,config:c,logger:l}),{requestMock:a,responseMock:d,loggerMock:l}};import z from"typescript";import w from"typescript";var s=w.factory,ee=[s.createModifier(w.SyntaxKind.ExportKeyword)],qo=[s.createModifier(w.SyntaxKind.PublicKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],er=[s.createModifier(w.SyntaxKind.ProtectedKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],Vo=s.createTemplateHead(""),Bo=s.createTemplateTail(""),Yo=s.createTemplateMiddle(" "),mt=e=>s.createTemplateLiteralType(Vo,e.map((r,t)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(r),t===e.length-1?Bo:Yo))),ut=mt(["M","P"]),He=(e,r,t)=>s.createParameterDeclaration(t,void 0,e,void 0,r),Ke=(e,r)=>Object.keys(e).reduce((t,o)=>t.concat(He(o,e[o],r)),[]),ft=(e,r)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(r)]),tr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),yt=(e,r)=>s.createPropertySignature(void 0,`"${e}"`,void 0,s.createTypeReferenceNode(r)),rr=(e,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,void 0,r)],w.NodeFlags.Const),gt=(e,r)=>s.createTypeAliasDeclaration(ee,e,void 0,s.createUnionTypeNode(r.map(t=>s.createLiteralTypeNode(s.createStringLiteral(t))))),Fe=(e,r)=>s.createTypeAliasDeclaration(ee,e,void 0,r),or=(e,r,t)=>s.createPropertyDeclaration(qo,e,void 0,r,t),nr=(e,r,t=[])=>s.createClassDeclaration(ee,e,void 0,void 0,[r,...t]),ir=(e,r)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),r)]),sr=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(w.SyntaxKind.AnyKeyword)]),xt=(e,r,t)=>s.createInterfaceDeclaration(ee,e,void 0,r,t),ar=e=>Object.keys(e).reduce((r,t)=>r.concat(s.createTypeParameterDeclaration([],t,s.createTypeReferenceNode(e[t]))),[]),dr=(e,r)=>s.createArrowFunction(void 0,void 0,e.map(t=>He(t)),void 0,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),"implementation"),void 0,r)),ht=(e,r,t)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[s.createIdentifier(e)]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,Ke({acc:void 0,key:void 0}),void 0,void 0,r),t]);import f from"typescript";import{z as Wo}from"zod";import D from"typescript";var{factory:_e}=D,Tt=(e,r)=>{D.addSyntheticLeadingComment(e,D.SyntaxKind.MultiLineCommentTrivia,`* ${r} `,!0)},St=(e,r,t)=>{let o=_e.createTypeAliasDeclaration(void 0,_e.createIdentifier(r),void 0,e);return t&&Tt(o,t),o},pr=(e,r)=>{let t=D.createSourceFile("print.ts","",D.ScriptTarget.Latest,!1,D.ScriptKind.TS);return D.createPrinter(r).printNode(D.EmitHint.Unspecified,e,t)},Jo=/^[A-Za-z_$][A-Za-z0-9_$]*$/,cr=e=>Jo.test(e)?_e.createIdentifier(e):_e.createStringLiteral(e);var{factory:m}=f,Qo={[f.SyntaxKind.AnyKeyword]:"",[f.SyntaxKind.BigIntKeyword]:BigInt(0),[f.SyntaxKind.BooleanKeyword]:!1,[f.SyntaxKind.NumberKeyword]:0,[f.SyntaxKind.ObjectKeyword]:{},[f.SyntaxKind.StringKeyword]:"",[f.SyntaxKind.UndefinedKeyword]:void 0},Xo=({schema:{value:e}})=>m.createLiteralTypeNode(typeof e=="number"?m.createNumericLiteral(e):typeof e=="boolean"?e?m.createTrue():m.createFalse():m.createStringLiteral(e)),en=({schema:{shape:e},isResponse:r,next:t})=>{let o=Object.entries(e).map(([n,i])=>{let a=r&&ie(i)?i instanceof Wo.ZodOptional:i.isOptional(),d=m.createPropertySignature(void 0,cr(n),a?m.createToken(f.SyntaxKind.QuestionToken):void 0,t({schema:i}));return i.description&&Tt(d,i.description),d});return m.createTypeLiteralNode(o)},tn=({schema:{element:e},next:r})=>m.createArrayTypeNode(r({schema:e})),rn=({schema:{options:e}})=>m.createUnionTypeNode(e.map(r=>m.createLiteralTypeNode(m.createStringLiteral(r)))),lr=({schema:{options:e},next:r})=>m.createUnionTypeNode(e.map(t=>r({schema:t}))),on=e=>Qo?.[e.kind],nn=({schema:e,next:r,isResponse:t})=>{let o=r({schema:e.innerType()}),n=e._def.effect;if(t&&n.type==="transform"){let i=Ze({effect:n,sample:on(o)}),a={number:f.SyntaxKind.NumberKeyword,bigint:f.SyntaxKind.BigIntKeyword,boolean:f.SyntaxKind.BooleanKeyword,string:f.SyntaxKind.StringKeyword,undefined:f.SyntaxKind.UndefinedKeyword,object:f.SyntaxKind.ObjectKeyword};return m.createKeywordTypeNode(i&&a[i]||f.SyntaxKind.AnyKeyword)}return o},sn=({schema:e})=>m.createUnionTypeNode(Object.values(e.enum).map(r=>m.createLiteralTypeNode(typeof r=="number"?m.createNumericLiteral(r):m.createStringLiteral(r)))),an=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createKeywordTypeNode(f.SyntaxKind.UndefinedKeyword)]),dn=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createLiteralTypeNode(m.createNull())]),pn=({next:e,schema:{items:r}})=>m.createTupleTypeNode(r.map(t=>e({schema:t}))),cn=({next:e,schema:{keySchema:r,valueSchema:t}})=>m.createExpressionWithTypeArguments(m.createIdentifier("Record"),[e({schema:r}),e({schema:t})]),ln=({next:e,schema:r})=>m.createIntersectionTypeNode([r._def.left,r._def.right].map(t=>e({schema:t}))),mn=({next:e,schema:r})=>e({schema:r._def.innerType}),v=e=>()=>m.createKeywordTypeNode(e),un=({next:e,schema:r})=>e({schema:r.unwrap()}),fn=({next:e,schema:r})=>e({schema:r._def.innerType}),yn=({schema:e,next:r,isResponse:t})=>r({schema:e._def[t?"out":"in"]}),gn=()=>m.createLiteralTypeNode(m.createNull()),xn={ZodString:v(f.SyntaxKind.StringKeyword),ZodNumber:v(f.SyntaxKind.NumberKeyword),ZodBigInt:v(f.SyntaxKind.BigIntKeyword),ZodBoolean:v(f.SyntaxKind.BooleanKeyword),ZodDateIn:v(f.SyntaxKind.StringKeyword),ZodDateOut:v(f.SyntaxKind.StringKeyword),ZodNull:gn,ZodArray:tn,ZodTuple:pn,ZodRecord:cn,ZodObject:en,ZodLiteral:Xo,ZodIntersection:ln,ZodUnion:lr,ZodFile:v(f.SyntaxKind.StringKeyword),ZodAny:v(f.SyntaxKind.AnyKeyword),ZodDefault:mn,ZodEnum:rn,ZodNativeEnum:sn,ZodEffects:nn,ZodOptional:an,ZodNullable:dn,ZodDiscriminatedUnion:lr,ZodBranded:un,ZodCatch:fn,ZodPipeline:yn},Ot=({schema:e,...r})=>K({schema:e,rules:xn,onMissing:()=>m.createKeywordTypeNode(f.SyntaxKind.AnyKeyword),...r});var bt=class{constructor(r){this.agg=[];this.registry={};this.paths=[];H({routing:r,onEndpoint:(y,h,S)=>{let F=se(h,S,"input"),_=se(h,S,"response"),xe=Ot({schema:y.getSchema("input"),isResponse:!1}),he=Ot({isResponse:!0,schema:y.getSchema("positive").or(y.getSchema("negative"))}),P=St(xe,F),Te=St(he,_);this.agg.push(P),this.agg.push(Te),S!=="options"&&(this.paths.push(h),this.registry[`${S} ${h}`]={in:F,out:_,isJson:y.getMimeTypes("positive").includes(j)})}});let t=gt("Path",this.paths),o=gt("Method",jt),n=Fe("MethodPath",mt([o.name,t.name])),i=[s.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[ft(n.name,z.SyntaxKind.AnyKeyword)])],a=xt("Input",i,Object.keys(this.registry).map(y=>yt(y,this.registry[y].in))),d=xt("Response",i,Object.keys(this.registry).map(y=>yt(y,this.registry[y].out))),l=s.createVariableStatement(ee,rr("jsonEndpoints",s.createObjectLiteralExpression(Object.keys(this.registry).filter(y=>this.registry[y].isJson).map(y=>s.createPropertyAssignment(`"${y}"`,s.createTrue()))))),c=Fe("Provider",s.createFunctionTypeNode(ar({M:o.name,P:t.name}),Ke({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(a.name),ut)}),ir(d.name,ut))),p=Fe("Implementation",s.createFunctionTypeNode(void 0,Ke({method:s.createTypeReferenceNode(o.name),path:s.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:ft(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),sr())),u=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(s.createIdentifier("key"),s.createTemplateTail(""))]),g=nr("ExpressZodAPIClient",tr([He("implementation",s.createTypeReferenceNode(p.name),er)]),[or("provide",s.createTypeReferenceNode(c.name),dr(["method","path","params"],[s.createIdentifier("method"),ht("params",s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("acc"),"replace"),void 0,[u,s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key"))]),s.createIdentifier("path")),ht("params",s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("path"),"indexOf"),void 0,[u]),z.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,s.createIdentifier("acc"),void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(s.createIdentifier("acc")),s.createPropertyAssignment("[key]",s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key")))])),s.createObjectLiteralExpression())]))]);z.addSyntheticLeadingComment(g,z.SyntaxKind.MultiLineCommentTrivia,`
34
+ export const exampleImplementation: Implementation = async (
35
+ method,
36
+ path,
37
+ params
38
+ ) => {
39
+ const searchParams =
40
+ method === "get" ? \`?\${new URLSearchParams(params)}\` : "";
41
+ const response = await fetch(\`https://example.com\${path}\${searchParams}\`, {
42
+ method: method.toUpperCase(),
43
+ headers:
44
+ method === "get" ? undefined : { "Content-Type": "application/json" },
45
+ body: method === "get" ? undefined : JSON.stringify(params),
46
+ });
47
+ if (\`\${method} \${path}\` in jsonEndpoints) {
48
+ return response.json();
49
+ }
50
+ return response.text();
51
+ };
52
+
53
+ const client = new ExpressZodAPIClient(exampleImplementation);
54
+ client.provide("get", "/v1/user/retrieve", { id: "10" });
55
+ `,!0),this.agg.push(t,o,n,a,d,l,c,p,g)}print(r){return this.agg.map(t=>pr(t,r)).join(`
56
+
57
+ `)}};import{INVALID as mr,ZodIssueCode as ur,ZodParsedType as fr,ZodType as hn,addIssueToContext as yr}from"zod";var Tn="ZodDateOut",Pt=class extends hn{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);return o.parsedType!==fr.date?(yr(o,{code:ur.invalid_type,expected:fr.date,received:o.parsedType}),mr):Pe(o.data)?{status:t.value,value:o.data.toISOString()}:(yr(o,{code:ur.invalid_date}),mr)}},fe=Pt;fe.create=()=>new Pt({typeName:Tn});import{INVALID as Sn,ZodIssueCode as gr,ZodParsedType as xr,ZodType as On,addIssueToContext as hr}from"zod";var bn="ZodFile",Pn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ge=class extends On{constructor(){super(...arguments);this.binary=t=>new ge({...this._def,checks:[...this._def.checks,{kind:"binary",...We(t)}]});this.base64=t=>new ge({...this._def,checks:[...this._def.checks,{kind:"base64",...We(t)}]})}_parse(t){let{status:o,ctx:n}=this._processInputParams(t);if(n.parsedType!==xr.string)return hr(n,{code:gr.invalid_type,expected:xr.string,received:n.parsedType}),Sn;for(let i of this._def.checks)i.kind==="base64"&&(Pn.test(n.data)||(hr(n,{code:gr.custom,message:i.message}),o.dirty()));return{status:o.value,value:n.data}}get isBinary(){return!!this._def.checks.find(t=>t.kind==="binary")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}},ye=ge;ye.create=()=>new ge({checks:[],typeName:bn});var Et;(n=>(n.file=ye.create,n.upload=L.create,n.dateIn=le.create,n.dateOut=fe.create))(Et||(Et={}));import Ua from"http-errors";export{W as AbstractEndpoint,bt as Client,pe as DependsOnMethod,ae as DependsOnMethodError,de as EndpointsFactory,C as InputValidationError,lt as OpenAPI,b as OpenAPIError,U as OutputValidationError,G as RoutingError,ce as ServeStatic,to as attachRouting,br as createConfig,Ua as createHttpError,Le as createLogger,Xe as createMiddleware,Ct as createResultHandler,ro as createServer,kr as defaultEndpointsFactory,J as defaultResultHandler,Et as ez,k as getMessageFromError,Ye as getStatusCodeFromError,Go as testEndpoint,$ as withMeta};
58
+ //# sourceMappingURL=index.js.map