express-zod-api 19.0.0-beta.4 → 19.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -7
- package/README.md +20 -39
- package/SECURITY.md +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +6 -6
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -5,25 +5,31 @@
|
|
|
5
5
|
### v19.0.0
|
|
6
6
|
|
|
7
7
|
- **Breaking changes**:
|
|
8
|
-
-
|
|
9
|
-
|
|
8
|
+
- Increased the minimum supported versions:
|
|
9
|
+
- For Node.js: 18.18.0, 20.9.0 or 22.0.0;
|
|
10
|
+
- For `zod`: 3.23.0;
|
|
11
|
+
- For `express`: [4.19.2](https://github.com/expressjs/express/security/advisories/GHSA-rv95-896h-c2vc);
|
|
12
|
+
- For `express-fileupload` and `@types/express-fileupload`: 1.5.0.
|
|
13
|
+
- Removed the deprecated method ~~`withMeta()`~~ (see [v18.5.0](#v1850) for details);
|
|
10
14
|
- Removed support for static options by `EndpointsFactory::addOptions()` (see [v18.6.0](#v1860) for details);
|
|
11
15
|
- Freezed the arrays returned by the methods or exposed by properties of `Endpoint` and `DependsOnMethod`;
|
|
12
|
-
- Changed
|
|
13
|
-
- Changed
|
|
16
|
+
- Changed interface for `ez.raw()`: additional properties should be supplied as its argument, not via `.extend()`;
|
|
17
|
+
- Changed the following config options:
|
|
18
|
+
- The function assigned to `server.upload.beforeUpload` now accepts `request` instead of `app`;
|
|
19
|
+
- The function assigned to `server.beforeRouting` is now called before parsing too.
|
|
14
20
|
- Features:
|
|
15
21
|
- New configurable level `info` for built-in logger (higher than `debug`, but lower than `warn`);
|
|
16
22
|
- Selective parsers equipped with a child logger:
|
|
17
23
|
- There are 3 types of endpoints depending on their input schema: having `ez.upload()`, having `ez.raw()`, others;
|
|
18
24
|
- Depending on that type, only the parsers needed for certain endpoint are processed;
|
|
19
|
-
- This makes all requests eligible for the assigned parsers and reverts changes made in [v18.5.2](#v1852)
|
|
25
|
+
- This makes all requests eligible for the assigned parsers and reverts changes made in [v18.5.2](#v1852);
|
|
26
|
+
- Specifying `rawParser` in config is no longer needed to enable the feature.
|
|
20
27
|
- Non-breaking significant changes:
|
|
21
28
|
- Request logging reflects the actual path instead of the configured route, and it's placed in front of parsing:
|
|
22
29
|
- The severity of those messaged reduced from `info` to `debug`;
|
|
23
30
|
- The debug messages from uploader are enabled by default when the logger level is set to `debug`;
|
|
24
|
-
- Specifying `rawParser` in config is no longer needed to enable the feature.
|
|
25
31
|
- How to migrate confidently:
|
|
26
|
-
- Upgrade Node
|
|
32
|
+
- Upgrade Node.js, `zod`, `express`, `express-fileupload` and `@types/express-fileupload` accordingly;
|
|
27
33
|
- Avoid mutating the readonly arrays;
|
|
28
34
|
- If you're using ~~`withMeta()`~~:
|
|
29
35
|
- Remove it and unwrap your schemas — you can use `.example()` method directly.
|
|
@@ -34,6 +40,8 @@
|
|
|
34
40
|
- Supply them directly as an argument to `ez.raw()` — see the example below.
|
|
35
41
|
- If you're using `beforeUpload` in your config:
|
|
36
42
|
- Adjust the implementation according to the example below.
|
|
43
|
+
- If you're using `beforeRouting` in your config for anything that requires a parsed request body:
|
|
44
|
+
- Add the required parsers using `app.use()` statements to the assigned function.
|
|
37
45
|
- If you're having `rawParser: express.raw()` in your config:
|
|
38
46
|
- You can now remove this line (it's the default value now), unless you're having any customizations.
|
|
39
47
|
|
|
@@ -84,6 +92,30 @@ const after = ez.raw({
|
|
|
84
92
|
|
|
85
93
|
## Version 18
|
|
86
94
|
|
|
95
|
+
### v18.6.2
|
|
96
|
+
|
|
97
|
+
- Compatibility improvement for Jest: all dynamic `import()` in CJS build are replaced with `require()`.
|
|
98
|
+
|
|
99
|
+
### v18.6.1
|
|
100
|
+
|
|
101
|
+
- Notice on creating connections within a function supplied to `EndpointsFactory::addOptions()`:
|
|
102
|
+
- Use it with caution: a new connection will be created for every request handled by endpoint made on that factory;
|
|
103
|
+
- Consider reusing `const` across your files for persistent connections;
|
|
104
|
+
- In case of intentional non-persistent connection, consider resources cleanup if necessary:
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
import { createResultHandler } from "express-zod-api";
|
|
108
|
+
|
|
109
|
+
const resultHandlerWithCleanup = createResultHandler({
|
|
110
|
+
handler: ({ options }) => {
|
|
111
|
+
// necessary to check for certain option presence:
|
|
112
|
+
if ("db" in options && options.db) {
|
|
113
|
+
options.db.connection.close(); // sample cleanup
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
87
119
|
### v18.6.0
|
|
88
120
|
|
|
89
121
|
- Feat: Supporting async functon as an argument for `EndpointsFactory::addOptions()`:
|
|
@@ -96,6 +128,7 @@ import { readFile } from "node:fs/promises";
|
|
|
96
128
|
import { defaultEndpointsFactory } from "express-zod-api";
|
|
97
129
|
|
|
98
130
|
const endpointsFactory = defaultEndpointsFactory.addOptions(async () => {
|
|
131
|
+
// caution: new connection on every request:
|
|
99
132
|
const db = mongoose.connect("mongodb://connection.string");
|
|
100
133
|
const privateKey = await readFile("private-key.pem", "utf-8");
|
|
101
134
|
return { db, privateKey };
|
package/README.md
CHANGED
|
@@ -52,8 +52,7 @@ Start your API server with I/O schema validation and custom middlewares in minut
|
|
|
52
52
|
2. [Array response](#array-response) for migrating legacy APIs
|
|
53
53
|
3. [Headers as input source](#headers-as-input-source)
|
|
54
54
|
4. [Accepting raw data](#accepting-raw-data)
|
|
55
|
-
5. [
|
|
56
|
-
6. [Subscriptions](#subscriptions)
|
|
55
|
+
5. [Subscriptions](#subscriptions)
|
|
57
56
|
7. [Integration and Documentation](#integration-and-documentation)
|
|
58
57
|
1. [Zod Plugin](#zod-plugin)
|
|
59
58
|
2. [Generating a Frontend Client](#generating-a-frontend-client)
|
|
@@ -293,20 +292,37 @@ You can connect as many middlewares as you want, they will be executed in order.
|
|
|
293
292
|
|
|
294
293
|
## Options
|
|
295
294
|
|
|
296
|
-
In case you'd like to provide your endpoints with options that do not depend on Request, like
|
|
297
|
-
|
|
295
|
+
In case you'd like to provide your endpoints with options that do not depend on Request, like non-persistent connection
|
|
296
|
+
to a database, consider shorthand method `addOptions`. For static options consider reusing `const` across your files.
|
|
298
297
|
|
|
299
298
|
```typescript
|
|
300
299
|
import { readFile } from "node:fs/promises";
|
|
301
300
|
import { defaultEndpointsFactory } from "express-zod-api";
|
|
302
301
|
|
|
303
302
|
const endpointsFactory = defaultEndpointsFactory.addOptions(async () => {
|
|
303
|
+
// caution: new connection on every request:
|
|
304
304
|
const db = mongoose.connect("mongodb://connection.string");
|
|
305
305
|
const privateKey = await readFile("private-key.pem", "utf-8");
|
|
306
306
|
return { db, privateKey };
|
|
307
307
|
});
|
|
308
308
|
```
|
|
309
309
|
|
|
310
|
+
**Notice on resources cleanup**: If necessary, you can release resources at the end of the request processing in a
|
|
311
|
+
custom [Result Handler](#response-customization):
|
|
312
|
+
|
|
313
|
+
```typescript
|
|
314
|
+
import { createResultHandler } from "express-zod-api";
|
|
315
|
+
|
|
316
|
+
const resultHandlerWithCleanup = createResultHandler({
|
|
317
|
+
handler: ({ options }) => {
|
|
318
|
+
// necessary to check for certain option presence:
|
|
319
|
+
if ("db" in options && options.db) {
|
|
320
|
+
options.db.connection.close(); // sample cleanup
|
|
321
|
+
}
|
|
322
|
+
},
|
|
323
|
+
});
|
|
324
|
+
```
|
|
325
|
+
|
|
310
326
|
## Using native express middlewares
|
|
311
327
|
|
|
312
328
|
There are two ways of connecting the native express middlewares depending on their nature and your objective.
|
|
@@ -1012,41 +1028,6 @@ const rawAcceptingEndpoint = defaultEndpointsFactory.build({
|
|
|
1012
1028
|
});
|
|
1013
1029
|
```
|
|
1014
1030
|
|
|
1015
|
-
## Resources cleanup
|
|
1016
|
-
|
|
1017
|
-
If some entities (database clients for example) do not care about automatically releasing their resources when their
|
|
1018
|
-
instances are destroyed, you can do the following. Return these instances in a middleware so that they become `options`
|
|
1019
|
-
for Endpoint's handler. Those `options` are also available as an argument to a Result Handler. Create your own one and
|
|
1020
|
-
clean up resources in accordance with the documentation of that software. The `options` may however be empty or
|
|
1021
|
-
incomplete in case of errors or failures, so it is necessary to check for their presence programmatically.
|
|
1022
|
-
|
|
1023
|
-
```typescript
|
|
1024
|
-
import {
|
|
1025
|
-
createResultHandler,
|
|
1026
|
-
EndpointsFactory,
|
|
1027
|
-
createMiddleware,
|
|
1028
|
-
} from "express-zod-api";
|
|
1029
|
-
|
|
1030
|
-
const resultHandlerWithCleanup = createResultHandler({
|
|
1031
|
-
handler: ({ options }) => {
|
|
1032
|
-
if ("dbClient" in options && options.dbClient) {
|
|
1033
|
-
(options.dbClient as DBClient).close(); // sample cleanup
|
|
1034
|
-
}
|
|
1035
|
-
// your implementation
|
|
1036
|
-
},
|
|
1037
|
-
});
|
|
1038
|
-
|
|
1039
|
-
const dbProvider = createMiddleware({
|
|
1040
|
-
handler: async () => ({
|
|
1041
|
-
dbClient: new DBClient(), // sample entity that requires cleanup
|
|
1042
|
-
}),
|
|
1043
|
-
});
|
|
1044
|
-
|
|
1045
|
-
const dbEquippedFactory = new EndpointsFactory(
|
|
1046
|
-
resultHandlerWithCleanup,
|
|
1047
|
-
).addMiddleware(dbProvider);
|
|
1048
|
-
```
|
|
1049
|
-
|
|
1050
1031
|
## Subscriptions
|
|
1051
1032
|
|
|
1052
1033
|
If you want the user of a client application to be able to subscribe to subsequent updates initiated by the server, the
|
package/SECURITY.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
| Version | Release | Supported |
|
|
6
6
|
| ------: | :------ | :----------------: |
|
|
7
|
-
| 19.x.x |
|
|
7
|
+
| 19.x.x | 05.2024 | :white_check_mark: |
|
|
8
8
|
| 18.x.x | 04.2024 | :white_check_mark: |
|
|
9
9
|
| 17.x.x | 02.2024 | :white_check_mark: |
|
|
10
10
|
| 16.x.x | 12.2023 | :white_check_mark: |
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var Oo=Object.create;var qe=Object.defineProperty;var Ao=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var
|
|
1
|
+
"use strict";var Oo=Object.create;var qe=Object.defineProperty;var Ao=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var Co=Object.getPrototypeOf,Io=Object.prototype.hasOwnProperty;var wo=(e,t)=>{for(var r in t)qe(e,r,{get:t[r],enumerable:!0})},Xt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Po(t))!Io.call(e,i)&&i!==r&&qe(e,i,{get:()=>t[i],enumerable:!(o=Ao(t,i))||o.enumerable});return e};var R=(e,t,r)=>(r=e!=null?Oo(Co(e)):{},Xt(t||!e||!e.__esModule?qe(r,"default",{value:e,enumerable:!0}):r,e)),Eo=e=>Xt(qe({},"__esModule",{value:!0}),e);var pi={};wo(pi,{AbstractEndpoint:()=>oe,DependsOnMethod:()=>he,Documentation:()=>ct,DocumentationError:()=>I,EndpointsFactory:()=>ge,InputValidationError:()=>j,Integration:()=>gt,MissingPeerError:()=>X,OutputValidationError:()=>V,RoutingError:()=>J,ServeStatic:()=>be,arrayEndpointsFactory:()=>Rr,arrayResultHandler:()=>nt,attachRouting:()=>kr,createConfig:()=>sr,createLogger:()=>it,createMiddleware:()=>rt,createResultHandler:()=>ot,createServer:()=>jr,defaultEndpointsFactory:()=>Sr,defaultResultHandler:()=>ye,ez:()=>So,getExamples:()=>H,getMessageFromError:()=>U,getStatusCodeFromError:()=>Ze,testEndpoint:()=>so});module.exports=Eo(pi);var ir=require("ramda"),Me=require("zod");var er=require("http-errors"),tr=require("crypto"),ce=require("ramda"),rr=require("zod");var J=class extends Error{name="RoutingError"},I=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
|
|
2
2
|
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},q=class extends Error{name="IOSchemaError"},V=class extends q{name="OutputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},j=class extends q{name="InputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},W=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},X=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var N={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var zo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(N.upload);return"files"in e&&r},xt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Zo=["body","query","params"],bt=e=>e.method.toLowerCase(),Tt=e=>e.startsWith("x-"),No=e=>(0,ce.pickBy)((0,ce.flip)(Tt),e),or=(e,t={})=>{let r=bt(e);return r==="options"?{}:(t[r]||xt[r]||Zo).filter(o=>o==="files"?zo(e):!0).map(o=>o==="headers"?No(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},le=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),U=e=>e instanceof rr.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Ze=e=>(0,er.isHttpError)(e)?e.statusCode:e instanceof j?400:500,St=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},ee=(e,t,r)=>e.length&&t.length?(0,ce.xprod)(e,t).map(r):e.concat(t),Ne=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Rt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};var xr=require("ramda");var re=e=>F(e)&&"or"in e,fe=e=>F(e)&&"and"in e,Pt=e=>({and:(0,xr.chain)(t=>fe(t)?t.and:[t],e)}),Xe=(e,t)=>fe(e)?{and:e.and.map(r=>re(r)?{or:r.or.map(t)}:t(r))}:re(e)?{or:e.or.map(r=>fe(r)?{and:r.and.map(t)}:t(r))}:t(e),It=e=>e.and.reduce((t,r)=>({or:ee(t.or,re(r)?r.or:[r],Pt)}),{or:[]}),ue=(e,t)=>fe(e)?re(t)?ue(It(e),t):Pt([e,t]):re(e)?fe(t)?ue(t,e):re(t)?{or:ee(e.or,t.or,Pt)}:ue(e,{and:[t]}):fe(t)||re(t)?ue(t,e):{and:[e,t]};var oe=class{},tt=class extends oe{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:u,shortDescription:m}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:u,short:m},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,Ct.default)(!Je(T),new q(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:Object.freeze(Ot(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[me.positive]})),negative:Object.freeze(Ot(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[me.negative]}))};for(let[y,T]of Object.entries(this.#t))(0,Ct.default)(T.length,new W(`ResultHandler must have at least one ${y} response schema specified.`));this.#i=gr(r)?"upload":hr(r)?"raw":"json",this.#s={input:Object.freeze([N[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:y})=>y)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:y})=>y))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ue(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof et.z.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof et.z.ZodError?new j(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof et.z.ZodError?new j(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){We({logger:i,response:o,error:new W(le(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=bt(t),p={},d=null,c=null;if(i.cors){let m=this.#m(s);typeof i.cors=="function"&&(m=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:m}));for(let y in m)r.set(y,m[y])}let u=or(t,i.inputSources);try{if(await this.#f({method:a,input:u,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:u,logger:o,options:p}))}catch(m){c=le(m)}await this.#g({input:u,output:d,request:t,response:r,error:c,logger:o,options:p})}};var wt=require("zod");var br=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>nr(s,i),o)};var Tr=O(require("assert/strict"),1),rt=e=>((0,Tr.default)(!Je(e.input),new q("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var M=require("zod");var ot=e=>e,ye=ot({getPositiveResponse:e=>{let t=H({schema:e}),r=M.z.object({status:M.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>M.z.object({status:M.z.literal("error"),error:M.z.object({message:M.z.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(me.positive).json({status:"success",data:r});return}let a=Ze(e);St({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),nt=ot({getPositiveResponse:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof M.z.ZodArray?e.shape.items:M.z.array(M.z.any());return t.reduce((o,i)=>F(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>M.z.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Ze(r);St({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(me.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var ge=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:wt.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,m=>{if(m&&m instanceof Error)return c(o(m));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(rt({input:wt.z.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,u="methods"in p?p.methods:[p.method],m=typeof a=="function"?a:()=>a,y="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],T="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new tt({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:y,tags:T,methods:u,getOperationId:m,description:i,shortDescription:s,inputSchema:br(d,t)})}},Sr=new ge(ye),Rr=new ge(nt);var Or=require("util");var Ar=require("ramda"),L=require("ansis"),Et={debug:10,info:20,warn:30,error:40},Pr=e=>F(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),it=({level:e,color:t=new L.Ansis().isSupported(),depth:r=2})=>{let o={debug:L.blue,info:L.green,warn:(0,L.hex)("#FFA500"),error:L.red},i=e==="debug",s=e==="silent"?100:Et[e],a=(p,d,c)=>{if(Et[p]<s)return;let u=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&u.push((0,Or.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Ar.mapObjIndexed)(({},p)=>(d,c)=>a(p,d,c),Et)};var xe=require("ramda"),he=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,xe.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,xe.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,xe.tail)(this.pairs).map(([r])=>r))}};var Ir=O(require("express"),1),be=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Ir.default.static(...this.params))}};var st=O(require("express"),1),Mr=O(require("http"),1),Lr=O(require("https"),1);var ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>require(e)[t])}catch{}throw new X(e)},Cr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await ne(t,r)}catch{}throw new X(e.map(({moduleName:t})=>t))};var zt=O(require("assert/strict"),1);var ie=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){zt.default.doesNotMatch(a,/\//,new J(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof oe){let c=p.getMethods().slice();i&&c.push("options");for(let u of c)t(p,d,u)}else if(p instanceof be)r&&p.apply(d,r);else if(p instanceof he){for(let[c,u]of p.pairs)(0,zt.default)(u.getMethods().includes(c),new J(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(u,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else ie({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Zt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>ie({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,u)=>s.execute({request:c,response:u,logger:u.locals[g]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});var De=O(require("http-errors"),1);var wr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:(0,De.isHttpError)(r)?r:(0,De.default)(400,le(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},Er=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,De.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){We({response:o,logger:s,error:new W(le(a).message,i)})}},Bo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},qo=e=>({log:e.debug.bind(e)}),zr=async({rootLogger:e,config:t})=>{let r=await ne("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let u=d.locals[g]?.logger||e;try{await i?.({request:p,logger:u})}catch(m){return c(m)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:qo(u)})(p,d,c)}),o&&a.push(Bo(o)),a},Zr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Nr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var E=require("ansis"),vr=()=>{let e=(0,E.italic)("Proudly supports transgender community.".padStart(109)),t=(0,E.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,E.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,E.italic)("for Dime".padEnd(20)),i=(0,E.hex)("#F5A9B8"),s=(0,E.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(E.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(E.gray,12,13);return`
|
|
4
|
+
`,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},ee=(e,t,r)=>e.length&&t.length?(0,ce.xprod)(e,t).map(r):e.concat(t),Ne=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Rt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),M=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(Rt).join(""),Ve=e=>(0,tr.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),$e=(e,t)=>{try{return typeof e.parse(t)}catch{return}},F=e=>typeof e=="object"&&e!==null;var _e=require("ramda"),g=Symbol.for("express-zod-api"),Ge=e=>{let t=e.describe(e.description);return t._def[g]=(0,_e.clone)(t._def[g])||{examples:[]},t},nr=(e,t)=>{if(!(g in e._def))return t;let r=Ge(t);return r._def[g].examples=ee(r._def[g].examples,e._def[g].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,_e.mergeDeepRight)({...o},{...i}):i),r};var Mo=function(e){let t=Ge(this);return t._def[g].examples.push(e),t},vo=function(e){let t=Ge(this);return t._def[g].defaultLabel=e,t},Lo=function(e){return new Me.z.ZodBranded({typeName:Me.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...(0,ir.clone)(this._def[g]),brand:e}})};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Me.z.ZodType.prototype,{example:{get(){return Mo.bind(this)}},brand:{set(){},get(){return Lo.bind(this)}}}),Object.defineProperty(Me.z.ZodDefault.prototype,"label",{get(){return vo.bind(this)}}));function sr(e){return e}var It=R(require("assert/strict"),1),et=require("zod");var ar=require("zod"),me={positive:200,negative:400},Ot=(e,t)=>e instanceof ar.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));var fr=require("zod");var dr=require("zod");var ve=require("zod"),$=Symbol("File"),pr=ve.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Do={buffer:()=>pr.brand($),string:()=>ve.z.string().brand($),binary:()=>pr.or(ve.z.string()).brand($),base64:()=>ve.z.string().base64().brand($)};function Ye(e){return Do[e||"string"]()}var te=Symbol("Raw"),cr=(e={})=>dr.z.object({raw:Ye("buffer")}).extend(e).brand(te);var lr=require("zod"),Le=Symbol("Upload"),mr=()=>lr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Le);var At=({schema:{options:e},next:t})=>e.some(t),yr=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),ko=({schema:e,next:t})=>Object.values(e.shape).some(t),ur=({schema:e,next:t})=>t(e.unwrap()),jo=({schema:e,next:t})=>t(e.innerType()),Uo=({schema:e,next:t})=>t(e.valueSchema),Ho=({schema:e,next:t})=>t(e.element),Fo=({schema:e,next:t})=>t(e._def.innerType),Ko={ZodObject:ko,ZodUnion:At,ZodDiscriminatedUnion:At,ZodIntersection:yr,ZodEffects:jo,ZodOptional:ur,ZodNullable:ur,ZodRecord:Uo,ZodArray:Ho,ZodDefault:Fo},Qe=({subject:e,condition:t,rules:r=Ko,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Qe({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},Je=e=>Qe({subject:e,maxDepth:3,rules:{ZodUnion:At,ZodIntersection:yr},condition:t=>t instanceof fr.z.ZodEffects&&t._def.effect.type!=="refinement"}),gr=e=>Qe({subject:e,condition:t=>t._def[g]?.brand===Le}),hr=e=>Qe({subject:e,condition:t=>t._def[g]?.brand===te,maxDepth:3});var We=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
5
|
+
Original error: ${e.originalError.message}.`:""))};var xr=require("ramda");var re=e=>F(e)&&"or"in e,fe=e=>F(e)&&"and"in e,Pt=e=>({and:(0,xr.chain)(t=>fe(t)?t.and:[t],e)}),Xe=(e,t)=>fe(e)?{and:e.and.map(r=>re(r)?{or:r.or.map(t)}:t(r))}:re(e)?{or:e.or.map(r=>fe(r)?{and:r.and.map(t)}:t(r))}:t(e),Ct=e=>e.and.reduce((t,r)=>({or:ee(t.or,re(r)?r.or:[r],Pt)}),{or:[]}),ue=(e,t)=>fe(e)?re(t)?ue(Ct(e),t):Pt([e,t]):re(e)?fe(t)?ue(t,e):re(t)?{or:ee(e.or,t.or,Pt)}:ue(e,{and:[t]}):fe(t)||re(t)?ue(t,e):{and:[e,t]};var oe=class{},tt=class extends oe{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:l=[],description:u,shortDescription:m}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(l),this.#e={long:u,short:m},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,It.default)(!Je(T),new q(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:Object.freeze(Ot(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[me.positive]})),negative:Object.freeze(Ot(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[me.negative]}))};for(let[y,T]of Object.entries(this.#t))(0,It.default)(T.length,new W(`ResultHandler must have at least one ${y} response schema specified.`));this.#i=gr(r)?"upload":hr(r)?"raw":"json",this.#s={input:Object.freeze([N[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:y})=>y)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:y})=>y))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ue(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof et.z.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(l){throw l instanceof et.z.ZodError?new j(l):l}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof et.z.ZodError?new j(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){We({logger:i,response:o,error:new W(le(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=bt(t),p={},d=null,l=null;if(i.cors){let m=this.#m(s);typeof i.cors=="function"&&(m=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:m}));for(let y in m)r.set(y,m[y])}let u=or(t,i.inputSources);try{if(await this.#f({method:a,input:u,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:u,logger:o,options:p}))}catch(m){l=le(m)}await this.#g({input:u,output:d,request:t,response:r,error:l,logger:o,options:p})}};var wt=require("zod");var br=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>nr(s,i),o)};var Tr=R(require("assert/strict"),1),rt=e=>((0,Tr.default)(!Je(e.input),new q("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var v=require("zod");var ot=e=>e,ye=ot({getPositiveResponse:e=>{let t=H({schema:e}),r=v.z.object({status:v.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>v.z.object({status:v.z.literal("error"),error:v.z.object({message:v.z.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(me.positive).json({status:"success",data:r});return}let a=Ze(e);St({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),nt=ot({getPositiveResponse:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.z.ZodArray?e.shape.items:v.z.array(v.z.any());return t.reduce((o,i)=>F(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>v.z.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Ze(r);St({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(me.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var ge=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:wt.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,l)=>{t(a,p,m=>{if(m&&m instanceof Error)return l(o(m));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(rt({input:wt.z.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:l}=this,u="methods"in p?p.methods:[p.method],m=typeof a=="function"?a:()=>a,y="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],T="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new tt({handler:r,middlewares:d,outputSchema:o,resultHandler:l,scopes:y,tags:T,methods:u,getOperationId:m,description:i,shortDescription:s,inputSchema:br(d,t)})}},Sr=new ge(ye),Rr=new ge(nt);var Or=require("util");var Ar=require("ramda"),L=require("ansis"),Et={debug:10,info:20,warn:30,error:40},Pr=e=>F(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),it=({level:e,color:t=new L.Ansis().isSupported(),depth:r=2})=>{let o={debug:L.blue,info:L.green,warn:(0,L.hex)("#FFA500"),error:L.red},i=e==="debug",s=e==="silent"?100:Et[e],a=(p,d,l)=>{if(Et[p]<s)return;let u=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];l!==void 0&&u.push((0,Or.inspect)(l,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Ar.mapObjIndexed)(({},p)=>(d,l)=>a(p,d,l),Et)};var xe=require("ramda"),he=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,xe.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,xe.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,xe.tail)(this.pairs).map(([r])=>r))}};var Cr=R(require("express"),1),be=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Cr.default.static(...this.params))}};var st=R(require("express"),1),vr=R(require("http"),1),Lr=R(require("https"),1);var ne=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>R(require(e))))[t]}catch{}throw new X(e)},Ir=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await ne(t,r)}catch{}throw new X(e.map(({moduleName:t})=>t))};var zt=R(require("assert/strict"),1);var ie=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){zt.default.doesNotMatch(a,/\//,new J(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof oe){let l=p.getMethods().slice();i&&l.push("options");for(let u of l)t(p,d,u)}else if(p instanceof be)r&&p.apply(d,r);else if(p instanceof he){for(let[l,u]of p.pairs)(0,zt.default)(u.getMethods().includes(l),new J(`Endpoint assigned to ${l} method of ${d} must support ${l} method.`)),t(u,d,l);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else ie({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Zt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>ie({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(l,u)=>s.execute({request:l,response:u,logger:u.locals[g]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});var De=R(require("http-errors"),1);var wr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:(0,De.isHttpError)(r)?r:(0,De.default)(400,le(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},Er=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,De.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){We({response:o,logger:s,error:new W(le(a).message,i)})}},Bo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},qo=e=>({log:e.debug.bind(e)}),zr=async({rootLogger:e,config:t})=>{let r=await ne("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,l)=>{let u=d.locals[g]?.logger||e;try{await i?.({request:p,logger:u})}catch(m){return l(m)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:qo(u)})(p,d,l)}),o&&a.push(Bo(o)),a},Zr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Nr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var E=require("ansis"),Mr=()=>{let e=(0,E.italic)("Proudly supports transgender community.".padStart(109)),t=(0,E.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,E.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,E.italic)("for Dime".padEnd(20)),i=(0,E.hex)("#F5A9B8"),s=(0,E.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(E.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(E.gray,12,13);return`
|
|
6
6
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
7
7
|
888 d88P 888 d88888 888 Y88b 888
|
|
8
8
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -16,8 +16,8 @@ Original error: ${e.originalError.message}.`:""))};var xr=require("ramda");var r
|
|
|
16
16
|
${o}888${t}
|
|
17
17
|
${r}
|
|
18
18
|
`.split(`
|
|
19
|
-
`).map((d,
|
|
20
|
-
`)};var Dr=e=>{e.startupLogo!==!1&&console.log(vr());let t={errorHandler:e.errorHandler||ye,rootLogger:Pr(e.logger)?it(e.logger):e.logger};t.rootLogger.debug("Running","v19.0.0-beta.4 (CJS)");let r=Er(t),o=wr(t);return{...t,notFoundHandler:r,parserFailureHandler:o}},kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=Dr(e);return Zt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},jr=async(e,t)=>{let r=(0,st.default)().disable("x-powered-by"),{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=Dr(e);if(r.use(Nr({rootLogger:o,config:e})),e.server.compression){let c=await ne("compression");r.use(c(typeof e.server.compression=="object"?e.server.compression:void 0))}let a={json:[e.server.jsonParser||st.default.json()],raw:[e.server.rawParser||st.default.raw(),Zr],upload:e.server.upload?await zr({config:e,rootLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),Zt({app:r,routing:t,rootLogger:o,config:e,parsers:a}),r.use(s,i);let p=(c,u)=>c.listen(u,()=>{o.info("Listening",u)}),d={httpServer:p(Mr.default.createServer(r),e.server.listen),httpsServer:e.https?p(Lr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...d,logger:o}};var no=O(require("assert/strict"),1),io=require("openapi3-ts/oas31");var K=O(require("assert/strict"),1),_=require("openapi3-ts/oas31"),l=require("ramda"),b=require("zod");var Te=require("zod");var at=e=>!isNaN(e.getTime());var ke=Symbol("DateIn"),Ur=()=>Te.z.union([Te.z.string().date(),Te.z.string().datetime(),Te.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Te.z.date().refine(at)).brand(ke);var Hr=require("zod");var je=Symbol("DateOut"),Fr=()=>Hr.z.date().refine(at).transform(e=>e.toISOString()).brand(je);var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:u=>se({schema:u,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),c=t&&t({schema:e,prev:d,...a});return c?{...d,...c}:d};var Kr=50,qr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Vo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vr=/:([A-Za-z0-9_]+)/g,$r=e=>e.match(Vr)?.map(t=>t.slice(1))||[],_r=e=>e.replace(Vr,t=>`{${t.slice(1)}}`),$o=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[g]?.defaultLabel||e._def.defaultValue()}),_o=({schema:{_def:{innerType:e}},next:t})=>t(e),Go=()=>({format:"any"}),Yo=e=>((0,K.default)(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Qo=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof b.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Jo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Wo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Xo=e=>{let[t,r]=e.filter(i=>!(0,_.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,K.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,l.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,l.concat)(i,s):i===s?s:K.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,l.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,l.mergeDeepRight)(i,s))),o},en=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Xo(o)}catch{}return{allOf:o}},tn=({schema:e,next:t})=>t(e.unwrap()),rn=({schema:e,next:t})=>t(e._def.innerType),on=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=Yr(r)),r},Gr=e=>{let t=(0,l.toLower)((0,l.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Br=({schema:e})=>({type:Gr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),nn=({schema:{value:e}})=>({type:Gr(e),const:e}),sn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ne(p)?p instanceof b.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=pt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},an=()=>({type:"null"}),pn=e=>((0,K.default)(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:qr}}),dn=e=>((0,K.default)(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:qr}}),cn=e=>K.default.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),ln=()=>({type:"boolean"}),mn=()=>({type:"integer",format:"bigint"}),un=e=>e.every(t=>t instanceof b.z.ZodLiteral),fn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof b.z.ZodEnum||e instanceof b.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=pt({schema:b.z.object((0,l.fromPairs)((0,l.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof b.z.ZodLiteral)return{type:"object",properties:pt({schema:b.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof b.z.ZodUnion&&un(e.options)){let o=(0,l.map)(s=>`${s.value}`,e.options),i=(0,l.fromPairs)((0,l.xprod)(o,[t]));return{type:"object",properties:pt({schema:b.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},yn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},gn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),hn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:u,_def:{checks:m}}})=>{let y=m.find(R=>R.kind==="regex"),T=m.find(R=>R.kind==="datetime"),S=y?y.regex:T?T.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,A={type:"string"},x={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in x)if(x[R]){A.format=R;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),S&&(A.pattern=S.source),A},xn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},pt=({schema:{shape:e},next:t})=>(0,l.map)(t,e),bn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Vo?.[t]},Yr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Tn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=$e(e,bn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(b.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Sn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Rn=({schema:e,next:t})=>t(e.unwrap()),On=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},An=({next:e,schema:t})=>e(t.unwrap().shape.raw),Qr=e=>e.length?(0,l.fromPairs)((0,l.zip)((0,l.range)(1,e.length+1).map(t=>`example${t}`),(0,l.map)((0,l.objOf)("value"),e))):void 0,Jr=(e,t,r=[])=>(0,l.pipe)(H,(0,l.map)((0,l.when)((0,l.both)(F,(0,l.complement)(Array.isArray)),(0,l.omit)(r))),Qr)({schema:e,variant:t?"parsed":"original",validate:!0}),Pn=(e,t)=>(0,l.pipe)(H,(0,l.filter)((0,l.has)(t)),(0,l.pluck)(t),Qr)({schema:e,variant:"original",validate:!0}),Se=(e,t)=>e instanceof b.z.ZodObject?e:e instanceof b.z.ZodBranded?Se(e.unwrap(),t):e instanceof b.z.ZodUnion||e instanceof b.z.ZodDiscriminatedUnion?e.options.map(r=>Se(r,t)).reduce((r,o)=>r.merge(o.partial()),b.z.object({})):e instanceof b.z.ZodEffects?((0,K.default)(e._def.effect.type==="refinement",t),Se(e._def.schema,t)):Se(e._def.left,t).merge(Se(e._def.right,t)),Wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=Se(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=$r(e),m=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=x=>y&&u.includes(x),A=x=>T&&Tt(x);return Object.keys(c).filter(x=>m||S(x)).map(x=>{let R=se({schema:c[x],isResponse:!1,rules:vt,onEach:Mt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Pe=p==="components"?a(v(d,x),R):R;return{name:x,in:S(x)?"path":A(x)?"header":"query",required:!c[x].isOptional(),description:R.description||d,schema:Pe,examples:Pn(r,x)}})},vt={ZodString:hn,ZodNumber:xn,ZodBigInt:mn,ZodBoolean:ln,ZodNull:an,ZodArray:yn,ZodTuple:gn,ZodRecord:fn,ZodObject:sn,ZodLiteral:nn,ZodIntersection:en,ZodUnion:Jo,ZodAny:Go,ZodDefault:$o,ZodEnum:Br,ZodNativeEnum:Br,ZodEffects:Tn,ZodOptional:tn,ZodNullable:on,ZodDiscriminatedUnion:Wo,ZodBranded:Rn,ZodDate:cn,ZodCatch:_o,ZodPipeline:Sn,ZodLazy:On,ZodReadonly:rn,[$]:Qo,[Le]:Yo,[je]:dn,[ke]:pn,[te]:An},Mt=({schema:e,isResponse:t,prev:r})=>{if((0,_.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof b.z.ZodLazy,s=r.type!==void 0,a=t&&Ne(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Yr(r)),d.length&&(c.examples=d.slice()),c},Lt=({schema:e,...t})=>K.default.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Nt=(e,t)=>{if((0,_.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,l.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,l.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Nt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Nt(o,t))),r},Xr=e=>(0,_.isReferenceObject)(e)?e:(0,l.omit)(["examples"],e),eo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:u,description:m=`${e.toUpperCase()} ${t} ${Rt(i)} response ${c?u:""}`.trim()})=>{let y=Xr(se({schema:r,isResponse:!0,rules:vt,onEach:Mt,onMissing:Lt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(v(m),y):y,examples:Jr(r,!0)};return{description:m,content:(0,l.fromPairs)((0,l.xprod)(o,[T]))}},In=()=>({type:"http",scheme:"basic"}),Cn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},wn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},En=({name:e})=>({type:"apiKey",in:"header",name:e}),zn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Zn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Nn=({flows:e={}})=>({type:"oauth2",flows:(0,l.map)(t=>({...t,scopes:t.scopes||{}}),(0,l.reject)(l.isNil,e))}),to=(e,t)=>{let r={basic:In,bearer:Cn,input:wn,header:En,cookie:zn,openid:Zn,oauth2:Nn};return Xe(e,o=>r[o.type](o,t))},dt=e=>"or"in e?e.or.map(t=>"and"in t?(0,l.mergeAll)((0,l.map)(({name:r,scopes:o})=>(0,l.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?dt(It(e)):dt({or:[e]}),ro=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=$r(t),u=Xr(Nt(se({schema:r,isResponse:!1,rules:vt,onEach:Mt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(v(d),u):u,examples:Jr(r,!1,c)};return{description:d,content:(0,l.fromPairs)((0,l.xprod)(o,[m]))}},oo=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Dt=e=>e.length<=Kr?e:e.slice(0,Kr-1)+"\u2026";var ct=class extends io.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||v(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&no.default.fail(new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=Ve}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});ie({routing:t,onEndpoint:(m,y,T)=>{let S=T,A={path:y,method:S,endpoint:m,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[x,R]=["short","long"].map(m.getDescription.bind(m)),Pe=x?Dt(x):p&&R?Dt(R):void 0,He=m.getTags(),Ie=r.inputSources?.[S]||xt[S],pe=this.ensureUniqOperationId(y,S,m.getOperationId(S)),Fe=Wr({...A,inputSources:Ie,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),Ke={};for(let k of["positive","negative"]){let Q=m.getResponses(k);for(let{mimeTypes:Ce,schema:P,statusCodes:I}of Q)for(let w of I)Ke[w]=eo({...A,variant:k,schema:P,mimeTypes:Ce,statusCode:w,hasMultipleStatusCodes:Q.length>1||I.length>1,description:a?.[`${k}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:w})})}let ht=Ie.includes("body")?ro({...A,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,Be=dt(Xe(to(m.getSecurity(),Ie),k=>{let Q=this.ensureUniqSecuritySchemaName(k),Ce=["oauth2","openIdConnect"].includes(k.type)?m.getScopes().slice():[];return this.addSecurityScheme(Q,k),{name:Q,scopes:Ce}}));this.addPath(_r(y),{[S]:{operationId:pe,summary:Pe,description:R,tags:He.length>0?He:void 0,parameters:Fe.length>0?Fe:void 0,requestBody:ht,security:Be.length>0?Be:void 0,responses:Ke}})}}),this.rootDoc.tags=r.tags?oo(r.tags):[]}};var kt=O(require("http"),1);var vn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),Mn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},Ln=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),so=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Cr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=vn({fnMethod:a,requestProps:t}),d=Mn({fnMethod:a,responseProps:r}),c=Ln({fnMethod:a,loggerProps:i}),u={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:u,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};var z=O(require("typescript"),1);var D=O(require("typescript"),1),Re=require("ramda"),n=D.default.factory,G=[n.createModifier(D.default.SyntaxKind.ExportKeyword)],Dn=[n.createModifier(D.default.SyntaxKind.AsyncKeyword)],kn=[n.createModifier(D.default.SyntaxKind.PublicKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],ao=[n.createModifier(D.default.SyntaxKind.ProtectedKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],jt=n.createTemplateHead(""),Oe=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Ht=e=>n.createTemplateLiteralType(jt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Oe:Ut))),Ft=Ht(["M","P"]),lt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),mt=(e,t)=>(0,Re.chain)(([r,o])=>[lt(n.createIdentifier(r),o,t)],(0,Re.toPairs)(e)),Kt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),po=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),co=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Y=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.default.NodeFlags.Const),Bt=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ut=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,t),lo=(e,t,r)=>n.createPropertyDeclaration(kn,e,void 0,t,r),mo=(e,t,r)=>n.createClassDeclaration(G,e,void 0,void 0,[t,...r]),uo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),fo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.default.SyntaxKind.AnyKeyword)]),yo=(e,t,r)=>n.createInterfaceDeclaration(G,e,void 0,t,r),go=e=>(0,Re.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Re.toPairs)(e)),qt=(e,t,r)=>n.createArrowFunction(r?Dn:void 0,void 0,e.map(o=>lt(o)),void 0,void 0,t),Vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,mt({acc:void 0,key:void 0}),void 0,void 0,t),r]),ho=(...e)=>`"${e.join(" ")}"`;var xo=["get","post","put","delete","patch"];var h=O(require("typescript"),1),yt=require("zod");var B=O(require("typescript"),1),{factory:ft}=B.default,$t=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ae=(e,t,r)=>{let o=ft.createTypeAliasDeclaration(void 0,ft.createIdentifier(t),void 0,e);return r&&$t(o,r),o},_t=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},jn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,bo=e=>jn.test(e)?ft.createIdentifier(e):ft.createStringLiteral(e);var{factory:f}=h.default,Un={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Hn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),Fn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ne(a)?a instanceof yt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,bo(s),p&&o?f.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&$t(d,a.description),d});return f.createTypeLiteralNode(i)},Kn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Bn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),To=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),qn=e=>Un?.[e.kind],Vn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=$e(e,qn(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},$n=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),_n=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},Gn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Yn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Qn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Jn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Wn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),Xn=({next:e,schema:t})=>e(t.unwrap()),ei=({next:e,schema:t})=>e(t._def.innerType),ti=({next:e,schema:t})=>e(t._def.innerType),ri=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),oi=()=>f.createLiteralTypeNode(f.createNull()),ni=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},ii=({schema:e})=>{let t=e.unwrap(),r=f.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),i=f.createUnionTypeNode([r,o]);return t instanceof yt.z.ZodString?r:t instanceof yt.z.ZodUnion?i:o},si=({next:e,schema:t})=>e(t.unwrap().shape.raw),ai={ZodString:ae(h.default.SyntaxKind.StringKeyword),ZodNumber:ae(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(h.default.SyntaxKind.BooleanKeyword),ZodAny:ae(h.default.SyntaxKind.AnyKeyword),[ke]:ae(h.default.SyntaxKind.StringKeyword),[je]:ae(h.default.SyntaxKind.StringKeyword),ZodNull:oi,ZodArray:Kn,ZodTuple:Yn,ZodRecord:Qn,ZodObject:Fn,ZodLiteral:Hn,ZodIntersection:Jn,ZodUnion:To,ZodDefault:Wn,ZodEnum:Bn,ZodNativeEnum:$n,ZodEffects:Vn,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:To,ZodBranded:Xn,ZodCatch:ti,ZodPipeline:ri,ZodLazy:ni,ZodReadonly:ei,[$]:ii,[te]:si},Ue=({schema:e,...t})=>se({schema:e,rules:ai,onMissing:()=>f.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),...t});var gt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ae(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Ve,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(P,I,w)=>{let de={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},we=v(w,I,"input"),Ee=Ue({...de,schema:P.getSchema("input"),isResponse:!1}),Z=i?v(w,I,"positive.response"):void 0,Gt=P.getSchema("positive"),Yt=i?Ue({...de,isResponse:!0,schema:Gt}):void 0,ze=i?v(w,I,"negative.response"):void 0,Qt=P.getSchema("negative"),Jt=i?Ue({...de,isResponse:!0,schema:Qt}):void 0,Wt=v(w,I,"response"),Ro=Z&&ze?n.createUnionTypeNode([n.createTypeReferenceNode(Z),n.createTypeReferenceNode(ze)]):Ue({...de,isResponse:!0,schema:Gt.or(Qt)});this.program.push(Ae(Ee,we)),Yt&&Z&&this.program.push(Ae(Yt,Z)),Jt&&ze&&this.program.push(Ae(Jt,ze)),this.program.push(Ae(Ro,Wt)),w!=="options"&&(this.paths.push(I),this.registry.set({method:w,path:I},{input:we,positive:Z,negative:ze,response:Wt,isJson:P.getMimeTypes("positive").includes(N.json),tags:P.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Bt(this.ids.pathType,this.paths)),this.program.push(Bt(this.ids.methodType,xo)),this.program.push(ut(this.ids.methodPathType,Ht([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.default.SyntaxKind.ExtendsKeyword,[Kt(this.ids.methodPathType,z.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:P,path:I},{isJson:w,tags:de,...we}]of this.registry){let Ee=ho(P,I);for(let Z of this.interfaces)Z.kind in we&&Z.props.push(co(Ee,we[Z.kind]));r!=="types"&&(w&&p.push(n.createPropertyAssignment(Ee,n.createTrue())),d.push(n.createPropertyAssignment(Ee,n.createArrayLiteralExpression(de.map(Z=>n.createStringLiteral(Z))))))}for(let{id:P,props:I}of this.interfaces)this.program.push(yo(P,a,I));if(r==="types")return;let c=n.createVariableStatement(G,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),u=n.createVariableStatement(G,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),m=ut(this.ids.providerType,n.createFunctionTypeNode(go({M:this.ids.methodType,P:this.ids.pathType}),mt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ft)}),uo(this.ids.responseInterface,Ft))),y=ut(this.ids.implementationType,n.createFunctionTypeNode(void 0,mt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.default.SyntaxKind.StringKeyword),params:Kt(z.default.SyntaxKind.StringKeyword,z.default.SyntaxKind.AnyKeyword)}),fo())),T=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Oe)]),S=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[T,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),A=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[T]),z.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),x=mo(this.ids.clientClass,po([lt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),ao)]),[lo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,S,A]),!0))]);this.program.push(c,u,m,y,x);let R=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Pe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),He=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),Ie=n.createVariableStatement(void 0,Y(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Oe)]),n.createObjectLiteralExpression([R,Pe,He])])))),pe=n.createVariableStatement(void 0,Y(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Fe=n.createVariableStatement(void 0,Y(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Oe)])))),[Ke,ht]=["json","text"].map(P=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,P),void 0,void 0))),Be=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(jt,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Oe)]),z.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Ke])),k=n.createVariableStatement(G,Y(this.ids.exampleImplementationConst,qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([pe,Fe,Ie,Be,ht]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Ce=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(k,Ce,Q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
|
|
19
|
+
`).map((d,l)=>a[l]?a[l](d):d).join(`
|
|
20
|
+
`)};var Dr=e=>{e.startupLogo!==!1&&console.log(Mr());let t=e.errorHandler||ye,r=Pr(e.logger)?it(e.logger):e.logger;r.debug("Running","v19.0.0 (CJS)");let o=Nr({rootLogger:r,config:e}),i=Er({rootLogger:r,errorHandler:t}),s=wr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=Dr(e);return Zt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},jr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=Dr(e),a=(0,st.default)().disable("x-powered-by").use(s);if(e.server.compression){let u=await ne("compression");a.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||st.default.json()],raw:[e.server.rawParser||st.default.raw(),Zr],upload:e.server.upload?await zr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Zt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(u,m)=>u.listen(m,()=>{r.info("Listening",m)}),l={httpServer:d(vr.default.createServer(a),e.server.listen),httpsServer:e.https?d(Lr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...l,logger:r}};var no=R(require("assert/strict"),1),io=require("openapi3-ts/oas31");var K=R(require("assert/strict"),1),_=require("openapi3-ts/oas31"),c=require("ramda"),b=require("zod");var Te=require("zod");var at=e=>!isNaN(e.getTime());var ke=Symbol("DateIn"),Ur=()=>Te.z.union([Te.z.string().date(),Te.z.string().datetime(),Te.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Te.z.date().refine(at)).brand(ke);var Hr=require("zod");var je=Symbol("DateOut"),Fr=()=>Hr.z.date().refine(at).transform(e=>e.toISOString()).brand(je);var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:u=>se({schema:u,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),l=t&&t({schema:e,prev:d,...a});return l?{...d,...l}:d};var Kr=50,qr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Vo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vr=/:([A-Za-z0-9_]+)/g,$r=e=>e.match(Vr)?.map(t=>t.slice(1))||[],_r=e=>e.replace(Vr,t=>`{${t.slice(1)}}`),$o=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[g]?.defaultLabel||e._def.defaultValue()}),_o=({schema:{_def:{innerType:e}},next:t})=>t(e),Go=()=>({format:"any"}),Yo=e=>((0,K.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Qo=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof b.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Jo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Wo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Xo=e=>{let[t,r]=e.filter(i=>!(0,_.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,K.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:K.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},en=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Xo(o)}catch{}return{allOf:o}},tn=({schema:e,next:t})=>t(e.unwrap()),rn=({schema:e,next:t})=>t(e._def.innerType),on=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=Yr(r)),r},Gr=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Br=({schema:e})=>({type:Gr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),nn=({schema:{value:e}})=>({type:Gr(e),const:e}),sn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ne(p)?p instanceof b.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=pt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},an=()=>({type:"null"}),pn=e=>((0,K.default)(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:qr}}),dn=e=>((0,K.default)(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:qr}}),cn=e=>K.default.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),ln=()=>({type:"boolean"}),mn=()=>({type:"integer",format:"bigint"}),un=e=>e.every(t=>t instanceof b.z.ZodLiteral),fn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof b.z.ZodEnum||e instanceof b.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=pt({schema:b.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof b.z.ZodLiteral)return{type:"object",properties:pt({schema:b.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof b.z.ZodUnion&&un(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:pt({schema:b.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},yn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},gn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),hn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:l,isDatetime:u,_def:{checks:m}}})=>{let y=m.find(O=>O.kind==="regex"),T=m.find(O=>O.kind==="datetime"),S=y?y.regex:T?T.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,A={type:"string"},x={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:l};for(let O in x)if(x[O]){A.format=O;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),S&&(A.pattern=S.source),A},xn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},pt=({schema:{shape:e},next:t})=>(0,c.map)(t,e),bn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Vo?.[t]},Yr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Tn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=$e(e,bn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(b.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Sn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Rn=({schema:e,next:t})=>t(e.unwrap()),On=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},An=({next:e,schema:t})=>e(t.unwrap().shape.raw),Qr=e=>e.length?(0,c.fromPairs)((0,c.zip)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e))):void 0,Jr=(e,t,r=[])=>(0,c.pipe)(H,(0,c.map)((0,c.when)((0,c.both)(F,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),Qr)({schema:e,variant:t?"parsed":"original",validate:!0}),Pn=(e,t)=>(0,c.pipe)(H,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),Qr)({schema:e,variant:"original",validate:!0}),Se=(e,t)=>e instanceof b.z.ZodObject?e:e instanceof b.z.ZodBranded?Se(e.unwrap(),t):e instanceof b.z.ZodUnion||e instanceof b.z.ZodDiscriminatedUnion?e.options.map(r=>Se(r,t)).reduce((r,o)=>r.merge(o.partial()),b.z.object({})):e instanceof b.z.ZodEffects?((0,K.default)(e._def.effect.type==="refinement",t),Se(e._def.schema,t)):Se(e._def.left,t).merge(Se(e._def.right,t)),Wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=Se(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=$r(e),m=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=x=>y&&u.includes(x),A=x=>T&&Tt(x);return Object.keys(l).filter(x=>m||S(x)).map(x=>{let O=se({schema:l[x],isResponse:!1,rules:Mt,onEach:vt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Pe=p==="components"?a(M(d,x),O):O;return{name:x,in:S(x)?"path":A(x)?"header":"query",required:!l[x].isOptional(),description:O.description||d,schema:Pe,examples:Pn(r,x)}})},Mt={ZodString:hn,ZodNumber:xn,ZodBigInt:mn,ZodBoolean:ln,ZodNull:an,ZodArray:yn,ZodTuple:gn,ZodRecord:fn,ZodObject:sn,ZodLiteral:nn,ZodIntersection:en,ZodUnion:Jo,ZodAny:Go,ZodDefault:$o,ZodEnum:Br,ZodNativeEnum:Br,ZodEffects:Tn,ZodOptional:tn,ZodNullable:on,ZodDiscriminatedUnion:Wo,ZodBranded:Rn,ZodDate:cn,ZodCatch:_o,ZodPipeline:Sn,ZodLazy:On,ZodReadonly:rn,[$]:Qo,[Le]:Yo,[je]:dn,[ke]:pn,[te]:An},vt=({schema:e,isResponse:t,prev:r})=>{if((0,_.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof b.z.ZodLazy,s=r.type!==void 0,a=t&&Ne(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),l={};return o&&(l.description=o),p&&(l.type=Yr(r)),d.length&&(l.examples=d.slice()),l},Lt=({schema:e,...t})=>K.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Nt=(e,t)=>{if((0,_.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Nt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Nt(o,t))),r},Xr=e=>(0,_.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),eo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:l,statusCode:u,description:m=`${e.toUpperCase()} ${t} ${Rt(i)} response ${l?u:""}`.trim()})=>{let y=Xr(se({schema:r,isResponse:!0,rules:Mt,onEach:vt,onMissing:Lt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(M(m),y):y,examples:Jr(r,!0)};return{description:m,content:(0,c.fromPairs)((0,c.xprod)(o,[T]))}},Cn=()=>({type:"http",scheme:"basic"}),In=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},wn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},En=({name:e})=>({type:"apiKey",in:"header",name:e}),zn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Zn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Nn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),to=(e,t)=>{let r={basic:Cn,bearer:In,input:wn,header:En,cookie:zn,openid:Zn,oauth2:Nn};return Xe(e,o=>r[o.type](o,t))},dt=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?dt(Ct(e)):dt({or:[e]}),ro=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let l=$r(t),u=Xr(Nt(se({schema:r,isResponse:!1,rules:Mt,onEach:vt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),l)),m={schema:p==="components"?a(M(d),u):u,examples:Jr(r,!1,l)};return{description:d,content:(0,c.fromPairs)((0,c.xprod)(o,[m]))}},oo=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Dt=e=>e.length<=Kr?e:e.slice(0,Kr-1)+"\u2026";var ct=class extends io.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||M(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&no.default.fail(new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:l=Ve}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});ie({routing:t,onEndpoint:(m,y,T)=>{let S=T,A={path:y,method:S,endpoint:m,composition:d,serializer:l,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[x,O]=["short","long"].map(m.getDescription.bind(m)),Pe=x?Dt(x):p&&O?Dt(O):void 0,He=m.getTags(),Ce=r.inputSources?.[S]||xt[S],pe=this.ensureUniqOperationId(y,S,m.getOperationId(S)),Fe=Wr({...A,inputSources:Ce,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),Ke={};for(let k of["positive","negative"]){let Q=m.getResponses(k);for(let{mimeTypes:Ie,schema:P,statusCodes:C}of Q)for(let w of C)Ke[w]=eo({...A,variant:k,schema:P,mimeTypes:Ie,statusCode:w,hasMultipleStatusCodes:Q.length>1||C.length>1,description:a?.[`${k}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:w})})}let ht=Ce.includes("body")?ro({...A,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,Be=dt(Xe(to(m.getSecurity(),Ce),k=>{let Q=this.ensureUniqSecuritySchemaName(k),Ie=["oauth2","openIdConnect"].includes(k.type)?m.getScopes().slice():[];return this.addSecurityScheme(Q,k),{name:Q,scopes:Ie}}));this.addPath(_r(y),{[S]:{operationId:pe,summary:Pe,description:O,tags:He.length>0?He:void 0,parameters:Fe.length>0?Fe:void 0,requestBody:ht,security:Be.length>0?Be:void 0,responses:Ke}})}}),this.rootDoc.tags=r.tags?oo(r.tags):[]}};var kt=R(require("http"),1);var Mn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),vn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},Ln=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),so=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Ir([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Mn({fnMethod:a,requestProps:t}),d=vn({fnMethod:a,responseProps:r}),l=Ln({fnMethod:a,loggerProps:i}),u={cors:!1,logger:l,...o};return await e.execute({request:p,response:d,config:u,logger:l}),{requestMock:p,responseMock:d,loggerMock:l}};var z=R(require("typescript"),1);var D=R(require("typescript"),1),Re=require("ramda"),n=D.default.factory,G=[n.createModifier(D.default.SyntaxKind.ExportKeyword)],Dn=[n.createModifier(D.default.SyntaxKind.AsyncKeyword)],kn=[n.createModifier(D.default.SyntaxKind.PublicKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],ao=[n.createModifier(D.default.SyntaxKind.ProtectedKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],jt=n.createTemplateHead(""),Oe=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Ht=e=>n.createTemplateLiteralType(jt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Oe:Ut))),Ft=Ht(["M","P"]),lt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),mt=(e,t)=>(0,Re.chain)(([r,o])=>[lt(n.createIdentifier(r),o,t)],(0,Re.toPairs)(e)),Kt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),po=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),co=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Y=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.default.NodeFlags.Const),Bt=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ut=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,t),lo=(e,t,r)=>n.createPropertyDeclaration(kn,e,void 0,t,r),mo=(e,t,r)=>n.createClassDeclaration(G,e,void 0,void 0,[t,...r]),uo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),fo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.default.SyntaxKind.AnyKeyword)]),yo=(e,t,r)=>n.createInterfaceDeclaration(G,e,void 0,t,r),go=e=>(0,Re.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Re.toPairs)(e)),qt=(e,t,r)=>n.createArrowFunction(r?Dn:void 0,void 0,e.map(o=>lt(o)),void 0,void 0,t),Vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,mt({acc:void 0,key:void 0}),void 0,void 0,t),r]),ho=(...e)=>`"${e.join(" ")}"`;var xo=["get","post","put","delete","patch"];var h=R(require("typescript"),1),yt=require("zod");var B=R(require("typescript"),1),{factory:ft}=B.default,$t=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ae=(e,t,r)=>{let o=ft.createTypeAliasDeclaration(void 0,ft.createIdentifier(t),void 0,e);return r&&$t(o,r),o},_t=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},jn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,bo=e=>jn.test(e)?ft.createIdentifier(e):ft.createStringLiteral(e);var{factory:f}=h.default,Un={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Hn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),Fn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ne(a)?a instanceof yt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,bo(s),p&&o?f.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&$t(d,a.description),d});return f.createTypeLiteralNode(i)},Kn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Bn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),To=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),qn=e=>Un?.[e.kind],Vn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=$e(e,qn(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},$n=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),_n=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},Gn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Yn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Qn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Jn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Wn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),Xn=({next:e,schema:t})=>e(t.unwrap()),ei=({next:e,schema:t})=>e(t._def.innerType),ti=({next:e,schema:t})=>e(t._def.innerType),ri=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),oi=()=>f.createLiteralTypeNode(f.createNull()),ni=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},ii=({schema:e})=>{let t=e.unwrap(),r=f.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),i=f.createUnionTypeNode([r,o]);return t instanceof yt.z.ZodString?r:t instanceof yt.z.ZodUnion?i:o},si=({next:e,schema:t})=>e(t.unwrap().shape.raw),ai={ZodString:ae(h.default.SyntaxKind.StringKeyword),ZodNumber:ae(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(h.default.SyntaxKind.BooleanKeyword),ZodAny:ae(h.default.SyntaxKind.AnyKeyword),[ke]:ae(h.default.SyntaxKind.StringKeyword),[je]:ae(h.default.SyntaxKind.StringKeyword),ZodNull:oi,ZodArray:Kn,ZodTuple:Yn,ZodRecord:Qn,ZodObject:Fn,ZodLiteral:Hn,ZodIntersection:Jn,ZodUnion:To,ZodDefault:Wn,ZodEnum:Bn,ZodNativeEnum:$n,ZodEffects:Vn,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:To,ZodBranded:Xn,ZodCatch:ti,ZodPipeline:ri,ZodLazy:ni,ZodReadonly:ei,[$]:ii,[te]:si},Ue=({schema:e,...t})=>se({schema:e,rules:ai,onMissing:()=>f.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),...t});var gt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ae(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Ve,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(P,C,w)=>{let de={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},we=M(w,C,"input"),Ee=Ue({...de,schema:P.getSchema("input"),isResponse:!1}),Z=i?M(w,C,"positive.response"):void 0,Gt=P.getSchema("positive"),Yt=i?Ue({...de,isResponse:!0,schema:Gt}):void 0,ze=i?M(w,C,"negative.response"):void 0,Qt=P.getSchema("negative"),Jt=i?Ue({...de,isResponse:!0,schema:Qt}):void 0,Wt=M(w,C,"response"),Ro=Z&&ze?n.createUnionTypeNode([n.createTypeReferenceNode(Z),n.createTypeReferenceNode(ze)]):Ue({...de,isResponse:!0,schema:Gt.or(Qt)});this.program.push(Ae(Ee,we)),Yt&&Z&&this.program.push(Ae(Yt,Z)),Jt&&ze&&this.program.push(Ae(Jt,ze)),this.program.push(Ae(Ro,Wt)),w!=="options"&&(this.paths.push(C),this.registry.set({method:w,path:C},{input:we,positive:Z,negative:ze,response:Wt,isJson:P.getMimeTypes("positive").includes(N.json),tags:P.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Bt(this.ids.pathType,this.paths)),this.program.push(Bt(this.ids.methodType,xo)),this.program.push(ut(this.ids.methodPathType,Ht([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.default.SyntaxKind.ExtendsKeyword,[Kt(this.ids.methodPathType,z.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:P,path:C},{isJson:w,tags:de,...we}]of this.registry){let Ee=ho(P,C);for(let Z of this.interfaces)Z.kind in we&&Z.props.push(co(Ee,we[Z.kind]));r!=="types"&&(w&&p.push(n.createPropertyAssignment(Ee,n.createTrue())),d.push(n.createPropertyAssignment(Ee,n.createArrayLiteralExpression(de.map(Z=>n.createStringLiteral(Z))))))}for(let{id:P,props:C}of this.interfaces)this.program.push(yo(P,a,C));if(r==="types")return;let l=n.createVariableStatement(G,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),u=n.createVariableStatement(G,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),m=ut(this.ids.providerType,n.createFunctionTypeNode(go({M:this.ids.methodType,P:this.ids.pathType}),mt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ft)}),uo(this.ids.responseInterface,Ft))),y=ut(this.ids.implementationType,n.createFunctionTypeNode(void 0,mt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.default.SyntaxKind.StringKeyword),params:Kt(z.default.SyntaxKind.StringKeyword,z.default.SyntaxKind.AnyKeyword)}),fo())),T=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Oe)]),S=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[T,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),A=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[T]),z.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),x=mo(this.ids.clientClass,po([lt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),ao)]),[lo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,S,A]),!0))]);this.program.push(l,u,m,y,x);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Pe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),He=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),Ce=n.createVariableStatement(void 0,Y(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Oe)]),n.createObjectLiteralExpression([O,Pe,He])])))),pe=n.createVariableStatement(void 0,Y(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Fe=n.createVariableStatement(void 0,Y(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Oe)])))),[Ke,ht]=["json","text"].map(P=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,P),void 0,void 0))),Be=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(jt,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Oe)]),z.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Ke])),k=n.createVariableStatement(G,Y(this.ids.exampleImplementationConst,qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([pe,Fe,Ce,Be,ht]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Ie=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(k,Ie,Q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
|
|
21
21
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&z.default.addSyntheticLeadingComment(z.default.addSyntheticLeadingComment(n.createEmptyStatement(),z.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),z.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
22
22
|
${r}`);return this.program.concat(o||[]).map((i,s)=>_t(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
23
23
|
|
package/dist/index.d.cts
CHANGED
|
@@ -493,7 +493,7 @@ interface ServerConfig<TAG extends string = string> extends CommonConfig<TAG> {
|
|
|
493
493
|
* */
|
|
494
494
|
rawParser?: RequestHandler;
|
|
495
495
|
/**
|
|
496
|
-
* @desc A code to execute
|
|
496
|
+
* @desc A code to execute before processing the Routing of your API (and before parsing).
|
|
497
497
|
* @desc This can be a good place for express middlewares establishing their own routes.
|
|
498
498
|
* @desc It can help to avoid making a DIY solution based on the attachRouting() approach.
|
|
499
499
|
* @default undefined
|
package/dist/index.d.ts
CHANGED
|
@@ -493,7 +493,7 @@ interface ServerConfig<TAG extends string = string> extends CommonConfig<TAG> {
|
|
|
493
493
|
* */
|
|
494
494
|
rawParser?: RequestHandler;
|
|
495
495
|
/**
|
|
496
|
-
* @desc A code to execute
|
|
496
|
+
* @desc A code to execute before processing the Routing of your API (and before parsing).
|
|
497
497
|
* @desc This can be a good place for express middlewares establishing their own routes.
|
|
498
498
|
* @desc It can help to avoid making a DIY solution based on the attachRouting() approach.
|
|
499
499
|
* @default undefined
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},L=class extends Error{name="IOSchemaError"},V=class extends L{name="OutputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},D=class extends L{name="InputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},$=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ne=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var
|
|
1
|
+
import{clone as po}from"ramda";import{z as Ue}from"zod";import{isHttpError as Jr}from"http-errors";import{createHash as Wr}from"crypto";import{flip as Xr,pickBy as eo,xprod as to}from"ramda";import{z as ro}from"zod";var oe=class extends Error{name="RoutingError"},C=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
|
|
2
|
+
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},L=class extends Error{name="IOSchemaError"},V=class extends L{name="OutputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},D=class extends L{name="InputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},$=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ne=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var oo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},nt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},no=["body","query","params"],it=e=>e.method.toLowerCase(),st=e=>e.startsWith("x-"),io=e=>eo(Xr(st),e),qt=(e,t={})=>{let r=it(e);return r==="options"?{}:(t[r]||nt[r]||no).filter(o=>o==="files"?oo(e):!0).map(o=>o==="headers"?io(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},ie=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),k=e=>e instanceof ro.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Le=e=>Jr(e)?e.statusCode:e instanceof D?400:500,at=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},j=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[y]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},_=(e,t,r)=>e.length&&t.length?
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};import{chain as Io}from"ramda";var Y=e=>v(e)&&"or"in e,pe=e=>v(e)&&"and"in e,lt=e=>({and:Io(t=>pe(t)?t.and:[t],e)}),Ve=(e,t)=>pe(e)?{and:e.and.map(r=>Y(r)?{or:r.or.map(t)}:t(r))}:Y(e)?{or:e.or.map(r=>pe(r)?{and:r.and.map(t)}:t(r))}:t(e),mt=e=>e.and.reduce((t,r)=>({or:_(t.or,Y(r)?r.or:[r],lt)}),{or:[]}),ae=(e,t)=>pe(e)?Y(t)?ae(mt(e),t):lt([e,t]):Y(e)?pe(t)?ae(t,e):Y(t)?{or:_(e.or,t.or,lt)}:ae(e,{and:[t]}):pe(t)||Y(t)?ae(t,e):{and:[e,t]};var de=class{},$e=class extends de{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:l}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:m,short:l},this.#r={input:r,output:o};for(let[f,b]of Object.entries(this.#r))er(!Be(b),new L(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:Object.freeze(dt(s.getPositiveResponse(o),{mimeTypes:[w.json],statusCodes:[se.positive]})),negative:Object.freeze(dt(s.getNegativeResponse(),{mimeTypes:[w.json],statusCodes:[se.negative]}))};for(let[f,b]of Object.entries(this.#t))er(b.length,new $(`ResultHandler must have at least one ${f} response schema specified.`));this.#i=Wt(r)?"upload":Xt(r)?"raw":"json",this.#s={input:Object.freeze([w[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:f})=>f)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:f})=>f))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ae(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ut.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof ut.ZodError?new D(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ut.ZodError?new D(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){qe({logger:i,response:o,error:new $(ie(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=it(t),p={},d=null,c=null;if(i.cors){let l=this.#m(s);typeof i.cors=="function"&&(l=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let f in l)r.set(f,l[f])}let m=Vt(t,i.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(l){c=ie(l)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as rr}from"zod";var tr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>$t(s,i),o)};import Co from"assert/strict";var ft=e=>(Co(!Be(e.input),new L("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as Z}from"zod";var yt=e=>e,Re=yt({getPositiveResponse:e=>{let t=j({schema:e}),r=Z.object({status:Z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>Z.object({status:Z.literal("error"),error:Z.object({message:Z.string()})}).example({status:"error",error:{message:k(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(se.positive).json({status:"success",data:r});return}let a=Le(e);at({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:k(e)}})}}),gt=yt({getPositiveResponse:e=>{let t=j({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof Z.ZodArray?e.shape.items:Z.array(Z.any());return t.reduce((o,i)=>v(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>Z.string().example(k(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);at({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(se.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Oe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:rr.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,l=>{if(l&&l instanceof Error)return c(o(l));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ft({input:rr.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],b="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new $e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:b,methods:m,getOperationId:l,description:i,shortDescription:s,inputSchema:tr(d,t)})}},wo=new Oe(Re),Eo=new Oe(gt);import{inspect as zo}from"util";import{mapObjIndexed as Zo}from"ramda";import{Ansis as No,blue as vo,green as Mo,hex as Lo,red as Do}from"ansis";var ht={debug:10,info:20,warn:30,error:40},or=e=>v(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),xt=({level:e,color:t=new No().isSupported(),depth:r=2})=>{let o={debug:vo,info:Mo,warn:Lo("#FFA500"),error:Do},i=e==="debug",s=e==="silent"?100:ht[e],a=(p,d,c)=>{if(ht[p]<s)return;let m=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&m.push(zo(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(m.join(" "))};return Zo(({},p)=>(d,c)=>a(p,d,c),ht)};import{head as ko,tail as jo,toPairs as Uo}from"ramda";var Ae=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(Uo(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=ko(this.pairs)?.[1],this.siblingMethods=Object.freeze(jo(this.pairs).map(([r])=>r))}};import Ho from"express";var Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Ho.static(...this.params))}};import Tt from"express";import $o from"http";import _o from"https";var Q=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>qt(e)[t])}catch{}throw new ne(e)},nr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await Q(t,r)}catch{}throw new ne(e.map(({moduleName:t})=>t))};import ir from"assert/strict";var J=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){ir.doesNotMatch(a,/\//,new oe(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof de){let c=p.getMethods().slice();i&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof Pe)r&&p.apply(d,r);else if(p instanceof Ae){for(let[c,m]of p.pairs)ir(m.getMethods().includes(c),new oe(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(m,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else J({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var bt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>J({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,m)=>s.execute({request:c,response:m,logger:m.locals[y]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});import sr,{isHttpError as Fo}from"http-errors";var ar=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:Fo(r)?r:sr(400,ie(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[y]?.logger||t})},pr=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=sr(404,`Can not ${r.method} ${r.path}`),s=o.locals[y]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){qe({response:o,logger:s,error:new $(ie(a).message,i)})}},Ko=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Bo=e=>({log:e.debug.bind(e)}),dr=async({rootLogger:e,config:t})=>{let r=await Q("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=d.locals[y]?.logger||e;try{await i?.({request:p,logger:m})}catch(l){return c(l)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Bo(m)})(p,d,c)}),o&&a.push(Ko(o)),a},cr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},lr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[y]={logger:s},i()};import{gray as qo,hex as mr,italic as _e,whiteBright as Vo}from"ansis";var ur=()=>{let e=_e("Proudly supports transgender community.".padStart(109)),t=_e("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=_e("Thank you for choosing Express Zod API for your project.".padStart(132)),o=_e("for Dime".padEnd(20)),i=mr("#F5A9B8"),s=mr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(Vo,5,7).fill(i,7,9).fill(s,9,12).fill(qo,12,13);return`
|
|
4
|
+
`,{url:t.url,payload:r})},j=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[y]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},_=(e,t,r)=>e.length&&t.length?to(e,t).map(r):e.concat(t),Te=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,pt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),E=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(pt).join(""),De=e=>Wr("sha1").update(JSON.stringify(e),"utf8").digest("hex"),ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},M=e=>typeof e=="object"&&e!==null;import{clone as so,mergeDeepRight as ao}from"ramda";var y=Symbol.for("express-zod-api"),je=e=>{let t=e.describe(e.description);return t._def[y]=so(t._def[y])||{examples:[]},t},Vt=(e,t)=>{if(!(y in e._def))return t;let r=je(t);return r._def[y].examples=_(r._def[y].examples,e._def[y].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?ao({...o},{...i}):i),r};var co=function(e){let t=je(this);return t._def[y].examples.push(e),t},lo=function(e){let t=je(this);return t._def[y].defaultLabel=e,t},mo=function(e){return new Ue.ZodBranded({typeName:Ue.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...po(this._def[y]),brand:e}})};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ue.ZodType.prototype,{example:{get(){return co.bind(this)}},brand:{set(){},get(){return mo.bind(this)}}}),Object.defineProperty(Ue.ZodDefault.prototype,"label",{get(){return lo.bind(this)}}));function uo(e){return e}import Xt from"assert/strict";import{z as ut}from"zod";import{z as fo}from"zod";var se={positive:200,negative:400},dt=(e,t)=>e instanceof fo.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));import{z as xo}from"zod";import{z as go}from"zod";import{z as He}from"zod";var U=Symbol("File"),$t=He.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),yo={buffer:()=>$t.brand(U),string:()=>He.string().brand(U),binary:()=>$t.or(He.string()).brand(U),base64:()=>He.string().base64().brand(U)};function Fe(e){return yo[e||"string"]()}var G=Symbol("Raw"),_t=(e={})=>go.object({raw:Fe("buffer")}).extend(e).brand(G);import{z as ho}from"zod";var Se=Symbol("Upload"),Gt=()=>ho.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Se);var ct=({schema:{options:e},next:t})=>e.some(t),Qt=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),bo=({schema:e,next:t})=>Object.values(e.shape).some(t),Yt=({schema:e,next:t})=>t(e.unwrap()),To=({schema:e,next:t})=>t(e.innerType()),So=({schema:e,next:t})=>t(e.valueSchema),Ro=({schema:e,next:t})=>t(e.element),Oo=({schema:e,next:t})=>t(e._def.innerType),Ao={ZodObject:bo,ZodUnion:ct,ZodDiscriminatedUnion:ct,ZodIntersection:Qt,ZodEffects:To,ZodOptional:Yt,ZodNullable:Yt,ZodRecord:So,ZodArray:Ro,ZodDefault:Oo},Ke=({subject:e,condition:t,rules:r=Ao,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Ke({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},Be=e=>Ke({subject:e,maxDepth:3,rules:{ZodUnion:ct,ZodIntersection:Qt},condition:t=>t instanceof xo.ZodEffects&&t._def.effect.type!=="refinement"}),Jt=e=>Ke({subject:e,condition:t=>t._def[y]?.brand===Se}),Wt=e=>Ke({subject:e,condition:t=>t._def[y]?.brand===G,maxDepth:3});var qe=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
5
|
+
Original error: ${e.originalError.message}.`:""))};import{chain as Po}from"ramda";var Y=e=>M(e)&&"or"in e,pe=e=>M(e)&&"and"in e,lt=e=>({and:Po(t=>pe(t)?t.and:[t],e)}),Ve=(e,t)=>pe(e)?{and:e.and.map(r=>Y(r)?{or:r.or.map(t)}:t(r))}:Y(e)?{or:e.or.map(r=>pe(r)?{and:r.and.map(t)}:t(r))}:t(e),mt=e=>e.and.reduce((t,r)=>({or:_(t.or,Y(r)?r.or:[r],lt)}),{or:[]}),ae=(e,t)=>pe(e)?Y(t)?ae(mt(e),t):lt([e,t]):Y(e)?pe(t)?ae(t,e):Y(t)?{or:_(e.or,t.or,lt)}:ae(e,{and:[t]}):pe(t)||Y(t)?ae(t,e):{and:[e,t]};var de=class{},$e=class extends de{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:l}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:m,short:l},this.#r={input:r,output:o};for(let[f,b]of Object.entries(this.#r))Xt(!Be(b),new L(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:Object.freeze(dt(s.getPositiveResponse(o),{mimeTypes:[w.json],statusCodes:[se.positive]})),negative:Object.freeze(dt(s.getNegativeResponse(),{mimeTypes:[w.json],statusCodes:[se.negative]}))};for(let[f,b]of Object.entries(this.#t))Xt(b.length,new $(`ResultHandler must have at least one ${f} response schema specified.`));this.#i=Jt(r)?"upload":Wt(r)?"raw":"json",this.#s={input:Object.freeze([w[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:f})=>f)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:f})=>f))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ae(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ut.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof ut.ZodError?new D(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ut.ZodError?new D(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){qe({logger:i,response:o,error:new $(ie(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=it(t),p={},d=null,c=null;if(i.cors){let l=this.#m(s);typeof i.cors=="function"&&(l=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let f in l)r.set(f,l[f])}let m=qt(t,i.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(l){c=ie(l)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as tr}from"zod";var er=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Vt(s,i),o)};import Co from"assert/strict";var ft=e=>(Co(!Be(e.input),new L("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as Z}from"zod";var yt=e=>e,Re=yt({getPositiveResponse:e=>{let t=j({schema:e}),r=Z.object({status:Z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>Z.object({status:Z.literal("error"),error:Z.object({message:Z.string()})}).example({status:"error",error:{message:k(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(se.positive).json({status:"success",data:r});return}let a=Le(e);at({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:k(e)}})}}),gt=yt({getPositiveResponse:e=>{let t=j({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof Z.ZodArray?e.shape.items:Z.array(Z.any());return t.reduce((o,i)=>M(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>Z.string().example(k(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);at({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(se.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Oe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:tr.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,l=>{if(l&&l instanceof Error)return c(o(l));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ft({input:tr.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],b="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new $e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:b,methods:m,getOperationId:l,description:i,shortDescription:s,inputSchema:er(d,t)})}},Io=new Oe(Re),wo=new Oe(gt);import{inspect as Eo}from"util";import{mapObjIndexed as zo}from"ramda";import{Ansis as Zo,blue as No,green as Mo,hex as vo,red as Lo}from"ansis";var ht={debug:10,info:20,warn:30,error:40},rr=e=>M(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),xt=({level:e,color:t=new Zo().isSupported(),depth:r=2})=>{let o={debug:No,info:Mo,warn:vo("#FFA500"),error:Lo},i=e==="debug",s=e==="silent"?100:ht[e],a=(p,d,c)=>{if(ht[p]<s)return;let m=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&m.push(Eo(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(m.join(" "))};return zo(({},p)=>(d,c)=>a(p,d,c),ht)};import{head as Do,tail as ko,toPairs as jo}from"ramda";var Ae=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(jo(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=Do(this.pairs)?.[1],this.siblingMethods=Object.freeze(ko(this.pairs).map(([r])=>r))}};import Uo from"express";var Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Uo.static(...this.params))}};import Tt from"express";import Vo from"http";import $o from"https";var Q=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new ne(e)},or=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await Q(t,r)}catch{}throw new ne(e.map(({moduleName:t})=>t))};import nr from"assert/strict";var J=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){nr.doesNotMatch(a,/\//,new oe(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof de){let c=p.getMethods().slice();i&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof Pe)r&&p.apply(d,r);else if(p instanceof Ae){for(let[c,m]of p.pairs)nr(m.getMethods().includes(c),new oe(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(m,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else J({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var bt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>J({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,m)=>s.execute({request:c,response:m,logger:m.locals[y]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});import ir,{isHttpError as Ho}from"http-errors";var sr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:Ho(r)?r:ir(400,ie(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[y]?.logger||t})},ar=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=ir(404,`Can not ${r.method} ${r.path}`),s=o.locals[y]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){qe({response:o,logger:s,error:new $(ie(a).message,i)})}},Fo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Ko=e=>({log:e.debug.bind(e)}),pr=async({rootLogger:e,config:t})=>{let r=await Q("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=d.locals[y]?.logger||e;try{await i?.({request:p,logger:m})}catch(l){return c(l)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Ko(m)})(p,d,c)}),o&&a.push(Fo(o)),a},dr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},cr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[y]={logger:s},i()};import{gray as Bo,hex as lr,italic as _e,whiteBright as qo}from"ansis";var mr=()=>{let e=_e("Proudly supports transgender community.".padStart(109)),t=_e("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=_e("Thank you for choosing Express Zod API for your project.".padStart(132)),o=_e("for Dime".padEnd(20)),i=lr("#F5A9B8"),s=lr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(qo,5,7).fill(i,7,9).fill(s,9,12).fill(Bo,12,13);return`
|
|
6
6
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
7
7
|
888 d88P 888 d88888 888 Y88b 888
|
|
8
8
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -17,8 +17,8 @@ ${o}888${t}
|
|
|
17
17
|
${r}
|
|
18
18
|
`.split(`
|
|
19
19
|
`).map((d,c)=>a[c]?a[c](d):d).join(`
|
|
20
|
-
`)};var fr=e=>{e.startupLogo!==!1&&console.log(ur());let t={errorHandler:e.errorHandler||Re,rootLogger:or(e.logger)?xt(e.logger):e.logger};t.rootLogger.debug("Running","v19.0.0-beta.4 (ESM)");let r=pr(t),o=ar(t);return{...t,notFoundHandler:r,parserFailureHandler:o}},Go=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=fr(e);return bt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Yo=async(e,t)=>{let r=Tt().disable("x-powered-by"),{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=fr(e);if(r.use(lr({rootLogger:o,config:e})),e.server.compression){let c=await Q("compression");r.use(c(typeof e.server.compression=="object"?e.server.compression:void 0))}let a={json:[e.server.jsonParser||Tt.json()],raw:[e.server.rawParser||Tt.raw(),cr],upload:e.server.upload?await dr({config:e,rootLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),bt({app:r,routing:t,rootLogger:o,config:e,parsers:a}),r.use(s,i);let p=(c,m)=>c.listen(m,()=>{o.info("Listening",m)}),d={httpServer:p($o.createServer(r),e.server.listen),httpsServer:e.https?p(_o.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...d,logger:o}};import ri from"assert/strict";import{OpenApiBuilder as oi}from"openapi3-ts/oas31";import H from"assert/strict";import{isReferenceObject as X}from"openapi3-ts/oas31";import{both as Jo,complement as Wo,concat as Xo,type as en,filter as tn,fromPairs as Ee,has as rn,isNil as on,map as le,mergeAll as nn,mergeDeepRight as sn,mergeDeepWith as an,objOf as br,omit as Qe,pipe as Tr,pluck as pn,range as dn,reject as cn,toLower as ln,union as mn,when as un,xprod as Je,zip as fn}from"ramda";import{z as x}from"zod";import{z as Ie}from"zod";var Ge=e=>!isNaN(e.getTime());var Ce=Symbol("DateIn"),yr=()=>Ie.union([Ie.string().date(),Ie.string().datetime(),Ie.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.date().refine(Ge)).brand(Ce);import{z as Qo}from"zod";var we=Symbol("DateOut"),gr=()=>Qo.date().refine(Ge).transform(e=>e.toISOString()).brand(we);var W=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:m=>W({schema:m,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),c=t&&t({schema:e,prev:d,...a});return c?{...d,...c}:d};var hr=50,Sr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",yn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Rr=/:([A-Za-z0-9_]+)/g,Or=e=>e.match(Rr)?.map(t=>t.slice(1))||[],Ar=e=>e.replace(Rr,t=>`{${t.slice(1)}}`),gn=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[y]?.defaultLabel||e._def.defaultValue()}),hn=({schema:{_def:{innerType:e}},next:t})=>t(e),xn=()=>({format:"any"}),bn=e=>(H(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Tn=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof x.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Sn=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Rn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),On=e=>{let[t,r]=e.filter(i=>!X(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));H(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=an((i,s)=>Array.isArray(i)&&Array.isArray(s)?Xo(i,s):i===s?s:H.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=mn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([i,s])=>sn(i,s))),o},An=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return On(o)}catch{}return{allOf:o}},Pn=({schema:e,next:t})=>t(e.unwrap()),In=({schema:e,next:t})=>t(e._def.innerType),Cn=({schema:e,next:t})=>{let r=t(e.unwrap());return X(r)||(r.type=Ir(r)),r},Pr=e=>{let t=ln(en(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},xr=({schema:e})=>({type:Pr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),wn=({schema:{value:e}})=>({type:Pr(e),const:e}),En=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Te(p)?p instanceof x.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=Ye({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},zn=()=>({type:"null"}),Zn=e=>(H(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Sr}}),Nn=e=>(H(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Sr}}),vn=e=>H.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Mn=()=>({type:"boolean"}),Ln=()=>({type:"integer",format:"bigint"}),Dn=e=>e.every(t=>t instanceof x.ZodLiteral),kn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=Ye({schema:x.object(Ee(Je(o,[t]))),...r}),i.required=o),i}if(e instanceof x.ZodLiteral)return{type:"object",properties:Ye({schema:x.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.ZodUnion&&Dn(e.options)){let o=le(s=>`${s.value}`,e.options),i=Ee(Je(o,[t]));return{type:"object",properties:Ye({schema:x.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},jn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},Un=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Hn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}}})=>{let f=l.find(S=>S.kind==="regex"),b=l.find(S=>S.kind==="datetime"),T=f?f.regex:b?b.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,R={type:"string"},h={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let S in h)if(h[S]){R.format=S;break}return r!==null&&(R.minLength=r),o!==null&&(R.maxLength=o),T&&(R.pattern=T.source),R},Fn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},Ye=({schema:{shape:e},next:t})=>le(t,e),Kn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return yn?.[t]},Ir=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Bn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!X(o)){let s=ke(e,Kn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(x.any())}if(!t&&i.type==="preprocess"&&!X(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},qn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Vn=({schema:e,next:t})=>t(e.unwrap()),$n=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},_n=({next:e,schema:t})=>e(t.unwrap().shape.raw),Cr=e=>e.length?Ee(fn(dn(1,e.length+1).map(t=>`example${t}`),le(br("value"),e))):void 0,wr=(e,t,r=[])=>Tr(j,le(un(Jo(v,Wo(Array.isArray)),Qe(r))),Cr)({schema:e,variant:t?"parsed":"original",validate:!0}),Gn=(e,t)=>Tr(j,tn(rn(t)),pn(t),Cr)({schema:e,variant:"original",validate:!0}),ce=(e,t)=>e instanceof x.ZodObject?e:e instanceof x.ZodBranded?ce(e.unwrap(),t):e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion?e.options.map(r=>ce(r,t)).reduce((r,o)=>r.merge(o.partial()),x.object({})):e instanceof x.ZodEffects?(H(e._def.effect.type==="refinement",t),ce(e._def.schema,t)):ce(e._def.left,t).merge(ce(e._def.right,t)),Er=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=ce(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),m=Or(e),l=o.includes("query"),f=o.includes("params"),b=o.includes("headers"),T=h=>f&&m.includes(h),R=h=>b&&st(h);return Object.keys(c).filter(h=>l||T(h)).map(h=>{let S=W({schema:c[h],isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:e,method:t}),fe=p==="components"?a(E(d,h),S):S;return{name:h,in:T(h)?"path":R(h)?"header":"query",required:!c[h].isOptional(),description:S.description||d,schema:fe,examples:Gn(r,h)}})},Rt={ZodString:Hn,ZodNumber:Fn,ZodBigInt:Ln,ZodBoolean:Mn,ZodNull:zn,ZodArray:jn,ZodTuple:Un,ZodRecord:kn,ZodObject:En,ZodLiteral:wn,ZodIntersection:An,ZodUnion:Sn,ZodAny:xn,ZodDefault:gn,ZodEnum:xr,ZodNativeEnum:xr,ZodEffects:Bn,ZodOptional:Pn,ZodNullable:Cn,ZodDiscriminatedUnion:Rn,ZodBranded:Vn,ZodDate:vn,ZodCatch:hn,ZodPipeline:qn,ZodLazy:$n,ZodReadonly:In,[U]:Tn,[Se]:bn,[we]:Nn,[Ce]:Zn,[G]:_n},Ot=({schema:e,isResponse:t,prev:r})=>{if(X(r))return{};let{description:o}=e,i=e instanceof x.ZodLazy,s=r.type!==void 0,a=t&&Te(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:j({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Ir(r)),d.length&&(c.examples=d.slice()),c},At=({schema:e,...t})=>H.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),St=(e,t)=>{if(X(e))return e;let r={...e};return r.properties&&(r.properties=Qe(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Qe(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>St(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>St(o,t))),r},zr=e=>X(e)?e:Qe(["examples"],e),Zr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:m,description:l=`${e.toUpperCase()} ${t} ${pt(i)} response ${c?m:""}`.trim()})=>{let f=zr(W({schema:r,isResponse:!0,rules:Rt,onEach:Ot,onMissing:At,serializer:s,getRef:a,makeRef:p,path:t,method:e})),b={schema:d==="components"?p(E(l),f):f,examples:wr(r,!0)};return{description:l,content:Ee(Je(o,[b]))}},Yn=()=>({type:"http",scheme:"basic"}),Qn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Jn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Wn=({name:e})=>({type:"apiKey",in:"header",name:e}),Xn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ei=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ti=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),cn(on,e))}),Nr=(e,t)=>{let r={basic:Yn,bearer:Qn,input:Jn,header:Wn,cookie:Xn,openid:ei,oauth2:ti};return Ve(e,o=>r[o.type](o,t))},We=e=>"or"in e?e.or.map(t=>"and"in t?nn(le(({name:r,scopes:o})=>br(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?We(mt(e)):We({or:[e]}),vr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Or(t),m=zr(St(W({schema:r,isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(E(d),m):m,examples:wr(r,!1,c)};return{description:d,content:Ee(Je(o,[l]))}},Mr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Pt=e=>e.length<=hr?e:e.slice(0,hr-1)+"\u2026";var It=class extends oi{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||E(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ri.fail(new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=De}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});J({routing:t,onEndpoint:(l,f,b)=>{let T=b,R={path:f,method:T,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,S]=["short","long"].map(l.getDescription.bind(l)),fe=h?Pt(h):p&&S?Pt(S):void 0,Ze=l.getTags(),ye=r.inputSources?.[T]||nt[T],te=this.ensureUniqOperationId(f,T,l.getOperationId(T)),Ne=Er({...R,inputSources:ye,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:f,operationId:te})}),ve={};for(let N of["positive","negative"]){let q=l.getResponses(N);for(let{mimeTypes:ge,schema:O,statusCodes:A}of q)for(let P of A)ve[P]=Zr({...R,variant:N,schema:O,mimeTypes:ge,statusCode:P,hasMultipleStatusCodes:q.length>1||A.length>1,description:a?.[`${N}Response`]?.call(null,{method:T,path:f,operationId:te,statusCode:P})})}let ot=ye.includes("body")?vr({...R,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:f,operationId:te})}):void 0,Me=We(Ve(Nr(l.getSecurity(),ye),N=>{let q=this.ensureUniqSecuritySchemaName(N),ge=["oauth2","openIdConnect"].includes(N.type)?l.getScopes().slice():[];return this.addSecurityScheme(q,N),{name:q,scopes:ge}}));this.addPath(Ar(f),{[T]:{operationId:te,summary:fe,description:S,tags:Ze.length>0?Ze:void 0,parameters:Ne.length>0?Ne:void 0,requestBody:ot,security:Me.length>0?Me:void 0,responses:ve}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import Lr from"http";var ni=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>w.json),...t}),ii=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Lr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Lr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},si=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ai=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await nr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=ni({fnMethod:a,requestProps:t}),d=ii({fnMethod:a,responseProps:r}),c=si({fnMethod:a,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:m,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import z from"typescript";import M from"typescript";import{chain as Dr,toPairs as kr}from"ramda";var n=M.factory,F=[n.createModifier(M.SyntaxKind.ExportKeyword)],pi=[n.createModifier(M.SyntaxKind.AsyncKeyword)],di=[n.createModifier(M.SyntaxKind.PublicKeyword),n.createModifier(M.SyntaxKind.ReadonlyKeyword)],jr=[n.createModifier(M.SyntaxKind.ProtectedKeyword),n.createModifier(M.SyntaxKind.ReadonlyKeyword)],Ct=n.createTemplateHead(""),me=n.createTemplateTail(""),wt=n.createTemplateMiddle(" "),Et=e=>n.createTemplateLiteralType(Ct,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?me:wt))),zt=Et(["M","P"]),Xe=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),et=(e,t)=>Dr(([r,o])=>[Xe(n.createIdentifier(r),o,t)],kr(e)),Zt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Ur=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Hr=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),K=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],M.NodeFlags.Const),Nt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),tt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,t),Fr=(e,t,r)=>n.createPropertyDeclaration(di,e,void 0,t,r),Kr=(e,t,r)=>n.createClassDeclaration(F,e,void 0,void 0,[t,...r]),Br=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),qr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(M.SyntaxKind.AnyKeyword)]),Vr=(e,t,r)=>n.createInterfaceDeclaration(F,e,void 0,t,r),$r=e=>Dr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],kr(e)),vt=(e,t,r)=>n.createArrowFunction(r?pi:void 0,void 0,e.map(o=>Xe(o)),void 0,void 0,t),Mt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,et({acc:void 0,key:void 0}),void 0,void 0,t),r]),_r=(...e)=>`"${e.join(" ")}"`;var Gr=["get","post","put","delete","patch"];import g from"typescript";import{z as kt}from"zod";import B from"typescript";var{factory:rt}=B,Lt=(e,t)=>{B.addSyntheticLeadingComment(e,B.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ue=(e,t,r)=>{let o=rt.createTypeAliasDeclaration(void 0,rt.createIdentifier(t),void 0,e);return r&&Lt(o,r),o},Dt=(e,t)=>{let r=B.createSourceFile("print.ts","",B.ScriptTarget.Latest,!1,B.ScriptKind.TS);return B.createPrinter(t).printNode(B.EmitHint.Unspecified,e,r)},ci=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yr=e=>ci.test(e)?rt.createIdentifier(e):rt.createStringLiteral(e);var{factory:u}=g,li={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},mi=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),ui=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Te(a)?a instanceof kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Yr(s),p&&o?u.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},fi=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),yi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Qr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),gi=e=>li?.[e.kind],hi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,gi(o)),a={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||g.SyntaxKind.AnyKeyword)}return o},xi=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),bi=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},Ti=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Si=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Ri=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Oi=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Ai=({next:e,schema:t})=>e(t._def.innerType),ee=e=>()=>u.createKeywordTypeNode(e),Pi=({next:e,schema:t})=>e(t.unwrap()),Ii=({next:e,schema:t})=>e(t._def.innerType),Ci=({next:e,schema:t})=>e(t._def.innerType),wi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Ei=()=>u.createLiteralTypeNode(u.createNull()),zi=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},Zi=({schema:e})=>{let t=e.unwrap(),r=u.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof kt.ZodString?r:t instanceof kt.ZodUnion?i:o},Ni=({next:e,schema:t})=>e(t.unwrap().shape.raw),vi={ZodString:ee(g.SyntaxKind.StringKeyword),ZodNumber:ee(g.SyntaxKind.NumberKeyword),ZodBigInt:ee(g.SyntaxKind.BigIntKeyword),ZodBoolean:ee(g.SyntaxKind.BooleanKeyword),ZodAny:ee(g.SyntaxKind.AnyKeyword),[Ce]:ee(g.SyntaxKind.StringKeyword),[we]:ee(g.SyntaxKind.StringKeyword),ZodNull:Ei,ZodArray:fi,ZodTuple:Si,ZodRecord:Ri,ZodObject:ui,ZodLiteral:mi,ZodIntersection:Oi,ZodUnion:Qr,ZodDefault:Ai,ZodEnum:yi,ZodNativeEnum:xi,ZodEffects:hi,ZodOptional:bi,ZodNullable:Ti,ZodDiscriminatedUnion:Qr,ZodBranded:Pi,ZodCatch:Ci,ZodPipeline:wi,ZodLazy:zi,ZodReadonly:Ii,[U]:Zi,[G]:Ni},ze=({schema:e,...t})=>W({schema:e,rules:vi,onMissing:()=>u.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),...t});var jt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ue(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=De,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){J({routing:t,onEndpoint:(O,A,P)=>{let re={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},he=E(P,A,"input"),xe=ze({...re,schema:O.getSchema("input"),isResponse:!1}),C=i?E(P,A,"positive.response"):void 0,Ut=O.getSchema("positive"),Ht=i?ze({...re,isResponse:!0,schema:Ut}):void 0,be=i?E(P,A,"negative.response"):void 0,Ft=O.getSchema("negative"),Kt=i?ze({...re,isResponse:!0,schema:Ft}):void 0,Bt=E(P,A,"response"),Jr=C&&be?n.createUnionTypeNode([n.createTypeReferenceNode(C),n.createTypeReferenceNode(be)]):ze({...re,isResponse:!0,schema:Ut.or(Ft)});this.program.push(ue(xe,he)),Ht&&C&&this.program.push(ue(Ht,C)),Kt&&be&&this.program.push(ue(Kt,be)),this.program.push(ue(Jr,Bt)),P!=="options"&&(this.paths.push(A),this.registry.set({method:P,path:A},{input:he,positive:C,negative:be,response:Bt,isJson:O.getMimeTypes("positive").includes(w.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Nt(this.ids.pathType,this.paths)),this.program.push(Nt(this.ids.methodType,Gr)),this.program.push(tt(this.ids.methodPathType,Et([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[Zt(this.ids.methodPathType,z.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:O,path:A},{isJson:P,tags:re,...he}]of this.registry){let xe=_r(O,A);for(let C of this.interfaces)C.kind in he&&C.props.push(Hr(xe,he[C.kind]));r!=="types"&&(P&&p.push(n.createPropertyAssignment(xe,n.createTrue())),d.push(n.createPropertyAssignment(xe,n.createArrayLiteralExpression(re.map(C=>n.createStringLiteral(C))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(Vr(O,a,A));if(r==="types")return;let c=n.createVariableStatement(F,K(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),m=n.createVariableStatement(F,K(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),l=tt(this.ids.providerType,n.createFunctionTypeNode($r({M:this.ids.methodType,P:this.ids.pathType}),et({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),zt)}),Br(this.ids.responseInterface,zt))),f=tt(this.ids.implementationType,n.createFunctionTypeNode(void 0,et({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:Zt(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),qr())),b=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,me)]),T=Mt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[b,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),R=Mt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[b]),z.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),h=Kr(this.ids.clientClass,Ur([Xe(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),jr)]),[Fr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),vt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,R]),!0))]);this.program.push(c,m,l,f,h);let S=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),fe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),Ze=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ye=n.createVariableStatement(void 0,K(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,me)]),n.createObjectLiteralExpression([S,fe,Ze])])))),te=n.createVariableStatement(void 0,K(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ne=n.createVariableStatement(void 0,K(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),me)])))),[ve,ot]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),Me=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ct,[n.createTemplateSpan(this.ids.methodParameter,wt),n.createTemplateSpan(this.ids.pathParameter,me)]),z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([ve])),N=n.createVariableStatement(F,K(this.ids.exampleImplementationConst,vt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([te,Ne,ye,Me,ot]),!0),n.createTypeReferenceNode(this.ids.implementationType))),q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),ge=n.createVariableStatement(void 0,K(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(N,ge,q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
|
|
20
|
+
`)};var ur=e=>{e.startupLogo!==!1&&console.log(mr());let t=e.errorHandler||Re,r=rr(e.logger)?xt(e.logger):e.logger;r.debug("Running","v19.0.0 (ESM)");let o=cr({rootLogger:r,config:e}),i=ar({rootLogger:r,errorHandler:t}),s=sr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},_o=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=ur(e);return bt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Go=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=ur(e),a=Tt().disable("x-powered-by").use(s);if(e.server.compression){let m=await Q("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||Tt.json()],raw:[e.server.rawParser||Tt.raw(),dr],upload:e.server.upload?await pr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),bt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,l)=>m.listen(l,()=>{r.info("Listening",l)}),c={httpServer:d(Vo.createServer(a),e.server.listen),httpsServer:e.https?d($o.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...c,logger:r}};import ti from"assert/strict";import{OpenApiBuilder as ri}from"openapi3-ts/oas31";import H from"assert/strict";import{isReferenceObject as X}from"openapi3-ts/oas31";import{both as Qo,complement as Jo,concat as Wo,type as Xo,filter as en,fromPairs as Ee,has as tn,isNil as rn,map as le,mergeAll as on,mergeDeepRight as nn,mergeDeepWith as sn,objOf as xr,omit as Qe,pipe as br,pluck as an,range as pn,reject as dn,toLower as cn,union as ln,when as mn,xprod as Je,zip as un}from"ramda";import{z as x}from"zod";import{z as Ce}from"zod";var Ge=e=>!isNaN(e.getTime());var Ie=Symbol("DateIn"),fr=()=>Ce.union([Ce.string().date(),Ce.string().datetime(),Ce.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ce.date().refine(Ge)).brand(Ie);import{z as Yo}from"zod";var we=Symbol("DateOut"),yr=()=>Yo.date().refine(Ge).transform(e=>e.toISOString()).brand(we);var W=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:m=>W({schema:m,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),c=t&&t({schema:e,prev:d,...a});return c?{...d,...c}:d};var gr=50,Tr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",fn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Sr=/:([A-Za-z0-9_]+)/g,Rr=e=>e.match(Sr)?.map(t=>t.slice(1))||[],Or=e=>e.replace(Sr,t=>`{${t.slice(1)}}`),yn=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[y]?.defaultLabel||e._def.defaultValue()}),gn=({schema:{_def:{innerType:e}},next:t})=>t(e),hn=()=>({format:"any"}),xn=e=>(H(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),bn=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof x.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Tn=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Sn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Rn=e=>{let[t,r]=e.filter(i=>!X(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));H(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=sn((i,s)=>Array.isArray(i)&&Array.isArray(s)?Wo(i,s):i===s?s:H.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=ln(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([i,s])=>nn(i,s))),o},On=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Rn(o)}catch{}return{allOf:o}},An=({schema:e,next:t})=>t(e.unwrap()),Pn=({schema:e,next:t})=>t(e._def.innerType),Cn=({schema:e,next:t})=>{let r=t(e.unwrap());return X(r)||(r.type=Pr(r)),r},Ar=e=>{let t=cn(Xo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},hr=({schema:e})=>({type:Ar(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),In=({schema:{value:e}})=>({type:Ar(e),const:e}),wn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Te(p)?p instanceof x.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=Ye({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},En=()=>({type:"null"}),zn=e=>(H(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Tr}}),Zn=e=>(H(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Tr}}),Nn=e=>H.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Mn=()=>({type:"boolean"}),vn=()=>({type:"integer",format:"bigint"}),Ln=e=>e.every(t=>t instanceof x.ZodLiteral),Dn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=Ye({schema:x.object(Ee(Je(o,[t]))),...r}),i.required=o),i}if(e instanceof x.ZodLiteral)return{type:"object",properties:Ye({schema:x.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.ZodUnion&&Ln(e.options)){let o=le(s=>`${s.value}`,e.options),i=Ee(Je(o,[t]));return{type:"object",properties:Ye({schema:x.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},kn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},jn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Un=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}}})=>{let f=l.find(S=>S.kind==="regex"),b=l.find(S=>S.kind==="datetime"),T=f?f.regex:b?b.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,R={type:"string"},h={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let S in h)if(h[S]){R.format=S;break}return r!==null&&(R.minLength=r),o!==null&&(R.maxLength=o),T&&(R.pattern=T.source),R},Hn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},Ye=({schema:{shape:e},next:t})=>le(t,e),Fn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return fn?.[t]},Pr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Kn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!X(o)){let s=ke(e,Fn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(x.any())}if(!t&&i.type==="preprocess"&&!X(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Bn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),qn=({schema:e,next:t})=>t(e.unwrap()),Vn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},$n=({next:e,schema:t})=>e(t.unwrap().shape.raw),Cr=e=>e.length?Ee(un(pn(1,e.length+1).map(t=>`example${t}`),le(xr("value"),e))):void 0,Ir=(e,t,r=[])=>br(j,le(mn(Qo(M,Jo(Array.isArray)),Qe(r))),Cr)({schema:e,variant:t?"parsed":"original",validate:!0}),_n=(e,t)=>br(j,en(tn(t)),an(t),Cr)({schema:e,variant:"original",validate:!0}),ce=(e,t)=>e instanceof x.ZodObject?e:e instanceof x.ZodBranded?ce(e.unwrap(),t):e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion?e.options.map(r=>ce(r,t)).reduce((r,o)=>r.merge(o.partial()),x.object({})):e instanceof x.ZodEffects?(H(e._def.effect.type==="refinement",t),ce(e._def.schema,t)):ce(e._def.left,t).merge(ce(e._def.right,t)),wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=ce(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),m=Rr(e),l=o.includes("query"),f=o.includes("params"),b=o.includes("headers"),T=h=>f&&m.includes(h),R=h=>b&&st(h);return Object.keys(c).filter(h=>l||T(h)).map(h=>{let S=W({schema:c[h],isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:e,method:t}),fe=p==="components"?a(E(d,h),S):S;return{name:h,in:T(h)?"path":R(h)?"header":"query",required:!c[h].isOptional(),description:S.description||d,schema:fe,examples:_n(r,h)}})},Rt={ZodString:Un,ZodNumber:Hn,ZodBigInt:vn,ZodBoolean:Mn,ZodNull:En,ZodArray:kn,ZodTuple:jn,ZodRecord:Dn,ZodObject:wn,ZodLiteral:In,ZodIntersection:On,ZodUnion:Tn,ZodAny:hn,ZodDefault:yn,ZodEnum:hr,ZodNativeEnum:hr,ZodEffects:Kn,ZodOptional:An,ZodNullable:Cn,ZodDiscriminatedUnion:Sn,ZodBranded:qn,ZodDate:Nn,ZodCatch:gn,ZodPipeline:Bn,ZodLazy:Vn,ZodReadonly:Pn,[U]:bn,[Se]:xn,[we]:Zn,[Ie]:zn,[G]:$n},Ot=({schema:e,isResponse:t,prev:r})=>{if(X(r))return{};let{description:o}=e,i=e instanceof x.ZodLazy,s=r.type!==void 0,a=t&&Te(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:j({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Pr(r)),d.length&&(c.examples=d.slice()),c},At=({schema:e,...t})=>H.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),St=(e,t)=>{if(X(e))return e;let r={...e};return r.properties&&(r.properties=Qe(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Qe(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>St(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>St(o,t))),r},Er=e=>X(e)?e:Qe(["examples"],e),zr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:m,description:l=`${e.toUpperCase()} ${t} ${pt(i)} response ${c?m:""}`.trim()})=>{let f=Er(W({schema:r,isResponse:!0,rules:Rt,onEach:Ot,onMissing:At,serializer:s,getRef:a,makeRef:p,path:t,method:e})),b={schema:d==="components"?p(E(l),f):f,examples:Ir(r,!0)};return{description:l,content:Ee(Je(o,[b]))}},Gn=()=>({type:"http",scheme:"basic"}),Yn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Qn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Jn=({name:e})=>({type:"apiKey",in:"header",name:e}),Wn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Xn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ei=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),dn(rn,e))}),Zr=(e,t)=>{let r={basic:Gn,bearer:Yn,input:Qn,header:Jn,cookie:Wn,openid:Xn,oauth2:ei};return Ve(e,o=>r[o.type](o,t))},We=e=>"or"in e?e.or.map(t=>"and"in t?on(le(({name:r,scopes:o})=>xr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?We(mt(e)):We({or:[e]}),Nr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Rr(t),m=Er(St(W({schema:r,isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(E(d),m):m,examples:Ir(r,!1,c)};return{description:d,content:Ee(Je(o,[l]))}},Mr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Pt=e=>e.length<=gr?e:e.slice(0,gr-1)+"\u2026";var Ct=class extends ri{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||E(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ti.fail(new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=De}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});J({routing:t,onEndpoint:(l,f,b)=>{let T=b,R={path:f,method:T,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,S]=["short","long"].map(l.getDescription.bind(l)),fe=h?Pt(h):p&&S?Pt(S):void 0,Ze=l.getTags(),ye=r.inputSources?.[T]||nt[T],te=this.ensureUniqOperationId(f,T,l.getOperationId(T)),Ne=wr({...R,inputSources:ye,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:f,operationId:te})}),Me={};for(let N of["positive","negative"]){let q=l.getResponses(N);for(let{mimeTypes:ge,schema:O,statusCodes:A}of q)for(let P of A)Me[P]=zr({...R,variant:N,schema:O,mimeTypes:ge,statusCode:P,hasMultipleStatusCodes:q.length>1||A.length>1,description:a?.[`${N}Response`]?.call(null,{method:T,path:f,operationId:te,statusCode:P})})}let ot=ye.includes("body")?Nr({...R,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:f,operationId:te})}):void 0,ve=We(Ve(Zr(l.getSecurity(),ye),N=>{let q=this.ensureUniqSecuritySchemaName(N),ge=["oauth2","openIdConnect"].includes(N.type)?l.getScopes().slice():[];return this.addSecurityScheme(q,N),{name:q,scopes:ge}}));this.addPath(Or(f),{[T]:{operationId:te,summary:fe,description:S,tags:Ze.length>0?Ze:void 0,parameters:Ne.length>0?Ne:void 0,requestBody:ot,security:ve.length>0?ve:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import vr from"http";var oi=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>w.json),...t}),ni=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:vr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=vr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},ii=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),si=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await or([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=oi({fnMethod:a,requestProps:t}),d=ni({fnMethod:a,responseProps:r}),c=ii({fnMethod:a,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:m,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import z from"typescript";import v from"typescript";import{chain as Lr,toPairs as Dr}from"ramda";var n=v.factory,F=[n.createModifier(v.SyntaxKind.ExportKeyword)],ai=[n.createModifier(v.SyntaxKind.AsyncKeyword)],pi=[n.createModifier(v.SyntaxKind.PublicKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],kr=[n.createModifier(v.SyntaxKind.ProtectedKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],It=n.createTemplateHead(""),me=n.createTemplateTail(""),wt=n.createTemplateMiddle(" "),Et=e=>n.createTemplateLiteralType(It,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?me:wt))),zt=Et(["M","P"]),Xe=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),et=(e,t)=>Lr(([r,o])=>[Xe(n.createIdentifier(r),o,t)],Dr(e)),Zt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),jr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Ur=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),K=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],v.NodeFlags.Const),Nt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),tt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,t),Hr=(e,t,r)=>n.createPropertyDeclaration(pi,e,void 0,t,r),Fr=(e,t,r)=>n.createClassDeclaration(F,e,void 0,void 0,[t,...r]),Kr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Br=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(v.SyntaxKind.AnyKeyword)]),qr=(e,t,r)=>n.createInterfaceDeclaration(F,e,void 0,t,r),Vr=e=>Lr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Dr(e)),Mt=(e,t,r)=>n.createArrowFunction(r?ai:void 0,void 0,e.map(o=>Xe(o)),void 0,void 0,t),vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,et({acc:void 0,key:void 0}),void 0,void 0,t),r]),$r=(...e)=>`"${e.join(" ")}"`;var _r=["get","post","put","delete","patch"];import g from"typescript";import{z as kt}from"zod";import B from"typescript";var{factory:rt}=B,Lt=(e,t)=>{B.addSyntheticLeadingComment(e,B.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ue=(e,t,r)=>{let o=rt.createTypeAliasDeclaration(void 0,rt.createIdentifier(t),void 0,e);return r&&Lt(o,r),o},Dt=(e,t)=>{let r=B.createSourceFile("print.ts","",B.ScriptTarget.Latest,!1,B.ScriptKind.TS);return B.createPrinter(t).printNode(B.EmitHint.Unspecified,e,r)},di=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gr=e=>di.test(e)?rt.createIdentifier(e):rt.createStringLiteral(e);var{factory:u}=g,ci={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},li=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),mi=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Te(a)?a instanceof kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Gr(s),p&&o?u.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},ui=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),fi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Yr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),yi=e=>ci?.[e.kind],gi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,yi(o)),a={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||g.SyntaxKind.AnyKeyword)}return o},hi=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),xi=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},bi=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ti=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Si=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Ri=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Oi=({next:e,schema:t})=>e(t._def.innerType),ee=e=>()=>u.createKeywordTypeNode(e),Ai=({next:e,schema:t})=>e(t.unwrap()),Pi=({next:e,schema:t})=>e(t._def.innerType),Ci=({next:e,schema:t})=>e(t._def.innerType),Ii=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),wi=()=>u.createLiteralTypeNode(u.createNull()),Ei=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},zi=({schema:e})=>{let t=e.unwrap(),r=u.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof kt.ZodString?r:t instanceof kt.ZodUnion?i:o},Zi=({next:e,schema:t})=>e(t.unwrap().shape.raw),Ni={ZodString:ee(g.SyntaxKind.StringKeyword),ZodNumber:ee(g.SyntaxKind.NumberKeyword),ZodBigInt:ee(g.SyntaxKind.BigIntKeyword),ZodBoolean:ee(g.SyntaxKind.BooleanKeyword),ZodAny:ee(g.SyntaxKind.AnyKeyword),[Ie]:ee(g.SyntaxKind.StringKeyword),[we]:ee(g.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:ui,ZodTuple:Ti,ZodRecord:Si,ZodObject:mi,ZodLiteral:li,ZodIntersection:Ri,ZodUnion:Yr,ZodDefault:Oi,ZodEnum:fi,ZodNativeEnum:hi,ZodEffects:gi,ZodOptional:xi,ZodNullable:bi,ZodDiscriminatedUnion:Yr,ZodBranded:Ai,ZodCatch:Ci,ZodPipeline:Ii,ZodLazy:Ei,ZodReadonly:Pi,[U]:zi,[G]:Zi},ze=({schema:e,...t})=>W({schema:e,rules:Ni,onMissing:()=>u.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),...t});var jt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ue(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=De,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){J({routing:t,onEndpoint:(O,A,P)=>{let re={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},he=E(P,A,"input"),xe=ze({...re,schema:O.getSchema("input"),isResponse:!1}),I=i?E(P,A,"positive.response"):void 0,Ut=O.getSchema("positive"),Ht=i?ze({...re,isResponse:!0,schema:Ut}):void 0,be=i?E(P,A,"negative.response"):void 0,Ft=O.getSchema("negative"),Kt=i?ze({...re,isResponse:!0,schema:Ft}):void 0,Bt=E(P,A,"response"),Qr=I&&be?n.createUnionTypeNode([n.createTypeReferenceNode(I),n.createTypeReferenceNode(be)]):ze({...re,isResponse:!0,schema:Ut.or(Ft)});this.program.push(ue(xe,he)),Ht&&I&&this.program.push(ue(Ht,I)),Kt&&be&&this.program.push(ue(Kt,be)),this.program.push(ue(Qr,Bt)),P!=="options"&&(this.paths.push(A),this.registry.set({method:P,path:A},{input:he,positive:I,negative:be,response:Bt,isJson:O.getMimeTypes("positive").includes(w.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Nt(this.ids.pathType,this.paths)),this.program.push(Nt(this.ids.methodType,_r)),this.program.push(tt(this.ids.methodPathType,Et([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[Zt(this.ids.methodPathType,z.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:O,path:A},{isJson:P,tags:re,...he}]of this.registry){let xe=$r(O,A);for(let I of this.interfaces)I.kind in he&&I.props.push(Ur(xe,he[I.kind]));r!=="types"&&(P&&p.push(n.createPropertyAssignment(xe,n.createTrue())),d.push(n.createPropertyAssignment(xe,n.createArrayLiteralExpression(re.map(I=>n.createStringLiteral(I))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(qr(O,a,A));if(r==="types")return;let c=n.createVariableStatement(F,K(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),m=n.createVariableStatement(F,K(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),l=tt(this.ids.providerType,n.createFunctionTypeNode(Vr({M:this.ids.methodType,P:this.ids.pathType}),et({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),zt)}),Kr(this.ids.responseInterface,zt))),f=tt(this.ids.implementationType,n.createFunctionTypeNode(void 0,et({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:Zt(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),Br())),b=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,me)]),T=vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[b,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),R=vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[b]),z.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),h=Fr(this.ids.clientClass,jr([Xe(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),kr)]),[Hr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,R]),!0))]);this.program.push(c,m,l,f,h);let S=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),fe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),Ze=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ye=n.createVariableStatement(void 0,K(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,me)]),n.createObjectLiteralExpression([S,fe,Ze])])))),te=n.createVariableStatement(void 0,K(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ne=n.createVariableStatement(void 0,K(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),me)])))),[Me,ot]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),ve=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(It,[n.createTemplateSpan(this.ids.methodParameter,wt),n.createTemplateSpan(this.ids.pathParameter,me)]),z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Me])),N=n.createVariableStatement(F,K(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([te,Ne,ye,ve,ot]),!0),n.createTypeReferenceNode(this.ids.implementationType))),q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),ge=n.createVariableStatement(void 0,K(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(N,ge,q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
|
|
21
21
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&z.addSyntheticLeadingComment(z.addSyntheticLeadingComment(n.createEmptyStatement(),z.SyntaxKind.SingleLineCommentTrivia," Usage example:"),z.SyntaxKind.MultiLineCommentTrivia,`
|
|
22
22
|
${r}`);return this.program.concat(o||[]).map((i,s)=>Dt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
23
23
|
|
|
24
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Q("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Mi={dateIn:
|
|
24
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Q("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Mi={dateIn:fr,dateOut:yr,file:Fe,upload:Gt,raw:_t};export{de as AbstractEndpoint,Ae as DependsOnMethod,Ct as Documentation,C as DocumentationError,Oe as EndpointsFactory,D as InputValidationError,jt as Integration,ne as MissingPeerError,V as OutputValidationError,oe as RoutingError,Pe as ServeStatic,wo as arrayEndpointsFactory,gt as arrayResultHandler,_o as attachRouting,uo as createConfig,xt as createLogger,ft as createMiddleware,yt as createResultHandler,Go as createServer,Io as defaultEndpointsFactory,Re as defaultResultHandler,Mi as ez,j as getExamples,k as getMessageFromError,Le as getStatusCodeFromError,si as testEndpoint};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "19.0.0
|
|
3
|
+
"version": "19.0.0",
|
|
4
4
|
"description": "A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -73,13 +73,13 @@
|
|
|
73
73
|
"peerDependencies": {
|
|
74
74
|
"@types/compression": "^1.7.5",
|
|
75
75
|
"@types/express": "^4.17.13",
|
|
76
|
-
"@types/express-fileupload": "^1.
|
|
76
|
+
"@types/express-fileupload": "^1.5.0",
|
|
77
77
|
"@types/http-errors": "^2.0.2",
|
|
78
78
|
"@types/jest": "*",
|
|
79
79
|
"@types/node": "*",
|
|
80
80
|
"compression": "^1.7.4",
|
|
81
|
-
"express": "^4.
|
|
82
|
-
"express-fileupload": "^1.
|
|
81
|
+
"express": "^4.19.2",
|
|
82
|
+
"express-fileupload": "^1.5.0",
|
|
83
83
|
"http-errors": "^2.0.0",
|
|
84
84
|
"jest": ">=28 <30",
|
|
85
85
|
"prettier": "^3.1.0",
|
|
@@ -128,7 +128,7 @@
|
|
|
128
128
|
"@types/compression": "^1.7.5",
|
|
129
129
|
"@types/cors": "^2.8.14",
|
|
130
130
|
"@types/express": "^4.17.17",
|
|
131
|
-
"@types/express-fileupload": "^1.
|
|
131
|
+
"@types/express-fileupload": "^1.5.0",
|
|
132
132
|
"@types/http-errors": "^2.0.2",
|
|
133
133
|
"@types/node": "^20.8.4",
|
|
134
134
|
"@types/ramda": "^0.30.0",
|
|
@@ -146,8 +146,8 @@
|
|
|
146
146
|
"eslint-plugin-import": "^2.28.1",
|
|
147
147
|
"eslint-plugin-prettier": "^5.0.0",
|
|
148
148
|
"eslint-plugin-unicorn": "^53.0.0",
|
|
149
|
-
"express": "^4.
|
|
150
|
-
"express-fileupload": "^1.
|
|
149
|
+
"express": "^4.19.2",
|
|
150
|
+
"express-fileupload": "^1.5.0",
|
|
151
151
|
"http-errors": "^2.0.0",
|
|
152
152
|
"husky": "^9.0.5",
|
|
153
153
|
"make-coverage-badge": "^1.2.0",
|