express-zod-api 17.7.0 → 18.0.0-beta2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +12 -21
- package/SECURITY.md +2 -1
- package/dist/index.cjs +22 -20
- package/dist/index.d.cts +8 -12
- package/dist/index.d.ts +8 -12
- package/dist/index.js +21 -19
- package/package.json +2 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Version 18
|
|
4
|
+
|
|
5
|
+
### v18.0.0
|
|
6
|
+
|
|
7
|
+
- **Breaking changes**:
|
|
8
|
+
- `winston` is no longer a default logger;
|
|
9
|
+
- `createLogger()` argument is changed, and it now returns a built-in logger instead of `winston`.
|
|
10
|
+
- Features:
|
|
11
|
+
- New built-in console logger with colorful pretty inspections and basic methods only.
|
|
12
|
+
- Non-breaking significant changes:
|
|
13
|
+
- Due to detaching from `winston`, the `attachRouting()` method is back to being synchronous.
|
|
14
|
+
- How to migrate confidently:
|
|
15
|
+
- If you're using `attachRouting()` method:
|
|
16
|
+
- Remove `await` before it (and possible async IIFE wrapper if present) — no longer required.
|
|
17
|
+
- If you're using a custom logger in config:
|
|
18
|
+
- No action required.
|
|
19
|
+
- If you're using `createLogger()` method in your code:
|
|
20
|
+
- Remove the `winston` property from its argument.
|
|
21
|
+
- If you're using the default logger in config (which used to be `winston` as a peer dependency):
|
|
22
|
+
- If you're only using its `info()`, `debug()`, `error()` and `warn()` methods:
|
|
23
|
+
- You can now uninstall `winston` — no further action required.
|
|
24
|
+
- If you're using its other methods, like `.child()` or `profile()`:
|
|
25
|
+
- Configure `winston` as a custom logger [according to the documentation](README.md#customizing-logger),
|
|
26
|
+
- Or consider any other compatible logger, like `pino` for example, which is easier to configure.
|
|
27
|
+
|
|
3
28
|
## Version 17
|
|
4
29
|
|
|
5
30
|
### v17.7.0
|
package/README.md
CHANGED
|
@@ -89,7 +89,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
|
|
|
89
89
|
- Web server — [Express.js](https://expressjs.com/).
|
|
90
90
|
- Schema validation — [Zod 3.x](https://github.com/colinhacks/zod).
|
|
91
91
|
- Supports any logger having `info()`, `debug()`, `error()` and `warn()` methods;
|
|
92
|
-
-
|
|
92
|
+
- Built-in console logger with colorful and pretty inspections by default.
|
|
93
93
|
- Generators:
|
|
94
94
|
- Documentation — [OpenAPI 3.1](https://github.com/metadevpro/openapi3-ts) (former Swagger);
|
|
95
95
|
- Client side types — inspired by [zod-to-ts](https://github.com/sachinraja/zod-to-ts).
|
|
@@ -118,14 +118,14 @@ Much can be customized to fit your needs.
|
|
|
118
118
|
Run one of the following commands to install the library, its peer dependencies and packages for types assistance.
|
|
119
119
|
|
|
120
120
|
```shell
|
|
121
|
-
yarn add express-zod-api express zod
|
|
121
|
+
yarn add express-zod-api express zod typescript http-errors
|
|
122
122
|
yarn add --dev @types/express @types/node @types/http-errors
|
|
123
123
|
```
|
|
124
124
|
|
|
125
125
|
or
|
|
126
126
|
|
|
127
127
|
```shell
|
|
128
|
-
npm install express-zod-api express zod
|
|
128
|
+
npm install express-zod-api express zod typescript http-errors
|
|
129
129
|
npm install -D @types/express @types/node @types/http-errors
|
|
130
130
|
```
|
|
131
131
|
|
|
@@ -146,7 +146,6 @@ Create a minimal configuration. _See all available options
|
|
|
146
146
|
|
|
147
147
|
```typescript
|
|
148
148
|
import { createConfig } from "express-zod-api";
|
|
149
|
-
import type { Logger } from "winston";
|
|
150
149
|
|
|
151
150
|
const config = createConfig({
|
|
152
151
|
server: {
|
|
@@ -155,11 +154,6 @@ const config = createConfig({
|
|
|
155
154
|
cors: true,
|
|
156
155
|
logger: { level: "debug", color: true },
|
|
157
156
|
});
|
|
158
|
-
|
|
159
|
-
// Setting the type of the logger used
|
|
160
|
-
declare module "express-zod-api" {
|
|
161
|
-
interface LoggerOverrides extends Logger {}
|
|
162
|
-
}
|
|
163
157
|
```
|
|
164
158
|
|
|
165
159
|
## Create an endpoints factory
|
|
@@ -525,8 +519,9 @@ your API at [Let's Encrypt](https://letsencrypt.org/).
|
|
|
525
519
|
|
|
526
520
|
## Customizing logger
|
|
527
521
|
|
|
528
|
-
|
|
529
|
-
`info()`, `debug()`, `error()` and `warn()
|
|
522
|
+
If the simple console output of the built-in logger is not enough for you, you can connect any other compatible one.
|
|
523
|
+
It must support at least the following methods: `info()`, `debug()`, `error()` and `warn()`.
|
|
524
|
+
Winston and Pino support is well known. Here is an example configuring `pino` logger with `pino-pretty` extension:
|
|
530
525
|
|
|
531
526
|
```typescript
|
|
532
527
|
import pino, { Logger } from "pino";
|
|
@@ -559,7 +554,7 @@ import { randomUUID } from "node:crypto";
|
|
|
559
554
|
const config = createConfig({
|
|
560
555
|
// logger: ...,
|
|
561
556
|
childLoggerProvider: ({ parent, request }) =>
|
|
562
|
-
parent.child({ requestId: randomUUID() }),
|
|
557
|
+
parent.child({ requestId: randomUUID() }), // assuming a custom logger having .child() method
|
|
563
558
|
});
|
|
564
559
|
```
|
|
565
560
|
|
|
@@ -792,7 +787,7 @@ Some options are forced in order to ensure the correct workflow:
|
|
|
792
787
|
{
|
|
793
788
|
abortOnLimit: false,
|
|
794
789
|
parseNested: true,
|
|
795
|
-
logger: {}, // the configured logger
|
|
790
|
+
logger: {}, // the configured logger, using its .debug() method
|
|
796
791
|
}
|
|
797
792
|
```
|
|
798
793
|
|
|
@@ -877,15 +872,11 @@ const app = express(); // or express.Router()
|
|
|
877
872
|
const config = createConfig({ app /* cors, logger, ... */ });
|
|
878
873
|
const routing: Routing = {}; // your endpoints go here
|
|
879
874
|
|
|
880
|
-
|
|
881
|
-
(async () => {
|
|
882
|
-
const { notFoundHandler, logger } = await attachRouting(config, routing);
|
|
883
|
-
|
|
884
|
-
app.use(notFoundHandler); // optional
|
|
885
|
-
app.listen();
|
|
875
|
+
const { notFoundHandler, logger } = attachRouting(config, routing);
|
|
886
876
|
|
|
887
|
-
|
|
888
|
-
|
|
877
|
+
app.use(notFoundHandler); // optional
|
|
878
|
+
app.listen();
|
|
879
|
+
logger.info("Glory to science!");
|
|
889
880
|
```
|
|
890
881
|
|
|
891
882
|
**Please note** that in this case you probably need to parse `request.body`, call `app.listen()` and handle `404`
|
package/SECURITY.md
CHANGED
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
|
|
5
5
|
| Version | Release | Supported |
|
|
6
6
|
| ------: | :------ | :----------------: |
|
|
7
|
+
| 18.x.x | 04.2024 | :white_check_mark: |
|
|
7
8
|
| 17.x.x | 02.2024 | :white_check_mark: |
|
|
8
9
|
| 16.x.x | 12.2023 | :white_check_mark: |
|
|
9
10
|
| 15.x.x | 12.2023 | :white_check_mark: |
|
|
10
|
-
| 14.x.x | 10.2023 |
|
|
11
|
+
| 14.x.x | 10.2023 | :x: |
|
|
11
12
|
| 12.x.x | 09.2023 | :x: |
|
|
12
13
|
| 11.x.x | 06.2023 | :x: |
|
|
13
14
|
| 10.x.x | 03.2023 | :x: |
|
package/dist/index.cjs
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}}
|
|
1
|
+
"use strict";var Ao=Object.create;var Fe=Object.defineProperty;var Ro=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var Co=Object.getPrototypeOf,Io=Object.prototype.hasOwnProperty;var Eo=(e,t)=>{for(var r in t)Fe(e,r,{get:t[r],enumerable:!0})},er=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Po(t))!Io.call(e,i)&&i!==r&&Fe(e,i,{get:()=>t[i],enumerable:!(o=Ro(t,i))||o.enumerable});return e};var A=(e,t,r)=>(r=e!=null?Ao(Co(e)):{},er(t||!e||!e.__esModule?Fe(r,"default",{value:e,enumerable:!0}):r,e)),wo=e=>er(Fe({},"__esModule",{value:!0}),e);var ii={};Eo(ii,{AbstractEndpoint:()=>ne,DependsOnMethod:()=>he,Documentation:()=>pt,DocumentationError:()=>I,EndpointsFactory:()=>ge,InputValidationError:()=>H,Integration:()=>ft,MissingPeerError:()=>ee,OutputValidationError:()=>V,RoutingError:()=>Q,ServeStatic:()=>Te,arrayEndpointsFactory:()=>Rr,arrayResultHandler:()=>rt,attachRouting:()=>Lr,createConfig:()=>tr,createLogger:()=>ot,createMiddleware:()=>et,createResultHandler:()=>tt,createServer:()=>jr,defaultEndpointsFactory:()=>Ar,defaultResultHandler:()=>ye,ez:()=>bo,getExamples:()=>F,getMessageFromError:()=>U,getStatusCodeFromError:()=>Ee,testEndpoint:()=>so,withMeta:()=>k});module.exports=wo(ii);function tr(e){return e}var Ct=A(require("assert/strict"),1),Qe=require("zod");var rr=require("zod"),ce={positive:200,negative:400},gt=(e,t)=>e instanceof rr.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 gr=require("zod");var nr=require("http-errors"),ir=require("crypto"),me=require("ramda"),sr=require("zod");var Q=class extends Error{name="RoutingError"},I=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)}},$=class extends Error{name="IOSchemaError"},V=class extends ${name="OutputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},H=class extends ${name="InputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},X=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ee=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 K="application/json",qe="multipart/form-data",or="application/octet-stream";var zo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(qe);return"files"in e&&r},ht={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Zo=["body","query","params"],xt=e=>e.method.toLowerCase(),Tt=e=>e.startsWith("x-"),Mo=e=>(0,me.pickBy)((0,me.flip)(Tt),e),ar=(e,t={})=>{let r=xt(e);return r==="options"?{}:(t[r]||ht[r]||Zo).filter(o=>o==="files"?zo(e):!0).map(o=>o==="headers"?Mo(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 sr.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,Ee=e=>(0,nr.isHttpError)(e)?e.statusCode:e instanceof H?400:500,bt=({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})},
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};var hr=require("ramda");var re=e=>Z(e)&&"or"in e,fe=e=>Z(e)&&"and"in e,Ot=e=>({and:(0,hr.chain)(t=>fe(t)?t.and:[t],e)}),We=(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),At=e=>e.and.reduce((t,r)=>({or:ee(t.or,re(r)?r.or:[r],Ot)}),{or:[]}),ue=(e,t)=>fe(e)?re(t)?ue(At(e),t):Ot([e,t]):re(e)?fe(t)?ue(t,e):re(t)?{or:ee(e.or,t.or,Ot)}:ue(e,{and:[t]}):fe(t)||re(t)?ue(t,e):{and:[e,t]};var oe=class{},Je=class extends oe{#e;#o;#n;#i;#t;#s;#a;#r;#p;#d;#c;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:m=[],description:u,shortDescription:l}){super(),this.#s=i,this.#a=s,this.#n=d,this.#c=a,this.#o=t,this.#p=p,this.#d=m,this.#e={long:u,short:l},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,Rt.default)(!_e(T),new V(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:ft(s.getPositiveResponse(o),{mimeTypes:[U],statusCodes:[ce.positive]}),negative:ft(s.getNegativeResponse(),{mimeTypes:[U],statusCodes:[ce.negative]})};for(let[y,T]of Object.entries(this.#t))(0,Rt.default)(T.length,new Q(`ResultHandler must have at least one ${y} response schema specified.`));this.#i={input:yr(r)?[Ke]:gr(r)?[er]:[U],positive:this.#t.positive.flatMap(({mimeTypes:y})=>y),negative: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.#i[t]}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ue(t,r.security):t,{and:[]})}getScopes(){return this.#p}getTags(){return this.#d}getOperationId(t){return this.#c(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#l(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof Ye.z.ZodError?new $(r):r}}async#u({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(m){throw m instanceof Ye.z.ZodError?new j(m):m}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#f({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof Ye.z.ZodError?new j(s):s}return this.#s({input:i,options:r,logger:o})}async#y({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#a.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Ge({logger:i,response:o,error:new Q(le(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=gt(t),p={},d=null,m=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 y in l)r.set(y,l[y])}let u=nr(t,i.inputSources);try{if(await this.#u({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.#l(await this.#f({input:u,logger:o,options:p}))}catch(l){m=le(l)}await this.#y({input:u,output:d,request:t,response:r,error:m,logger:o,options:p})}};var Pt=require("zod");var xr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>sr(s,i),o)};var Tr=R(require("assert/strict"),1),Qe=e=>((0,Tr.default)(!_e(e.input),new V("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var M=require("zod");var Xe=e=>e,ye=Xe({getPositiveResponse:e=>{let t=K({schema:e}),r=D(M.z.object({status:M.z.literal("success"),data:e}));return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>D(M.z.object({status:M.z.literal("error"),error:M.z.object({message:M.z.string()})})).example({status:"error",error:{message:H(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(ce.positive).json({status:"success",data:r});return}let a=Ce(e);xt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:H(e)}})}}),et=Xe({getPositiveResponse:e=>{let t=K({schema:e}),r=D("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)=>Z(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>D(M.z.string()).example(H(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Ce(r);xt({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(ce.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:Pt.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,m)=>{t(a,p,l=>{if(l&&l instanceof Error)return m(o(l));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(Qe({input:Pt.z.object({}),middleware:async()=>t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:m}=this,u="methods"in p?p.methods:[p.method],l=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 Je({handler:r,middlewares:d,outputSchema:o,resultHandler:m,scopes:y,tags:T,methods:u,getOperationId:l,description:i,shortDescription:s,inputSchema:xr(d,t)})}},br=new ge(ye),Sr=new ge(et);var Or=require("util");var Ar=e=>Z(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","debug"].includes(e.level)&&Object.values(e).find(t=>typeof t=="function")===void 0,tt=({winston:{createLogger:e,transports:t,format:{printf:r,timestamp:o,colorize:i,combine:s},config:{npm:a}},...p})=>{let d=p.level==="silent",m=p.level==="debug",u=y=>(0,Or.inspect)(y,{colors:p.color,depth:p.depth,breakLength:m?80:1/0,compact:m?3:!0}),l=r(({timestamp:y,message:T,level:S,durationMs:A,...h})=>{typeof T=="object"&&(h[Symbol.for("splat")]=[T],T="[No message]");let b=[];A&&b.push("duration:",`${A}ms`);let q=h?.[Symbol.for("splat")];return Array.isArray(q)&&b.push(...q.map(u)),[y,`${S}:`,T,...b].join(" ")});return e({silent:d,levels:a.levels,exitOnError:!1,transports:[new t.Console({level:d?"warn":p.level,handleExceptions:!0,format:s(o(),...p.color?[i()]:[],l)})]})};var xe=require("ramda"),he=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=(0,xe.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=(0,xe.head)(this.pairs)?.[1],this.siblingMethods=(0,xe.tail)(this.pairs).map(([r])=>r)}};var Rr=R(require("express"),1),Te=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Rr.default.static(...this.params))}};var Et=R(require("express"),1),zr=R(require("http"),1),Zr=R(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)},Pr=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 Ct=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){Ct.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 m=p.getMethods().slice();i&&m.push("options");for(let u of m)t(p,d,u)}else if(p instanceof Te)r&&p.apply(d,r);else if(p instanceof he){for(let[m,u]of p.pairs)(0,Ct.default)(u.getMethods().includes(m),new J(`Endpoint assigned to ${m} method of ${d} must support ${m} method.`)),t(u,d,m);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else ie({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Cr=()=>`
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`;var It=({app:e,rootLogger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(Cr()),t.debug("Running","v17.7.0 (CJS)"),ie({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,m)=>{let u=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;u.info(`${d.method}: ${s}`),await i.execute({request:d,response:m,logger:u,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}})};var Ze=R(require("http-errors"),1);var Ir=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:(0,Ze.isHttpError)(o)?o:(0,Ze.default)(400,le(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},Er=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=(0,Ze.default)(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Ge({response:i,logger:a,error:new Q(le(p).message,s)})}},wr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};var Mr=async e=>{let t=Ar(e.logger)?tt({...e.logger,winston:await ne("winston")}):e.logger,r=e.errorHandler||ye,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=Er(i),a=Ir(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Nr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o}=await Mr(e);return It({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},vr=async(e,t)=>{let r=(0,Et.default)().disable("x-powered-by");if(e.server.compression){let d=await ne("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||Et.default.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await Mr(e);if(e.server.upload){let d=await ne("express-fileupload"),{limitError:m,beforeUpload:u,...l}={...typeof e.server.upload=="object"&&e.server.upload};u&&u({app:r,logger:o}),r.use(d({...l,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),m&&r.use(wr(m))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},m)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),m()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),It({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,m)=>d.listen(m,()=>{o.info("Listening",m)}),p={httpServer:a(zr.default.createServer(r),e.server.listen),httpsServer:e.https?a(Zr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};var eo=R(require("assert/strict"),1),to=require("openapi3-ts/oas31");var F=R(require("assert/strict"),1),G=require("openapi3-ts/oas31"),c=require("ramda"),O=require("zod");var wt=require("zod");var rt=e=>!isNaN(e.getTime()),ot=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Me="DateIn",Dr=()=>E(Me,wt.z.string().regex(ot).transform(e=>new Date(e)).pipe(wt.z.date().refine(rt)));var kr=require("zod");var Ne="DateOut",Lr=()=>E(Ne,kr.z.date().refine(rt).transform(e=>e.toISOString()));var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Ee(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,m=a?a({schema:e,...p,next:l=>se({schema:l,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),u=t&&t({schema:e,prev:m,...p});return u?{...m,...u}:m};var jr=50,Ur="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",jo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Kr=/:([A-Za-z0-9_]+)/g,Fr=e=>e.match(Kr)?.map(t=>t.slice(1))||[],Br=e=>e.replace(Kr,t=>`{${t.slice(1)}}`),Ho=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Uo=({schema:{_def:{innerType:e}},next:t})=>t(e),Ko=()=>({format:"any"}),Fo=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Bo=({schema:e})=>({type:"string",format:e instanceof O.z.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),qo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Vo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),$o=e=>{let[t,r]=e.filter(i=>!(0,G.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,F.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:F.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},_o=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return $o(o)}catch{}return{allOf:o}},Go=({schema:e,next:t})=>t(e.unwrap()),Wo=({schema:e,next:t})=>t(e._def.innerType),Yo=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,G.isReferenceObject)(r)||(r.type=Vr(r)),r},qr=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},Hr=({schema:e})=>({type:qr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jo=({schema:{value:e}})=>({type:qr(e),const:e}),Qo=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ie(p)?p instanceof O.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=nt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},Xo=()=>({type:"null"}),en=e=>((0,F.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:ot.source,externalDocs:{url:Ur}}),tn=e=>((0,F.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:Ur}}),rn=e=>F.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})),on=()=>({type:"boolean"}),nn=()=>({type:"integer",format:"bigint"}),sn=e=>e.every(t=>t instanceof O.z.ZodLiteral),an=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof O.z.ZodEnum||e instanceof O.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=nt({schema:O.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof O.z.ZodLiteral)return{type:"object",properties:nt({schema:O.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof O.z.ZodUnion&&sn(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:nt({schema:O.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},pn=({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},dn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),cn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:m,isDatetime:u,_def:{checks:l}}})=>{let y=l.find(b=>b.kind==="regex"),T=l.find(b=>b.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"},h={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:m};for(let b in h)if(h[b]){A.format=b;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),S&&(A.pattern=S.source),A},mn=({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},nt=({schema:{shape:e},next:t})=>(0,c.map)(t,e),ln=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return jo?.[t]},Vr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},un=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,G.isReferenceObject)(o)){let s=Be(e,ln(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(O.z.any())}if(!t&&i.type==="preprocess"&&!(0,G.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},fn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),yn=({schema:e,next:t})=>t(e.unwrap()),gn=({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)))},hn=({next:e,schema:t})=>e(t.shape.raw),$r=e=>e.length?(0,c.zipObj)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e)):void 0,_r=(e,t,r=[])=>(0,c.pipe)(K,(0,c.map)((0,c.when)((0,c.both)(Z,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),$r)({schema:e,variant:t?"parsed":"original",validate:!0}),xn=(e,t)=>(0,c.pipe)(K,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),$r)({schema:e,variant:"original",validate:!0}),ve=(e,t)=>e instanceof O.z.ZodObject?e:e instanceof O.z.ZodUnion||e instanceof O.z.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>ve(r,t)).reduce((r,o)=>r.merge(o.partial()),O.z.object({})):e instanceof O.z.ZodEffects?((0,F.default)(e._def.effect.type==="refinement",t),ve(e._def.schema,t)):ve(e._def.left,t).merge(ve(e._def.right,t)),Gr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=ve(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=Fr(e),l=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=h=>y&&u.includes(h),A=h=>T&&ht(h);return Object.keys(m).filter(h=>l||S(h)).map(h=>{let b=se({schema:m[h],isResponse:!1,rules:Zt,onEach:Mt,onMissing:Nt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),q=p==="components"?a(z(d,h),b):b;return{name:h,in:S(h)?"path":A(h)?"header":"query",required:!m[h].isOptional(),description:b.description||d,schema:q,examples:xn(r,h)}})},Zt={ZodString:cn,ZodNumber:mn,ZodBigInt:nn,ZodBoolean:on,ZodNull:Xo,ZodArray:pn,ZodTuple:dn,ZodRecord:an,ZodObject:Qo,ZodLiteral:Jo,ZodIntersection:_o,ZodUnion:qo,ZodAny:Ko,ZodDefault:Ho,ZodEnum:Hr,ZodNativeEnum:Hr,ZodEffects:un,ZodOptional:Go,ZodNullable:Yo,ZodDiscriminatedUnion:Vo,ZodBranded:yn,ZodDate:rn,ZodCatch:Uo,ZodPipeline:fn,ZodLazy:gn,ZodReadonly:Wo,[_]:Bo,[ze]:Fo,[Ne]:tn,[Me]:en,[te]:hn},Mt=({schema:e,isResponse:t,prev:r})=>{if((0,G.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof O.z.ZodLazy,s=r.type!==void 0,a=t&&Ie(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),m={};return o&&(m.description=o),p&&(m.type=Vr(r)),d.length&&(m.examples=Array.from(d)),m},Nt=({schema:e,...t})=>F.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),zt=(e,t)=>{if((0,G.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=>zt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>zt(o,t))),r},Wr=e=>(0,G.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),Yr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:m,statusCode:u,description:l=`${e.toUpperCase()} ${t} ${Tt(i)} response ${m?u:""}`.trim()})=>{let y=Wr(se({schema:r,isResponse:!0,rules:Zt,onEach:Mt,onMissing:Nt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(z(l),y):y,examples:_r(r,!0)};return{description:l,content:(0,c.fromPairs)((0,c.xprod)(o,[T]))}},Tn=()=>({type:"http",scheme:"basic"}),bn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Sn=({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},On=({name:e})=>({type:"apiKey",in:"header",name:e}),An=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Pn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),Jr=(e,t)=>{let r={basic:Tn,bearer:bn,input:Sn,header:On,cookie:An,openid:Rn,oauth2:Pn};return We(e,o=>r[o.type](o,t))},it=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?it(At(e)):it({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let m=Fr(t),u=Wr(zt(se({schema:r,isResponse:!1,rules:Zt,onEach:Mt,onMissing:Nt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),m)),l={schema:p==="components"?a(z(d),u):u,examples:_r(r,!1,m)};return{description:d,content:(0,c.fromPairs)((0,c.xprod)(o,[l]))}},Xr=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}),vt=e=>e.length<=jr?e:e.slice(0,jr-1)+"\u2026";var st=class extends to.OpenApiBuilder{lastSecuritySchemaIds={};lastOperationIdSuffixes={};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){if(o)return(0,eo.default)(!(o in this.lastOperationIdSuffixes),new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=z(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:m=Fe}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});ie({routing:t,onEndpoint:(l,y,T)=>{let S=T,A={path:y,method:S,endpoint:l,composition:d,serializer:m,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,b]=["short","long"].map(l.getDescription.bind(l)),q=h?vt(h):p&&b?vt(b):void 0,ke=l.getTags(),Ae=r.inputSources?.[S]||yt[S],pe=this.ensureUniqOperationId(y,S,l.getOperationId(S)),Le=Gr({...A,inputSources:Ae,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),je={};for(let L of["positive","negative"]){let x=l.getResponses(L);for(let{mimeTypes:P,schema:C,statusCodes:N}of x)for(let de of N)je[de]=Yr({...A,variant:L,schema:C,mimeTypes:P,statusCode:de,hasMultipleStatusCodes:x.length>1||N.length>1,description:a?.[`${L}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:de})})}let ut=Ae.includes("body")?Qr({...A,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,He=it(We(Jr(l.getSecurity(),Ae),L=>{let x=this.ensureUniqSecuritySchemaName(L),P=["oauth2","openIdConnect"].includes(L.type)?l.getScopes():[];return this.addSecurityScheme(x,L),{name:x,scopes:P}}));this.addPath(Br(y),{[S]:{operationId:pe,summary:q,description:b,tags:ke.length>0?ke:void 0,parameters:Le.length>0?Le:void 0,requestBody:ut,security:He.length>0?He:void 0,responses:je}})}}),this.rootDoc.tags=r.tags?Xr(r.tags):[]}};var Dt=R(require("http"),1);var Cn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>U),...t}),In=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Dt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Dt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},En=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ro=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Pr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Cn({fnMethod:a,requestProps:t}),d=In({fnMethod:a,responseProps:r}),m=En({fnMethod:a,loggerProps:i}),u={cors:!1,logger:m,...o};return await e.execute({request:p,response:d,config:u,logger:m}),{requestMock:p,responseMock:d,loggerMock:m}};var w=R(require("typescript"),1);var k=R(require("typescript"),1),be=require("ramda"),n=k.default.factory,W=[n.createModifier(k.default.SyntaxKind.ExportKeyword)],wn=[n.createModifier(k.default.SyntaxKind.AsyncKeyword)],zn=[n.createModifier(k.default.SyntaxKind.PublicKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],oo=[n.createModifier(k.default.SyntaxKind.ProtectedKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],kt=n.createTemplateHead(""),Se=n.createTemplateTail(""),Lt=n.createTemplateMiddle(" "),jt=e=>n.createTemplateLiteralType(kt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Se:Lt))),Ht=jt(["M","P"]),at=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),pt=(e,t)=>(0,be.chain)(([r,o])=>[at(n.createIdentifier(r),o,t)],(0,be.toPairs)(e)),Ut=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),no=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),io=(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)],k.default.NodeFlags.Const),Kt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),dt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,t),so=(e,t,r)=>n.createPropertyDeclaration(zn,e,void 0,t,r),ao=(e,t,r)=>n.createClassDeclaration(W,e,void 0,void 0,[t,...r]),po=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),co=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.default.SyntaxKind.AnyKeyword)]),mo=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),lo=e=>(0,be.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,be.toPairs)(e)),Ft=(e,t,r)=>n.createArrowFunction(r?wn:void 0,void 0,e.map(o=>at(o)),void 0,void 0,t),Bt=(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,pt({acc:void 0,key:void 0}),void 0,void 0,t),r]);var uo=["get","post","put","delete","patch"];var g=R(require("typescript"),1),mt=require("zod");var B=R(require("typescript"),1),{factory:ct}=B.default,qt=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Oe=(e,t,r)=>{let o=ct.createTypeAliasDeclaration(void 0,ct.createIdentifier(t),void 0,e);return r&&qt(o,r),o},Vt=(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)},Zn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fo=e=>Zn.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:f}=g.default,Mn={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Nn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),vn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ie(a)?a instanceof mt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,fo(s),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&qt(d,a.description),d});return f.createTypeLiteralNode(i)},Dn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),kn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),yo=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),Ln=e=>Mn?.[e.kind],jn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Be(e,Ln(o)),a={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||g.default.SyntaxKind.AnyKeyword)}return o},Hn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Un=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Kn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Fn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Bn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),qn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Vn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),$n=({next:e,schema:t})=>e(t.unwrap()),_n=({next:e,schema:t})=>e(t._def.innerType),Gn=({next:e,schema:t})=>e(t._def.innerType),Wn=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Yn=()=>f.createLiteralTypeNode(f.createNull()),Jn=({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)))},Qn=({schema:e})=>{let t=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),r=f.createTypeReferenceNode("Buffer"),o=f.createUnionTypeNode([t,r]);return e instanceof mt.z.ZodString?t:e instanceof mt.z.ZodUnion?o:r},Xn=({next:e,schema:t})=>e(t.shape.raw),ei={ZodString:ae(g.default.SyntaxKind.StringKeyword),ZodNumber:ae(g.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(g.default.SyntaxKind.BooleanKeyword),ZodAny:ae(g.default.SyntaxKind.AnyKeyword),[Me]:ae(g.default.SyntaxKind.StringKeyword),[Ne]:ae(g.default.SyntaxKind.StringKeyword),ZodNull:Yn,ZodArray:Dn,ZodTuple:Fn,ZodRecord:Bn,ZodObject:vn,ZodLiteral:Nn,ZodIntersection:qn,ZodUnion:yo,ZodDefault:Vn,ZodEnum:kn,ZodNativeEnum:Hn,ZodEffects:jn,ZodOptional:Un,ZodNullable:Kn,ZodDiscriminatedUnion:yo,ZodBranded:$n,ZodCatch:Gn,ZodPipeline:Wn,ZodLazy:Jn,ZodReadonly:_n,[_]:Qn,[te]:Xn},De=({schema:e,...t})=>se({schema:e,rules:ei,onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),...t});var lt=class{program=[];usage=[];registry={};paths=[];aliases={};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 t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=Oe(r,t),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Fe,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(x,P,C)=>{let N={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},de=z(C,P,"input"),ho=De({...N,schema:x.getSchema("input"),isResponse:!1}),Re=i?z(C,P,"positive.response"):void 0,$t=x.getSchema("positive"),_t=i?De({...N,isResponse:!0,schema:$t}):void 0,Pe=i?z(C,P,"negative.response"):void 0,Gt=x.getSchema("negative"),Wt=i?De({...N,isResponse:!0,schema:Gt}):void 0,Yt=z(C,P,"response"),xo=Re&&Pe?n.createUnionTypeNode([n.createTypeReferenceNode(Re),n.createTypeReferenceNode(Pe)]):De({...N,isResponse:!0,schema:$t.or(Gt)});this.program.push(Oe(ho,de)),_t&&Re&&this.program.push(Oe(_t,Re)),Wt&&Pe&&this.program.push(Oe(Wt,Pe)),this.program.push(Oe(xo,Yt)),C!=="options"&&(this.paths.push(P),this.registry[`${C} ${P}`]={input:de,positive:Re,negative:Pe,response:Yt,isJson:x.getMimeTypes("positive").includes(U),tags:x.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(Kt(this.ids.pathType,this.paths)),this.program.push(Kt(this.ids.methodType,uo)),this.program.push(dt(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.default.SyntaxKind.ExtendsKeyword,[Ut(this.ids.methodPathType,w.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:x,kind:P}of this.interfaces)this.program.push(mo(x,a,Object.keys(this.registry).map(C=>{let N=this.registry[C][P];return N?io(C,N):void 0}).filter(C=>C!==void 0)));if(r==="types")return;let p=n.createVariableStatement(W,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(x=>this.registry[x].isJson).map(x=>n.createPropertyAssignment(`"${x}"`,n.createTrue()))))),d=n.createVariableStatement(W,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(x=>n.createPropertyAssignment(`"${x}"`,n.createArrayLiteralExpression(this.registry[x].tags.map(P=>n.createStringLiteral(P)))))))),m=dt(this.ids.providerType,n.createFunctionTypeNode(lo({M:this.ids.methodType,P:this.ids.pathType}),pt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ht)}),po(this.ids.responseInterface,Ht))),u=dt(this.ids.implementationType,n.createFunctionTypeNode(void 0,pt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.default.SyntaxKind.StringKeyword),params:Ut(w.default.SyntaxKind.StringKeyword,w.default.SyntaxKind.AnyKeyword)}),co())),l=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Se)]),y=Bt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[l,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),T=Bt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[l]),w.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()),S=ao(this.ids.clientClass,no([at(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),oo)]),[so(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Ft([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,y,T]),!0))]);this.program.push(p,d,m,u,S);let A=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),h=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(U))]),void 0,this.ids.undefinedValue)),b=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)),q=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,Se)]),n.createObjectLiteralExpression([A,h,b])])))),ke=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])))),Ae=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]),Se)])))),[pe,Le]=["json","text"].map(x=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,x),void 0,void 0))),je=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(kt,[n.createTemplateSpan(this.ids.methodParameter,Lt),n.createTemplateSpan(this.ids.pathParameter,Se)]),w.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([pe])),ut=n.createVariableStatement(W,Y(this.ids.exampleImplementationConst,Ft([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([ke,Ae,q,je,Le]),!0),n.createTypeReferenceNode(this.ids.implementationType))),He=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"))])])),L=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(ut,L,He)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Vt(r,t)).join(`
|
|
19
|
-
`)
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((i,s)=>Vt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
4
|
+
`,{url:t.url,payload:r})},F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=ze(e,"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},te=(e,t,r)=>e.length&&t.length?(0,me.xprod)(e,t).map(r):e.concat(t),we=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,St=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),Z=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(St).join(""),Be=e=>(0,ir.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),$e=(e,t)=>{try{return typeof e.parse(t)}catch{return}},M=e=>typeof e=="object"&&e!==null;var Ve=require("ramda"),D="expressZodApiMeta",No=e=>e.describe(e.description),k=e=>{let t=No(e);return t._def[D]=(0,Ve.clone)(t._def[D])||{examples:[]},Object.defineProperties(t,{example:{get:()=>r=>{let o=k(t);return o._def[D].examples.push(r),o}}})},pr=e=>D in e._def&&M(e._def[D]),ze=(e,t)=>pr(e)?e._def[D][t]:void 0,dr=(e,t)=>{if(!pr(e))return t;let r=k(t);return r._def[D].examples=te(r._def[D].examples,e._def[D].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,Ve.mergeDeepRight)({...o},{...i}):i),r},E=(e,t)=>{let r=k(t);return r._def[D].kind=e,r},Ot=(e,t)=>ze(e,"kind")===t;var mr=require("zod");var Ze=require("zod");var _="File",cr=Ze.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),vo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Do={buffer:()=>E(_,cr),string:()=>E(_,Ze.z.string()),binary:()=>E(_,cr.or(Ze.z.string())),base64:()=>E(_,Ze.z.string().regex(vo,"Does not match base64 encoding"))};function _e(e){return Do[e||"string"]()}var re="Raw",lr=()=>E(re,mr.z.object({raw:_e("buffer")}));var ur=require("zod");var Me="Upload",fr=()=>E(Me,ur.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}`})));var At=({schema:{options:e},next:t})=>e.some(t),hr=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),ko=({schema:e,next:t})=>Object.values(e.shape).some(t),yr=({schema:e,next:t})=>t(e.unwrap()),Lo=({schema:e,next:t})=>t(e.innerType()),jo=({schema:e,next:t})=>t(e.valueSchema),Ho=({schema:e,next:t})=>t(e.element),Uo=({schema:e,next:t})=>t(e._def.innerType),Ko={ZodObject:ko,ZodUnion:At,ZodDiscriminatedUnion:At,ZodIntersection:hr,ZodEffects:Lo,ZodOptional:yr,ZodNullable:yr,ZodRecord:jo,ZodArray:Ho,ZodDefault:Uo},Ge=({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=>Ge({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},Ye=e=>Ge({subject:e,maxDepth:3,rules:{ZodUnion:At,ZodIntersection:hr},condition:t=>t instanceof gr.z.ZodEffects&&t._def.effect.type!=="refinement"}),xr=e=>Ge({subject:e,condition:t=>Ot(t,Me)}),Tr=e=>Ge({subject:e,condition:t=>Ot(t,re),maxDepth:3});var Je=({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 br=require("ramda");var oe=e=>M(e)&&"or"in e,fe=e=>M(e)&&"and"in e,Rt=e=>({and:(0,br.chain)(t=>fe(t)?t.and:[t],e)}),We=(e,t)=>fe(e)?{and:e.and.map(r=>oe(r)?{or:r.or.map(t)}:t(r))}:oe(e)?{or:e.or.map(r=>fe(r)?{and:r.and.map(t)}:t(r))}:t(e),Pt=e=>e.and.reduce((t,r)=>({or:te(t.or,oe(r)?r.or:[r],Rt)}),{or:[]}),ue=(e,t)=>fe(e)?oe(t)?ue(Pt(e),t):Rt([e,t]):oe(e)?fe(t)?ue(t,e):oe(t)?{or:te(e.or,t.or,Rt)}:ue(e,{and:[t]}):fe(t)||oe(t)?ue(t,e):{and:[e,t]};var ne=class{},Xe=class extends ne{#e;#o;#n;#i;#t;#s;#a;#r;#p;#d;#c;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:u,shortDescription:l}){super(),this.#s=i,this.#a=s,this.#n=d,this.#c=a,this.#o=t,this.#p=p,this.#d=c,this.#e={long:u,short:l},this.#r={input:r,output:o};for(let[y,S]of Object.entries(this.#r))(0,Ct.default)(!Ye(S),new $(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:gt(s.getPositiveResponse(o),{mimeTypes:[K],statusCodes:[ce.positive]}),negative:gt(s.getNegativeResponse(),{mimeTypes:[K],statusCodes:[ce.negative]})};for(let[y,S]of Object.entries(this.#t))(0,Ct.default)(S.length,new X(`ResultHandler must have at least one ${y} response schema specified.`));this.#i={input:xr(r)?[qe]:Tr(r)?[or]:[K],positive:this.#t.positive.flatMap(({mimeTypes:y})=>y),negative: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.#i[t]}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ue(t,r.security):t,{and:[]})}getScopes(){return this.#p}getTags(){return this.#d}getOperationId(t){return this.#c(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#l(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof Qe.z.ZodError?new V(r):r}}async#u({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 Qe.z.ZodError?new H(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#f({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof Qe.z.ZodError?new H(s):s}return this.#s({input:i,options:r,logger:o})}async#y({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#a.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Je({logger:i,response:o,error:new X(le(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=xt(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 y in l)r.set(y,l[y])}let u=ar(t,i.inputSources);try{if(await this.#u({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.#l(await this.#f({input:u,logger:o,options:p}))}catch(l){c=le(l)}await this.#y({input:u,output:d,request:t,response:r,error:c,logger:o,options:p})}};var It=require("zod");var Sr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>dr(s,i),o)};var Or=A(require("assert/strict"),1),et=e=>((0,Or.default)(!Ye(e.input),new $("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var N=require("zod");var tt=e=>e,ye=tt({getPositiveResponse:e=>{let t=F({schema:e}),r=k(N.z.object({status:N.z.literal("success"),data:e}));return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>k(N.z.object({status:N.z.literal("error"),error:N.z.object({message:N.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(ce.positive).json({status:"success",data:r});return}let a=Ee(e);bt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),rt=tt({getPositiveResponse:e=>{let t=F({schema:e}),r=k("shape"in e&&"items"in e.shape&&e.shape.items instanceof N.z.ZodArray?e.shape.items:N.z.array(N.z.any()));return t.reduce((o,i)=>M(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>k(N.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=Ee(r);bt({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(ce.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:It.z.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(et({input:It.z.object({}),middleware:async()=>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],l=typeof a=="function"?a:()=>a,y="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],S="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Xe({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:y,tags:S,methods:u,getOperationId:l,description:i,shortDescription:s,inputSchema:Sr(d,t)})}},Ar=new ge(ye),Rr=new ge(rt);var Pr=require("util");var Cr=require("ramda"),G=require("ansis"),Et={debug:10,info:20,warn:30,error:40},Ir=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","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),ot=({level:e,color:t=!1,depth:r=2})=>{let o={debug:G.blue,info:G.green,warn:(0,G.hex)("#FFA500"),error:G.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,Pr.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Cr.mapObjIndexed)(({},p)=>(d,c)=>a(p,d,c),Et)};var xe=require("ramda"),he=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=(0,xe.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=(0,xe.head)(this.pairs)?.[1],this.siblingMethods=(0,xe.tail)(this.pairs).map(([r])=>r)}};var Er=A(require("express"),1),Te=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Er.default.static(...this.params))}};var Zt=A(require("express"),1),vr=A(require("http"),1),Dr=A(require("https"),1);var be=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>require(e)[t])}catch{}throw new ee(e)},wr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await be(t,r)}catch{}throw new ee(e.map(({moduleName:t})=>t))};var wt=A(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){wt.default.doesNotMatch(a,/\//,new Q(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ne){let c=p.getMethods().slice();i&&c.push("options");for(let u of c)t(p,d,u)}else if(p instanceof Te)r&&p.apply(d,r);else if(p instanceof he){for(let[c,u]of p.pairs)(0,wt.default)(u.getMethods().includes(c),new Q(`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})=>ie({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let u=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;u.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:u,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}});var Ne=A(require("http-errors"),1);var zr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:(0,Ne.isHttpError)(o)?o:(0,Ne.default)(400,le(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},Zr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=(0,Ne.default)(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Je({response:i,logger:a,error:new X(le(p).message,s)})}},Mr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};var w=require("ansis"),Nr=()=>{let e=(0,w.italic)("Proudly supports transgender community.".padStart(109)),t=(0,w.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,w.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,w.italic)("for Victoria".padEnd(20)),i=(0,w.hex)("#F5A9B8"),s=(0,w.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(w.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(w.gray,12,13);return`
|
|
6
|
+
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
7
|
+
888 d88P 888 d88888 888 Y88b 888
|
|
8
|
+
888 d88P 888 d88P888 888 888 888
|
|
9
|
+
8888888 888 888 88888b. 888d888 .d88b. .d8888b .d8888b d88P .d88b. .d88888 d88P 888 888 d88P 888
|
|
10
|
+
888 \u1FEFY8bd8P' 888 "88b 888P" d8P Y8b 88K 88K d88P d88""88b d88" 888 d88P 888 8888888P" 888
|
|
11
|
+
888 X88K 888 888 888 88888888 "Y8888b. "Y8888b. d88P 888 888 888 888 d88P 888 888 888
|
|
12
|
+
888 .d8""8b. 888 d88P 888 Y8b. X88 X88 d88P Y88..88P Y88b 888 d8888888888 888 888
|
|
13
|
+
8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P' d8888888888 "Y88P" "Y88888 d88P 888 888 8888888
|
|
14
|
+
888
|
|
15
|
+
888${e}
|
|
16
|
+
${o}888${t}
|
|
17
|
+
${r}
|
|
18
|
+
`.split(`
|
|
19
|
+
`).map((d,c)=>a[c]?a[c](d):d).join(`
|
|
20
|
+
`)};var kr=e=>{e.startupLogo!==!1&&console.log(Nr());let t=Ir(e.logger)?ot(e.logger):e.logger;t.debug("Running","v18.0.0-beta2 (CJS)");let r=e.errorHandler||ye,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=Zr(i),a=zr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Lr=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=kr(e);return zt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},jr=async(e,t)=>{let r=(0,Zt.default)().disable("x-powered-by");if(e.server.compression){let d=await be("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||Zt.default.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=kr(e);if(e.server.upload){let d=await be("express-fileupload"),{limitError:c,beforeUpload:u,...l}={...typeof e.server.upload=="object"&&e.server.upload};u&&u({app:r,logger:o}),r.use(d({...l,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),c&&r.use(Mr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),zt({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(vr.default.createServer(r),e.server.listen),httpsServer:e.https?a(Dr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};var no=A(require("assert/strict"),1),io=require("openapi3-ts/oas31");var q=A(require("assert/strict"),1),Y=require("openapi3-ts/oas31"),m=require("ramda"),T=require("zod");var Mt=require("zod");var nt=e=>!isNaN(e.getTime()),it=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var ve="DateIn",Hr=()=>E(ve,Mt.z.string().regex(it).transform(e=>new Date(e)).pipe(Mt.z.date().refine(nt)));var Ur=require("zod");var De="DateOut",Kr=()=>E(De,Ur.z.date().refine(nt).transform(e=>e.toISOString()));var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=ze(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:l=>se({schema:l,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),u=t&&t({schema:e,prev:c,...p});return u?{...c,...u}:c};var Fr=50,Br="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Fo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},$r=/:([A-Za-z0-9_]+)/g,Vr=e=>e.match($r)?.map(t=>t.slice(1))||[],_r=e=>e.replace($r,t=>`{${t.slice(1)}}`),qo=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Bo=({schema:{_def:{innerType:e}},next:t})=>t(e),$o=()=>({format:"any"}),Vo=e=>((0,q.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),_o=({schema:e})=>({type:"string",format:e instanceof T.z.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),Go=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Yo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),Jo=e=>{let[t,r]=e.filter(i=>!(0,Y.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,m.concat)(i,s):i===s?s:q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=te(t.examples||[],r.examples||[],([i,s])=>(0,m.mergeDeepRight)(i,s))),o},Wo=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Jo(o)}catch{}return{allOf:o}},Qo=({schema:e,next:t})=>t(e.unwrap()),Xo=({schema:e,next:t})=>t(e._def.innerType),en=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,Y.isReferenceObject)(r)||(r.type=Yr(r)),r},Gr=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},qr=({schema:e})=>({type:Gr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),tn=({schema:{value:e}})=>({type:Gr(e),const:e}),rn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&we(p)?p instanceof T.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=st({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},on=()=>({type:"null"}),nn=e=>((0,q.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:it.source,externalDocs:{url:Br}}),sn=e=>((0,q.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:Br}}),an=e=>q.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})),pn=()=>({type:"boolean"}),dn=()=>({type:"integer",format:"bigint"}),cn=e=>e.every(t=>t instanceof T.z.ZodLiteral),mn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof T.z.ZodEnum||e instanceof T.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=st({schema:T.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof T.z.ZodLiteral)return{type:"object",properties:st({schema:T.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof T.z.ZodUnion&&cn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),i=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:st({schema:T.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},ln=({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)}),fn=({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:l}}})=>{let y=l.find(O=>O.kind==="regex"),S=l.find(O=>O.kind==="datetime"),b=y?y.regex:S?S.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,P={type:"string"},x={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let O in x)if(x[O]){P.format=O;break}return r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),b&&(P.pattern=b.source),P},yn=({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},st=({schema:{shape:e},next:t})=>(0,m.map)(t,e),gn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Fo?.[t]},Yr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},hn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,Y.isReferenceObject)(o)){let s=$e(e,gn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.z.any())}if(!t&&i.type==="preprocess"&&!(0,Y.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},xn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Tn=({schema:e,next:t})=>t(e.unwrap()),bn=({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)))},Sn=({next:e,schema:t})=>e(t.shape.raw),Jr=e=>e.length?(0,m.zipObj)((0,m.range)(1,e.length+1).map(t=>`example${t}`),(0,m.map)((0,m.objOf)("value"),e)):void 0,Wr=(e,t,r=[])=>(0,m.pipe)(F,(0,m.map)((0,m.when)((0,m.both)(M,(0,m.complement)(Array.isArray)),(0,m.omit)(r))),Jr)({schema:e,variant:t?"parsed":"original",validate:!0}),On=(e,t)=>(0,m.pipe)(F,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),Jr)({schema:e,variant:"original",validate:!0}),ke=(e,t)=>e instanceof T.z.ZodObject?e:e instanceof T.z.ZodUnion||e instanceof T.z.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>ke(r,t)).reduce((r,o)=>r.merge(o.partial()),T.z.object({})):e instanceof T.z.ZodEffects?((0,q.default)(e._def.effect.type==="refinement",t),ke(e._def.schema,t)):ke(e._def.left,t).merge(ke(e._def.right,t)),Qr=({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}=ke(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=Vr(e),l=o.includes("query"),y=o.includes("params"),S=o.includes("headers"),b=x=>y&&u.includes(x),P=x=>S&&Tt(x);return Object.keys(c).filter(x=>l||b(x)).map(x=>{let O=se({schema:c[x],isResponse:!1,rules:vt,onEach:Dt,onMissing:kt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Re=p==="components"?a(Z(d,x),O):O;return{name:x,in:b(x)?"path":P(x)?"header":"query",required:!c[x].isOptional(),description:O.description||d,schema:Re,examples:On(r,x)}})},vt={ZodString:fn,ZodNumber:yn,ZodBigInt:dn,ZodBoolean:pn,ZodNull:on,ZodArray:ln,ZodTuple:un,ZodRecord:mn,ZodObject:rn,ZodLiteral:tn,ZodIntersection:Wo,ZodUnion:Go,ZodAny:$o,ZodDefault:qo,ZodEnum:qr,ZodNativeEnum:qr,ZodEffects:hn,ZodOptional:Qo,ZodNullable:en,ZodDiscriminatedUnion:Yo,ZodBranded:Tn,ZodDate:an,ZodCatch:Bo,ZodPipeline:xn,ZodLazy:bn,ZodReadonly:Xo,[_]:_o,[Me]:Vo,[De]:sn,[ve]:nn,[re]:Sn},Dt=({schema:e,isResponse:t,prev:r})=>{if((0,Y.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof T.z.ZodLazy,s=r.type!==void 0,a=t&&we(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Yr(r)),d.length&&(c.examples=Array.from(d)),c},kt=({schema:e,...t})=>q.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Nt=(e,t)=>{if((0,Y.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.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,Y.isReferenceObject)(e)?e:(0,m.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:l=`${e.toUpperCase()} ${t} ${St(i)} response ${c?u:""}`.trim()})=>{let y=Xr(se({schema:r,isResponse:!0,rules:vt,onEach:Dt,onMissing:kt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),S={schema:d==="components"?p(Z(l),y):y,examples:Wr(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[S]))}},An=()=>({type:"http",scheme:"basic"}),Rn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Pn=({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},Cn=({name:e})=>({type:"apiKey",in:"header",name:e}),In=({name:e})=>({type:"apiKey",in:"cookie",name:e}),En=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),wn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),to=(e,t)=>{let r={basic:An,bearer:Rn,input:Pn,header:Cn,cookie:In,openid:En,oauth2:wn};return We(e,o=>r[o.type](o,t))},at=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?at(Pt(e)):at({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=Vr(t),u=Xr(Nt(se({schema:r,isResponse:!1,rules:vt,onEach:Dt,onMissing:kt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(Z(d),u):u,examples:Wr(r,!1,c)};return{description:d,content:(0,m.fromPairs)((0,m.xprod)(o,[l]))}},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}),Lt=e=>e.length<=Fr?e:e.slice(0,Fr-1)+"\u2026";var pt=class extends io.OpenApiBuilder{lastSecuritySchemaIds={};lastOperationIdSuffixes={};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){if(o)return(0,no.default)(!(o in this.lastOperationIdSuffixes),new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=Z(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=Be}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});ie({routing:t,onEndpoint:(l,y,S)=>{let b=S,P={path:y,method:b,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[x,O]=["short","long"].map(l.getDescription.bind(l)),Re=x?Lt(x):p&&O?Lt(O):void 0,je=l.getTags(),Pe=r.inputSources?.[b]||ht[b],pe=this.ensureUniqOperationId(y,b,l.getOperationId(b)),He=Qr({...P,inputSources:Pe,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:y,operationId:pe})}),Ue={};for(let j of["positive","negative"]){let h=l.getResponses(j);for(let{mimeTypes:R,schema:C,statusCodes:v}of h)for(let de of v)Ue[de]=eo({...P,variant:j,schema:C,mimeTypes:R,statusCode:de,hasMultipleStatusCodes:h.length>1||v.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:y,operationId:pe,statusCode:de})})}let yt=Pe.includes("body")?ro({...P,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:y,operationId:pe})}):void 0,Ke=at(We(to(l.getSecurity(),Pe),j=>{let h=this.ensureUniqSecuritySchemaName(j),R=["oauth2","openIdConnect"].includes(j.type)?l.getScopes():[];return this.addSecurityScheme(h,j),{name:h,scopes:R}}));this.addPath(_r(y),{[b]:{operationId:pe,summary:Re,description:O,tags:je.length>0?je:void 0,parameters:He.length>0?He:void 0,requestBody:yt,security:Ke.length>0?Ke:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?oo(r.tags):[]}};var jt=A(require("http"),1);var zn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>K),...t}),Zn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:jt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=jt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},Mn=({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 wr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=zn({fnMethod:a,requestProps:t}),d=Zn({fnMethod:a,responseProps:r}),c=Mn({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=A(require("typescript"),1);var L=A(require("typescript"),1),Se=require("ramda"),n=L.default.factory,J=[n.createModifier(L.default.SyntaxKind.ExportKeyword)],Nn=[n.createModifier(L.default.SyntaxKind.AsyncKeyword)],vn=[n.createModifier(L.default.SyntaxKind.PublicKeyword),n.createModifier(L.default.SyntaxKind.ReadonlyKeyword)],ao=[n.createModifier(L.default.SyntaxKind.ProtectedKeyword),n.createModifier(L.default.SyntaxKind.ReadonlyKeyword)],Ht=n.createTemplateHead(""),Oe=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Kt=e=>n.createTemplateLiteralType(Ht,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Oe:Ut))),Ft=Kt(["M","P"]),dt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ct=(e,t)=>(0,Se.chain)(([r,o])=>[dt(n.createIdentifier(r),o,t)],(0,Se.toPairs)(e)),qt=(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)),W=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],L.default.NodeFlags.Const),Bt=(e,t)=>n.createTypeAliasDeclaration(J,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),mt=(e,t)=>n.createTypeAliasDeclaration(J,e,void 0,t),mo=(e,t,r)=>n.createPropertyDeclaration(vn,e,void 0,t,r),lo=(e,t,r)=>n.createClassDeclaration(J,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(L.default.SyntaxKind.AnyKeyword)]),yo=(e,t,r)=>n.createInterfaceDeclaration(J,e,void 0,t,r),go=e=>(0,Se.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Se.toPairs)(e)),$t=(e,t,r)=>n.createArrowFunction(r?Nn:void 0,void 0,e.map(o=>dt(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,ct({acc:void 0,key:void 0}),void 0,void 0,t),r]);var ho=["get","post","put","delete","patch"];var g=A(require("typescript"),1),ut=require("zod");var B=A(require("typescript"),1),{factory:lt}=B.default,_t=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ae=(e,t,r)=>{let o=lt.createTypeAliasDeclaration(void 0,lt.createIdentifier(t),void 0,e);return r&&_t(o,r),o},Gt=(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)},Dn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,xo=e=>Dn.test(e)?lt.createIdentifier(e):lt.createStringLiteral(e);var{factory:f}=g.default,kn={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Ln=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),jn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&we(a)?a instanceof ut.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,xo(s),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&_t(d,a.description),d});return f.createTypeLiteralNode(i)},Hn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Un=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),To=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),Kn=e=>kn?.[e.kind],Fn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=$e(e,Kn(o)),a={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||g.default.SyntaxKind.AnyKeyword)}return o},qn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Bn=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},$n=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Vn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),_n=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Gn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Yn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),Jn=({next:e,schema:t})=>e(t.unwrap()),Wn=({next:e,schema:t})=>e(t._def.innerType),Qn=({next:e,schema:t})=>e(t._def.innerType),Xn=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),ei=()=>f.createLiteralTypeNode(f.createNull()),ti=({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)))},ri=({schema:e})=>{let t=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),r=f.createTypeReferenceNode("Buffer"),o=f.createUnionTypeNode([t,r]);return e instanceof ut.z.ZodString?t:e instanceof ut.z.ZodUnion?o:r},oi=({next:e,schema:t})=>e(t.shape.raw),ni={ZodString:ae(g.default.SyntaxKind.StringKeyword),ZodNumber:ae(g.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(g.default.SyntaxKind.BooleanKeyword),ZodAny:ae(g.default.SyntaxKind.AnyKeyword),[ve]:ae(g.default.SyntaxKind.StringKeyword),[De]:ae(g.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Hn,ZodTuple:Vn,ZodRecord:_n,ZodObject:jn,ZodLiteral:Ln,ZodIntersection:Gn,ZodUnion:To,ZodDefault:Yn,ZodEnum:Un,ZodNativeEnum:qn,ZodEffects:Fn,ZodOptional:Bn,ZodNullable:$n,ZodDiscriminatedUnion:To,ZodBranded:Jn,ZodCatch:Qn,ZodPipeline:Xn,ZodLazy:ti,ZodReadonly:Wn,[_]:ri,[re]:oi},Le=({schema:e,...t})=>se({schema:e,rules:ni,onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),...t});var ft=class{program=[];usage=[];registry={};paths=[];aliases={};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 t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=Ae(r,t),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Be,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(h,R,C)=>{let v={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},de=Z(C,R,"input"),So=Le({...v,schema:h.getSchema("input"),isResponse:!1}),Ce=i?Z(C,R,"positive.response"):void 0,Yt=h.getSchema("positive"),Jt=i?Le({...v,isResponse:!0,schema:Yt}):void 0,Ie=i?Z(C,R,"negative.response"):void 0,Wt=h.getSchema("negative"),Qt=i?Le({...v,isResponse:!0,schema:Wt}):void 0,Xt=Z(C,R,"response"),Oo=Ce&&Ie?n.createUnionTypeNode([n.createTypeReferenceNode(Ce),n.createTypeReferenceNode(Ie)]):Le({...v,isResponse:!0,schema:Yt.or(Wt)});this.program.push(Ae(So,de)),Jt&&Ce&&this.program.push(Ae(Jt,Ce)),Qt&&Ie&&this.program.push(Ae(Qt,Ie)),this.program.push(Ae(Oo,Xt)),C!=="options"&&(this.paths.push(R),this.registry[`${C} ${R}`]={input:de,positive:Ce,negative:Ie,response:Xt,isJson:h.getMimeTypes("positive").includes(K),tags:h.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(Bt(this.ids.pathType,this.paths)),this.program.push(Bt(this.ids.methodType,ho)),this.program.push(mt(this.ids.methodPathType,Kt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.default.SyntaxKind.ExtendsKeyword,[qt(this.ids.methodPathType,z.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:h,kind:R}of this.interfaces)this.program.push(yo(h,a,Object.keys(this.registry).map(C=>{let v=this.registry[C][R];return v?co(C,v):void 0}).filter(C=>C!==void 0)));if(r==="types")return;let p=n.createVariableStatement(J,W(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(h=>this.registry[h].isJson).map(h=>n.createPropertyAssignment(`"${h}"`,n.createTrue()))))),d=n.createVariableStatement(J,W(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(h=>n.createPropertyAssignment(`"${h}"`,n.createArrayLiteralExpression(this.registry[h].tags.map(R=>n.createStringLiteral(R)))))))),c=mt(this.ids.providerType,n.createFunctionTypeNode(go({M:this.ids.methodType,P:this.ids.pathType}),ct({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ft)}),uo(this.ids.responseInterface,Ft))),u=mt(this.ids.implementationType,n.createFunctionTypeNode(void 0,ct({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.default.SyntaxKind.StringKeyword),params:qt(z.default.SyntaxKind.StringKeyword,z.default.SyntaxKind.AnyKeyword)}),fo())),l=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Oe)]),y=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[l,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),S=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[l]),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()),b=lo(this.ids.clientClass,po([dt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),ao)]),[mo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,y,S]),!0))]);this.program.push(p,d,c,u,b);let P=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),x=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(K))]),void 0,this.ids.undefinedValue)),O=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)),Re=n.createVariableStatement(void 0,W(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([P,x,O])])))),je=n.createVariableStatement(void 0,W(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Pe=n.createVariableStatement(void 0,W(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)])))),[pe,He]=["json","text"].map(h=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,h),void 0,void 0))),Ue=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ht,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Oe)]),z.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([pe])),yt=n.createVariableStatement(J,W(this.ids.exampleImplementationConst,$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([je,Pe,Re,Ue,He]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Ke=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"))])])),j=n.createVariableStatement(void 0,W(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(yt,j,Ke)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Gt(r,t)).join(`
|
|
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
|
+
${r}`);return this.program.concat(o||[]).map((i,s)=>Gt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
23
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
24
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await be("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 bo={dateIn:Hr,dateOut:Kr,file:_e,upload:fr,raw:lr};0&&(module.exports={AbstractEndpoint,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,MissingPeerError,OutputValidationError,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createLogger,createMiddleware,createResultHandler,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint,withMeta});
|
package/dist/index.d.cts
CHANGED
|
@@ -5,7 +5,6 @@ import express_fileupload__default from 'express-fileupload';
|
|
|
5
5
|
import https, { ServerOptions } from 'node:https';
|
|
6
6
|
import * as zod from 'zod';
|
|
7
7
|
import { z, ZodError } from 'zod';
|
|
8
|
-
import Winston from 'winston';
|
|
9
8
|
import { HttpError } from 'http-errors';
|
|
10
9
|
import { ListenOptions } from 'node:net';
|
|
11
10
|
import * as qs from 'qs';
|
|
@@ -47,7 +46,7 @@ interface LoggerOverrides {
|
|
|
47
46
|
}
|
|
48
47
|
/** @desc You can use any logger compatible with this type. */
|
|
49
48
|
type AbstractLogger = Record<"info" | "debug" | "warn" | "error", (message: string, meta?: any) => any> & LoggerOverrides;
|
|
50
|
-
interface
|
|
49
|
+
interface BuiltinLoggerConfig {
|
|
51
50
|
/**
|
|
52
51
|
* @desc The minimal severity to log or "silent" to disable logging
|
|
53
52
|
* @example "debug" also enables pretty output for inspected entities
|
|
@@ -67,13 +66,10 @@ interface SimplifiedWinstonConfig {
|
|
|
67
66
|
depth?: number | null;
|
|
68
67
|
}
|
|
69
68
|
/**
|
|
70
|
-
* @desc
|
|
71
|
-
* @
|
|
72
|
-
* @example createLogger({ winston, level: "debug", color: true, depth: 4 })
|
|
69
|
+
* @desc Creates the built-in console logger with optional colorful inspections
|
|
70
|
+
* @example createLogger({ level: "debug", color: true, depth: 4 })
|
|
73
71
|
* */
|
|
74
|
-
declare const createLogger: ({
|
|
75
|
-
winston: typeof Winston;
|
|
76
|
-
}) => Winston.Logger;
|
|
72
|
+
declare const createLogger: ({ level, color, depth, }: BuiltinLoggerConfig) => AbstractLogger;
|
|
77
73
|
|
|
78
74
|
type Method = "get" | "post" | "put" | "delete" | "patch";
|
|
79
75
|
|
|
@@ -552,10 +548,10 @@ interface CommonConfig<TAG extends string = string> {
|
|
|
552
548
|
*/
|
|
553
549
|
errorHandler?: AnyResultHandlerDefinition;
|
|
554
550
|
/**
|
|
555
|
-
* @desc
|
|
551
|
+
* @desc Built-in logger configuration or an instance of any compatible logger.
|
|
556
552
|
* @example { level: "debug", color: true }
|
|
557
553
|
* */
|
|
558
|
-
logger:
|
|
554
|
+
logger: BuiltinLoggerConfig | AbstractLogger;
|
|
559
555
|
/**
|
|
560
556
|
* @desc A child logger returned by this function can override the logger in all handlers for each request
|
|
561
557
|
* @example ({ parent }) => parent.child({ requestId: uuid() })
|
|
@@ -718,10 +714,10 @@ interface Routing {
|
|
|
718
714
|
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
|
|
719
715
|
}
|
|
720
716
|
|
|
721
|
-
declare const attachRouting: (config: AppConfig, routing: Routing) =>
|
|
717
|
+
declare const attachRouting: (config: AppConfig, routing: Routing) => {
|
|
722
718
|
notFoundHandler: express.RequestHandler<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>>;
|
|
723
719
|
logger: AbstractLogger;
|
|
724
|
-
}
|
|
720
|
+
};
|
|
725
721
|
declare const createServer: (config: ServerConfig, routing: Routing) => Promise<{
|
|
726
722
|
logger: AbstractLogger;
|
|
727
723
|
httpServer: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,6 @@ import express_fileupload__default from 'express-fileupload';
|
|
|
5
5
|
import https, { ServerOptions } from 'node:https';
|
|
6
6
|
import * as zod from 'zod';
|
|
7
7
|
import { z, ZodError } from 'zod';
|
|
8
|
-
import Winston from 'winston';
|
|
9
8
|
import { HttpError } from 'http-errors';
|
|
10
9
|
import { ListenOptions } from 'node:net';
|
|
11
10
|
import * as qs from 'qs';
|
|
@@ -47,7 +46,7 @@ interface LoggerOverrides {
|
|
|
47
46
|
}
|
|
48
47
|
/** @desc You can use any logger compatible with this type. */
|
|
49
48
|
type AbstractLogger = Record<"info" | "debug" | "warn" | "error", (message: string, meta?: any) => any> & LoggerOverrides;
|
|
50
|
-
interface
|
|
49
|
+
interface BuiltinLoggerConfig {
|
|
51
50
|
/**
|
|
52
51
|
* @desc The minimal severity to log or "silent" to disable logging
|
|
53
52
|
* @example "debug" also enables pretty output for inspected entities
|
|
@@ -67,13 +66,10 @@ interface SimplifiedWinstonConfig {
|
|
|
67
66
|
depth?: number | null;
|
|
68
67
|
}
|
|
69
68
|
/**
|
|
70
|
-
* @desc
|
|
71
|
-
* @
|
|
72
|
-
* @example createLogger({ winston, level: "debug", color: true, depth: 4 })
|
|
69
|
+
* @desc Creates the built-in console logger with optional colorful inspections
|
|
70
|
+
* @example createLogger({ level: "debug", color: true, depth: 4 })
|
|
73
71
|
* */
|
|
74
|
-
declare const createLogger: ({
|
|
75
|
-
winston: typeof Winston;
|
|
76
|
-
}) => Winston.Logger;
|
|
72
|
+
declare const createLogger: ({ level, color, depth, }: BuiltinLoggerConfig) => AbstractLogger;
|
|
77
73
|
|
|
78
74
|
type Method = "get" | "post" | "put" | "delete" | "patch";
|
|
79
75
|
|
|
@@ -552,10 +548,10 @@ interface CommonConfig<TAG extends string = string> {
|
|
|
552
548
|
*/
|
|
553
549
|
errorHandler?: AnyResultHandlerDefinition;
|
|
554
550
|
/**
|
|
555
|
-
* @desc
|
|
551
|
+
* @desc Built-in logger configuration or an instance of any compatible logger.
|
|
556
552
|
* @example { level: "debug", color: true }
|
|
557
553
|
* */
|
|
558
|
-
logger:
|
|
554
|
+
logger: BuiltinLoggerConfig | AbstractLogger;
|
|
559
555
|
/**
|
|
560
556
|
* @desc A child logger returned by this function can override the logger in all handlers for each request
|
|
561
557
|
* @example ({ parent }) => parent.child({ requestId: uuid() })
|
|
@@ -718,10 +714,10 @@ interface Routing {
|
|
|
718
714
|
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
|
|
719
715
|
}
|
|
720
716
|
|
|
721
|
-
declare const attachRouting: (config: AppConfig, routing: Routing) =>
|
|
717
|
+
declare const attachRouting: (config: AppConfig, routing: Routing) => {
|
|
722
718
|
notFoundHandler: express.RequestHandler<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>>;
|
|
723
719
|
logger: AbstractLogger;
|
|
724
|
-
}
|
|
720
|
+
};
|
|
725
721
|
declare const createServer: (config: ServerConfig, routing: Routing) => Promise<{
|
|
726
722
|
logger: AbstractLogger;
|
|
727
723
|
httpServer: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
package/dist/index.js
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
|
-
var
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},
|
|
1
|
+
var qt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function Xr(e){return e}import tr from"assert/strict";import{z as ut}from"zod";import{z as eo}from"zod";var oe={positive:200,negative:400},ot=(e,t)=>e instanceof eo.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{isHttpError as to}from"http-errors";import{createHash as ro}from"crypto";import{flip as oo,pickBy as no,xprod as io}from"ramda";import{z as so}from"zod";var ne=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(H(t)),this.originalError=t}},j=class extends L{name="InputValidationError";originalError;constructor(t){super(H(t)),this.originalError=t}},_=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ie=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 v="application/json",Ne="multipart/form-data",Bt="application/octet-stream";var ao=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Ne);return"files"in e&&r},nt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},po=["body","query","params"],it=e=>e.method.toLowerCase(),st=e=>e.startsWith("x-"),co=e=>no(oo(st),e),$t=(e,t={})=>{let r=it(e);return r==="options"?{}:(t[r]||nt[r]||po).filter(o=>o==="files"?ao(e):!0).map(o=>o==="headers"?co(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},se=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),H=e=>e instanceof so.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,ve=e=>to(e)?e.statusCode:e instanceof j?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})},
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};import{chain as Oo}from"ramda";var J=e=>E(e)&&"or"in e,ce=e=>E(e)&&"and"in e,ct=e=>({and:Oo(t=>ce(t)?t.and:[t],e)}),Fe=(e,t)=>ce(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>ce(r)?{and:r.and.map(t)}:t(r))}:t(e),mt=e=>e.and.reduce((t,r)=>({or:W(t.or,J(r)?r.or:[r],ct)}),{or:[]}),de=(e,t)=>ce(e)?J(t)?de(mt(e),t):ct([e,t]):J(e)?ce(t)?de(t,e):J(t)?{or:W(e.or,t.or,ct)}:de(e,{and:[t]}):ce(t)||J(t)?de(t,e):{and:[e,t]};var me=class{},Be=class extends me{#e;#o;#n;#i;#t;#s;#a;#r;#p;#d;#c;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:m}){super(),this.#s=i,this.#a=s,this.#n=d,this.#c=a,this.#o=t,this.#p=p,this.#d=c,this.#e={long:l,short:m},this.#r={input:r,output:o};for(let[f,x]of Object.entries(this.#r))Xt(!Ue(x),new j(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:rt(s.getPositiveResponse(o),{mimeTypes:[v],statusCodes:[ie.positive]}),negative:rt(s.getNegativeResponse(),{mimeTypes:[v],statusCodes:[ie.negative]})};for(let[f,x]of Object.entries(this.#t))Xt(x.length,new G(`ResultHandler must have at least one ${f} response schema specified.`));this.#i={input:Jt(r)?[Ne]:Qt(r)?[Ft]:[v],positive:this.#t.positive.flatMap(({mimeTypes:f})=>f),negative: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.#i[t]}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?de(t,r.security):t,{and:[]})}getScopes(){return this.#p}getTags(){return this.#d}getOperationId(t){return this.#c(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#l(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof lt.ZodError?new _(r):r}}async#u({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 lt.ZodError?new H(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#f({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof lt.ZodError?new H(s):s}return this.#s({input:i,options:r,logger:o})}async#y({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#a.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Ke({logger:i,response:o,error:new G(pe(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=nt(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 f in m)r.set(f,m[f])}let l=Bt(t,i.inputSources);try{if(await this.#u({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#l(await this.#f({input:l,logger:o,options:p}))}catch(m){c=pe(m)}await this.#y({input:l,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 Ao from"assert/strict";var ut=e=>(Ao(!Ue(e.input),new j("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as M}from"zod";var ft=e=>e,Se=ft({getPositiveResponse:e=>{let t=K({schema:e}),r=D(M.object({status:M.literal("success"),data:e}));return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>D(M.object({status:M.literal("error"),error:M.object({message:M.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(ie.positive).json({status:"success",data:r});return}let a=ve(e);st({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),yt=ft({getPositiveResponse:e=>{let t=K({schema:e}),r=D("shape"in e&&"items"in e.shape&&e.shape.items instanceof M.ZodArray?e.shape.items:M.array(M.any()));return t.reduce((o,i)=>E(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>D(M.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=ve(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(ie.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,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(ut({input:tr.object({}),middleware:async()=>t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],m=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],x="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Be({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:x,methods:l,getOperationId:m,description:i,shortDescription:s,inputSchema:er(d,t)})}},Ro=new Oe(Se),Po=new Oe(yt);import{inspect as Co}from"util";var rr=e=>E(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","debug"].includes(e.level)&&Object.values(e).find(t=>typeof t=="function")===void 0,gt=({winston:{createLogger:e,transports:t,format:{printf:r,timestamp:o,colorize:i,combine:s},config:{npm:a}},...p})=>{let d=p.level==="silent",c=p.level==="debug",l=f=>Co(f,{colors:p.color,depth:p.depth,breakLength:c?80:1/0,compact:c?3:!0}),m=r(({timestamp:f,message:x,level:b,durationMs:O,...g})=>{typeof x=="object"&&(g[Symbol.for("splat")]=[x],x="[No message]");let T=[];O&&T.push("duration:",`${O}ms`);let L=g?.[Symbol.for("splat")];return Array.isArray(L)&&T.push(...L.map(l)),[f,`${b}:`,x,...T].join(" ")});return e({silent:d,levels:a.levels,exitOnError:!1,transports:[new t.Console({level:d?"warn":p.level,handleExceptions:!0,format:s(o(),...p.color?[i()]:[],m)})]})};import{head as Io,tail as Eo,toPairs as wo}from"ramda";var Ae=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=wo(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=Io(this.pairs)?.[1],this.siblingMethods=Eo(this.pairs).map(([r])=>r)}};import zo from"express";var Re=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,zo.static(...this.params))}};import cr from"express";import Mo from"http";import No from"https";var Q=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>Kt(e)[t])}catch{}throw new ae(e)},or=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await Q(t,r)}catch{}throw new ae(e.map(({moduleName:t})=>t))};import nr from"assert/strict";var X=({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 se(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof me){let c=p.getMethods().slice();i&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Re)r&&p.apply(d,r);else if(p instanceof Ae){for(let[c,l]of p.pairs)nr(l.getMethods().includes(c),new se(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else X({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var ir=()=>`
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`;var ht=({app:e,rootLogger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(ir()),t.debug("Running","v17.7.0 (ESM)"),X({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let l=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;l.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:l,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}})};import sr,{isHttpError as Zo}from"http-errors";var ar=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:Zo(o)?o:sr(400,pe(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},pr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=sr(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Ke({response:i,logger:a,error:new G(pe(p).message,s)})}},dr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};var mr=async e=>{let t=rr(e.logger)?gt({...e.logger,winston:await Q("winston")}):e.logger,r=e.errorHandler||Se,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=pr(i),a=ar(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},vo=async(e,t)=>{let{rootLogger:r,notFoundHandler:o}=await mr(e);return ht({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Do=async(e,t)=>{let r=cr().disable("x-powered-by");if(e.server.compression){let d=await Q("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||cr.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await mr(e);if(e.server.upload){let d=await Q("express-fileupload"),{limitError:c,beforeUpload:l,...m}={...typeof e.server.upload=="object"&&e.server.upload};l&&l({app:r,logger:o}),r.use(d({...m,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),c&&r.use(dr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),ht({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(Mo.createServer(r),e.server.listen),httpsServer:e.https?a(No.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import Fn from"assert/strict";import{OpenApiBuilder as Bn}from"openapi3-ts/oas31";import B from"assert/strict";import{isReferenceObject as te}from"openapi3-ts/oas31";import{both as Lo,complement as jo,concat as Ho,type as Uo,filter as Ko,fromPairs as _e,has as Fo,isNil as Bo,map as le,mergeAll as qo,mergeDeepRight as Vo,mergeDeepWith as $o,objOf as hr,omit as Ge,pipe as xr,pluck as _o,range as Go,reject as Wo,toLower as Yo,union as Jo,when as Qo,xprod as We,zipObj as Xo}from"ramda";import{z as S}from"zod";import{z as lr}from"zod";var qe=e=>!isNaN(e.getTime()),Ve=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Pe="DateIn",ur=()=>P(Pe,lr.string().regex(Ve).transform(e=>new Date(e)).pipe(lr.date().refine(qe)));import{z as ko}from"zod";var Ce="DateOut",fr=()=>P(Ce,ko.date().refine(qe).transform(e=>e.toISOString()));var ee=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Te(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:m=>ee({schema:m,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),l=t&&t({schema:e,prev:c,...p});return l?{...c,...l}:c};var yr=50,Tr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",en={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},br=/:([A-Za-z0-9_]+)/g,Sr=e=>e.match(br)?.map(t=>t.slice(1))||[],Or=e=>e.replace(br,t=>`{${t.slice(1)}}`),tn=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),rn=({schema:{_def:{innerType:e}},next:t})=>t(e),on=()=>({format:"any"}),nn=e=>(B(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),sn=({schema:e})=>({type:"string",format:e instanceof S.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),an=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),pn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),dn=e=>{let[t,r]=e.filter(i=>!te(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));B(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=$o((i,s)=>Array.isArray(i)&&Array.isArray(s)?Ho(i,s):i===s?s:B.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Jo(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=W(t.examples||[],r.examples||[],([i,s])=>Vo(i,s))),o},cn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return dn(o)}catch{}return{allOf:o}},mn=({schema:e,next:t})=>t(e.unwrap()),ln=({schema:e,next:t})=>t(e._def.innerType),un=({schema:e,next:t})=>{let r=t(e.unwrap());return te(r)||(r.type=Rr(r)),r},Ar=e=>{let t=Yo(Uo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},gr=({schema:e})=>({type:Ar(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),fn=({schema:{value:e}})=>({type:Ar(e),const:e}),yn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&xe(p)?p instanceof S.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=$e({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},gn=()=>({type:"null"}),hn=e=>(B(!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:Ve.source,externalDocs:{url:Tr}}),xn=e=>(B(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}}),Tn=e=>B.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})),bn=()=>({type:"boolean"}),Sn=()=>({type:"integer",format:"bigint"}),On=e=>e.every(t=>t instanceof S.ZodLiteral),An=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=$e({schema:S.object(_e(We(o,[t]))),...r}),i.required=o),i}if(e instanceof S.ZodLiteral)return{type:"object",properties:$e({schema:S.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof S.ZodUnion&&On(e.options)){let o=le(s=>`${s.value}`,e.options),i=_e(We(o,[t]));return{type:"object",properties:$e({schema:S.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},Rn=({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},Pn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Cn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:m}}})=>{let f=m.find(T=>T.kind==="regex"),x=m.find(T=>T.kind==="datetime"),b=f?f.regex:x?x.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,O={type:"string"},g={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let T in g)if(g[T]){O.format=T;break}return r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),b&&(O.pattern=b.source),O},In=({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},$e=({schema:{shape:e},next:t})=>le(t,e),En=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return en?.[t]},Rr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},wn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!te(o)){let s=ke(e,En(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.any())}if(!t&&i.type==="preprocess"&&!te(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},zn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Zn=({schema:e,next:t})=>t(e.unwrap()),Mn=({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)))},Nn=({next:e,schema:t})=>e(t.shape.raw),Pr=e=>e.length?Xo(Go(1,e.length+1).map(t=>`example${t}`),le(hr("value"),e)):void 0,Cr=(e,t,r=[])=>xr(K,le(Qo(Lo(E,jo(Array.isArray)),Ge(r))),Pr)({schema:e,variant:t?"parsed":"original",validate:!0}),vn=(e,t)=>xr(K,Ko(Fo(t)),_o(t),Pr)({schema:e,variant:"original",validate:!0}),Ie=(e,t)=>e instanceof S.ZodObject?e:e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>Ie(r,t)).reduce((r,o)=>r.merge(o.partial()),S.object({})):e instanceof S.ZodEffects?(B(e._def.effect.type==="refinement",t),Ie(e._def.schema,t)):Ie(e._def.left,t).merge(Ie(e._def.right,t)),Ir=({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}=Ie(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Sr(e),m=o.includes("query"),f=o.includes("params"),x=o.includes("headers"),b=g=>f&&l.includes(g),O=g=>x&&it(g);return Object.keys(c).filter(g=>m||b(g)).map(g=>{let T=ee({schema:c[g],isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:a,path:e,method:t}),L=p==="components"?a(I(d,g),T):T;return{name:g,in:b(g)?"path":O(g)?"header":"query",required:!c[g].isOptional(),description:T.description||d,schema:L,examples:vn(r,g)}})},Tt={ZodString:Cn,ZodNumber:In,ZodBigInt:Sn,ZodBoolean:bn,ZodNull:gn,ZodArray:Rn,ZodTuple:Pn,ZodRecord:An,ZodObject:yn,ZodLiteral:fn,ZodIntersection:cn,ZodUnion:an,ZodAny:on,ZodDefault:tn,ZodEnum:gr,ZodNativeEnum:gr,ZodEffects:wn,ZodOptional:mn,ZodNullable:un,ZodDiscriminatedUnion:pn,ZodBranded:Zn,ZodDate:Tn,ZodCatch:rn,ZodPipeline:zn,ZodLazy:Mn,ZodReadonly:ln,[F]:sn,[be]:nn,[Ce]:xn,[Pe]:hn,[Y]:Nn},bt=({schema:e,isResponse:t,prev:r})=>{if(te(r))return{};let{description:o}=e,i=e instanceof S.ZodLazy,s=r.type!==void 0,a=t&&xe(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Rr(r)),d.length&&(c.examples=Array.from(d)),c},St=({schema:e,...t})=>B.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),xt=(e,t)=>{if(te(e))return e;let r={...e};return r.properties&&(r.properties=Ge(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Ge(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>xt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>xt(o,t))),r},Er=e=>te(e)?e:Ge(["examples"],e),wr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:m=`${e.toUpperCase()} ${t} ${at(i)} response ${c?l:""}`.trim()})=>{let f=Er(ee({schema:r,isResponse:!0,rules:Tt,onEach:bt,onMissing:St,serializer:s,getRef:a,makeRef:p,path:t,method:e})),x={schema:d==="components"?p(I(m),f):f,examples:Cr(r,!0)};return{description:m,content:_e(We(o,[x]))}},Dn=()=>({type:"http",scheme:"basic"}),kn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ln=({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}),Hn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Un=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Kn=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),Wo(Bo,e))}),zr=(e,t)=>{let r={basic:Dn,bearer:kn,input:Ln,header:jn,cookie:Hn,openid:Un,oauth2:Kn};return Fe(e,o=>r[o.type](o,t))},Ye=e=>"or"in e?e.or.map(t=>"and"in t?qo(le(({name:r,scopes:o})=>hr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?Ye(mt(e)):Ye({or:[e]}),Zr=({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=Sr(t),l=Er(xt(ee({schema:r,isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(I(d),l):l,examples:Cr(r,!1,c)};return{description:d,content:_e(We(o,[m]))}},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}),Ot=e=>e.length<=yr?e:e.slice(0,yr-1)+"\u2026";var At=class extends Bn{lastSecuritySchemaIds={};lastOperationIdSuffixes={};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){if(o)return Fn(!(o in this.lastOperationIdSuffixes),new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=I(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}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 m of typeof s=="string"?[s]:s)this.addServer({url:m});X({routing:t,onEndpoint:(m,f,x)=>{let b=x,O={path:f,method:b,endpoint:m,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[g,T]=["short","long"].map(m.getDescription.bind(m)),L=g?Ot(g):p&&T?Ot(T):void 0,we=m.getTags(),ye=r.inputSources?.[b]||ot[b],oe=this.ensureUniqOperationId(f,b,m.getOperationId(b)),ze=Ir({...O,inputSources:ye,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:f,operationId:oe})}),Ze={};for(let N of["positive","negative"]){let h=m.getResponses(N);for(let{mimeTypes:A,schema:R,statusCodes:z}of h)for(let ne of z)Ze[ne]=wr({...O,variant:N,schema:R,mimeTypes:A,statusCode:ne,hasMultipleStatusCodes:h.length>1||z.length>1,description:a?.[`${N}Response`]?.call(null,{method:b,path:f,operationId:oe,statusCode:ne})})}let tt=ye.includes("body")?Zr({...O,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:f,operationId:oe})}):void 0,Me=Ye(Fe(zr(m.getSecurity(),ye),N=>{let h=this.ensureUniqSecuritySchemaName(N),A=["oauth2","openIdConnect"].includes(N.type)?m.getScopes():[];return this.addSecurityScheme(h,N),{name:h,scopes:A}}));this.addPath(Or(f),{[b]:{operationId:oe,summary:L,description:T,tags:we.length>0?we:void 0,parameters:ze.length>0?ze:void 0,requestBody:tt,security:Me.length>0?Me:void 0,responses:Ze}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import Nr from"http";var qn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>v),...t}),Vn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Nr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Nr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},$n=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),_n=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=qn({fnMethod:a,requestProps:t}),d=Vn({fnMethod:a,responseProps:r}),c=$n({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import w from"typescript";import k from"typescript";import{chain as vr,toPairs as Dr}from"ramda";var n=k.factory,q=[n.createModifier(k.SyntaxKind.ExportKeyword)],Gn=[n.createModifier(k.SyntaxKind.AsyncKeyword)],Wn=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],kr=[n.createModifier(k.SyntaxKind.ProtectedKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Rt=n.createTemplateHead(""),ue=n.createTemplateTail(""),Pt=n.createTemplateMiddle(" "),Ct=e=>n.createTemplateLiteralType(Rt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ue:Pt))),It=Ct(["M","P"]),Je=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),Qe=(e,t)=>vr(([r,o])=>[Je(n.createIdentifier(r),o,t)],Dr(e)),Et=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Lr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),jr=(e,t)=>n.createPropertySignature(void 0,`"${e}"`,void 0,n.createTypeReferenceNode(t)),V=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.NodeFlags.Const),wt=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),Xe=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,t),Hr=(e,t,r)=>n.createPropertyDeclaration(Wn,e,void 0,t,r),Ur=(e,t,r)=>n.createClassDeclaration(q,e,void 0,void 0,[t,...r]),Kr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Fr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),Br=(e,t,r)=>n.createInterfaceDeclaration(q,e,void 0,t,r),qr=e=>vr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Dr(e)),zt=(e,t,r)=>n.createArrowFunction(r?Gn:void 0,void 0,e.map(o=>Je(o)),void 0,void 0,t),Zt=(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,Qe({acc:void 0,key:void 0}),void 0,void 0,t),r]);var Vr=["get","post","put","delete","patch"];import y from"typescript";import{z as vt}from"zod";import $ from"typescript";var{factory:et}=$,Mt=(e,t)=>{$.addSyntheticLeadingComment(e,$.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},fe=(e,t,r)=>{let o=et.createTypeAliasDeclaration(void 0,et.createIdentifier(t),void 0,e);return r&&Mt(o,r),o},Nt=(e,t)=>{let r=$.createSourceFile("print.ts","",$.ScriptTarget.Latest,!1,$.ScriptKind.TS);return $.createPrinter(t).printNode($.EmitHint.Unspecified,e,r)},Yn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,$r=e=>Yn.test(e)?et.createIdentifier(e):et.createStringLiteral(e);var{factory:u}=y,Jn={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Qn=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Xn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&xe(a)?a instanceof vt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,$r(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Mt(d,a.description),d});return u.createTypeLiteralNode(i)},ei=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),ti=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),_r=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),ri=e=>Jn?.[e.kind],oi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,ri(o)),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||y.SyntaxKind.AnyKeyword)}return o},ni=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),ii=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},si=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),ai=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),pi=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),di=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ci=({next:e,schema:t})=>e(t._def.innerType),re=e=>()=>u.createKeywordTypeNode(e),mi=({next:e,schema:t})=>e(t.unwrap()),li=({next:e,schema:t})=>e(t._def.innerType),ui=({next:e,schema:t})=>e(t._def.innerType),fi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),yi=()=>u.createLiteralTypeNode(u.createNull()),gi=({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)))},hi=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof vt.ZodString?t:e instanceof vt.ZodUnion?o:r},xi=({next:e,schema:t})=>e(t.shape.raw),Ti={ZodString:re(y.SyntaxKind.StringKeyword),ZodNumber:re(y.SyntaxKind.NumberKeyword),ZodBigInt:re(y.SyntaxKind.BigIntKeyword),ZodBoolean:re(y.SyntaxKind.BooleanKeyword),ZodAny:re(y.SyntaxKind.AnyKeyword),[Pe]:re(y.SyntaxKind.StringKeyword),[Ce]:re(y.SyntaxKind.StringKeyword),ZodNull:yi,ZodArray:ei,ZodTuple:ai,ZodRecord:pi,ZodObject:Xn,ZodLiteral:Qn,ZodIntersection:di,ZodUnion:_r,ZodDefault:ci,ZodEnum:ti,ZodNativeEnum:ni,ZodEffects:oi,ZodOptional:ii,ZodNullable:si,ZodDiscriminatedUnion:_r,ZodBranded:mi,ZodCatch:ui,ZodPipeline:fi,ZodLazy:gi,ZodReadonly:li,[F]:hi,[Y]:xi},Ee=({schema:e,...t})=>ee({schema:e,rules:Ti,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Dt=class{program=[];usage=[];registry={};paths=[];aliases={};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 t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=fe(r,t),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=De,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){X({routing:t,onEndpoint:(h,A,R)=>{let z={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},ne=I(R,A,"input"),Gr=Ee({...z,schema:h.getSchema("input"),isResponse:!1}),ge=i?I(R,A,"positive.response"):void 0,kt=h.getSchema("positive"),Lt=i?Ee({...z,isResponse:!0,schema:kt}):void 0,he=i?I(R,A,"negative.response"):void 0,jt=h.getSchema("negative"),Ht=i?Ee({...z,isResponse:!0,schema:jt}):void 0,Ut=I(R,A,"response"),Wr=ge&&he?n.createUnionTypeNode([n.createTypeReferenceNode(ge),n.createTypeReferenceNode(he)]):Ee({...z,isResponse:!0,schema:kt.or(jt)});this.program.push(fe(Gr,ne)),Lt&&ge&&this.program.push(fe(Lt,ge)),Ht&&he&&this.program.push(fe(Ht,he)),this.program.push(fe(Wr,Ut)),R!=="options"&&(this.paths.push(A),this.registry[`${R} ${A}`]={input:ne,positive:ge,negative:he,response:Ut,isJson:h.getMimeTypes("positive").includes(v),tags:h.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(wt(this.ids.pathType,this.paths)),this.program.push(wt(this.ids.methodType,Vr)),this.program.push(Xe(this.ids.methodPathType,Ct([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.SyntaxKind.ExtendsKeyword,[Et(this.ids.methodPathType,w.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:h,kind:A}of this.interfaces)this.program.push(Br(h,a,Object.keys(this.registry).map(R=>{let z=this.registry[R][A];return z?jr(R,z):void 0}).filter(R=>R!==void 0)));if(r==="types")return;let p=n.createVariableStatement(q,V(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(h=>this.registry[h].isJson).map(h=>n.createPropertyAssignment(`"${h}"`,n.createTrue()))))),d=n.createVariableStatement(q,V(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(h=>n.createPropertyAssignment(`"${h}"`,n.createArrayLiteralExpression(this.registry[h].tags.map(A=>n.createStringLiteral(A)))))))),c=Xe(this.ids.providerType,n.createFunctionTypeNode(qr({M:this.ids.methodType,P:this.ids.pathType}),Qe({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),It)}),Kr(this.ids.responseInterface,It))),l=Xe(this.ids.implementationType,n.createFunctionTypeNode(void 0,Qe({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.SyntaxKind.StringKeyword),params:Et(w.SyntaxKind.StringKeyword,w.SyntaxKind.AnyKeyword)}),Fr())),m=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ue)]),f=Zt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[m,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),x=Zt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[m]),w.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()),b=Ur(this.ids.clientClass,Lr([Je(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),kr)]),[Hr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),zt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,f,x]),!0))]);this.program.push(p,d,c,l,b);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),g=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(v))]),void 0,this.ids.undefinedValue)),T=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)),L=n.createVariableStatement(void 0,V(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,ue)]),n.createObjectLiteralExpression([O,g,T])])))),we=n.createVariableStatement(void 0,V(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ye=n.createVariableStatement(void 0,V(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]),ue)])))),[oe,ze]=["json","text"].map(h=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,h),void 0,void 0))),Ze=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Rt,[n.createTemplateSpan(this.ids.methodParameter,Pt),n.createTemplateSpan(this.ids.pathParameter,ue)]),w.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([oe])),tt=n.createVariableStatement(q,V(this.ids.exampleImplementationConst,zt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([we,ye,L,Ze,ze]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Me=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"))])])),N=n.createVariableStatement(void 0,V(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(tt,N,Me)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Nt(r,t)).join(`
|
|
4
|
+
`,{url:t.url,payload:r})},U=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=Te(e,"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},G=(e,t,r)=>e.length&&t.length?io(e,t).map(r):e.concat(t),xe=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,pt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),I=(...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=>ro("sha1").update(JSON.stringify(e),"utf8").digest("hex"),ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},E=e=>typeof e=="object"&&e!==null;import{clone as mo,mergeDeepRight as lo}from"ramda";var Z="expressZodApiMeta",uo=e=>e.describe(e.description),D=e=>{let t=uo(e);return t._def[Z]=mo(t._def[Z])||{examples:[]},Object.defineProperties(t,{example:{get:()=>r=>{let o=D(t);return o._def[Z].examples.push(r),o}}})},Vt=e=>Z in e._def&&E(e._def[Z]),Te=(e,t)=>Vt(e)?e._def[Z][t]:void 0,_t=(e,t)=>{if(!Vt(e))return t;let r=D(t);return r._def[Z].examples=G(r._def[Z].examples,e._def[Z].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?lo({...o},{...i}):i),r},P=(e,t)=>{let r=D(t);return r._def[Z].kind=e,r},dt=(e,t)=>Te(e,"kind")===t;import{z as go}from"zod";import{z as Le}from"zod";var K="File",Gt=Le.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),fo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,yo={buffer:()=>P(K,Gt),string:()=>P(K,Le.string()),binary:()=>P(K,Gt.or(Le.string())),base64:()=>P(K,Le.string().regex(fo,"Does not match base64 encoding"))};function je(e){return yo[e||"string"]()}var Y="Raw",Yt=()=>P(Y,go.object({raw:je("buffer")}));import{z as ho}from"zod";var be="Upload",Jt=()=>P(be,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}`})));var ct=({schema:{options:e},next:t})=>e.some(t),Qt=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),To=({schema:e,next:t})=>Object.values(e.shape).some(t),Wt=({schema:e,next:t})=>t(e.unwrap()),bo=({schema:e,next:t})=>t(e.innerType()),So=({schema:e,next:t})=>t(e.valueSchema),Oo=({schema:e,next:t})=>t(e.element),Ao=({schema:e,next:t})=>t(e._def.innerType),Ro={ZodObject:To,ZodUnion:ct,ZodDiscriminatedUnion:ct,ZodIntersection:Qt,ZodEffects:bo,ZodOptional:Wt,ZodNullable:Wt,ZodRecord:So,ZodArray:Oo,ZodDefault:Ao},He=({subject:e,condition:t,rules:r=Ro,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=>He({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},Ue=e=>He({subject:e,maxDepth:3,rules:{ZodUnion:ct,ZodIntersection:Qt},condition:t=>t instanceof xo.ZodEffects&&t._def.effect.type!=="refinement"}),Xt=e=>He({subject:e,condition:t=>dt(t,be)}),er=e=>He({subject:e,condition:t=>dt(t,Y),maxDepth:3});var Ke=({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 J=e=>E(e)&&"or"in e,pe=e=>E(e)&&"and"in e,mt=e=>({and:Po(t=>pe(t)?t.and:[t],e)}),Fe=(e,t)=>pe(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>pe(r)?{and:r.and.map(t)}:t(r))}:t(e),lt=e=>e.and.reduce((t,r)=>({or:G(t.or,J(r)?r.or:[r],mt)}),{or:[]}),ae=(e,t)=>pe(e)?J(t)?ae(lt(e),t):mt([e,t]):J(e)?pe(t)?ae(t,e):J(t)?{or:G(e.or,t.or,mt)}:ae(e,{and:[t]}):pe(t)||J(t)?ae(t,e):{and:[e,t]};var de=class{},qe=class extends de{#e;#o;#n;#i;#t;#s;#a;#r;#p;#d;#c;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:m}){super(),this.#s=i,this.#a=s,this.#n=d,this.#c=a,this.#o=t,this.#p=p,this.#d=c,this.#e={long:l,short:m},this.#r={input:r,output:o};for(let[f,b]of Object.entries(this.#r))tr(!Ue(b),new L(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:ot(s.getPositiveResponse(o),{mimeTypes:[v],statusCodes:[oe.positive]}),negative:ot(s.getNegativeResponse(),{mimeTypes:[v],statusCodes:[oe.negative]})};for(let[f,b]of Object.entries(this.#t))tr(b.length,new _(`ResultHandler must have at least one ${f} response schema specified.`));this.#i={input:Xt(r)?[Ne]:er(r)?[Bt]:[v],positive:this.#t.positive.flatMap(({mimeTypes:f})=>f),negative: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.#i[t]}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ae(t,r.security):t,{and:[]})}getScopes(){return this.#p}getTags(){return this.#d}getOperationId(t){return this.#c(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#l(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ut.ZodError?new V(r):r}}async#u({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 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#f({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ut.ZodError?new j(s):s}return this.#s({input:i,options:r,logger:o})}async#y({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#a.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Ke({logger:i,response:o,error:new _(se(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 m=this.#m(s);typeof i.cors=="function"&&(m=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:m}));for(let f in m)r.set(f,m[f])}let l=$t(t,i.inputSources);try{if(await this.#u({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#l(await this.#f({input:l,logger:o,options:p}))}catch(m){c=se(m)}await this.#y({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as or}from"zod";var rr=(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(!Ue(e.input),new L("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as M}from"zod";var yt=e=>e,Se=yt({getPositiveResponse:e=>{let t=U({schema:e}),r=D(M.object({status:M.literal("success"),data:e}));return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>D(M.object({status:M.literal("error"),error:M.object({message:M.string()})})).example({status:"error",error:{message:H(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(oe.positive).json({status:"success",data:r});return}let a=ve(e);at({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:H(e)}})}}),gt=yt({getPositiveResponse:e=>{let t=U({schema:e}),r=D("shape"in e&&"items"in e.shape&&e.shape.items instanceof M.ZodArray?e.shape.items:M.array(M.any()));return t.reduce((o,i)=>E(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>D(M.string()).example(H(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=ve(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(oe.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:or.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(ft({input:or.object({}),middleware:async()=>t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],m=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 qe({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:b,methods:l,getOperationId:m,description:i,shortDescription:s,inputSchema:rr(d,t)})}},Io=new Oe(Se),Eo=new Oe(gt);import{inspect as wo}from"util";import{mapObjIndexed as zo}from"ramda";import{blue as Zo,green as Mo,hex as No,red as vo}from"ansis";var ht={debug:10,info:20,warn:30,error:40},nr=e=>E(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","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),xt=({level:e,color:t=!1,depth:r=2})=>{let o={debug:Zo,info:Mo,warn:No("#FFA500"),error:vo},i=e==="debug",s=e==="silent"?100:ht[e],a=(p,d,c)=>{if(ht[p]<s)return;let l=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&l.push(wo(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(l.join(" "))};return zo(({},p)=>(d,c)=>a(p,d,c),ht)};import{head as Do,tail as ko,toPairs as Lo}from"ramda";var Ae=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Lo(t).filter(r=>r!==void 0&&r[1]!==void 0),this.firstEndpoint=Do(this.pairs)?.[1],this.siblingMethods=ko(this.pairs).map(([r])=>r)}};import jo from"express";var Re=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,jo.static(...this.params))}};import ur from"express";import Fo from"http";import qo from"https";var ce=async(e,t="default")=>{try{return(await import(e))[t]}catch{}try{return await Promise.resolve().then(()=>qt(e)[t])}catch{}throw new ie(e)},ir=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await ce(t,r)}catch{}throw new ie(e.map(({moduleName:t})=>t))};import sr from"assert/strict";var W=({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){sr.doesNotMatch(a,/\//,new ne(`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 l of c)t(p,d,l)}else if(p instanceof Re)r&&p.apply(d,r);else if(p instanceof Ae){for(let[c,l]of p.pairs)sr(l.getMethods().includes(c),new ne(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else W({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Tt=({app:e,rootLogger:t,config:r,routing:o})=>W({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let l=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;l.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:l,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}});import ar,{isHttpError as Ho}from"http-errors";var pr=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:Ho(o)?o:ar(400,se(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},dr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=ar(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Ke({response:i,logger:a,error:new _(se(p).message,s)})}},cr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};import{gray as Uo,hex as mr,italic as Be,whiteBright as Ko}from"ansis";var lr=()=>{let e=Be("Proudly supports transgender community.".padStart(109)),t=Be("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=Be("Thank you for choosing Express Zod API for your project.".padStart(132)),o=Be("for Victoria".padEnd(20)),i=mr("#F5A9B8"),s=mr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(Ko,5,7).fill(i,7,9).fill(s,9,12).fill(Uo,12,13);return`
|
|
6
|
+
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
7
|
+
888 d88P 888 d88888 888 Y88b 888
|
|
8
|
+
888 d88P 888 d88P888 888 888 888
|
|
9
|
+
8888888 888 888 88888b. 888d888 .d88b. .d8888b .d8888b d88P .d88b. .d88888 d88P 888 888 d88P 888
|
|
10
|
+
888 \u1FEFY8bd8P' 888 "88b 888P" d8P Y8b 88K 88K d88P d88""88b d88" 888 d88P 888 8888888P" 888
|
|
11
|
+
888 X88K 888 888 888 88888888 "Y8888b. "Y8888b. d88P 888 888 888 888 d88P 888 888 888
|
|
12
|
+
888 .d8""8b. 888 d88P 888 Y8b. X88 X88 d88P Y88..88P Y88b 888 d8888888888 888 888
|
|
13
|
+
8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P' d8888888888 "Y88P" "Y88888 d88P 888 888 8888888
|
|
14
|
+
888
|
|
15
|
+
888${e}
|
|
16
|
+
${o}888${t}
|
|
17
|
+
${r}
|
|
18
|
+
`.split(`
|
|
19
|
+
`).map((d,c)=>a[c]?a[c](d):d).join(`
|
|
20
|
+
`)};var fr=e=>{e.startupLogo!==!1&&console.log(lr());let t=nr(e.logger)?xt(e.logger):e.logger;t.debug("Running","v18.0.0-beta2 (ESM)");let r=e.errorHandler||Se,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=dr(i),a=pr(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Bo=(e,t)=>{let{rootLogger:r,notFoundHandler:o}=fr(e);return Tt({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},$o=async(e,t)=>{let r=ur().disable("x-powered-by");if(e.server.compression){let d=await ce("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||ur.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=fr(e);if(e.server.upload){let d=await ce("express-fileupload"),{limitError:c,beforeUpload:l,...m}={...typeof e.server.upload=="object"&&e.server.upload};l&&l({app:r,logger:o}),r.use(d({...m,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),c&&r.use(cr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),Tt({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(Fo.createServer(r),e.server.listen),httpsServer:e.https?a(qo.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import Qn from"assert/strict";import{OpenApiBuilder as Xn}from"openapi3-ts/oas31";import F from"assert/strict";import{isReferenceObject as X}from"openapi3-ts/oas31";import{both as _o,complement as Go,concat as Yo,type as Jo,filter as Wo,fromPairs as Ge,has as Qo,isNil as Xo,map as me,mergeAll as en,mergeDeepRight as tn,mergeDeepWith as rn,objOf as br,omit as Ye,pipe as Sr,pluck as on,range as nn,reject as sn,toLower as an,union as pn,when as dn,xprod as Je,zipObj as cn}from"ramda";import{z as T}from"zod";import{z as yr}from"zod";var $e=e=>!isNaN(e.getTime()),Ve=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Pe="DateIn",gr=()=>P(Pe,yr.string().regex(Ve).transform(e=>new Date(e)).pipe(yr.date().refine($e)));import{z as Vo}from"zod";var Ce="DateOut",hr=()=>P(Ce,Vo.date().refine($e).transform(e=>e.toISOString()));var Q=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Te(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:m=>Q({schema:m,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),l=t&&t({schema:e,prev:c,...p});return l?{...c,...l}:c};var xr=50,Or="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",mn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ar=/:([A-Za-z0-9_]+)/g,Rr=e=>e.match(Ar)?.map(t=>t.slice(1))||[],Pr=e=>e.replace(Ar,t=>`{${t.slice(1)}}`),ln=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),un=({schema:{_def:{innerType:e}},next:t})=>t(e),fn=()=>({format:"any"}),yn=e=>(F(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),gn=({schema:e})=>({type:"string",format:e instanceof T.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),hn=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),xn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),Tn=e=>{let[t,r]=e.filter(i=>!X(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));F(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=rn((i,s)=>Array.isArray(i)&&Array.isArray(s)?Yo(i,s):i===s?s:F.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=pn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=G(t.examples||[],r.examples||[],([i,s])=>tn(i,s))),o},bn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Tn(o)}catch{}return{allOf:o}},Sn=({schema:e,next:t})=>t(e.unwrap()),On=({schema:e,next:t})=>t(e._def.innerType),An=({schema:e,next:t})=>{let r=t(e.unwrap());return X(r)||(r.type=Ir(r)),r},Cr=e=>{let t=an(Jo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Tr=({schema:e})=>({type:Cr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Rn=({schema:{value:e}})=>({type:Cr(e),const:e}),Pn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&xe(p)?p instanceof T.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=_e({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},Cn=()=>({type:"null"}),In=e=>(F(!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:Ve.source,externalDocs:{url:Or}}),En=e=>(F(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:Or}}),wn=e=>F.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})),zn=()=>({type:"boolean"}),Zn=()=>({type:"integer",format:"bigint"}),Mn=e=>e.every(t=>t instanceof T.ZodLiteral),Nn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=_e({schema:T.object(Ge(Je(o,[t]))),...r}),i.required=o),i}if(e instanceof T.ZodLiteral)return{type:"object",properties:_e({schema:T.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof T.ZodUnion&&Mn(e.options)){let o=me(s=>`${s.value}`,e.options),i=Ge(Je(o,[t]));return{type:"object",properties:_e({schema:T.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},vn=({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},Dn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),kn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:m}}})=>{let f=m.find(S=>S.kind==="regex"),b=m.find(S=>S.kind==="datetime"),x=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,A={type:"string"},h={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let S in h)if(h[S]){A.format=S;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),x&&(A.pattern=x.source),A},Ln=({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},_e=({schema:{shape:e},next:t})=>me(t,e),jn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return mn?.[t]},Ir=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Hn=({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,jn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.any())}if(!t&&i.type==="preprocess"&&!X(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Un=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Kn=({schema:e,next:t})=>t(e.unwrap()),Fn=({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)))},qn=({next:e,schema:t})=>e(t.shape.raw),Er=e=>e.length?cn(nn(1,e.length+1).map(t=>`example${t}`),me(br("value"),e)):void 0,wr=(e,t,r=[])=>Sr(U,me(dn(_o(E,Go(Array.isArray)),Ye(r))),Er)({schema:e,variant:t?"parsed":"original",validate:!0}),Bn=(e,t)=>Sr(U,Wo(Qo(t)),on(t),Er)({schema:e,variant:"original",validate:!0}),Ie=(e,t)=>e instanceof T.ZodObject?e:e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>Ie(r,t)).reduce((r,o)=>r.merge(o.partial()),T.object({})):e instanceof T.ZodEffects?(F(e._def.effect.type==="refinement",t),Ie(e._def.schema,t)):Ie(e._def.left,t).merge(Ie(e._def.right,t)),zr=({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}=Ie(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Rr(e),m=o.includes("query"),f=o.includes("params"),b=o.includes("headers"),x=h=>f&&l.includes(h),A=h=>b&&st(h);return Object.keys(c).filter(h=>m||x(h)).map(h=>{let S=Q({schema:c[h],isResponse:!1,rules:St,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:e,method:t}),fe=p==="components"?a(I(d,h),S):S;return{name:h,in:x(h)?"path":A(h)?"header":"query",required:!c[h].isOptional(),description:S.description||d,schema:fe,examples:Bn(r,h)}})},St={ZodString:kn,ZodNumber:Ln,ZodBigInt:Zn,ZodBoolean:zn,ZodNull:Cn,ZodArray:vn,ZodTuple:Dn,ZodRecord:Nn,ZodObject:Pn,ZodLiteral:Rn,ZodIntersection:bn,ZodUnion:hn,ZodAny:fn,ZodDefault:ln,ZodEnum:Tr,ZodNativeEnum:Tr,ZodEffects:Hn,ZodOptional:Sn,ZodNullable:An,ZodDiscriminatedUnion:xn,ZodBranded:Kn,ZodDate:wn,ZodCatch:un,ZodPipeline:Un,ZodLazy:Fn,ZodReadonly:On,[K]:gn,[be]:yn,[Ce]:En,[Pe]:In,[Y]:qn},Ot=({schema:e,isResponse:t,prev:r})=>{if(X(r))return{};let{description:o}=e,i=e instanceof T.ZodLazy,s=r.type!==void 0,a=t&&xe(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:U({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Ir(r)),d.length&&(c.examples=Array.from(d)),c},At=({schema:e,...t})=>F.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),bt=(e,t)=>{if(X(e))return e;let r={...e};return r.properties&&(r.properties=Ye(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Ye(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>bt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>bt(o,t))),r},Zr=e=>X(e)?e:Ye(["examples"],e),Mr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:m=`${e.toUpperCase()} ${t} ${pt(i)} response ${c?l:""}`.trim()})=>{let f=Zr(Q({schema:r,isResponse:!0,rules:St,onEach:Ot,onMissing:At,serializer:s,getRef:a,makeRef:p,path:t,method:e})),b={schema:d==="components"?p(I(m),f):f,examples:wr(r,!0)};return{description:m,content:Ge(Je(o,[b]))}},$n=()=>({type:"http",scheme:"basic"}),Vn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},_n=({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},Gn=({name:e})=>({type:"apiKey",in:"header",name:e}),Yn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Jn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Wn=({flows:e={}})=>({type:"oauth2",flows:me(t=>({...t,scopes:t.scopes||{}}),sn(Xo,e))}),Nr=(e,t)=>{let r={basic:$n,bearer:Vn,input:_n,header:Gn,cookie:Yn,openid:Jn,oauth2:Wn};return Fe(e,o=>r[o.type](o,t))},We=e=>"or"in e?e.or.map(t=>"and"in t?en(me(({name:r,scopes:o})=>br(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?We(lt(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=Rr(t),l=Zr(bt(Q({schema:r,isResponse:!1,rules:St,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(I(d),l):l,examples:wr(r,!1,c)};return{description:d,content:Ge(Je(o,[m]))}},Dr=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}),Rt=e=>e.length<=xr?e:e.slice(0,xr-1)+"\u2026";var Pt=class extends Xn{lastSecuritySchemaIds={};lastOperationIdSuffixes={};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){if(o)return Qn(!(o in this.lastOperationIdSuffixes),new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=I(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}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 m of typeof s=="string"?[s]:s)this.addServer({url:m});W({routing:t,onEndpoint:(m,f,b)=>{let x=b,A={path:f,method:x,endpoint:m,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,S]=["short","long"].map(m.getDescription.bind(m)),fe=h?Rt(h):p&&S?Rt(S):void 0,we=m.getTags(),ye=r.inputSources?.[x]||nt[x],te=this.ensureUniqOperationId(f,x,m.getOperationId(x)),ze=zr({...A,inputSources:ye,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:x,path:f,operationId:te})}),Ze={};for(let N of["positive","negative"]){let g=m.getResponses(N);for(let{mimeTypes:O,schema:R,statusCodes:z}of g)for(let re of z)Ze[re]=Mr({...A,variant:N,schema:R,mimeTypes:O,statusCode:re,hasMultipleStatusCodes:g.length>1||z.length>1,description:a?.[`${N}Response`]?.call(null,{method:x,path:f,operationId:te,statusCode:re})})}let rt=ye.includes("body")?vr({...A,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:x,path:f,operationId:te})}):void 0,Me=We(Fe(Nr(m.getSecurity(),ye),N=>{let g=this.ensureUniqSecuritySchemaName(N),O=["oauth2","openIdConnect"].includes(N.type)?m.getScopes():[];return this.addSecurityScheme(g,N),{name:g,scopes:O}}));this.addPath(Pr(f),{[x]:{operationId:te,summary:fe,description:S,tags:we.length>0?we:void 0,parameters:ze.length>0?ze:void 0,requestBody:rt,security:Me.length>0?Me:void 0,responses:Ze}})}}),this.rootDoc.tags=r.tags?Dr(r.tags):[]}};import kr from"http";var ei=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>v),...t}),ti=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},ri=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),oi=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=ei({fnMethod:a,requestProps:t}),d=ti({fnMethod:a,responseProps:r}),c=ri({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import w from"typescript";import k from"typescript";import{chain as Lr,toPairs as jr}from"ramda";var n=k.factory,q=[n.createModifier(k.SyntaxKind.ExportKeyword)],ni=[n.createModifier(k.SyntaxKind.AsyncKeyword)],ii=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Hr=[n.createModifier(k.SyntaxKind.ProtectedKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Ct=n.createTemplateHead(""),le=n.createTemplateTail(""),It=n.createTemplateMiddle(" "),Et=e=>n.createTemplateLiteralType(Ct,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?le:It))),wt=Et(["M","P"]),Qe=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),Xe=(e,t)=>Lr(([r,o])=>[Qe(n.createIdentifier(r),o,t)],jr(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([])),Kr=(e,t)=>n.createPropertySignature(void 0,`"${e}"`,void 0,n.createTypeReferenceNode(t)),B=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.NodeFlags.Const),Zt=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),et=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,t),Fr=(e,t,r)=>n.createPropertyDeclaration(ii,e,void 0,t,r),qr=(e,t,r)=>n.createClassDeclaration(q,e,void 0,void 0,[t,...r]),Br=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),$r=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),Vr=(e,t,r)=>n.createInterfaceDeclaration(q,e,void 0,t,r),_r=e=>Lr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],jr(e)),Mt=(e,t,r)=>n.createArrowFunction(r?ni:void 0,void 0,e.map(o=>Qe(o)),void 0,void 0,t),Nt=(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,Xe({acc:void 0,key:void 0}),void 0,void 0,t),r]);var Gr=["get","post","put","delete","patch"];import y from"typescript";import{z as kt}from"zod";import $ from"typescript";var{factory:tt}=$,vt=(e,t)=>{$.addSyntheticLeadingComment(e,$.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ue=(e,t,r)=>{let o=tt.createTypeAliasDeclaration(void 0,tt.createIdentifier(t),void 0,e);return r&&vt(o,r),o},Dt=(e,t)=>{let r=$.createSourceFile("print.ts","",$.ScriptTarget.Latest,!1,$.ScriptKind.TS);return $.createPrinter(t).printNode($.EmitHint.Unspecified,e,r)},si=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yr=e=>si.test(e)?tt.createIdentifier(e):tt.createStringLiteral(e);var{factory:u}=y,ai={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},pi=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),di=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&xe(a)?a instanceof kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Yr(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&vt(d,a.description),d});return u.createTypeLiteralNode(i)},ci=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),mi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Jr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),li=e=>ai?.[e.kind],ui=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,li(o)),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||y.SyntaxKind.AnyKeyword)}return o},fi=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),yi=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},gi=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),hi=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),xi=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Ti=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),bi=({next:e,schema:t})=>e(t._def.innerType),ee=e=>()=>u.createKeywordTypeNode(e),Si=({next:e,schema:t})=>e(t.unwrap()),Oi=({next:e,schema:t})=>e(t._def.innerType),Ai=({next:e,schema:t})=>e(t._def.innerType),Ri=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Pi=()=>u.createLiteralTypeNode(u.createNull()),Ci=({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)))},Ii=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof kt.ZodString?t:e instanceof kt.ZodUnion?o:r},Ei=({next:e,schema:t})=>e(t.shape.raw),wi={ZodString:ee(y.SyntaxKind.StringKeyword),ZodNumber:ee(y.SyntaxKind.NumberKeyword),ZodBigInt:ee(y.SyntaxKind.BigIntKeyword),ZodBoolean:ee(y.SyntaxKind.BooleanKeyword),ZodAny:ee(y.SyntaxKind.AnyKeyword),[Pe]:ee(y.SyntaxKind.StringKeyword),[Ce]:ee(y.SyntaxKind.StringKeyword),ZodNull:Pi,ZodArray:ci,ZodTuple:hi,ZodRecord:xi,ZodObject:di,ZodLiteral:pi,ZodIntersection:Ti,ZodUnion:Jr,ZodDefault:bi,ZodEnum:mi,ZodNativeEnum:fi,ZodEffects:ui,ZodOptional:yi,ZodNullable:gi,ZodDiscriminatedUnion:Jr,ZodBranded:Si,ZodCatch:Ai,ZodPipeline:Ri,ZodLazy:Ci,ZodReadonly:Oi,[K]:Ii,[Y]:Ei},Ee=({schema:e,...t})=>Q({schema:e,rules:wi,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Lt=class{program=[];usage=[];registry={};paths=[];aliases={};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 t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[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}}){W({routing:t,onEndpoint:(g,O,R)=>{let z={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},re=I(R,O,"input"),Wr=Ee({...z,schema:g.getSchema("input"),isResponse:!1}),ge=i?I(R,O,"positive.response"):void 0,jt=g.getSchema("positive"),Ht=i?Ee({...z,isResponse:!0,schema:jt}):void 0,he=i?I(R,O,"negative.response"):void 0,Ut=g.getSchema("negative"),Kt=i?Ee({...z,isResponse:!0,schema:Ut}):void 0,Ft=I(R,O,"response"),Qr=ge&&he?n.createUnionTypeNode([n.createTypeReferenceNode(ge),n.createTypeReferenceNode(he)]):Ee({...z,isResponse:!0,schema:jt.or(Ut)});this.program.push(ue(Wr,re)),Ht&&ge&&this.program.push(ue(Ht,ge)),Kt&&he&&this.program.push(ue(Kt,he)),this.program.push(ue(Qr,Ft)),R!=="options"&&(this.paths.push(O),this.registry[`${R} ${O}`]={input:re,positive:ge,negative:he,response:Ft,isJson:g.getMimeTypes("positive").includes(v),tags:g.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(Zt(this.ids.pathType,this.paths)),this.program.push(Zt(this.ids.methodType,Gr)),this.program.push(et(this.ids.methodPathType,Et([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.SyntaxKind.ExtendsKeyword,[zt(this.ids.methodPathType,w.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:g,kind:O}of this.interfaces)this.program.push(Vr(g,a,Object.keys(this.registry).map(R=>{let z=this.registry[R][O];return z?Kr(R,z):void 0}).filter(R=>R!==void 0)));if(r==="types")return;let p=n.createVariableStatement(q,B(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(g=>this.registry[g].isJson).map(g=>n.createPropertyAssignment(`"${g}"`,n.createTrue()))))),d=n.createVariableStatement(q,B(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(g=>n.createPropertyAssignment(`"${g}"`,n.createArrayLiteralExpression(this.registry[g].tags.map(O=>n.createStringLiteral(O)))))))),c=et(this.ids.providerType,n.createFunctionTypeNode(_r({M:this.ids.methodType,P:this.ids.pathType}),Xe({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),wt)}),Br(this.ids.responseInterface,wt))),l=et(this.ids.implementationType,n.createFunctionTypeNode(void 0,Xe({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.SyntaxKind.StringKeyword),params:zt(w.SyntaxKind.StringKeyword,w.SyntaxKind.AnyKeyword)}),$r())),m=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,le)]),f=Nt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[m,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),b=Nt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[m]),w.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=qr(this.ids.clientClass,Ur([Qe(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Hr)]),[Fr(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,f,b]),!0))]);this.program.push(p,d,c,l,x);let A=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),h=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(v))]),void 0,this.ids.undefinedValue)),S=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)),fe=n.createVariableStatement(void 0,B(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,le)]),n.createObjectLiteralExpression([A,h,S])])))),we=n.createVariableStatement(void 0,B(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ye=n.createVariableStatement(void 0,B(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]),le)])))),[te,ze]=["json","text"].map(g=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,g),void 0,void 0))),Ze=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ct,[n.createTemplateSpan(this.ids.methodParameter,It),n.createTemplateSpan(this.ids.pathParameter,le)]),w.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([te])),rt=n.createVariableStatement(q,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([we,ye,fe,Ze,ze]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Me=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"))])])),N=n.createVariableStatement(void 0,B(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(rt,N,Me)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
|
|
19
21
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&w.addSyntheticLeadingComment(w.addSyntheticLeadingComment(n.createEmptyStatement(),w.SyntaxKind.SingleLineCommentTrivia," Usage example:"),w.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((i,s)=>
|
|
22
|
+
${r}`);return this.program.concat(o||[]).map((i,s)=>Dt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
23
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
24
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await ce("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 zi={dateIn:gr,dateOut:hr,file:je,upload:Jt,raw:Yt};export{de as AbstractEndpoint,Ae as DependsOnMethod,Pt as Documentation,C as DocumentationError,Oe as EndpointsFactory,j as InputValidationError,Lt as Integration,ie as MissingPeerError,V as OutputValidationError,ne as RoutingError,Re as ServeStatic,Eo as arrayEndpointsFactory,gt as arrayResultHandler,Bo as attachRouting,Xr as createConfig,xt as createLogger,ft as createMiddleware,yt as createResultHandler,$o as createServer,Io as defaultEndpointsFactory,Se as defaultResultHandler,zi as ez,U as getExamples,H as getMessageFromError,ve as getStatusCodeFromError,oi as testEndpoint,D as withMeta};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "18.0.0-beta2",
|
|
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": {
|
|
@@ -25,7 +25,6 @@
|
|
|
25
25
|
"build:docs": "tsx example/generate-documentation.ts",
|
|
26
26
|
"build:client": "tsx example/generate-client.ts",
|
|
27
27
|
"build:license": "tsx tools/license.ts",
|
|
28
|
-
"build:logo": "tsx tools/startup-logo.ts",
|
|
29
28
|
"test": "yarn test:types && yarn test:unit && yarn test:badge",
|
|
30
29
|
"test:cjs": "yarn --cwd tests/cjs && vitest run -r tests/cjs",
|
|
31
30
|
"test:esm": "yarn --cwd tests/esm && vitest run -r tests/esm",
|
|
@@ -68,6 +67,7 @@
|
|
|
68
67
|
"node": "^18.0.0 || ^20.0.0"
|
|
69
68
|
},
|
|
70
69
|
"dependencies": {
|
|
70
|
+
"ansis": "^3.1.0",
|
|
71
71
|
"openapi3-ts": "^4.2.1",
|
|
72
72
|
"ramda": "^0.29.1"
|
|
73
73
|
},
|
|
@@ -86,7 +86,6 @@
|
|
|
86
86
|
"prettier": "^3.1.0",
|
|
87
87
|
"typescript": "^5.1.3",
|
|
88
88
|
"vitest": "^1.0.4",
|
|
89
|
-
"winston": "^3.10.0",
|
|
90
89
|
"zod": "^3.22.3"
|
|
91
90
|
},
|
|
92
91
|
"peerDependenciesMeta": {
|
|
@@ -122,9 +121,6 @@
|
|
|
122
121
|
},
|
|
123
122
|
"vitest": {
|
|
124
123
|
"optional": true
|
|
125
|
-
},
|
|
126
|
-
"winston": {
|
|
127
|
-
"optional": true
|
|
128
124
|
}
|
|
129
125
|
},
|
|
130
126
|
"devDependencies": {
|
|
@@ -142,7 +138,6 @@
|
|
|
142
138
|
"@typescript-eslint/eslint-plugin": "^7.1.0",
|
|
143
139
|
"@typescript-eslint/parser": "^7.1.0",
|
|
144
140
|
"@vitest/coverage-istanbul": "^1.0.4",
|
|
145
|
-
"chalk": "^5.3.0",
|
|
146
141
|
"compression": "^1.7.4",
|
|
147
142
|
"cors": "^2.8.5",
|
|
148
143
|
"eslint": "^8.48.0",
|
|
@@ -165,7 +160,6 @@
|
|
|
165
160
|
"tsx": "^4.6.2",
|
|
166
161
|
"typescript": "^5.2.2",
|
|
167
162
|
"vitest": "^1.0.4",
|
|
168
|
-
"winston": "^3.10.0",
|
|
169
163
|
"zod": "^3.22.3"
|
|
170
164
|
},
|
|
171
165
|
"keywords": [
|