express-zod-api 10.0.0-beta1 → 10.0.0-beta4

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,8 +2,51 @@
2
2
 
3
3
  ## Version 10
4
4
 
5
+ ### v10.0.0-beta4
6
+
7
+ - No changes.
8
+
9
+ ### v10.0.0-beta3
10
+
11
+ - This release contains features from versions 9.3.0 (incl. hotfix 9.3.1) and 9.4.0.
12
+ - **BREAKING** changes:
13
+ - `Client::constructor()` now requires an object argument having `routing` property.
14
+
15
+ ```ts
16
+ // before
17
+ new Client(routing).print();
18
+ // after
19
+ new Client({ routing }).print();
20
+ ```
21
+
22
+ ### v10.0.0-beta2
23
+
24
+ - **BREAKING** changes to the behavior of a public method.
25
+ - The feature method `withMeta` _(introduced in v2.1.0)_ used to mutate its argument (`zod` schema) in order to
26
+ extend it with additional methods.
27
+ - If you're using this feature _within_ the call of `EndpointsFactory::build()`, there is no issue.
28
+ - However, if you're using a schema assignment (to some const) along with this method, this might lead to unexpected
29
+ results.
30
+ - The following case is reported by [@McMerph](https://github.com/McMerph) in issue #827.
31
+ - Reusing a schema assigned to a const for its several wrappings by `withMeta` and setting different examples.
32
+ - In this case all examples were set to the original const.
33
+ - This release fixes that behavior by making `withMeta` immutable: it returns a new copy of its argument.
34
+
35
+ ```ts
36
+ // the example case
37
+ const originalSchema = z.string();
38
+ const schemaA = withMeta(originalSchema).example("A");
39
+ const schemaB = withMeta(originalSchema).example("B");
40
+ // BEFORE: all three const have both examples "A" and "B"
41
+ // AFTER:
42
+ // - originalSchema remains intact
43
+ // - schemaA has example "A"
44
+ // - schemaB has example "B"
45
+ ```
46
+
5
47
  ### v10.0.0-beta1
6
48
 
49
+ - This release is based on the features of version 9.2.1.
7
50
  - **BREAKING** changes to the concept of dependencies.
8
51
  - `zod` becomes a peer dependency, fixes issue #822.
9
52
  - You need to install it manually and adjust your imports accordingly.
@@ -15,6 +58,7 @@
15
58
  - Proprietary schemas are now exported under the namespace `ez`.
16
59
  - Imports and utilization should be adjusted accordingly.
17
60
  - Affected schemas: `file`, `dateIn`, `dateOut`, `upload`.
61
+ - If facing Typescript errors `TS4023` or `TS4094`, ensure disabling `declaration` option in your `tsconfig.json`.
18
62
  - **BREAKING** changes to the engines.
19
63
  - The minimal Node version is now 14.18.0.
20
64
  - Due to switching to `tsup` builder, the file structure has changed:
@@ -22,8 +66,84 @@
22
66
  - `/dist/esm/index.js` — ESM bundle;
23
67
  - `/dist/index.d.ts` — types declaration bundle.
24
68
 
69
+ ```ts
70
+ // before
71
+ import { z } from "express-zod-api";
72
+ const stringSchema = z.string();
73
+ const uploadSchema = z.upload();
74
+ ```
75
+
76
+ ```ts
77
+ // after
78
+ import { z } from "zod"; // module changed
79
+ import { ez } from "express-zod-api"; // new namespace
80
+ const stringSchema = z.string(); // remains the same
81
+ const uploadSchema = ez.upload(); // namespace changed
82
+ ```
83
+
25
84
  ## Version 9
26
85
 
86
+ ### v9.4.0
87
+
88
+ - Feature #875, proposed by [@VideoSystemsTech](https://github.com/VideoSystemsTech).
89
+ - Ability to document the API specification keeping the schemas organized within named components.
90
+ - `OpenAPI::constructor()` is equipped with a new optional property `composition` that can be:
91
+ - `inline` (default) — schemas are depicted directly in a place of their usage;
92
+ - `components` (feature) — schemas are depicted within the `components` section and have references by their names.
93
+
94
+ ```ts
95
+ // example usage
96
+ new OpenAPI({
97
+ routing,
98
+ config,
99
+ version: "1.2.3",
100
+ title: "My API",
101
+ serverUrl: "https://example.com",
102
+ composition: "components", // <——
103
+ }).getSpecAsYaml();
104
+ ```
105
+
106
+ ### v9.3.1
107
+
108
+ - Hotfix for the feature #856
109
+ - `$ref` is equipped with the required prefix: `#/components/schemas/`.
110
+
111
+ ```yaml
112
+ before:
113
+ $ref: 2048581c137c5b2130eb860e3ae37da196dfc25b
114
+ after:
115
+ $ref: "#/components/schemas/2048581c137c5b2130eb860e3ae37da196dfc25b"
116
+ ```
117
+
118
+ ### v9.3.0
119
+
120
+ - Feature #856, proposed by [@TheWisestOne](https://github.com/TheWisestOne) in discussion #801.
121
+ - Supporting `z.lazy()` in the documentation generator (OpenAPI), including circular schemas.
122
+ - The feature is only available for the OpenAPI generator, it's not available for the client generator yet.
123
+ - OpenAPI references are utilized in order to limit the possible recursion.
124
+ - A new optional property added to the constructor of the OpenAPI class:
125
+ - `serializer` is the function that accepts a schema and returns its unique identifier in order to compare them.
126
+ - When omitted, the default one used, which is `JSON.stringify()` + `SHA1` hash as a `hex` digest.
127
+ - If/when it's not enough precise, consider specifying your own implementation.
128
+
129
+ ```yaml
130
+ # having z.lazy() within your IO schema
131
+ before:
132
+ error: Zod type ZodLazy is unsupported
133
+ after:
134
+ schema:
135
+ type: object
136
+ properties:
137
+ lazyProperty:
138
+ $ref: 2048581c137c5b2130eb860e3ae37da196dfc25b # sample reference
139
+ components:
140
+ schemas:
141
+ 2048581c137c5b2130eb860e3ae37da196dfc25b:
142
+ type: array
143
+ items:
144
+ $ref: 2048581c137c5b2130eb860e3ae37da196dfc25b # circular reference
145
+ ```
146
+
27
147
  ### v9.2.1
28
148
 
29
149
  - `zod` version is 3.21.4.
package/README.md CHANGED
@@ -811,7 +811,11 @@ Consuming the generated client requires Typescript version 4.1 or higher.
811
811
  import fs from "fs";
812
812
  import { Client } from "express-zod-api";
813
813
 
814
- fs.writeFileSync("./frontend/client.ts", new Client(routing).print(), "utf-8");
814
+ fs.writeFileSync(
815
+ "./frontend/client.ts",
816
+ new Client({ routing }).print(),
817
+ "utf-8"
818
+ );
815
819
  ```
816
820
 
817
821
  ```typescript
@@ -847,6 +851,7 @@ const yamlString = new OpenAPI({
847
851
  version: "1.2.3",
848
852
  title: "Example API",
849
853
  serverUrl: "https://example.com",
854
+ composition: "inline", // optional, or "components" for keeping schemas in a separate dedicated section using refs
850
855
  }).getSpecAsYaml();
851
856
  ```
852
857
 
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.
package/dist/esm/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var br=(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)=>(br(e,r,"access private method"),t);var Rt={silent:!0,warn:!0,debug:!0},Pr=e=>e;import{z as N}from"zod";import{HttpError as Dr}from"http-errors";import{z as S}from"zod";import{mergeDeepRight as At}from"ramda";var x="expressZodApiMeta",ee=e=>{let r=e._def;return r[x]=r[x]||{examples:[]},"example"in e||Object.defineProperties(e,{example:{get:()=>t=>(r[x].examples.push(t),e)}}),e},It=e=>x in e._def?typeof e._def[x]=="object"&&e._def[x]!==null:!1;function Oe(e,r){if(!It(e))return;let t=e._def;return r in t[x]?t[x][r]:void 0}var te=(e,r)=>{if(!It(e))return r;r=ee(r);let t=r._def,o=re(t[x].examples,e._def[x].examples);if(t[x]=At({...t[x],examples:[]},{...e._def[x],examples:[]}),o.type==="single")t[x].examples=o.value;else for(let[n,i]of o.value)t[x].examples.push(At({...n},{...i}));return r};import Er from"mime";var j=Er.getType("json")||"application/json",oe="multipart/form-data";import{INVALID as Zr,OK as Rr,ZodIssueCode as Ar,ZodParsedType as Ir,ZodType as Cr,addIssueToContext as Mr}from"zod";var Nr="ZodUpload",wr=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 Cr{_parse(r){let{ctx:t}=this._processInputParams(r);return t.parsedType!==Ir.object||!wr(t.data)?(Mr(t,{code:Ar.custom,message:`Expected file upload, received ${t.parsedType}`}),Zr):Rr(t.data)}},L=Ge;L.create=()=>new Ge({typeName:Nr});var qe=/:([A-Za-z0-9_]+)/g;function vr(e){let t=(e.header("content-type")||"").slice(0,oe.length).toLowerCase()===oe;return"files"in e&&t}var be={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},zr=["body","query","params"],Ve=e=>e.method.toLowerCase();function Ct(e,r){let t=Ve(e);if(t==="options")return{};let o=zr;return t in be&&(o=be[t]),r&&t in r&&(o=r[t]||o),o.filter(n=>n==="files"?vr(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 ie(e){return e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`)}function k(e){return e instanceof S.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 Dr?e.statusCode:e instanceof C?400:500}var Ee=(e,r)=>{let t=Oe(e,"examples");return t===void 0?[]:t.reduce((o,n)=>{let i=e.safeParse(n);return o.concat(i.success?r?i.data:n:[])},[])},re=(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 ne=e=>e.reduce((r,t)=>r||t,!1);function I(e){return e instanceof S.ZodEffects&&e._def.effect.type!=="refinement"?!0:e instanceof S.ZodUnion?ne(e.options.map(I)):e instanceof S.ZodIntersection?ne([e._def.left,e._def.right].map(I)):!1}function Z(e){return e instanceof L?!0:e instanceof S.ZodObject?ne(Object.values(e.shape).map(Z)):e instanceof S.ZodUnion?ne(e.options.map(Z)):e instanceof S.ZodIntersection?ne([e._def.left,e._def.right].map(Z)):e instanceof S.ZodOptional||e instanceof S.ZodNullable?Z(e.unwrap()):e instanceof S.ZodEffects||e instanceof S.ZodTransformer?Z(e._def.schema):e instanceof S.ZodRecord?Z(e._def.valueType):e instanceof S.ZodArray?Z(e._def.type):e instanceof S.ZodDefault?Z(e._def.innerType):!1}var se=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,ae=(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 $=class extends Error{constructor(){super(...arguments);this.name="RoutingError"}},pe=class extends ${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}},G=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=re(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:[]}),q=(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 q(Qe(e),r)}return Re([e,r])}if("or"in e){if(R(r)){if("and"in r)return q(r,e);if("or"in r){let t=re(e.or,r.or);return{or:t.type==="single"?t.value:t.value.map(Re)}}}return q(e,{and:[r]})}}return R(r)&&("and"in r||"or"in r)?q(r,e):{and:[e,r]}};import{z as V}from"zod";var B={positive:200,negative:400},Mt=e=>e,Y=Mt({getPositiveResponse:e=>{let r=Oe(e,"examples")||[],t=ee(V.object({status:V.literal("success"),data:e}));for(let o of r)t.example({status:"success",data:o});return t},getNegativeResponse:()=>ee(V.object({status:V.literal("error"),error:V.object({message:V.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(B.positive).json({status:"success",data:t});return}let a=Ye(e);a===500&&i.error(`Internal server error
1
+ var Zr=(e,r,t)=>{if(!r.has(e))throw TypeError("Cannot "+t)};var M=(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 R=(e,r,t)=>(Zr(e,r,"access private method"),t);var Ct={silent:!0,warn:!0,debug:!0},Er=e=>e;import{z as v}from"zod";import{HttpError as Ur}from"http-errors";import{z as S}from"zod";import{clone as Ar,mergeDeepRight as Ir}from"ramda";var O="expressZodApiMeta",Cr=e=>{let r=e.constructor,t=Ar(e._def);return t[O]=t[O]||{examples:[]},new r(t)},G=e=>{let r=Cr(e);return Object.defineProperties(r,{example:{get:()=>t=>{let o=G(r);return o._def[O].examples.push(t),o}}}),r},Mt=e=>O in e._def?typeof e._def[O]=="object"&&e._def[O]!==null:!1;function Oe(e,r){if(!Mt(e))return;let t=e._def;return r in t[O]?t[O][r]:void 0}var be=(e,r)=>{if(!Mt(e))return r;let t=G(r),o=ne(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,s]of o.value)t._def[O].examples.push(Ir({...n},{...s}));return t};import Mr from"mime";var U=Mr.getType("json")||"application/json",se="multipart/form-data";import{INVALID as Nr,OK as wr,ZodIssueCode as Dr,ZodParsedType as vr,ZodType as zr,addIssueToContext as jr}from"zod";var Lr="ZodUpload",kr=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",Ve=class extends zr{_parse(r){let{ctx:t}=this._processInputParams(r);return t.parsedType!==vr.object||!kr(t.data)?(jr(t,{code:Dr.custom,message:`Expected file upload, received ${t.parsedType}`}),Nr):wr(t.data)}},H=Ve;H.create=()=>new Ve({typeName:Lr});var Be=/:([A-Za-z0-9_]+)/g;function Hr(e){let t=(e.header("content-type")||"").slice(0,se.length).toLowerCase()===se;return"files"in e&&t}var Pe={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Kr=["body","query","params"],Ye=e=>e.method.toLowerCase();function Nt(e,r){let t=Ye(e);if(t==="options")return{};let o=Kr;return t in Pe&&(o=Pe[t]),r&&t in r&&(o=r[t]||o),o.filter(n=>n==="files"?Hr(e):!0).reduce((n,s)=>({...n,...e[s]}),{})}function Je(e){return typeof e=="object"&&"level"in e&&"color"in e&&Object.keys(Ct).includes(e.level)&&typeof e.color=="boolean"}function Re(e){return!isNaN(e.getTime())}function ae(e){return e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`)}function K(e){return e instanceof S.ZodError?e.issues.map(({path:r,message:t})=>(r.length?[r.join("/")]:[]).concat(t).join(": ")).join("; "):e instanceof F?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message}function We(e){return e instanceof Ur?e.statusCode:e instanceof w?400:500}var Ze=(e,r)=>{let t=Oe(e,"examples");return t===void 0?[]:t.reduce((o,n)=>{let s=e.safeParse(n);return o.concat(s.success?r?s.data:n:[])},[])},ne=(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 Qe(e){let r=e.match(Be);return r?r.map(t=>t.slice(1)):[]}var ie=e=>e.reduce((r,t)=>r||t,!1);function N(e){return e instanceof S.ZodEffects&&e._def.effect.type!=="refinement"?!0:e instanceof S.ZodUnion?ie(e.options.map(N)):e instanceof S.ZodIntersection?ie([e._def.left,e._def.right].map(N)):!1}function Z(e){return e instanceof H?!0:e instanceof S.ZodObject?ie(Object.values(e.shape).map(Z)):e instanceof S.ZodUnion?ie(e.options.map(Z)):e instanceof S.ZodIntersection?ie([e._def.left,e._def.right].map(Z)):e instanceof S.ZodOptional||e instanceof S.ZodNullable?Z(e.unwrap()):e instanceof S.ZodEffects||e instanceof S.ZodTransformer?Z(e._def.schema):e instanceof S.ZodRecord?Z(e._def.valueType):e instanceof S.ZodArray?Z(e._def.type):e instanceof S.ZodDefault?Z(e._def.innerType):!1}var pe=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,A=(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(""),Ee=({effect:e,sample:r})=>{try{return typeof e.transform(r,{addIssue:()=>{},path:[]})}catch{return}},Xe=e=>typeof e=="string"?{message:e}:e||{};var q=class extends Error{constructor(){super(...arguments);this.name="RoutingError"}},de=class extends q{constructor(){super(...arguments);this.name="DependsOnMethodError"}},P=class extends Error{constructor(){super(...arguments);this.name="OpenAPIError"}},D=class extends Error{constructor(){super(...arguments);this.name="IOSchemaError"}},F=class extends D{constructor(t){super(K(t));this.name="OutputValidationError";this.originalError=t}},w=class extends D{constructor(t){super(K(t));this.name="InputValidationError";this.originalError=t}},V=class extends Error{constructor(t,o){super(t);this.name="ResultHandlerError";this.originalError=o||void 0}};var I=e=>typeof e=="object"&&e!==null,Ae=e=>({and:e.reduce((r,t)=>r.concat(I(t)&&"and"in t?t.and:t),[])}),Ie=(e,r)=>{if(I(e)){if("and"in e)return{and:e.and.map(t=>I(t)&&"or"in t?{or:t.or.map(r)}:r(t))};if("or"in e)return{or:e.or.map(t=>I(t)&&"and"in t?{and:t.and.map(r)}:r(t))}}return r(e)},et=e=>e.and.reduce((r,t)=>{let o=ne(r.or,I(t)&&"or"in t?t.or:[t]);return o.type==="single"?r.or.push(...o.value):r.or=o.value.map(Ae),r},{or:[]}),B=(e,r)=>{if(I(e)){if("and"in e){if(I(r)){if("and"in r)return Ae([e,r]);if("or"in r)return B(et(e),r)}return Ae([e,r])}if("or"in e){if(I(r)){if("and"in r)return B(r,e);if("or"in r){let t=ne(e.or,r.or);return{or:t.type==="single"?t.value:t.value.map(Ae)}}}return B(e,{and:[r]})}}return I(r)&&("and"in r||"or"in r)?B(r,e):{and:[e,r]}};import{z as Y}from"zod";var J={positive:200,negative:400},wt=e=>e,W=wt({getPositiveResponse:e=>{let r=Oe(e,"examples")||[],t=G(Y.object({status:Y.literal("success"),data:e}));return r.reduce((o,n)=>o.example({status:"success",data:n}),t)},getNegativeResponse:()=>G(Y.object({status:Y.literal("error"),error:Y.object({message:Y.string()})})).example({status:"error",error:{message:K(new Error("Sample error message"))}}),handler:({error:e,input:r,output:t,request:o,response:n,logger:s})=>{if(!e){n.status(J.positive).json({status:"success",data:t});return}let a=We(e);a===500&&s.error(`Internal server error
2
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 Nt=(e,r=[j])=>{if(e instanceof N.ZodType)return r;let{mimeTypes:t,mimeType:o}=e;return o?[o]:t||r},J=class{},Me,wt,Ne,Dt,we,vt,De,zt,ve,jt,Ce=class extends J{constructor({middlewares:t,inputSchema:o,outputSchema:n,handler:i,resultHandler:a,description:p,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 d={positive:a.getPositiveResponse(n),negative:a.getNegativeResponse()};this.mimeTypes={input:Z(o)?[oe]:[j],positive:Nt(d.positive),negative:Nt(d.negative)},this.schemas={input:o,output:n,positive:d.positive instanceof N.ZodType?d.positive:d.positive.schema,negative:d.negative instanceof N.ZodType?d.negative:d.negative.schema},this.statusCodes={positive:d.positive instanceof N.ZodType?B.positive:d.positive.statusCode||B.positive,negative:d.negative instanceof N.ZodType?B.negative:d.negative.statusCode||B.negative},this.handler=i,this.resultHandler=a,this.descriptions={long:p,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?q(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),p,l=null;if(i.cors){let d=E(this,Me,wt).call(this);typeof i.cors=="function"&&(d=await i.cors({request:t,logger:n,endpoint:this,defaultHeaders:d}));for(let u in d)o.set(u,d[u])}let c=Ct(t,i.inputSources);try{let{options:d,isStreamClosed:u}=await E(this,we,vt).call(this,{method:a,input:c,request:t,response:o,logger:n});if(u)return;if(a==="options"){o.status(200).end();return}p=await E(this,Ne,Dt).call(this,await E(this,De,zt).call(this,{input:c,options:d,logger:n}))}catch(d){l=ie(d)}await E(this,ve,jt).call(this,{input:c,output:p,request:t,response:o,error:l,logger:n})}};Me=new WeakSet,wt=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,Dt=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,vt=async function({method:t,input:o,request:n,response:i,logger:a}){let p={},l=!1;for(let c of this.middlewares){if(t==="options"&&c.type==="proprietary")continue;let d;try{d=await c.input.parseAsync(o)}catch(u){throw u instanceof N.ZodError?new C(u):u}if(Object.assign(p,await c.middleware({input:d,options:p,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:`,p);break}}return{options:p,isStreamClosed:l}},De=new WeakSet,zt=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,jt=async function({error:t,request:o,response:n,logger:i,input:a,output:p}){try{await this.resultHandler.handler({error:t,output:p,request:o,response:n,logger:i,input:a})}catch(l){Ie({logger:i,response:n,error:new G(ie(l).message,t)})}};var Lt=["get","post","put","delete","patch"];import{z as Ut}from"zod";var kt=(e,r)=>{let t=e.map(({input:o})=>o).concat(r).reduce((o,n)=>o.and(n));for(let o of e)te(o.input,t);return te(r,t),t};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 Q,ze,W=class{constructor(r){this.middlewares=[];this.use=this.addExpressMiddleware;this.resultHandler="resultHandler"in r?r.resultHandler:r}addMiddleware(r){var t;return E(t=W,Q,ze).call(t,this.middlewares.concat(r),this.resultHandler)}addExpressMiddleware(r,t){var a;let o=t?.transformer||(p=>p),n=t?.provider||(()=>({})),i={type:"express",input:Ut.object({}),middleware:async({request:p,response:l})=>new Promise((c,d)=>{r(p,l,g=>{if(g&&g instanceof Error)return d(o(g));c(n(p,l))})})};return E(a=W,Q,ze).call(a,this.middlewares.concat(i),this.resultHandler)}addOptions(r){var t;return E(t=W,Q,ze).call(t,this.middlewares.concat(Xe({input:Ut.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:kt(i,r),...n})}},de=W;Q=new WeakSet,ze=function(r,t){let o=new W(t);return o.middlewares=r,o},A(de,Q);var jr=new de(Y);import{inspect as Lr}from"util";import{LEVEL as kr,MESSAGE as Ur,SPLAT as Hr}from"triple-beam";import je from"winston";var{combine:Kr,colorize:Fr,timestamp:_r,printf:$r}=je.format;function Le(e){let r=i=>{let{[kr]:a,[Ur]:p,[Hr]:l,...c}=i;return Lr(c,!1,1,e.color)},t=i=>$r(({timestamp:a,message:p,level:l,durationMs:c,...d})=>(typeof p=="object"&&(d={...d,...p},p="[No message]"),`${a} ${l}: ${p}`+(c===void 0?"":` duration: ${c}ms`)+(Object.keys(d).length===0?"":" "+(i?r(d):JSON.stringify(d))))),o=[_r()],n={handleExceptions:!0};switch(e.color&&o.push(Fr()),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=Kr(...o),je.createLogger({silent:e.level==="silent",levels:je.config.npm.levels,transports:[new je.transports.Console(n)],exitOnError:!1})}var ce=class{constructor(r){this.methods=r;Object.keys(r).forEach(t=>{if(t in r&&!(r[t]?.getMethods()||[]).includes(t))throw new pe(`The endpoint assigned to the '${t}' parameter must have at least this method in its specification.
3
+ `,{url:o.url,payload:r}),n.status(a).json({status:"error",error:{message:K(e)}})}}),Ce=({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 Dt=(e,r=[U])=>{if(e instanceof v.ZodType)return r;let{mimeTypes:t,mimeType:o}=e;return o?[o]:t||r},Q=class{},Ne,vt,we,zt,De,jt,ve,Lt,ze,kt,Me=class extends Q{constructor({middlewares:t,inputSchema:o,outputSchema:n,handler:s,resultHandler:a,description:p,shortDescription:l,...d}){super();M(this,Ne);M(this,we);M(this,De);M(this,ve);M(this,ze);this.methods=[];this.siblingMethods=[];this.middlewares=[];this.scopes=[];this.tags=[];[{name:"input schema",schema:o},{name:"output schema",schema:n}].forEach(({name:f,schema:h})=>{if(N(h))throw new D(`Using transformations on the top level of endpoint ${f} is not allowed.`)}),this.middlewares=t;let c={positive:a.getPositiveResponse(n),negative:a.getNegativeResponse()};this.mimeTypes={input:Z(o)?[se]:[U],positive:Dt(c.positive),negative:Dt(c.negative)},this.schemas={input:o,output:n,positive:c.positive instanceof v.ZodType?c.positive:c.positive.schema,negative:c.negative instanceof v.ZodType?c.negative:c.negative.schema},this.statusCodes={positive:c.positive instanceof v.ZodType?J.positive:c.positive.statusCode||J.positive,negative:c.negative instanceof v.ZodType?J.negative:c.negative.statusCode||J.negative},this.handler=s,this.resultHandler=a,this.descriptions={long:p,short:l},"scopes"in d&&d.scopes&&this.scopes.push(...d.scopes),"scope"in d&&d.scope&&this.scopes.push(d.scope),"tags"in d&&d.tags&&this.tags.push(...d.tags),"tag"in d&&d.tag&&this.tags.push(d.tag),"methods"in d?this.methods=d.methods:this.methods=[d.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?B(t,o.security):t,{and:[]})}getScopes(){return this.scopes}getTags(){return this.tags}async execute({request:t,response:o,logger:n,config:s}){let a=Ye(t),p,l=null;if(s.cors){let c=R(this,Ne,vt).call(this);typeof s.cors=="function"&&(c=await s.cors({request:t,logger:n,endpoint:this,defaultHeaders:c}));for(let f in c)o.set(f,c[f])}let d=Nt(t,s.inputSources);try{let{options:c,isStreamClosed:f}=await R(this,De,jt).call(this,{method:a,input:d,request:t,response:o,logger:n});if(f)return;if(a==="options"){o.status(200).end();return}p=await R(this,we,zt).call(this,await R(this,ve,Lt).call(this,{input:d,options:c,logger:n}))}catch(c){l=ae(c)}await R(this,ze,kt).call(this,{input:d,output:p,request:t,response:o,error:l,logger:n})}};Ne=new WeakSet,vt=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"}},we=new WeakSet,zt=async function(t){try{return await this.schemas.output.parseAsync(t)}catch(o){throw o instanceof v.ZodError?new F(o):o}},De=new WeakSet,jt=async function({method:t,input:o,request:n,response:s,logger:a}){let p={},l=!1;for(let d of this.middlewares){if(t==="options"&&d.type==="proprietary")continue;let c;try{c=await d.input.parseAsync(o)}catch(f){throw f instanceof v.ZodError?new w(f):f}if(Object.assign(p,await d.middleware({input:c,options:p,request:n,response:s,logger:a})),l="writableEnded"in s&&s.writableEnded,l){a.warn(`The middleware ${d.middleware.name} has closed the stream. Accumulated options:`,p);break}}return{options:p,isStreamClosed:l}},ve=new WeakSet,Lt=async function({input:t,options:o,logger:n}){let s;try{s=await this.schemas.input.parseAsync(t)}catch(a){throw a instanceof v.ZodError?new w(a):a}return this.handler({input:s,options:o,logger:n})},ze=new WeakSet,kt=async function({error:t,request:o,response:n,logger:s,input:a,output:p}){try{await this.resultHandler.handler({error:t,output:p,request:o,response:n,logger:s,input:a})}catch(l){Ce({logger:s,response:n,error:new V(ae(l).message,t)})}};var Ut=["get","post","put","delete","patch"];import{z as Kt}from"zod";var Ht=(e,r)=>{let t=e.map(({input:n})=>n).concat(r),o=t.reduce((n,s)=>n.and(s));return t.reduce((n,s)=>be(s,n),o)};var tt=e=>{if(N(e.input))throw new D("Using transformations on the top level of middleware input schema is not allowed.");return{...e,type:"proprietary"}};var ee,je,X=class{constructor(r){this.middlewares=[];this.use=this.addExpressMiddleware;this.resultHandler="resultHandler"in r?r.resultHandler:r}addMiddleware(r){var t;return R(t=X,ee,je).call(t,this.middlewares.concat(r),this.resultHandler)}addExpressMiddleware(r,t){var a;let o=t?.transformer||(p=>p),n=t?.provider||(()=>({})),s={type:"express",input:Kt.object({}),middleware:async({request:p,response:l})=>new Promise((d,c)=>{r(p,l,h=>{if(h&&h instanceof Error)return c(o(h));d(n(p,l))})})};return R(a=X,ee,je).call(a,this.middlewares.concat(s),this.resultHandler)}addOptions(r){var t;return R(t=X,ee,je).call(t,this.middlewares.concat(tt({input:Kt.object({}),middleware:async()=>r})),this.resultHandler)}build({input:r,handler:t,output:o,...n}){let{middlewares:s,resultHandler:a}=this;return new Me({handler:t,middlewares:s,outputSchema:o,resultHandler:a,inputSchema:Ht(s,r),...n})}},ce=X;ee=new WeakSet,je=function(r,t){let o=new X(t);return o.middlewares=r,o},M(ce,ee);var Fr=new ce(W);import{inspect as $r}from"util";import{LEVEL as _r,MESSAGE as Gr,SPLAT as qr}from"triple-beam";import Le from"winston";var{combine:Vr,colorize:Br,timestamp:Yr,printf:Jr}=Le.format;function ke(e){let r=s=>{let{[_r]:a,[Gr]:p,[qr]:l,...d}=s;return $r(d,!1,1,e.color)},t=s=>Jr(({timestamp:a,message:p,level:l,durationMs:d,...c})=>(typeof p=="object"&&(c={...c,...p},p="[No message]"),`${a} ${l}: ${p}`+(d===void 0?"":` duration: ${d}ms`)+(Object.keys(c).length===0?"":" "+(s?r(c):JSON.stringify(c))))),o=[Yr()],n={handleExceptions:!0};switch(e.color&&o.push(Br()),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=Vr(...o),Le.createLogger({silent:e.level==="silent",levels:Le.config.npm.levels,transports:[new Le.transports.Console(n)],exitOnError:!1})}var le=class{constructor(r){this.methods=r;Object.keys(r).forEach(t=>{if(t in r&&!(r[t]?.getMethods()||[]).includes(t))throw new de(`The endpoint assigned to the '${t}' parameter must have at least this method in its specification.
5
5
  This error should prevent mistakes during the development process.
6
6
  Example:
7
7
 
@@ -12,8 +12,8 @@ new ${this.constructor.name}({
12
12
  ...
13
13
  })
14
14
  });
15
- `)})}};import Gr from"express";var le=class{constructor(...r){this.params=r}apply(r,t){return t(r,Gr.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 $(`Routing elements should not contain '/' character.
16
- The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let p=`${o||""}${i?`/${i}`:""}`;if(a instanceof J){let l=a.getMethods().slice();n&&l.push("options"),l.forEach(c=>{r(a,p,c)})}else if(a instanceof le)t&&a.apply(p,t);else if(a instanceof ce){if(Object.entries(a.methods).forEach(([l,c])=>{r(c,p,l)}),n&&Object.keys(a.methods).length>0){let[l,...c]=Object.keys(a.methods),d=a.methods[l];d._setSiblingMethods(c),r(d,p,"options")}}else H({onEndpoint:r,onStatic:t,hasCors:n,routing:a,parentPath:p})})};var Ht=()=>`
15
+ `)})}};import Wr from"express";var me=class{constructor(...r){this.params=r}apply(r,t){return t(r,Wr.static(...this.params))}};var $=({routing:e,onEndpoint:r,onStatic:t,parentPath:o,hasCors:n})=>{Object.entries(e).forEach(([s,a])=>{if(s=s.trim(),s.match(/\//))throw new q(`Routing elements should not contain '/' character.
16
+ The error caused by ${o?`'${o}' route that has a '${s}'`:`'${s}'`} entry.`);let p=`${o||""}${s?`/${s}`:""}`;if(a instanceof Q){let l=a.getMethods().slice();n&&l.push("options"),l.forEach(d=>{r(a,p,d)})}else if(a instanceof me)t&&a.apply(p,t);else if(a instanceof le){if(Object.entries(a.methods).forEach(([l,d])=>{r(d,p,l)}),n&&Object.keys(a.methods).length>0){let[l,...d]=Object.keys(a.methods),c=a.methods[l];c._setSiblingMethods(d),r(c,p,"options")}}else $({onEndpoint:r,onStatic:t,hasCors:n,routing:a,parentPath:p})})};var Ft=()=>`
17
17
  \x1B[94m\x1B[39m
18
18
  \x1B[94m\x1B[39m
19
19
  \x1B[94m8888888888 8888888888P 888 d8888 8888888b. 8888888 \x1B[39m
@@ -26,11 +26,11 @@ The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let
26
26
  \x1B[95m8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P' d8888888888 "Y88P" "Y88888 d88P 888 888 8888888\x1B[39m\x1B[94m\x1B[39m
27
27
  \x1B[94m 888\x1B[39m
28
28
  \x1B[94m 888\x1B[3m Proudly supports transgender community.\x1B[23m\x1B[39m
29
- \x1B[94m\x1B[3mfor Brianna \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
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
30
  \x1B[90m\x1B[3m Thank you for choosing Express Zod API for your project.\x1B[23m\x1B[39m\x1B[0m\x1B[0m
31
31
  \x1B[0m\x1B[0m
32
32
  \x1B[0m\x1B[0m
33
- `.trim();var et=({app:e,logger:r,config:t,routing:o})=>{t.startupLogo!==!1&&console.log(Ht()),H({routing:o,hasCors:!!t.cors,onEndpoint:(n,i,a)=>{e[a](i,async(p,l)=>{r.info(`${p.method}: ${i}`),await n.execute({request:p,response:l,logger:r,config:t})})},onStatic:(n,i)=>{e.use(n,i)}})};import qr,{json as Vr}from"express";import Br from"compression";import Yr from"express-fileupload";import Jr from"https";import Wr from"http-errors";var Qr=(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})},Kt=(e,r)=>(t,o)=>{let n=Wr(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 G(ie(i).message,n)})}};function Xr(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||Y;return{notFoundHandler:Kt(o,t),logger:t}}function eo(e,r){let t=Be(e.logger)?Le(e.logger):e.logger,o=qr();o.disable("x-powered-by");let n=e.errorHandler||Y,i=e.server.compression?Br({...typeof e.server.compression=="object"?e.server.compression:{}}):void 0,a=e.server.jsonParser||Vr(),p=e.server.upload?Yr({...typeof e.server.upload=="object"?e.server.upload:{},abortOnLimit:!1,parseNested:!0}):void 0,l=[].concat(i||[]).concat(a).concat(p||[]);o.use(l),o.use(Qr(n,t)),et({app:o,routing:r,logger:t,config:e}),o.use(Kt(n,t));let c=o.listen(e.server.listen,()=>{t.info(`Listening ${e.server.listen}`)}),d;return e.https&&(d=Jr.createServer(e.https.options,o).listen(e.https.listen,()=>{t.info(`Listening ${e.https.listen}`)})),{app:o,httpServer:c,httpsServer:d,logger:t}}import{OpenApiBuilder as Ho}from"openapi3-ts";import{omit as fe}from"ramda";import{z as h}from"zod";import{INVALID as Ft,ZodIssueCode as tt,ZodParsedType as _t,ZodType as to,addIssueToContext as rt}from"zod";var ot=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/,ro="ZodDateIn",nt=class extends to{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);if(o.parsedType!==_t.string)return rt(o,{code:tt.invalid_type,expected:_t.string,received:o.parsedType}),Ft;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}),Ft)}},me=nt;me.create=()=>new nt({typeName:ro});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,qt="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",oo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vt=e=>e.replace(qe,r=>`{${r.slice(1)}}`),no=({schema:{_def:{innerType:e,defaultValue:r}},next:t})=>({...t({schema:e}),default:r()}),io=({schema:{_def:{innerType:e}},next:r})=>r({schema:e}),so=()=>({format:"any"}),ao=({isResponse:e})=>{if(e)throw new b("Please use z.upload() only for input.");return{type:"string",format:"binary"}},po=({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"}},co=({schema:{options:e},next:r})=>({oneOf:e.map(t=>r({schema:t}))}),lo=({schema:{options:e,discriminator:r},next:t})=>({discriminator:{propertyName:r},oneOf:Array.from(e.values()).map(o=>t({schema:o}))}),mo=({schema:{_def:{left:e,right:r}},next:t})=>({allOf:[e,r].map(o=>t({schema:o}))}),uo=({schema:e,next:r})=>r({schema:e.unwrap()}),fo=({schema:e,next:r})=>({nullable:!0,...r({schema:e.unwrap()})}),Gt=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),yo=({schema:{value:e}})=>({type:typeof e,enum:[e]}),go=({schema:e,isResponse:r,next:t})=>{let o=Object.keys(e.shape).filter(n=>{let i=e.shape[n];return!(r&&se(i)?i instanceof h.ZodOptional:i.isOptional())});return{type:"object",properties:ke({schema:e,isResponse:r,next:t}),...o.length?{required:o}:{}}},xo=()=>({type:"string",nullable:!0,format:"null"}),ho=({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:qt}}},To=({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:qt}}},So=({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.`)},Oo=()=>({type:"boolean"}),bo=()=>({type:"integer",format:"bigint"}),Po=({schema:{keySchema:e,valueSchema:r},isResponse:t,next:o})=>{if(e instanceof h.ZodEnum||e instanceof h.ZodNativeEnum){let n=Object.values(e.enum),i=n.reduce((a,p)=>({...a,[p]:r}),{});return{type:"object",properties:ke({schema:h.object(i),isResponse:t,next:o}),...n.length?{required:n}:{}}}if(e instanceof h.ZodLiteral)return{type:"object",properties:ke({schema:h.object({[e.value]:r}),isResponse:t,next:o}),required:[e.value]};if(e instanceof h.ZodUnion&&e.options.reduce((i,a)=>i&&a instanceof h.ZodLiteral,!0)){let i=e.options.reduce((a,p)=>({...a,[p.value]:r}),{});return{type:"object",properties:ke({schema:h.object(i),isResponse:t,next:o}),required:e.options.map(a=>a.value)}}return{type:"object",additionalProperties:o({schema:r})}},Eo=({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}}),Zo=({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(", ")}}}},Ro=({schema:{isEmail:e,isURL:r,minLength:t,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:d,_def:{checks:u}}})=>{let g=u.find(O=>O.kind==="regex"),y=u.find(O=>O.kind==="datetime"),T=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",...d&&{format:"date-time"},...e&&{format:"email"},...r&&{format:"url"},...n&&{format:"uuid"},...i&&{format:"cuid"},...a&&{format:"cuid2"},...p&&{format:"ulid"},...l&&{format:"ip"},...c&&{format:"emoji"},...t!==null&&{minLength:t},...o!==null&&{maxLength:o},...T&&{pattern:`/${T.source}/${T.flags}`}}},Ao=({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]})}),{}),Io=e=>{let r=Array.isArray(e.type)?e.type[0]:e.type;return oo?.[r]},Co=({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:Io(o)});return i&&["number","string","boolean"].includes(i)?{type:i}:t({schema:h.any()})}if(!r&&n.type==="preprocess"){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Mo=({schema:e,isResponse:r,next:t})=>t({schema:e._def[r?"out":"in"]}),No=({schema:e,next:r})=>r({schema:e.unwrap()}),Bt=(e,r,t=[])=>{let o=Ee(e,r);return o.length===0?{}:{examples:o.reduce((n,i,a)=>({...n,[`example${a+1}`]:{value:fe(t,i)}}),{})}},wo=(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 ue(e){if(e instanceof h.ZodObject)return e;let r;if(e instanceof h.ZodUnion||e instanceof h.ZodDiscriminatedUnion)r=Array.from(e.options.values()).map(t=>ue(t)).reduce((t,o)=>t.merge(o.partial()),h.object({}));else if(e instanceof h.ZodEffects){if(I(e))throw new b("Using transformations on the top level of input schema is not allowed.");r=ue(e._def.schema)}else r=ue(e._def.left).merge(ue(e._def.right));return te(e,r)}var Yt=({path:e,method:r,endpoint:t,inputSources:o})=>{let n=t.getSchema("input"),i=ue(n).shape,a=Je(e),p=o.includes("query"),l=o.includes("params"),c=d=>l&&a.includes(d);return Object.keys(i).filter(d=>p||c(d)).map(d=>({name:d,in:c(d)?"path":"query",required:!i[d].isOptional(),schema:{description:`${r.toUpperCase()} ${e} parameter`,...K({schema:i[d],isResponse:!1,rules:st,onEach:at,onMissing:pt})},...wo(n,!1,d)}))},st={ZodString:Ro,ZodNumber:Ao,ZodBigInt:bo,ZodBoolean:Oo,ZodDateIn:ho,ZodDateOut:To,ZodNull:xo,ZodArray:Eo,ZodTuple:Zo,ZodRecord:Po,ZodObject:go,ZodLiteral:yo,ZodIntersection:mo,ZodUnion:co,ZodFile:po,ZodUpload:ao,ZodAny:so,ZodDefault:no,ZodEnum:Gt,ZodNativeEnum:Gt,ZodEffects:Co,ZodOptional:uo,ZodNullable:fo,ZodDiscriminatedUnion:lo,ZodBranded:No,ZodDate:So,ZodCatch:io,ZodPipeline:Mo},at=({schema:e,isResponse:r})=>{let{description:t}=e,o=Ee(e,r);return{...t&&{description:t},...e.isNullable()&&!(r&&se(e))&&{nullable:!0},...o.length>0&&{example:o[0]}}},pt=e=>{throw new b(`Zod type ${e.constructor.name} is unsupported`)},it=(e,r)=>{let t=e.properties?fe(r,e.properties):void 0,o=e.example?fe(r,e.example):void 0,n=e.required?e.required.filter(p=>!r.includes(p)):void 0,i=e.allOf?e.allOf.map(p=>it(p,r)):void 0,a=e.oneOf?e.oneOf.map(p=>it(p,r)):void 0;return fe(Object.entries({properties:t,required:n,example:o,allOf:i,oneOf:a}).filter(([{},p])=>p===void 0).map(([p])=>p),{...e,properties:t,required:n,example:o,allOf:i,oneOf:a})},Jt=e=>fe(["example"],e),dt=({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"),p=Jt(K({schema:i,isResponse:!0,rules:st,onEach:at,onMissing:pt})),l=Bt(i,!0);return{description:`${e.toUpperCase()} ${r} ${t}`,content:a.reduce((c,d)=>({...c,[d]:{schema:p,...l}}),{})}},Do=()=>({type:"http",scheme:"basic"}),vo=({format:e})=>({type:"http",scheme:"bearer",...e&&{bearerFormat:e}}),zo=({name:e})=>({type:"apiKey",in:"query",name:e}),jo=({name:e})=>({type:"apiKey",in:"header",name:e}),Lo=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ko=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Uo=({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}}},{})}),Wt=e=>{let r={basic:Do,bearer:vo,input:zo,header:jo,cookie:Lo,openid:ko,oauth2:Uo};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]})},Qt=({method:e,path:r,endpoint:t})=>{let o=Je(r),n=Jt(it(K({schema:t.getSchema("input"),isResponse:!1,rules:st,onEach:at,onMissing:pt}),o)),i=Bt(t.getSchema("input"),!1,o);return{content:t.getMimeTypes("input").reduce((a,p)=>({...a,[p]:{schema:{description:`${e.toUpperCase()} ${r} request body`,...n},...i}}),{})}},Xt=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 Ho{constructor({routing:t,config:o,title:n,version:i,serverUrl:a,successfulResponseDescription:p="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 T=y,O={path:g,method:T,endpoint:u},[F,_]=["short","long"].map(u.getDescription.bind(u)),he=o.inputSources?.[T]||be[T],Te=Yt({...O,inputSources:he}),P={operationId:this.ensureUniqOperationId(g,T),responses:{[u.getStatusCode("positive")]:dt({...O,description:p,isPositive:!0}),[u.getStatusCode("negative")]:dt({...O,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()),Te.length>0&&(P.parameters=Te),he.includes("body")&&(P.requestBody=Qt(O));let Se=Ue(Ae(Wt(u.getSecurity()),$e=>{let Zt=this.ensureUniqSecuritySchemaName($e),Or=["oauth2","openIdConnect"].includes($e.type)?u.getScopes():[];return this.addSecurityScheme(Zt,$e),{name:Zt,scopes:Or}}));Se.length>0&&(P.security=Se);let Sr=Vt(g);this.addPath(Sr,{[T]:P})}}),this.rootDoc.tags=o.tags?Xt(o.tags):[]}ensureUniqOperationId(t,o){let n=ae(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 er from"http";var Ko=e=>({method:"GET",header:jest.fn(()=>j),...e}),Fo=e=>{let r={writableEnded:!1,statusCode:200,statusMessage:er.STATUS_CODES[200],set:jest.fn(()=>r),status:jest.fn(t=>(r.statusCode=t,r.statusMessage=er.STATUS_CODES[t],r)),json:jest.fn(()=>r),end:jest.fn(()=>(r.writableEnded=!0,r)),...e};return r},_o=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=Ko(r),p=Fo(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:p,config:c,logger:l}),{requestMock:a,responseMock:p,loggerMock:l}};import z from"typescript";import w from"typescript";var s=w.factory,X=[s.createModifier(w.SyntaxKind.ExportKeyword)],$o=[s.createModifier(w.SyntaxKind.PublicKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],tr=[s.createModifier(w.SyntaxKind.ProtectedKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],Go=s.createTemplateHead(""),qo=s.createTemplateTail(""),Vo=s.createTemplateMiddle(" "),mt=e=>s.createTemplateLiteralType(Go,e.map((r,t)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(r),t===e.length-1?qo:Vo))),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)]),rr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),yt=(e,r)=>s.createPropertySignature(void 0,`"${e}"`,void 0,s.createTypeReferenceNode(r)),or=(e,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,void 0,r)],w.NodeFlags.Const),gt=(e,r)=>s.createTypeAliasDeclaration(X,e,void 0,s.createUnionTypeNode(r.map(t=>s.createLiteralTypeNode(s.createStringLiteral(t))))),Fe=(e,r)=>s.createTypeAliasDeclaration(X,e,void 0,r),nr=(e,r,t)=>s.createPropertyDeclaration($o,e,void 0,r,t),ir=(e,r,t=[])=>s.createClassDeclaration(X,e,void 0,void 0,[r,...t]),sr=(e,r)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),r)]),ar=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(w.SyntaxKind.AnyKeyword)]),xt=(e,r,t)=>s.createInterfaceDeclaration(X,e,void 0,r,t),pr=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 Yo}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},cr=(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)},Bo=/^[A-Za-z_$][A-Za-z0-9_$]*$/,lr=e=>Bo.test(e)?_e.createIdentifier(e):_e.createStringLiteral(e);var{factory:m}=f,Jo={[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},Wo=({schema:{value:e}})=>m.createLiteralTypeNode(typeof e=="number"?m.createNumericLiteral(e):typeof e=="boolean"?e?m.createTrue():m.createFalse():m.createStringLiteral(e)),Qo=({schema:{shape:e},isResponse:r,next:t})=>{let o=Object.entries(e).map(([n,i])=>{let a=r&&se(i)?i instanceof Yo.ZodOptional:i.isOptional(),p=m.createPropertySignature(void 0,lr(n),a?m.createToken(f.SyntaxKind.QuestionToken):void 0,t({schema:i}));return i.description&&Tt(p,i.description),p});return m.createTypeLiteralNode(o)},Xo=({schema:{element:e},next:r})=>m.createArrayTypeNode(r({schema:e})),en=({schema:{options:e}})=>m.createUnionTypeNode(e.map(r=>m.createLiteralTypeNode(m.createStringLiteral(r)))),mr=({schema:{options:e},next:r})=>m.createUnionTypeNode(e.map(t=>r({schema:t}))),tn=e=>Jo?.[e.kind],rn=({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:tn(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},on=({schema:e})=>m.createUnionTypeNode(Object.values(e.enum).map(r=>m.createLiteralTypeNode(typeof r=="number"?m.createNumericLiteral(r):m.createStringLiteral(r)))),nn=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createKeywordTypeNode(f.SyntaxKind.UndefinedKeyword)]),sn=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createLiteralTypeNode(m.createNull())]),an=({next:e,schema:{items:r}})=>m.createTupleTypeNode(r.map(t=>e({schema:t}))),pn=({next:e,schema:{keySchema:r,valueSchema:t}})=>m.createExpressionWithTypeArguments(m.createIdentifier("Record"),[e({schema:r}),e({schema:t})]),dn=({next:e,schema:r})=>m.createIntersectionTypeNode([r._def.left,r._def.right].map(t=>e({schema:t}))),cn=({next:e,schema:r})=>e({schema:r._def.innerType}),v=e=>()=>m.createKeywordTypeNode(e),ln=({next:e,schema:r})=>e({schema:r.unwrap()}),mn=({next:e,schema:r})=>e({schema:r._def.innerType}),un=({schema:e,next:r,isResponse:t})=>r({schema:e._def[t?"out":"in"]}),fn=()=>m.createLiteralTypeNode(m.createNull()),yn={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:fn,ZodArray:Xo,ZodTuple:an,ZodRecord:pn,ZodObject:Qo,ZodLiteral:Wo,ZodIntersection:dn,ZodUnion:mr,ZodFile:v(f.SyntaxKind.StringKeyword),ZodAny:v(f.SyntaxKind.AnyKeyword),ZodDefault:cn,ZodEnum:en,ZodNativeEnum:on,ZodEffects:rn,ZodOptional:nn,ZodNullable:sn,ZodDiscriminatedUnion:mr,ZodBranded:ln,ZodCatch:mn,ZodPipeline:un},Ot=({schema:e,...r})=>K({schema:e,rules:yn,onMissing:()=>m.createKeywordTypeNode(f.SyntaxKind.AnyKeyword),...r});var bt=class{constructor(r){this.agg=[];this.registry={};this.paths=[];H({routing:r,onEndpoint:(y,T,O)=>{let F=ae(T,O,"input"),_=ae(T,O,"response"),he=Ot({schema:y.getSchema("input"),isResponse:!1}),Te=Ot({isResponse:!0,schema:y.getSchema("positive").or(y.getSchema("negative"))}),P=St(he,F),Se=St(Te,_);this.agg.push(P),this.agg.push(Se),O!=="options"&&(this.paths.push(T),this.registry[`${O} ${T}`]={in:F,out:_,isJson:y.getMimeTypes("positive").includes(j)})}});let t=gt("Path",this.paths),o=gt("Method",Lt),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))),p=xt("Response",i,Object.keys(this.registry).map(y=>yt(y,this.registry[y].out))),l=s.createVariableStatement(X,or("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(pr({M:o.name,P:t.name}),Ke({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(a.name),ut)}),sr(p.name,ut))),d=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)}),ar())),u=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(s.createIdentifier("key"),s.createTemplateTail(""))]),g=ir("ExpressZodAPIClient",rr([He("implementation",s.createTypeReferenceNode(d.name),tr)]),[nr("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,`
33
+ `.trim();var rt=({app:e,logger:r,config:t,routing:o})=>{t.startupLogo!==!1&&console.log(Ft()),$({routing:o,hasCors:!!t.cors,onEndpoint:(n,s,a)=>{e[a](s,async(p,l)=>{r.info(`${p.method}: ${s}`),await n.execute({request:p,response:l,logger:r,config:t})})},onStatic:(n,s)=>{e.use(n,s)}})};import Qr,{json as Xr}from"express";import eo from"compression";import to from"express-fileupload";import ro from"https";import oo from"http-errors";var no=(e,r)=>(t,o,n,s)=>{if(!t)return s();e.handler({error:t,request:o,response:n,logger:r,input:o.body,output:null})},$t=(e,r)=>(t,o)=>{let n=oo(404,`Can not ${t.method} ${t.path}`);try{e.handler({request:t,response:o,logger:r,error:n,input:null,output:null})}catch(s){Ce({response:o,logger:r,error:new V(ae(s).message,n)})}};function so(e,r){let t=Je(e.logger)?ke(e.logger):e.logger;rt({app:e.app,routing:r,logger:t,config:e});let o=e.errorHandler||W;return{notFoundHandler:$t(o,t),logger:t}}function io(e,r){let t=Je(e.logger)?ke(e.logger):e.logger,o=Qr();o.disable("x-powered-by");let n=e.errorHandler||W,s=e.server.compression?eo({...typeof e.server.compression=="object"?e.server.compression:{}}):void 0,a=e.server.jsonParser||Xr(),p=e.server.upload?to({...typeof e.server.upload=="object"?e.server.upload:{},abortOnLimit:!1,parseNested:!0}):void 0,l=[].concat(s||[]).concat(a).concat(p||[]);o.use(l),o.use(no(n,t)),rt({app:o,routing:r,logger:t,config:e}),o.use($t(n,t));let d=o.listen(e.server.listen,()=>{t.info(`Listening ${e.server.listen}`)}),c;return e.https&&(c=ro.createServer(e.https.options,o).listen(e.https.listen,()=>{t.info(`Listening ${e.https.listen}`)})),{app:o,httpServer:d,httpsServer:c,logger:t}}import{OpenApiBuilder as Yo}from"openapi3-ts";import{createHash as co}from"crypto";import{isReferenceObject as lo,isSchemaObject as He}from"openapi3-ts";import{omit as ye}from"ramda";import{z as T}from"zod";import{INVALID as _t,ZodIssueCode as ot,ZodParsedType as Gt,ZodType as ao,addIssueToContext as nt}from"zod";var st=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/,po="ZodDateIn",it=class extends ao{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);if(o.parsedType!==Gt.string)return nt(o,{code:ot.invalid_type,expected:Gt.string,received:o.parsedType}),_t;st.test(o.data)||(nt(o,{code:ot.invalid_string,validation:"regex"}),t.dirty());let n=new Date(o.data);return Re(n)?{status:t.value,value:n}:(nt(o,{code:ot.invalid_date}),_t)}},ue=it;ue.create=()=>new it({typeName:po});var _=({schema:e,onEach:r,rules:t,onMissing:o,...n})=>{let s=r&&r({schema:e,...n}),a="typeName"in e._def?t[e._def.typeName]:void 0,l=a?a({schema:e,...n,next:d=>_({...d,...n,onEach:r,rules:t,onMissing:o})}):o(e);return s?{...l,...s}:l};var qt=50,Bt="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",mo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Yt=e=>e.replace(Be,r=>`{${r.slice(1)}}`),uo=({schema:{_def:{innerType:e,defaultValue:r}},next:t})=>({...t({schema:e}),default:r()}),fo=({schema:{_def:{innerType:e}},next:r})=>r({schema:e}),yo=()=>({format:"any"}),go=({isResponse:e})=>{if(e)throw new P("Please use z.upload() only for input.");return{type:"string",format:"binary"}},ho=({schema:{isBinary:e,isBase64:r},isResponse:t})=>{if(!t)throw new P("Please use z.file() only within ResultHandler.");return{type:"string",format:e?"binary":r?"byte":"file"}},xo=({schema:{options:e},next:r})=>({oneOf:e.map(t=>r({schema:t}))}),To=({schema:{options:e,discriminator:r},next:t})=>({discriminator:{propertyName:r},oneOf:Array.from(e.values()).map(o=>t({schema:o}))}),So=({schema:{_def:{left:e,right:r}},next:t})=>({allOf:[e,r].map(o=>t({schema:o}))}),Oo=({schema:e,next:r})=>r({schema:e.unwrap()}),bo=({schema:e,next:r})=>({nullable:!0,...r({schema:e.unwrap()})}),Vt=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),Po=({schema:{value:e}})=>({type:typeof e,enum:[e]}),Ro=({schema:e,isResponse:r,...t})=>{let o=Object.keys(e.shape).filter(n=>{let s=e.shape[n];return!(r&&pe(s)?s instanceof T.ZodOptional:s.isOptional())});return{type:"object",properties:Ue({schema:e,isResponse:r,...t}),...o.length?{required:o}:{}}},Zo=()=>({type:"string",nullable:!0,format:"null"}),Eo=({isResponse:e})=>{if(e)throw new P("Please use z.dateOut() for output.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:st.source,externalDocs:{url:Bt}}},Ao=({isResponse:e})=>{if(!e)throw new P("Please use z.dateIn() for input.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Bt}}},Io=({isResponse:e})=>{throw new P(`Using z.date() within ${e?"output":"input"} schema is forbidden. Please use z.date${e?"Out":"In"}() instead. Check out the documentation for details.`)},Co=()=>({type:"boolean"}),Mo=()=>({type:"integer",format:"bigint"}),No=({schema:{keySchema:e,valueSchema:r},...t})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),n=o.reduce((s,a)=>({...s,[a]:r}),{});return{type:"object",properties:Ue({schema:T.object(n),...t}),...o.length?{required:o}:{}}}if(e instanceof T.ZodLiteral)return{type:"object",properties:Ue({schema:T.object({[e.value]:r}),...t}),required:[e.value]};if(e instanceof T.ZodUnion&&e.options.reduce((n,s)=>n&&s instanceof T.ZodLiteral,!0)){let n=e.options.reduce((s,a)=>({...s,[a.value]:r}),{});return{type:"object",properties:Ue({schema:T.object(n),...t}),required:e.options.map(s=>s.value)}}return{type:"object",additionalProperties:t.next({schema:r})}},wo=({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}}),Do=({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}: ${He(o)?o.type:o.$ref}`).join(", ")}}}},vo=({schema:{isEmail:e,isURL:r,minLength:t,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:p,isIP:l,isEmoji:d,isDatetime:c,_def:{checks:f}}})=>{let h=f.find(g=>g.kind==="regex"),m=f.find(g=>g.kind==="datetime"),x=h?h.regex:m?m.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",...c&&{format:"date-time"},...e&&{format:"email"},...r&&{format:"url"},...n&&{format:"uuid"},...s&&{format:"cuid"},...a&&{format:"cuid2"},...p&&{format:"ulid"},...l&&{format:"ip"},...d&&{format:"emoji"},...t!==null&&{minLength:t},...o!==null&&{maxLength:o},...x&&{pattern:`/${x.source}/${x.flags}`}}},zo=({schema:e})=>{let r=e._def.checks.find(({kind:s})=>s==="min"),t=r?r.inclusive:!0,o=e._def.checks.find(({kind:s})=>s==="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}},Ue=({schema:{shape:e},next:r})=>Object.keys(e).reduce((t,o)=>({...t,[o]:r({schema:e[o]})}),{}),jo=e=>{let r=Array.isArray(e.type)?e.type[0]:e.type;return mo?.[r]},Lo=({schema:e,isResponse:r,next:t})=>{let o=t({schema:e.innerType()}),{effect:n}=e._def;if(r&&n.type==="transform"&&He(o)){let s=Ee({effect:n,sample:jo(o)});return s&&["number","string","boolean"].includes(s)?{type:s}:t({schema:T.any()})}if(!r&&n.type==="preprocess"&&He(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ko=({schema:e,isResponse:r,next:t})=>t({schema:e._def[r?"out":"in"]}),Uo=({schema:e,next:r})=>r({schema:e.unwrap()}),Jt=e=>co("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ho=({next:e,schema:r,serializer:t,hasRef:o,makeRef:n})=>{let s=t(r.schema);if(o(s))return{$ref:`#/components/schemas/${s}`};let a=n(s,{});return n(s,e({schema:r.schema})),a},Wt=(e,r,t=[])=>{let o=Ze(e,r);return o.length===0?{}:{examples:o.reduce((n,s,a)=>({...n,[`example${a+1}`]:{value:ye(t,s)}}),{})}},Ko=(e,r,t)=>{let o=Ze(e,r);return o.length===0?{}:{examples:o.reduce((n,s,a)=>t in s?{...n,[`example${a+1}`]:{value:s[t]}}:n,{})}};function fe(e){if(e instanceof T.ZodObject)return e;let r;if(e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion)r=Array.from(e.options.values()).map(t=>fe(t)).reduce((t,o)=>t.merge(o.partial()),T.object({}));else if(e instanceof T.ZodEffects){if(N(e))throw new P("Using transformations on the top level of input schema is not allowed.");r=fe(e._def.schema)}else r=fe(e._def.left).merge(fe(e._def.right));return be(e,r)}var Qt=({path:e,method:r,endpoint:t,inputSources:o,serializer:n,hasRef:s,makeRef:a,composition:p,clue:l="parameter"})=>{let d=t.getSchema("input"),c=fe(d).shape,f=Qe(e),h=o.includes("query"),m=o.includes("params"),x=g=>m&&f.includes(g);return Object.keys(c).filter(g=>h||x(g)).map(g=>{let b=_({schema:c[g],isResponse:!1,rules:pt,onEach:dt,onMissing:ct,serializer:n,hasRef:s,makeRef:a}),E=p==="components"?a(A(e,r,`${l} ${g}`),b):b;return{name:g,in:x(g)?"path":"query",required:!c[g].isOptional(),description:`${r.toUpperCase()} ${e} ${l}`,schema:E,...Ko(d,!1,g)}})},pt={ZodString:vo,ZodNumber:zo,ZodBigInt:Mo,ZodBoolean:Co,ZodDateIn:Eo,ZodDateOut:Ao,ZodNull:Zo,ZodArray:wo,ZodTuple:Do,ZodRecord:No,ZodObject:Ro,ZodLiteral:Po,ZodIntersection:So,ZodUnion:xo,ZodFile:ho,ZodUpload:go,ZodAny:yo,ZodDefault:uo,ZodEnum:Vt,ZodNativeEnum:Vt,ZodEffects:Lo,ZodOptional:Oo,ZodNullable:bo,ZodDiscriminatedUnion:To,ZodBranded:Uo,ZodDate:Io,ZodCatch:fo,ZodPipeline:ko,ZodLazy:Ho},dt=({schema:e,isResponse:r})=>{let{description:t}=e,o=e instanceof T.ZodLazy,n=o?[]:Ze(e,r);return{...t&&{description:t},...!o&&e.isNullable()&&!(r&&pe(e))&&{nullable:!0},...n.length>0&&{example:n[0]}}},ct=e=>{throw new P(`Zod type ${e.constructor.name} is unsupported`)},at=(e,r)=>{if(lo(e))return e;let t=e.properties?ye(r,e.properties):void 0,o=e.example?ye(r,e.example):void 0,n=e.required?e.required.filter(p=>!r.includes(p)):void 0,s=e.allOf?e.allOf.map(p=>at(p,r)):void 0,a=e.oneOf?e.oneOf.map(p=>at(p,r)):void 0;return ye(Object.entries({properties:t,required:n,example:o,allOf:s,oneOf:a}).filter(([{},p])=>p===void 0).map(([p])=>p),{...e,properties:t,required:n,example:o,allOf:s,oneOf:a})},Xt=e=>He(e)?ye(["example"],e):e,lt=({method:e,path:r,endpoint:t,isPositive:o,serializer:n,hasRef:s,makeRef:a,composition:p,clue:l="response"})=>{let d=t.getSchema(o?"positive":"negative"),c=t.getMimeTypes(o?"positive":"negative"),f=Xt(_({schema:d,isResponse:!0,rules:pt,onEach:dt,onMissing:ct,serializer:n,hasRef:s,makeRef:a})),h=Wt(d,!0),m=p==="components"?a(A(r,e,l),f):f;return{description:`${e.toUpperCase()} ${r} ${l}`,content:c.reduce((x,g)=>({...x,[g]:{schema:m,...h}}),{})}},Fo=()=>({type:"http",scheme:"basic"}),$o=({format:e})=>({type:"http",scheme:"bearer",...e&&{bearerFormat:e}}),_o=({name:e})=>({type:"apiKey",in:"query",name:e}),Go=({name:e})=>({type:"apiKey",in:"header",name:e}),qo=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Vo=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Bo=({flows:e={}})=>({type:"oauth2",flows:Object.keys(e).reduce((r,t)=>{let o=e[t];if(!o)return r;let{scopes:n={},...s}=o;return{...r,[t]:{...s,scopes:n}}},{})}),er=e=>{let r={basic:Fo,bearer:$o,input:_o,header:Go,cookie:qo,openid:Vo,oauth2:Bo};return Ie(e,t=>r[t.type](t))},Ke=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 Ke(et(e))}return Ke({or:[e]})},tr=({method:e,path:r,endpoint:t,serializer:o,hasRef:n,makeRef:s,composition:a,clue:p="request body"})=>{let l=Qe(r),d=Xt(at(_({schema:t.getSchema("input"),isResponse:!1,rules:pt,onEach:dt,onMissing:ct,serializer:o,hasRef:n,makeRef:s}),l)),c=Wt(t.getSchema("input"),!1,l),f=a==="components"?s(A(r,e,p),d):d;return{description:`${e.toUpperCase()} ${r} ${p}`,content:t.getMimeTypes("input").reduce((h,m)=>({...h,[m]:{schema:f,...c}}),{})}},rr=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}}}}),mt=e=>e.length<=qt?e:e.slice(0,qt-1)+"\u2026";var ut=class extends Yo{constructor({routing:t,config:o,title:n,version:s,serverUrl:a,successfulResponseDescription:p="Successful response",errorResponseDescription:l="Error response",hasSummaryFromDescription:d=!0,composition:c="inline",serializer:f=Jt}){super();this.lastSecuritySchemaIds={};this.lastOperationIdSuffixes={};this.addInfo({title:n,version:s}).addServer({url:a}),$({routing:t,onEndpoint:(m,x,g)=>{let b=g,E={path:x,method:b,endpoint:m,composition:c,serializer:f,hasRef:this.hasRef.bind(this),makeRef:this.makeRef.bind(this)},[re,oe]=["short","long"].map(m.getDescription.bind(m)),Te=o.inputSources?.[b]||Pe[b],Se=Qt({...E,inputSources:Te}),C={operationId:this.ensureUniqOperationId(x,b),responses:{[m.getStatusCode("positive")]:lt({...E,clue:p,isPositive:!0}),[m.getStatusCode("negative")]:lt({...E,clue:l,isPositive:!1})}};oe&&(C.description=oe,d&&re===void 0&&(C.summary=mt(oe))),re&&(C.summary=mt(re)),m.getTags().length>0&&(C.tags=m.getTags()),Se.length>0&&(C.parameters=Se),Te.includes("body")&&(C.requestBody=tr(E));let At=Ke(Ie(er(m.getSecurity()),qe=>{let It=this.ensureUniqSecuritySchemaName(qe),Rr=["oauth2","openIdConnect"].includes(qe.type)?m.getScopes():[];return this.addSecurityScheme(It,qe),{name:It,scopes:Rr}}));At.length>0&&(C.security=At);let Pr=Yt(x);this.addPath(Pr,{[b]:C})}}),this.rootDoc.tags=o.tags?rr(o.tags):[]}makeRef(t,o){return this.addSchema(t,o),{$ref:`#/components/schemas/${t}`}}hasRef(t){return t in(this.rootDoc.components?.schemas||{})}ensureUniqOperationId(t,o){let n=A(t,o);return n in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[n]++,`${n}${this.lastOperationIdSuffixes[n]}`):(this.lastOperationIdSuffixes[n]=1,n)}ensureUniqSecuritySchemaName(t){let o=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(o===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}};import or from"http";var Jo=e=>({method:"GET",header:jest.fn(()=>U),...e}),Wo=e=>{let r={writableEnded:!1,statusCode:200,statusMessage:or.STATUS_CODES[200],set:jest.fn(()=>r),status:jest.fn(t=>(r.statusCode=t,r.statusMessage=or.STATUS_CODES[t],r)),json:jest.fn(()=>r),end:jest.fn(()=>(r.writableEnded=!0,r)),...e};return r},Qo=async({endpoint:e,requestProps:r,responseProps:t,configProps:o,loggerProps:n,__noJest:s})=>{if(!jest||s)throw new Error("You need to install Jest in order to use testEndpoint().");let a=Jo(r),p=Wo(t),l={info:jest.fn(),warn:jest.fn(),error:jest.fn(),debug:jest.fn(),...n},d={cors:!1,logger:l,...o};return await e.execute({request:a,response:p,config:d,logger:l}),{requestMock:a,responseMock:p,loggerMock:l}};import k from"typescript";import z from"typescript";var i=z.factory,te=[i.createModifier(z.SyntaxKind.ExportKeyword)],Xo=[i.createModifier(z.SyntaxKind.PublicKeyword),i.createModifier(z.SyntaxKind.ReadonlyKeyword)],nr=[i.createModifier(z.SyntaxKind.ProtectedKeyword),i.createModifier(z.SyntaxKind.ReadonlyKeyword)],en=i.createTemplateHead(""),tn=i.createTemplateTail(""),rn=i.createTemplateMiddle(" "),ft=e=>i.createTemplateLiteralType(en,e.map((r,t)=>i.createTemplateLiteralTypeSpan(i.createTypeReferenceNode(r),t===e.length-1?tn:rn))),yt=ft(["M","P"]),Fe=(e,r,t)=>i.createParameterDeclaration(t,void 0,e,void 0,r),$e=(e,r)=>Object.keys(e).reduce((t,o)=>t.concat(Fe(o,e[o],r)),[]),gt=(e,r)=>i.createExpressionWithTypeArguments(i.createIdentifier("Record"),[typeof e=="number"?i.createKeywordTypeNode(e):i.createTypeReferenceNode(e),i.createKeywordTypeNode(r)]),sr=e=>i.createConstructorDeclaration(void 0,e,i.createBlock([])),ht=(e,r)=>i.createPropertySignature(void 0,`"${e}"`,void 0,i.createTypeReferenceNode(r)),ir=(e,r)=>i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,void 0,r)],z.NodeFlags.Const),xt=(e,r)=>i.createTypeAliasDeclaration(te,e,void 0,i.createUnionTypeNode(r.map(t=>i.createLiteralTypeNode(i.createStringLiteral(t))))),_e=(e,r)=>i.createTypeAliasDeclaration(te,e,void 0,r),ar=(e,r,t)=>i.createPropertyDeclaration(Xo,e,void 0,r,t),pr=(e,r,t=[])=>i.createClassDeclaration(te,e,void 0,void 0,[r,...t]),dr=(e,r)=>i.createTypeReferenceNode("Promise",[i.createIndexedAccessTypeNode(i.createTypeReferenceNode(e),r)]),cr=()=>i.createTypeReferenceNode("Promise",[i.createKeywordTypeNode(z.SyntaxKind.AnyKeyword)]),Tt=(e,r,t)=>i.createInterfaceDeclaration(te,e,void 0,r,t),lr=e=>Object.keys(e).reduce((r,t)=>r.concat(i.createTypeParameterDeclaration([],t,i.createTypeReferenceNode(e[t]))),[]),mr=(e,r)=>i.createArrowFunction(void 0,void 0,e.map(t=>Fe(t)),void 0,void 0,i.createCallExpression(i.createPropertyAccessExpression(i.createThis(),"implementation"),void 0,r)),St=(e,r,t)=>i.createCallExpression(i.createPropertyAccessExpression(i.createCallExpression(i.createPropertyAccessExpression(i.createIdentifier("Object"),"keys"),void 0,[i.createIdentifier(e)]),"reduce"),void 0,[i.createArrowFunction(void 0,void 0,$e({acc:void 0,key:void 0}),void 0,void 0,r),t]);import y from"typescript";import{z as nn}from"zod";import j from"typescript";var{factory:Ge}=j,Ot=(e,r)=>{j.addSyntheticLeadingComment(e,j.SyntaxKind.MultiLineCommentTrivia,`* ${r} `,!0)},bt=(e,r,t)=>{let o=Ge.createTypeAliasDeclaration(void 0,Ge.createIdentifier(r),void 0,e);return t&&Ot(o,t),o},ur=(e,r)=>{let t=j.createSourceFile("print.ts","",j.ScriptTarget.Latest,!1,j.ScriptKind.TS);return j.createPrinter(r).printNode(j.EmitHint.Unspecified,e,t)},on=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fr=e=>on.test(e)?Ge.createIdentifier(e):Ge.createStringLiteral(e);var{factory:u}=y,sn={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},an=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),pn=({schema:{shape:e},isResponse:r,next:t})=>{let o=Object.entries(e).map(([n,s])=>{let a=r&&pe(s)?s instanceof nn.ZodOptional:s.isOptional(),p=u.createPropertySignature(void 0,fr(n),a?u.createToken(y.SyntaxKind.QuestionToken):void 0,t({schema:s}));return s.description&&Ot(p,s.description),p});return u.createTypeLiteralNode(o)},dn=({schema:{element:e},next:r})=>u.createArrayTypeNode(r({schema:e})),cn=({schema:{options:e}})=>u.createUnionTypeNode(e.map(r=>u.createLiteralTypeNode(u.createStringLiteral(r)))),yr=({schema:{options:e},next:r})=>u.createUnionTypeNode(e.map(t=>r({schema:t}))),ln=e=>sn?.[e.kind],mn=({schema:e,next:r,isResponse:t})=>{let o=r({schema:e.innerType()}),n=e._def.effect;if(t&&n.type==="transform"){let s=Ee({effect:n,sample:ln(o)}),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||y.SyntaxKind.AnyKeyword)}return o},un=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(r=>u.createLiteralTypeNode(typeof r=="number"?u.createNumericLiteral(r):u.createStringLiteral(r)))),fn=({next:e,schema:r})=>u.createUnionTypeNode([e({schema:r.unwrap()}),u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]),yn=({next:e,schema:r})=>u.createUnionTypeNode([e({schema:r.unwrap()}),u.createLiteralTypeNode(u.createNull())]),gn=({next:e,schema:{items:r}})=>u.createTupleTypeNode(r.map(t=>e({schema:t}))),hn=({next:e,schema:{keySchema:r,valueSchema:t}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e({schema:r}),e({schema:t})]),xn=({next:e,schema:r})=>u.createIntersectionTypeNode([r._def.left,r._def.right].map(t=>e({schema:t}))),Tn=({next:e,schema:r})=>e({schema:r._def.innerType}),L=e=>()=>u.createKeywordTypeNode(e),Sn=({next:e,schema:r})=>e({schema:r.unwrap()}),On=({next:e,schema:r})=>e({schema:r._def.innerType}),bn=({schema:e,next:r,isResponse:t})=>r({schema:e._def[t?"out":"in"]}),Pn=()=>u.createLiteralTypeNode(u.createNull()),Rn={ZodString:L(y.SyntaxKind.StringKeyword),ZodNumber:L(y.SyntaxKind.NumberKeyword),ZodBigInt:L(y.SyntaxKind.BigIntKeyword),ZodBoolean:L(y.SyntaxKind.BooleanKeyword),ZodDateIn:L(y.SyntaxKind.StringKeyword),ZodDateOut:L(y.SyntaxKind.StringKeyword),ZodNull:Pn,ZodArray:dn,ZodTuple:gn,ZodRecord:hn,ZodObject:pn,ZodLiteral:an,ZodIntersection:xn,ZodUnion:yr,ZodFile:L(y.SyntaxKind.StringKeyword),ZodAny:L(y.SyntaxKind.AnyKeyword),ZodDefault:Tn,ZodEnum:cn,ZodNativeEnum:un,ZodEffects:mn,ZodOptional:fn,ZodNullable:yn,ZodDiscriminatedUnion:yr,ZodBranded:Sn,ZodCatch:On,ZodPipeline:bn},Pt=({schema:e,...r})=>_({schema:e,rules:Rn,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...r});var Rt=class{constructor({routing:r}){this.agg=[];this.registry={};this.paths=[];$({routing:r,onEndpoint:(m,x,g)=>{let b=A(x,g,"input"),E=A(x,g,"response"),re=Pt({schema:m.getSchema("input"),isResponse:!1}),oe=Pt({isResponse:!0,schema:m.getSchema("positive").or(m.getSchema("negative"))}),Te=bt(re,b),Se=bt(oe,E);this.agg.push(Te),this.agg.push(Se),g!=="options"&&(this.paths.push(x),this.registry[`${g} ${x}`]={in:b,out:E,isJson:m.getMimeTypes("positive").includes(U)})}});let t=xt("Path",this.paths),o=xt("Method",Ut),n=_e("MethodPath",ft([o.name,t.name])),s=[i.createHeritageClause(k.SyntaxKind.ExtendsKeyword,[gt(n.name,k.SyntaxKind.AnyKeyword)])],a=Tt("Input",s,Object.keys(this.registry).map(m=>ht(m,this.registry[m].in))),p=Tt("Response",s,Object.keys(this.registry).map(m=>ht(m,this.registry[m].out))),l=i.createVariableStatement(te,ir("jsonEndpoints",i.createObjectLiteralExpression(Object.keys(this.registry).filter(m=>this.registry[m].isJson).map(m=>i.createPropertyAssignment(`"${m}"`,i.createTrue()))))),d=_e("Provider",i.createFunctionTypeNode(lr({M:o.name,P:t.name}),$e({method:i.createTypeReferenceNode("M"),path:i.createTypeReferenceNode("P"),params:i.createIndexedAccessTypeNode(i.createTypeReferenceNode(a.name),yt)}),dr(p.name,yt))),c=_e("Implementation",i.createFunctionTypeNode(void 0,$e({method:i.createTypeReferenceNode(o.name),path:i.createKeywordTypeNode(k.SyntaxKind.StringKeyword),params:gt(k.SyntaxKind.StringKeyword,k.SyntaxKind.AnyKeyword)}),cr())),f=i.createTemplateExpression(i.createTemplateHead(":"),[i.createTemplateSpan(i.createIdentifier("key"),i.createTemplateTail(""))]),h=pr("ExpressZodAPIClient",sr([Fe("implementation",i.createTypeReferenceNode(c.name),nr)]),[ar("provide",i.createTypeReferenceNode(d.name),mr(["method","path","params"],[i.createIdentifier("method"),St("params",i.createCallExpression(i.createPropertyAccessExpression(i.createIdentifier("acc"),"replace"),void 0,[f,i.createElementAccessExpression(i.createIdentifier("params"),i.createIdentifier("key"))]),i.createIdentifier("path")),St("params",i.createConditionalExpression(i.createBinaryExpression(i.createCallExpression(i.createPropertyAccessExpression(i.createIdentifier("path"),"indexOf"),void 0,[f]),k.SyntaxKind.GreaterThanEqualsToken,i.createNumericLiteral(0)),void 0,i.createIdentifier("acc"),void 0,i.createObjectLiteralExpression([i.createSpreadAssignment(i.createIdentifier("acc")),i.createPropertyAssignment("[key]",i.createElementAccessExpression(i.createIdentifier("params"),i.createIdentifier("key")))])),i.createObjectLiteralExpression())]))]);k.addSyntheticLeadingComment(h,k.SyntaxKind.MultiLineCommentTrivia,`
34
34
  export const exampleImplementation: Implementation = async (
35
35
  method,
36
36
  path,
@@ -52,7 +52,7 @@ export const exampleImplementation: Implementation = async (
52
52
 
53
53
  const client = new ExpressZodAPIClient(exampleImplementation);
54
54
  client.provide("get", "/v1/user/retrieve", { id: "10" });
55
- `,!0),this.agg.push(t,o,n,a,p,l,c,d,g)}print(r){return this.agg.map(t=>cr(t,r)).join(`
55
+ `,!0),this.agg.push(t,o,n,a,p,l,d,c,h)}print(r){return this.agg.map(t=>ur(t,r)).join(`
56
56
 
57
- `)}};import{INVALID as ur,ZodIssueCode as fr,ZodParsedType as yr,ZodType as gn,addIssueToContext as gr}from"zod";var xn="ZodDateOut",Pt=class extends gn{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);return o.parsedType!==yr.date?(gr(o,{code:fr.invalid_type,expected:yr.date,received:o.parsedType}),ur):Pe(o.data)?{status:t.value,value:o.data.toISOString()}:(gr(o,{code:fr.invalid_date}),ur)}},ye=Pt;ye.create=()=>new Pt({typeName:xn});import{INVALID as hn,ZodIssueCode as xr,ZodParsedType as hr,ZodType as Tn,addIssueToContext as Tr}from"zod";var Sn="ZodFile",On=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,xe=class extends Tn{constructor(){super(...arguments);this.binary=t=>new xe({...this._def,checks:[...this._def.checks,{kind:"binary",...We(t)}]});this.base64=t=>new xe({...this._def,checks:[...this._def.checks,{kind:"base64",...We(t)}]})}_parse(t){let{status:o,ctx:n}=this._processInputParams(t);if(n.parsedType!==hr.string)return Tr(n,{code:xr.invalid_type,expected:hr.string,received:n.parsedType}),hn;for(let i of this._def.checks)i.kind==="base64"&&(On.test(n.data)||(Tr(n,{code:xr.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")}},ge=xe;ge.create=()=>new xe({checks:[],typeName:Sn});var Et;(n=>(n.file=ge.create,n.upload=L.create,n.dateIn=me.create,n.dateOut=ye.create))(Et||(Et={}));import La from"http-errors";export{J as AbstractEndpoint,bt as Client,ce as DependsOnMethod,pe as DependsOnMethodError,de as EndpointsFactory,C as InputValidationError,lt as OpenAPI,b as OpenAPIError,U as OutputValidationError,$ as RoutingError,le as ServeStatic,Xr as attachRouting,Pr as createConfig,La as createHttpError,Le as createLogger,Xe as createMiddleware,Mt as createResultHandler,eo as createServer,jr as defaultEndpointsFactory,Y as defaultResultHandler,Et as ez,k as getMessageFromError,Ye as getStatusCodeFromError,_o as testEndpoint,ee as withMeta};
57
+ `)}};import{INVALID as gr,ZodIssueCode as hr,ZodParsedType as xr,ZodType as Zn,addIssueToContext as Tr}from"zod";var En="ZodDateOut",Zt=class extends Zn{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);return o.parsedType!==xr.date?(Tr(o,{code:hr.invalid_type,expected:xr.date,received:o.parsedType}),gr):Re(o.data)?{status:t.value,value:o.data.toISOString()}:(Tr(o,{code:hr.invalid_date}),gr)}},ge=Zt;ge.create=()=>new Zt({typeName:En});import{INVALID as An,ZodIssueCode as Sr,ZodParsedType as Or,ZodType as In,addIssueToContext as br}from"zod";var Cn="ZodFile",Mn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,xe=class extends In{constructor(){super(...arguments);this.binary=t=>new xe({...this._def,checks:[...this._def.checks,{kind:"binary",...Xe(t)}]});this.base64=t=>new xe({...this._def,checks:[...this._def.checks,{kind:"base64",...Xe(t)}]})}_parse(t){let{status:o,ctx:n}=this._processInputParams(t);if(n.parsedType!==Or.string)return br(n,{code:Sr.invalid_type,expected:Or.string,received:n.parsedType}),An;for(let s of this._def.checks)s.kind==="base64"&&(Mn.test(n.data)||(br(n,{code:Sr.custom,message:s.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")}},he=xe;he.create=()=>new xe({checks:[],typeName:Cn});var Et;(n=>(n.file=he.create,n.upload=H.create,n.dateIn=ue.create,n.dateOut=ge.create))(Et||(Et={}));import cp from"http-errors";export{Q as AbstractEndpoint,Rt as Client,le as DependsOnMethod,de as DependsOnMethodError,ce as EndpointsFactory,w as InputValidationError,ut as OpenAPI,P as OpenAPIError,F as OutputValidationError,q as RoutingError,me as ServeStatic,so as attachRouting,Er as createConfig,cp as createHttpError,ke as createLogger,tt as createMiddleware,wt as createResultHandler,io as createServer,Fr as defaultEndpointsFactory,W as defaultResultHandler,Et as ez,K as getMessageFromError,We as getStatusCodeFromError,Qo as testEndpoint,G as withMeta};
58
58
  //# sourceMappingURL=index.js.map