express-zod-api 20.14.2 → 20.14.3
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 +13 -6
- package/README.md +2 -1
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +27 -1
- package/dist/index.d.ts +27 -1
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 20
|
|
4
4
|
|
|
5
|
+
### v20.14.3
|
|
6
|
+
|
|
7
|
+
- Fixed: missing export of `testMiddleware`:
|
|
8
|
+
- The feature introduced in v20.4.0 but was not available;
|
|
9
|
+
- The issue reported by [@Tomtec331](https://github.com/Tomtec331).
|
|
10
|
+
|
|
5
11
|
### v20.14.2
|
|
6
12
|
|
|
7
13
|
- Documentation: promoting Express 5 as the recommended version for new projects;
|
|
@@ -197,7 +203,8 @@ declare module "express-zod-api" {
|
|
|
197
203
|
- Feat: middleware testing helper: `testMiddleware()`, similar to `testEndpoint()`:
|
|
198
204
|
- There is also an ability to pass `options` collected from outputs of previous middlewares, if the one being tested
|
|
199
205
|
somehow depends on them.
|
|
200
|
-
- The method returns: `Promise<{ output, requestMock, responseMock, loggerMock }
|
|
206
|
+
- The method returns: `Promise<{ output, requestMock, responseMock, loggerMock }>`;
|
|
207
|
+
- Export fixed in v20.14.3.
|
|
201
208
|
|
|
202
209
|
```typescript
|
|
203
210
|
import { z } from "zod";
|
|
@@ -2025,7 +2032,7 @@ new Client({
|
|
|
2025
2032
|
|
|
2026
2033
|
### v10.1.3
|
|
2027
2034
|
|
|
2028
|
-
- Fixed issue #929, found and reported by [@
|
|
2035
|
+
- Fixed issue #929, found and reported by [@niklashigi](https://github.com/niklashigi).
|
|
2029
2036
|
- Customized description of request parameters have not been depicted correctly when generating the documentation.
|
|
2030
2037
|
|
|
2031
2038
|
### v10.1.2
|
|
@@ -2477,7 +2484,7 @@ output/anything: Number must be greater than 0
|
|
|
2477
2484
|
### v8.4.3
|
|
2478
2485
|
|
|
2479
2486
|
- The regular expression used for validating `z.dateIn()` made easier
|
|
2480
|
-
by [@
|
|
2487
|
+
by [@niklashigi](https://github.com/niklashigi).
|
|
2481
2488
|
|
|
2482
2489
|
```typescript
|
|
2483
2490
|
const before = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?)?Z?$/;
|
|
@@ -2556,7 +2563,7 @@ z.object({}).transform(() => []); // never[] inherits Array inherits Object, {}
|
|
|
2556
2563
|
|
|
2557
2564
|
### v8.3.3
|
|
2558
2565
|
|
|
2559
|
-
- Fixed the bug #672 found and reported by [@
|
|
2566
|
+
- Fixed the bug #672 found and reported by [@niklashigi](https://github.com/niklashigi).
|
|
2560
2567
|
- Preserving the custom description of `z.dateIn()` and `z.dateOut()` schemas when generating OpenAPI documentation.
|
|
2561
2568
|
|
|
2562
2569
|
```yaml
|
|
@@ -2569,7 +2576,7 @@ after:
|
|
|
2569
2576
|
|
|
2570
2577
|
### v8.3.2
|
|
2571
2578
|
|
|
2572
|
-
- Fixed the bug #673 found and reported by [@
|
|
2579
|
+
- Fixed the bug #673 found and reported by [@niklashigi](https://github.com/niklashigi).
|
|
2573
2580
|
- Preventing double parsing of incoming data by input schemas of middlewares containing transformations.
|
|
2574
2581
|
- The bug caused inability of using any transforming schema in middlewares.
|
|
2575
2582
|
- In particular, but not limited with: using `z.dateIn()` in middlewares.
|
|
@@ -2719,7 +2726,7 @@ const routing: Routing = {
|
|
|
2719
2726
|
### v7.9.3
|
|
2720
2727
|
|
|
2721
2728
|
- This version contains a cherry-picked fix made in v8.3.2.
|
|
2722
|
-
- Fixed the bug #673 found and reported by [@
|
|
2729
|
+
- Fixed the bug #673 found and reported by [@niklashigi](https://github.com/niklashigi).
|
|
2723
2730
|
- Preventing double parsing of incoming data by input schemas of middlewares containing transformations.
|
|
2724
2731
|
- The bug caused inability of using any transforming schema in middlewares.
|
|
2725
2732
|
- In particular, but not limited with: using `z.dateIn()` in middlewares.
|
package/README.md
CHANGED
|
@@ -83,6 +83,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
|
|
|
83
83
|
|
|
84
84
|
These people contributed to the improvement of the library by reporting bugs, making changes and suggesting ideas:
|
|
85
85
|
|
|
86
|
+
[<img src="https://github.com/Tomtec331.png" alt="@Tomtec331" width="50px" />](https://github.com/Tomtec331)
|
|
86
87
|
[<img src="https://github.com/rottmann.png" alt="@rottmann" width="50px" />](https://github.com/rottmann)
|
|
87
88
|
[<img src="https://github.com/boarush.png" alt="@boarush" width="50px" />](https://github.com/boarush)
|
|
88
89
|
[<img src="https://github.com/daniel-white.png" alt="@daniel-white" width="50px" />](https://github.com/daniel-white)
|
|
@@ -99,7 +100,7 @@ These people contributed to the improvement of the library by reporting bugs, ma
|
|
|
99
100
|
[<img src="https://github.com/miki725.png" alt="@miki725" width="50px" />](https://github.com/miki725)
|
|
100
101
|
[<img src="https://github.com/dev-m1-macbook.png" alt="@dev-m1-macbook" width="50px" />](https://github.com/dev-m1-macbook)
|
|
101
102
|
[<img src="https://github.com/McMerph.png" alt="@McMerph" width="50px" />](https://github.com/McMerph)
|
|
102
|
-
[<img src="https://github.com/
|
|
103
|
+
[<img src="https://github.com/niklashigi.png" alt="@niklashigi" width="50px" />](https://github.com/niklashigi)
|
|
103
104
|
[<img src="https://github.com/maxcohn.png" alt="@maxcohn" width="50px" />](https://github.com/maxcohn)
|
|
104
105
|
[<img src="https://github.com/VideoSystemsTech.png" alt="@VideoSystemsTech" width="50px" />](https://github.com/VideoSystemsTech)
|
|
105
106
|
[<img src="https://github.com/TheWisestOne.png" alt="@TheWisestOne" width="50px" />](https://github.com/TheWisestOne)
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},Ye=class extends Error{name="IOSchemaError"},G=class extends Ye{constructor(r){super(F(r));this.originalError=r}name="OutputValidationError"},U=class extends Ye{constructor(r){super(F(r));this.originalError=r}name="InputValidationError"},_=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},fe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var
|
|
1
|
+
"use strict";var Fo=Object.create;var _e=Object.defineProperty;var Ko=Object.getOwnPropertyDescriptor;var Bo=Object.getOwnPropertyNames;var qo=Object.getPrototypeOf,$o=Object.prototype.hasOwnProperty;var Vo=(e,t)=>{for(var r in t)_e(e,r,{get:t[r],enumerable:!0})},sr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Bo(t))!$o.call(e,n)&&n!==r&&_e(e,n,{get:()=>t[n],enumerable:!(o=Ko(t,n))||o.enumerable});return e};var O=(e,t,r)=>(r=e!=null?Fo(qo(e)):{},sr(t||!e||!e.__esModule?_e(r,"default",{value:e,enumerable:!0}):r,e)),Go=e=>sr(_e({},"__esModule",{value:!0}),e);var Cs={};Vo(Cs,{BuiltinLogger:()=>Oe,DependsOnMethod:()=>Re,Documentation:()=>ft,DocumentationError:()=>z,EndpointsFactory:()=>Te,InputValidationError:()=>U,Integration:()=>Ot,Middleware:()=>B,MissingPeerError:()=>fe,OutputValidationError:()=>G,ResultHandler:()=>be,RoutingError:()=>te,ServeStatic:()=>Pe,arrayEndpointsFactory:()=>Cr,arrayResultHandler:()=>at,attachRouting:()=>eo,createConfig:()=>dr,createServer:()=>to,defaultEndpointsFactory:()=>Pr,defaultResultHandler:()=>Se,ez:()=>Ho,getExamples:()=>K,getMessageFromError:()=>F,getStatusCodeFromError:()=>Me,testEndpoint:()=>Ao,testMiddleware:()=>Po});module.exports=Go(Cs);var P=require("ramda"),ne=require("zod");var ir=require("http-errors"),ar=require("node:crypto"),Qe=require("ramda"),pr=require("zod");var te=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
|
|
2
|
+
Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},Ye=class extends Error{name="IOSchemaError"},G=class extends Ye{constructor(r){super(F(r));this.originalError=r}name="OutputValidationError"},U=class extends Ye{constructor(r){super(F(r));this.originalError=r}name="InputValidationError"},_=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},fe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var _o=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},At={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Yo=["body","query","params"],Pt=e=>e.method.toLowerCase(),Ct=e=>e.startsWith("x-"),Qo=e=>(0,Qe.pickBy)((t,r)=>Ct(r),e),Je=(e,t={})=>{let r=Pt(e);return r==="options"?{}:(t[r]||At[r]||Yo).filter(o=>o==="files"?_o(e):!0).map(o=>o==="headers"?Qo(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},ye=e=>e instanceof Error?e:new Error(String(e)),F=e=>e instanceof pr.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Me=e=>(0,ir.isHttpError)(e)?e.statusCode:e instanceof U?400:500,It=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},K=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[h]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},re=(e,t,r)=>e.length&&t.length?(0,Qe.xprod)(e,t).map(r):e.concat(t),Ue=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,zt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),N=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(zt).join(""),
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};var Sr=require("ramda");var ie=e=>oe(e)&&"or"in e,he=e=>oe(e)&&"and"in e,Et=e=>({and:(0,Sr.chain)(t=>he(t)?t.and:[t],e)}),ot=(e,t)=>he(e)?{and:e.and.map(r=>ie(r)?{or:r.or.map(t)}:t(r))}:ie(e)?{or:e.or.map(r=>he(r)?{and:r.and.map(t)}:t(r))}:t(e),Zt=e=>e.and.reduce((t,r)=>({or:re(t.or,ie(r)?r.or:[r],Et)}),{or:[]}),ge=(e,t)=>he(e)?ie(t)?ge(Zt(e),t):Et([e,t]):ie(e)?he(t)?ge(t,e):ie(t)?{or:re(e.or,t.or,Et)}:ge(e,{and:[t]}):he(t)||ie(t)?ge(t,e):{and:[e,t]};var jt=require("zod");var vt=class{},B=class extends vt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof jt.z.ZodError?new U(o):o}}},xe=class extends B{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:jt.z.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let l=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,l)?.catch(l)})})}};var Fe=class{},nt=class extends Fe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:l=[],tags:c=[],description:m,shortDescription:y}){super(),this.#a=n,this.#p=i,this.#r=l,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:m,short:y},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=xr(r)?"upload":br(r)?"raw":"json",this.#i={input:Object.freeze([w[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?ge(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof Lt.z.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof xe))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof Lt.z.ZodError?new U(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(l){rt({logger:n,response:o,error:new _(ye(l).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=At(t),p={},l=null,c=null;if(n.cors){let y=this.#m(i);typeof n.cors=="function"&&(y=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let u in y)r.set(u,y[u])}let m=Ct(t,n.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}l=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){c=ye(y)}await this.#g({input:m,output:l,request:t,response:r,error:c,logger:o,options:p})}};var Tr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>cr(i,n),o)};var k=require("zod");var ae={positive:200,negative:400};var Or=O(require("node:assert/strict"),1),Rr=require("zod");var st=(e,t)=>typeof e=="function"?st(e(...t.arguments),t):e instanceof Rr.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&(0,Or.default)(e.length,new _(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var Nt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Nt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return st(this.#e,{variant:"positive",arguments:[t],statusCodes:[ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return st(this.#t,{variant:"negative",arguments:[],statusCodes:[ae.negative],mimeTypes:[w.json]})}},Se=new be({positive:e=>{let t=K({schema:e}),r=k.z.object({status:k.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:k.z.object({status:k.z.literal("error"),error:k.z.object({message:k.z.string()})}).example({status:"error",error:{message:F(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(ae.positive).json({status:"success",data:r});return}let a=Me(e);It({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:F(e)}})}}),it=new be({positive:e=>{let t=K({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.z.ZodArray?e.shape.items:k.z.array(k.z.any());return t.reduce((o,n)=>oe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:k.z.string().example(F(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Me(r);It({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ae.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var Te=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 instanceof B?t:new B(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new xe(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new B({input:Ar.z.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:l,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],y=typeof a=="function"?a:()=>a,u="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 nt({handler:r,middlewares:l,outputSchema:o,resultHandler:c,scopes:u,tags:x,methods:m,getOperationId:y,description:n,shortDescription:i,inputSchema:Tr(l,t)})}},Pr=new Te(Se),Cr=new Te(it);var E=require("ansis"),jr=require("node:util"),kt=require("node:perf_hooks");var pt={debug:10,info:20,warn:30,error:40},zr=e=>oe(e)&&Object.keys(pt).some(t=>t in e),wr=e=>e in pt,Er=(e,t)=>pt[e]<pt[t],Zr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),at=Zr(),Ir=Zr(2),rn=e=>e<1e-6?["picosecond",e/1e-9,at]:e<.001?["nanosecond",e/1e-6,at]:e<1?["microsecond",e/.001,at]:e<1e3?["millisecond",e,at]:e<6e4?["second",e/1e3,Ir]:["minute",e/6e4,Ir],vr=e=>{let[t,r,o]=rn(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var Oe=class e{constructor(t){this.config=t;let{color:r=new E.Ansis().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:E.blue,info:E.green,warn:(0,E.hex)("#FFA500"),error:E.red};prettyPrint(t){let{depth:r=2}=this.config;return(0,jr.inspect)(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||Er(t,this.config.level))return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?(0,E.cyanBright)(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=kt.performance.now();return()=>{let o=kt.performance.now()-r,{message:n,severity:i="debug",formatter:a=vr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};var Ae=require("ramda"),Re=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,Ae.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,Ae.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,Ae.tail)(this.pairs).map(([r])=>r))}};var Lr=O(require("express"),1),Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Lr.default.static(...this.params))}};var ct=O(require("express"),1),Jr=O(require("node:http"),1),Wr=O(require("node:https"),1);var Ce=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>O(require(e))))[t]}catch{}throw new fe(e)};var Mt=O(require("node:assert/strict"),1);var pe=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){Mt.default.doesNotMatch(a,/\//,new te(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let l=`${o||""}${a?`/${a}`:""}`;if(p instanceof Fe){let c=p.getMethods().slice();n&&c.push("options");for(let m of c)t(p,l,m)}else if(p instanceof Pe)r&&p.apply(l,r);else if(p instanceof Re){for(let[c,m]of p.pairs)(0,Mt.default)(m.getMethods().includes(c),new te(`Endpoint assigned to ${c} method of ${l} must support ${c} method.`)),t(m,l,c);n&&p.firstEndpoint&&t(p.firstEndpoint,l,"options",p.siblingMethods)}else pe({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:l})}};var Ut=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>pe({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,l)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,m)=>i.execute({request:c,response:m,logger:t(c),config:r,siblingMethods:l}))},onStatic:(i,a)=>{e.use(i,a)}});var Ke=O(require("http-errors"),1);var Dr=require("node:timers/promises");var Nr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",kr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Mr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Ur=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Hr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Fr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(Nr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let l=async()=>{for(let c of e)c.on("request",Ur);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Mr(c)||kr(c))&&a(c);for await(let c of(0,Dr.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(Hr))};return{sockets:n,shutdown:()=>o??=l()}};var Kr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:(0,Ke.isHttpError)(r)?r:(0,Ke.default)(400,ye(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Br=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=(0,Ke.default)(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){rt({response:o,logger:i,error:new _(ye(a).message,n)})}},on=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},nn=e=>({log:e.debug.bind(e)}),qr=async({getChildLogger:e,config:t})=>{let r=await Ce("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,l,c)=>{let m=e(p);try{await n?.({request:p,logger:m})}catch(y){return c(y)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:nn(m)})(p,l,c)}),o&&a.push(on(o)),a},$r=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Vr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[h]={logger:i}),n()},Gr=e=>t=>t.res?.locals[h]?.logger||e,_r=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
4
|
+
`,{url:t.url,payload:r})},K=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[h]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},re=(e,t,r)=>e.length&&t.length?(0,Qe.xprod)(e,t).map(r):e.concat(t),Ue=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,zt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),N=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(zt).join(""),We=e=>(0,ar.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Xe=(e,t)=>{try{return typeof e.parse(t)}catch{return}},oe=e=>typeof e=="object"&&e!==null;var et=require("ramda"),h=Symbol.for("express-zod-api"),tt=e=>{let t=e.describe(e.description);return t._def[h]=(0,et.clone)(t._def[h])||{examples:[]},t},cr=(e,t)=>{if(!(h in e._def))return t;let r=tt(t);return r._def[h].examples=re(r._def[h].examples,e._def[h].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?(0,et.mergeDeepRight)({...o},{...n}):n),r};var Jo=function(e){let t=tt(this);return t._def[h].examples.push(e),t},Wo=function(e){let t=tt(this);return t._def[h].defaultLabel=e,t},Xo=function(e){return new ne.z.ZodBranded({typeName:ne.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[h]:{examples:[],...(0,P.clone)(this._def[h]),brand:e}})},en=function(e){let t=typeof e=="function"?e:(0,P.pipe)(P.toPairs,(0,P.map)(([n,i])=>(0,P.pair)(e[String(n)]||n,i)),P.fromPairs),r=t((0,P.clone)(this.shape)),o=ne.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};h in globalThis||(globalThis[h]=!0,Object.defineProperties(ne.z.ZodType.prototype,{example:{get(){return Jo.bind(this)}},brand:{set(){},get(){return Xo.bind(this)}}}),Object.defineProperty(ne.z.ZodDefault.prototype,"label",{get(){return Wo.bind(this)}}),Object.defineProperty(ne.z.ZodObject.prototype,"remap",{get(){return en.bind(this)}}));function dr(e){return e}var Ar=require("zod");var Lt=require("zod");var mr=require("zod");var He=require("zod"),Y=Symbol("File"),lr=He.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),tn={buffer:()=>lr.brand(Y),string:()=>He.z.string().brand(Y),binary:()=>lr.or(He.z.string()).brand(Y),base64:()=>He.z.string().base64().brand(Y)};function rt(e){return tn[e||"string"]()}var se=Symbol("Raw"),ur=(e={})=>mr.z.object({raw:rt("buffer")}).extend(e).brand(se);var fr=require("zod"),De=Symbol("Upload"),yr=()=>fr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(De);var gr=(e,{next:t})=>e.options.some(t),rn=({_def:e},{next:t})=>[e.left,e.right].some(t),hr=(e,{next:t})=>t(e.unwrap()),on={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:gr,ZodDiscriminatedUnion:gr,ZodIntersection:rn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:hr,ZodNullable:hr,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},wt=(e,{condition:t,rules:r=on,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>wt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},xr=e=>wt(e,{condition:t=>t._def[h]?.brand===De}),br=e=>wt(e,{condition:t=>t._def[h]?.brand===se,maxDepth:3});var ot=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
5
|
+
Original error: ${e.originalError.message}.`:""))};var Sr=require("ramda");var ie=e=>oe(e)&&"or"in e,he=e=>oe(e)&&"and"in e,Et=e=>({and:(0,Sr.chain)(t=>he(t)?t.and:[t],e)}),nt=(e,t)=>he(e)?{and:e.and.map(r=>ie(r)?{or:r.or.map(t)}:t(r))}:ie(e)?{or:e.or.map(r=>he(r)?{and:r.and.map(t)}:t(r))}:t(e),Zt=e=>e.and.reduce((t,r)=>({or:re(t.or,ie(r)?r.or:[r],Et)}),{or:[]}),ge=(e,t)=>he(e)?ie(t)?ge(Zt(e),t):Et([e,t]):ie(e)?he(t)?ge(t,e):ie(t)?{or:re(e.or,t.or,Et)}:ge(e,{and:[t]}):he(t)||ie(t)?ge(t,e):{and:[e,t]};var jt=require("zod");var vt=class{},B=class extends vt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof jt.z.ZodError?new U(o):o}}},xe=class extends B{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:jt.z.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let l=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,l)?.catch(l)})})}};var Fe=class{},st=class extends Fe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:l=[],tags:c=[],description:m,shortDescription:y}){super(),this.#a=n,this.#p=i,this.#r=l,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:m,short:y},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=xr(r)?"upload":br(r)?"raw":"json",this.#i={input:Object.freeze([w[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?ge(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof Lt.z.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof xe))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof Lt.z.ZodError?new U(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(l){ot({logger:n,response:o,error:new _(ye(l).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=Pt(t),p={},l=null,c=null;if(n.cors){let y=this.#m(i);typeof n.cors=="function"&&(y=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let u in y)r.set(u,y[u])}let m=Je(t,n.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}l=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){c=ye(y)}await this.#g({input:m,output:l,request:t,response:r,error:c,logger:o,options:p})}};var Tr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>cr(i,n),o)};var k=require("zod");var ae={positive:200,negative:400};var Or=O(require("node:assert/strict"),1),Rr=require("zod");var it=(e,t)=>typeof e=="function"?it(e(...t.arguments),t):e instanceof Rr.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&(0,Or.default)(e.length,new _(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var Nt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Nt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return it(this.#e,{variant:"positive",arguments:[t],statusCodes:[ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return it(this.#t,{variant:"negative",arguments:[],statusCodes:[ae.negative],mimeTypes:[w.json]})}},Se=new be({positive:e=>{let t=K({schema:e}),r=k.z.object({status:k.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:k.z.object({status:k.z.literal("error"),error:k.z.object({message:k.z.string()})}).example({status:"error",error:{message:F(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(ae.positive).json({status:"success",data:r});return}let a=Me(e);It({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:F(e)}})}}),at=new be({positive:e=>{let t=K({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.z.ZodArray?e.shape.items:k.z.array(k.z.any());return t.reduce((o,n)=>oe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:k.z.string().example(F(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Me(r);It({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ae.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var Te=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 instanceof B?t:new B(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new xe(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new B({input:Ar.z.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:l,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],y=typeof a=="function"?a:()=>a,u="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 st({handler:r,middlewares:l,outputSchema:o,resultHandler:c,scopes:u,tags:x,methods:m,getOperationId:y,description:n,shortDescription:i,inputSchema:Tr(l,t)})}},Pr=new Te(Se),Cr=new Te(at);var E=require("ansis"),jr=require("node:util"),kt=require("node:perf_hooks");var ct={debug:10,info:20,warn:30,error:40},zr=e=>oe(e)&&Object.keys(ct).some(t=>t in e),wr=e=>e in ct,Er=(e,t)=>ct[e]<ct[t],Zr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),pt=Zr(),Ir=Zr(2),nn=e=>e<1e-6?["picosecond",e/1e-9,pt]:e<.001?["nanosecond",e/1e-6,pt]:e<1?["microsecond",e/.001,pt]:e<1e3?["millisecond",e,pt]:e<6e4?["second",e/1e3,Ir]:["minute",e/6e4,Ir],vr=e=>{let[t,r,o]=nn(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var Oe=class e{constructor(t){this.config=t;let{color:r=new E.Ansis().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:E.blue,info:E.green,warn:(0,E.hex)("#FFA500"),error:E.red};prettyPrint(t){let{depth:r=2}=this.config;return(0,jr.inspect)(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||Er(t,this.config.level))return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?(0,E.cyanBright)(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=kt.performance.now();return()=>{let o=kt.performance.now()-r,{message:n,severity:i="debug",formatter:a=vr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};var Ae=require("ramda"),Re=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,Ae.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,Ae.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,Ae.tail)(this.pairs).map(([r])=>r))}};var Lr=O(require("express"),1),Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Lr.default.static(...this.params))}};var dt=O(require("express"),1),Jr=O(require("node:http"),1),Wr=O(require("node:https"),1);var Ce=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>O(require(e))))[t]}catch{}throw new fe(e)};var Mt=O(require("node:assert/strict"),1);var pe=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){Mt.default.doesNotMatch(a,/\//,new te(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let l=`${o||""}${a?`/${a}`:""}`;if(p instanceof Fe){let c=p.getMethods().slice();n&&c.push("options");for(let m of c)t(p,l,m)}else if(p instanceof Pe)r&&p.apply(l,r);else if(p instanceof Re){for(let[c,m]of p.pairs)(0,Mt.default)(m.getMethods().includes(c),new te(`Endpoint assigned to ${c} method of ${l} must support ${c} method.`)),t(m,l,c);n&&p.firstEndpoint&&t(p.firstEndpoint,l,"options",p.siblingMethods)}else pe({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:l})}};var Ut=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>pe({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,l)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,m)=>i.execute({request:c,response:m,logger:t(c),config:r,siblingMethods:l}))},onStatic:(i,a)=>{e.use(i,a)}});var Ke=O(require("http-errors"),1);var Dr=require("node:timers/promises");var Nr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",kr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Mr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Ur=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Hr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Fr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(Nr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let l=async()=>{for(let c of e)c.on("request",Ur);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Mr(c)||kr(c))&&a(c);for await(let c of(0,Dr.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(Hr))};return{sockets:n,shutdown:()=>o??=l()}};var Kr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:(0,Ke.isHttpError)(r)?r:(0,Ke.default)(400,ye(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Br=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=(0,Ke.default)(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){ot({response:o,logger:i,error:new _(ye(a).message,n)})}},sn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},an=e=>({log:e.debug.bind(e)}),qr=async({getChildLogger:e,config:t})=>{let r=await Ce("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,l,c)=>{let m=e(p);try{await n?.({request:p,logger:m})}catch(y){return c(y)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:an(m)})(p,l,c)}),o&&a.push(sn(o)),a},$r=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Vr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[h]={logger:i}),n()},Gr=e=>t=>t.res?.locals[h]?.logger||e,_r=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
6
6
|
`).slice(1))),Yr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Fr(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};var Z=require("ansis"),Qr=()=>{let e=(0,Z.italic)("Proudly supports transgender community.".padStart(109)),t=(0,Z.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,Z.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,Z.italic)("for Zoey".padEnd(20)),n=(0,Z.hex)("#F5A9B8"),i=(0,Z.hex)("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(Z.whiteBright,5,7).fill(n,7,9).fill(i,9,12).fill(Z.gray,12,13);return`
|
|
7
7
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
8
8
|
888 d88P 888 d88888 888 Y88b 888
|
|
@@ -18,8 +18,8 @@ ${o}888${t}
|
|
|
18
18
|
${r}
|
|
19
19
|
`.split(`
|
|
20
20
|
`).map((l,c)=>a[c]?a[c](l):l).join(`
|
|
21
|
-
`)};var Xr=e=>{e.startupLogo!==!1&&console.log(Qr());let t=e.errorHandler||Se,r=zr(e.logger)?e.logger:new Oe(e.logger);r.debug("Running","v20.14.2 (CJS)"),_r(r);let o=Vr({rootLogger:r,config:e}),i={getChildLogger:Gr(r),errorHandler:t},a=Br(i),p=Kr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},eo=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Xr(e);return Ut({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},to=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Xr(e),p=(0,ct.default)().disable("x-powered-by").use(a);if(e.server.compression){let u=await Ce("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let l={json:[e.server.jsonParser||ct.default.json()],raw:[e.server.rawParser||ct.default.raw(),$r],upload:e.server.upload?await qr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ut({app:p,routing:t,getChildLogger:o,config:e,parsers:l}),p.use(i,n);let c=(u,x)=>u.listen(x,()=>r.info("Listening",x)),m=Jr.default.createServer(p),y=e.https&&Wr.default.createServer(e.https.options,p);return e.gracefulShutdown&&Yr({servers:[m].concat(y||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:y&&c(y,e.https?.listen)}};var To=O(require("node:assert/strict"),1),Oo=require("openapi3-ts/oas31"),ft=require("ramda");var Q=O(require("node:assert/strict"),1),q=require("openapi3-ts/oas31"),d=require("ramda"),S=require("zod");var Ie=require("zod");var dt=e=>!isNaN(e.getTime());var Be=Symbol("DateIn"),ro=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(dt)).brand(Be);var oo=require("zod");var qe=Symbol("DateOut"),no=()=>oo.z.date().refine(dt).transform(e=>e.toISOString()).brand(qe);var ce=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>ce(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),l=t&&t(e,{prev:p,...n});return l?{...p,...l}:p};var so=50,ao="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",sn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},po=/:([A-Za-z0-9_]+)/g,an=e=>e.match(po)?.map(t=>t.slice(1))||[],co=e=>e.replace(po,t=>`{${t.slice(1)}}`),pn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),cn=({_def:{innerType:e}},{next:t})=>t(e),dn=()=>({format:"any"}),ln=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),mn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},un=({options:e},{next:t})=>({oneOf:e.map(t)}),fn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),yn=e=>{let[t,r]=e.filter(q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));(0,Q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,d.mergeDeepWith)((n,i)=>Array.isArray(n)&&Array.isArray(i)?(0,d.concat)(n,i):n===i?i:Q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,d.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=re(t.examples||[],r.examples||[],([n,i])=>(0,d.mergeDeepRight)(n,i))),o},gn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return yn(o)}catch{}return{allOf:o}},hn=(e,{next:t})=>t(e.unwrap()),xn=(e,{next:t})=>t(e.unwrap()),bn=(e,{next:t})=>{let r=t(e.unwrap());return(0,q.isSchemaObject)(r)&&(r.type=mo(r)),r},lo=e=>{let t=(0,d.toLower)((0,d.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},io=e=>({type:lo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Sn=({value:e})=>({type:lo(e),const:e}),Tn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=lt(e,r)),i.length&&(a.required=i),a},On=()=>({type:"null"}),Rn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:ao}}),An=({},e)=>((0,Q.default)(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:ao}}),Pn=({},e)=>Q.default.fail(new z({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})),Cn=()=>({type:"boolean"}),In=()=>({type:"integer",format:"bigint"}),zn=e=>e.every(t=>t instanceof S.z.ZodLiteral),wn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=lt(S.z.object((0,d.fromPairs)((0,d.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:lt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&zn(e.options)){let o=(0,d.map)(i=>`${i.value}`,e.options),n=(0,d.fromPairs)((0,d.xprod)(o,[t]));return{type:"object",properties:lt(S.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},En=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Zn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),vn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),j=u?u.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,T={type:"string"},M={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:l,emoji:c};for(let C in M)if(M[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),j&&(T.pattern=j.source),T},jn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(y=>y.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(y=>y.kind==="max"),l=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=l:m.exclusiveMaximum=l,m},lt=({shape:e},t)=>(0,d.map)(t,e),Ln=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return sn?.[t]},mo=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Nn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,q.isSchemaObject)(o)){let i=We(e,Ln(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.z.any())}if(!t&&n.type==="preprocess"&&(0,q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},kn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Mn=(e,{next:t})=>t(e.unwrap()),Un=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},Hn=(e,{next:t})=>t(e.unwrap().shape.raw),uo=e=>e.length?(0,d.fromPairs)((0,d.zip)((0,d.range)(1,e.length+1).map(t=>`example${t}`),(0,d.map)((0,d.objOf)("value"),e))):void 0,fo=(e,t,r=[])=>(0,d.pipe)(K,(0,d.map)((0,d.when)(o=>(0,d.type)(o)==="Object",(0,d.omit)(r))),uo)({schema:e,variant:t?"parsed":"original",validate:!0}),Dn=(e,t)=>(0,d.pipe)(K,(0,d.filter)((0,d.has)(t)),(0,d.pluck)(t),uo)({schema:e,variant:"original",validate:!0}),de=e=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?de(e.unwrap()):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(t=>de(t)).reduce((t,r)=>t.merge(r.partial()),S.z.object({})):e instanceof S.z.ZodEffects?de(e._def.schema):e instanceof S.z.ZodPipeline?de(e._def.in):de(e._def.left).merge(de(e._def.right)),yo=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=de(r),y=an(e),u=o.includes("query"),x=o.includes("params"),j=o.includes("headers"),T=b=>x&&y.includes(b),M=b=>j&&Pt(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":M(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:Ze})=>{let V=ce(m[b],{rules:{...l,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),X=p==="components"?a(N(c,b),V):V;return{name:b,in:Ze,required:!m[b].isOptional(),description:V.description||c,schema:X,examples:Dn(r,b)}})},Dt={ZodString:vn,ZodNumber:jn,ZodBigInt:In,ZodBoolean:Cn,ZodNull:On,ZodArray:En,ZodTuple:Zn,ZodRecord:wn,ZodObject:Tn,ZodLiteral:Sn,ZodIntersection:gn,ZodUnion:un,ZodAny:dn,ZodDefault:pn,ZodEnum:io,ZodNativeEnum:io,ZodEffects:Nn,ZodOptional:hn,ZodNullable:bn,ZodDiscriminatedUnion:fn,ZodBranded:Mn,ZodDate:Pn,ZodCatch:cn,ZodPipeline:kn,ZodLazy:Un,ZodReadonly:xn,[Y]:mn,[De]:ln,[qe]:An,[Be]:Rn,[se]:Hn},Ft=(e,{isResponse:t,prev:r})=>{if((0,q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof S.z.ZodLazy,i=r.type!==void 0,a=t&&Ue(e),p=!n&&i&&!a&&e.isNullable(),l=n?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=mo(r)),l.length&&(c.examples=l.slice()),c},Kt=(e,t)=>Q.default.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Ht=(e,t)=>{if((0,q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,d.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,d.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ht(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ht(o,t))),r},go=e=>(0,q.isReferenceObject)(e)?e:(0,d.omit)(["examples"],e),ho=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:l,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${zt(n)} response ${c?m:""}`.trim()})=>{let x=go(ce(r,{rules:{...y,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),j={schema:l==="components"?p(N(u),x):x,examples:fo(r,!0)};return{description:u,content:(0,d.fromPairs)((0,d.xprod)(o,[j]))}},Fn=()=>({type:"http",scheme:"basic"}),Kn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Bn=({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},qn=({name:e})=>({type:"apiKey",in:"header",name:e}),$n=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Vn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Gn=({flows:e={}})=>({type:"oauth2",flows:(0,d.map)(t=>({...t,scopes:t.scopes||{}}),(0,d.reject)(d.isNil,e))}),xo=(e,t)=>{let r={basic:Fn,bearer:Kn,input:Bn,header:qn,cookie:$n,openid:Vn,oauth2:Gn};return ot(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,d.mergeAll)((0,d.map)(({name:r,scopes:o})=>(0,d.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(Zt(e)):mt({or:[e]}),bo=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,paramNames:c,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=go(Ht(ce(r,{rules:{...l,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),u={schema:p==="components"?a(N(m),y):y,examples:fo(r,!1,c)};return{description:m,content:(0,d.fromPairs)((0,d.xprod)(o,[u]))}},So=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}),Bt=e=>e.length<=so?e:e.slice(0,so-1)+"\u2026";var ut=class extends Oo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=(0,ft.keys)(ae);makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||N(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&To.default.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:l=!0,composition:c="inline",serializer:m=Je}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});pe({routing:t,onEndpoint:(u,x,j)=>{let T=j,M={path:x,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),Ze=C?Bt(C):l&&b?Bt(b):void 0,V=u.getTags(),X=r.inputSources?.[T]||Rt[T],me=this.ensureUniqOperationId(x,T,u.getOperationId(T)),ve=yo({...M,inputSources:X,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:me})}),Ve={};for(let D of this.responseVariants){let ee=u.getResponses(D);for(let{mimeTypes:je,schema:R,statusCodes:A}of ee)for(let I of A)Ve[I]=ho({...M,variant:D,schema:R,mimeTypes:je,statusCode:I,hasMultipleStatusCodes:ee.length>1||A.length>1,description:a?.[`${D}Response`]?.call(null,{method:T,path:x,operationId:me,statusCode:I})})}let Ot=X.includes("body")?bo({...M,paramNames:(0,ft.pluck)("name",ve),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:me})}):void 0,Ge=mt(ot(xo(u.getSecurity(),X),D=>{let ee=this.ensureUniqSecuritySchemaName(D),je=["oauth2","openIdConnect"].includes(D.type)?u.getScopes().slice():[];return this.addSecurityScheme(ee,D),{name:ee,scopes:je}}));this.addPath(co(x),{[T]:{operationId:me,summary:Ze,description:b,tags:V.length>0?V:void 0,parameters:ve.length>0?ve:void 0,requestBody:Ot,security:Ge.length>0?Ge:void 0,responses:Ve}})}}),this.rootDoc.tags=r.tags?So(r.tags):[]}};var yt=require("node-mocks-http"),_n=e=>(0,yt.createRequest)({...e,headers:{"content-type":w.json,...e?.headers}}),Yn=e=>(0,yt.createResponse)(e),Qn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:wr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Jn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=_n(e),i=Yn({req:n,...t});i.req=t?.req||n,n.res=i;let a=Qn(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Ro=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Jn(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};var v=O(require("typescript"),1);var H=O(require("typescript"),1),ze=require("ramda"),s=H.default.factory,J=[s.createModifier(H.default.SyntaxKind.ExportKeyword)],Wn=[s.createModifier(H.default.SyntaxKind.AsyncKeyword)],Xn=[s.createModifier(H.default.SyntaxKind.PublicKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Ao=[s.createModifier(H.default.SyntaxKind.ProtectedKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],qt=s.createTemplateHead(""),we=s.createTemplateTail(""),$t=s.createTemplateMiddle(" "),Vt=e=>s.createTemplateLiteralType(qt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?we:$t))),Gt=Vt(["M","P"]),gt=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ht=(e,t)=>(0,ze.chain)(([r,o])=>[gt(s.createIdentifier(r),o,t)],(0,ze.toPairs)(e)),_t=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Po=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Co=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),W=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],H.default.NodeFlags.Const),Yt=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),xt=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,t),Io=(e,t,r)=>s.createPropertyDeclaration(Xn,e,void 0,t,r),zo=(e,t,r)=>s.createClassDeclaration(J,e,void 0,void 0,[t,...r]),wo=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),Eo=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(H.default.SyntaxKind.AnyKeyword)]),Zo=(e,t,r)=>s.createInterfaceDeclaration(J,e,void 0,t,r),es=(0,ze.chain)(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),vo=e=>es((0,ze.toPairs)(e)),Qt=(e,t,r)=>s.createArrowFunction(r?Wn:void 0,void 0,e.map(o=>gt(o)),void 0,void 0,t),Jt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,ht({acc:void 0,key:void 0}),void 0,void 0,t),r]),jo=(...e)=>`"${e.join(" ")}"`;var Lo=["get","post","put","delete","patch"];var g=O(require("typescript"),1),St=require("zod");var $=O(require("typescript"),1),{factory:bt}=$.default,Wt=(e,t)=>{$.default.addSyntheticLeadingComment(e,$.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ee=(e,t,r)=>{let o=bt.createTypeAliasDeclaration(void 0,bt.createIdentifier(t),void 0,e);return r&&Wt(o,r),o},Xt=(e,t)=>{let r=$.default.createSourceFile("print.ts","",$.default.ScriptTarget.Latest,!1,$.default.ScriptKind.TS);return $.default.createPrinter(t).printNode($.default.EmitHint.Unspecified,e,r)},ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,No=e=>ts.test(e)?bt.createIdentifier(e):bt.createStringLiteral(e);var{factory:f}=g.default,rs={[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},os=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),ns=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Ue(a)?a instanceof St.z.ZodOptional:a.isOptional(),l=f.createPropertySignature(void 0,No(i),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Wt(l,a.description),l});return f.createTypeLiteralNode(n)},ss=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),is=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),ko=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),as=e=>rs?.[e.kind],ps=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=We(e,as(o)),i={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(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},cs=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ds=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},ls=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),ms=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),us=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),fs=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),ys=({_def:e},{next:t})=>t(e.innerType),le=e=>()=>f.createKeywordTypeNode(e),gs=(e,{next:t})=>t(e.unwrap()),hs=(e,{next:t})=>t(e.unwrap()),xs=({_def:e},{next:t})=>t(e.innerType),bs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ss=()=>f.createLiteralTypeNode(f.createNull()),Ts=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,f.createLiteralTypeNode(f.createNull())),r(i,o(e)))},Os=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof St.z.ZodString?r:t instanceof St.z.ZodUnion?n:o},Rs=(e,{next:t})=>t(e.unwrap().shape.raw),As={ZodString:le(g.default.SyntaxKind.StringKeyword),ZodNumber:le(g.default.SyntaxKind.NumberKeyword),ZodBigInt:le(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:le(g.default.SyntaxKind.BooleanKeyword),ZodAny:le(g.default.SyntaxKind.AnyKeyword),[Be]:le(g.default.SyntaxKind.StringKeyword),[qe]:le(g.default.SyntaxKind.StringKeyword),ZodNull:Ss,ZodArray:ss,ZodTuple:ms,ZodRecord:us,ZodObject:ns,ZodLiteral:os,ZodIntersection:fs,ZodUnion:ko,ZodDefault:ys,ZodEnum:is,ZodNativeEnum:cs,ZodEffects:ps,ZodOptional:ds,ZodNullable:ls,ZodDiscriminatedUnion:ko,ZodBranded:gs,ZodCatch:xs,ZodPipeline:bs,ZodLazy:Ts,ZodReadonly:hs,[Y]:Os,[se]:Rs},$e=(e,{brandHandling:t,ctx:r})=>ce(e,{rules:{...t,...As},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var Tt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ee(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Je,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){pe({routing:t,onEndpoint:(R,A,I)=>{let ue={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Le=N(I,A,"input"),Ne=$e(R.getSchema("input"),{brandHandling:r,ctx:{...ue,isResponse:!1}}),L=i?N(I,A,"positive.response"):void 0,er=R.getSchema("positive"),tr=i?$e(er,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,ke=i?N(I,A,"negative.response"):void 0,rr=R.getSchema("negative"),or=i?$e(rr,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,nr=N(I,A,"response"),Uo=L&&ke?s.createUnionTypeNode([s.createTypeReferenceNode(L),s.createTypeReferenceNode(ke)]):$e(er.or(rr),{brandHandling:r,ctx:{...ue,isResponse:!0}});this.program.push(Ee(Ne,Le)),tr&&L&&this.program.push(Ee(tr,L)),or&&ke&&this.program.push(Ee(or,ke)),this.program.push(Ee(Uo,nr)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Le,positive:L,negative:ke,response:nr,isJson:R.getMimeTypes("positive").includes(w.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Yt(this.ids.pathType,this.paths)),this.program.push(Yt(this.ids.methodType,Lo)),this.program.push(xt(this.ids.methodPathType,Vt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(v.default.SyntaxKind.ExtendsKeyword,[_t(this.ids.methodPathType,v.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let l=[],c=[];for(let[{method:R,path:A},{isJson:I,tags:ue,...Le}]of this.registry){let Ne=jo(R,A);for(let L of this.interfaces)L.kind in Le&&L.props.push(Co(Ne,Le[L.kind]));o!=="types"&&(I&&l.push(s.createPropertyAssignment(Ne,s.createTrue())),c.push(s.createPropertyAssignment(Ne,s.createArrayLiteralExpression(ue.map(L=>s.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(Zo(R,p,A));if(o==="types")return;let m=s.createVariableStatement(J,W(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),y=s.createVariableStatement(J,W(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),u=xt(this.ids.providerType,s.createFunctionTypeNode(vo({M:this.ids.methodType,P:this.ids.pathType}),ht({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Gt)}),wo(this.ids.responseInterface,Gt))),x=xt(this.ids.implementationType,s.createFunctionTypeNode(void 0,ht({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(v.default.SyntaxKind.StringKeyword),params:_t(v.default.SyntaxKind.StringKeyword,v.default.SyntaxKind.AnyKeyword)}),Eo())),j=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,we)]),T=Jt(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[j,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),M=Jt(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[j]),v.default.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),C=zo(this.ids.clientClass,Po([gt(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Ao)]),[Io(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,M]),!0))]);this.program.push(m,y,u,x,C);let b=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ze=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),V=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),X=s.createVariableStatement(void 0,W(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,we)]),s.createObjectLiteralExpression([b,Ze,V])])))),me=s.createVariableStatement(void 0,W(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=s.createVariableStatement(void 0,W(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),we)])))),[Ve,Ot]=["json","text"].map(R=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Ge=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(qt,[s.createTemplateSpan(this.ids.methodParameter,$t),s.createTemplateSpan(this.ids.pathParameter,we)]),v.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ve])),D=s.createVariableStatement(J,W(this.ids.exampleImplementationConst,Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([me,ve,X,Ge,Ot]),!0),s.createTypeReferenceNode(this.ids.implementationType))),ee=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),je=s.createVariableStatement(void 0,W(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(D,je,ee)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
|
|
21
|
+
`)};var Xr=e=>{e.startupLogo!==!1&&console.log(Qr());let t=e.errorHandler||Se,r=zr(e.logger)?e.logger:new Oe(e.logger);r.debug("Running","v20.14.3 (CJS)"),_r(r);let o=Vr({rootLogger:r,config:e}),i={getChildLogger:Gr(r),errorHandler:t},a=Br(i),p=Kr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},eo=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Xr(e);return Ut({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},to=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Xr(e),p=(0,dt.default)().disable("x-powered-by").use(a);if(e.server.compression){let u=await Ce("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let l={json:[e.server.jsonParser||dt.default.json()],raw:[e.server.rawParser||dt.default.raw(),$r],upload:e.server.upload?await qr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ut({app:p,routing:t,getChildLogger:o,config:e,parsers:l}),p.use(i,n);let c=(u,x)=>u.listen(x,()=>r.info("Listening",x)),m=Jr.default.createServer(p),y=e.https&&Wr.default.createServer(e.https.options,p);return e.gracefulShutdown&&Yr({servers:[m].concat(y||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:y&&c(y,e.https?.listen)}};var To=O(require("node:assert/strict"),1),Oo=require("openapi3-ts/oas31"),yt=require("ramda");var Q=O(require("node:assert/strict"),1),q=require("openapi3-ts/oas31"),d=require("ramda"),S=require("zod");var Ie=require("zod");var lt=e=>!isNaN(e.getTime());var Be=Symbol("DateIn"),ro=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(lt)).brand(Be);var oo=require("zod");var qe=Symbol("DateOut"),no=()=>oo.z.date().refine(lt).transform(e=>e.toISOString()).brand(qe);var ce=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>ce(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),l=t&&t(e,{prev:p,...n});return l?{...p,...l}:p};var so=50,ao="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",pn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},po=/:([A-Za-z0-9_]+)/g,cn=e=>e.match(po)?.map(t=>t.slice(1))||[],co=e=>e.replace(po,t=>`{${t.slice(1)}}`),dn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),ln=({_def:{innerType:e}},{next:t})=>t(e),mn=()=>({format:"any"}),un=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),fn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},yn=({options:e},{next:t})=>({oneOf:e.map(t)}),gn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),hn=e=>{let[t,r]=e.filter(q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));(0,Q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,d.mergeDeepWith)((n,i)=>Array.isArray(n)&&Array.isArray(i)?(0,d.concat)(n,i):n===i?i:Q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,d.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=re(t.examples||[],r.examples||[],([n,i])=>(0,d.mergeDeepRight)(n,i))),o},xn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return hn(o)}catch{}return{allOf:o}},bn=(e,{next:t})=>t(e.unwrap()),Sn=(e,{next:t})=>t(e.unwrap()),Tn=(e,{next:t})=>{let r=t(e.unwrap());return(0,q.isSchemaObject)(r)&&(r.type=mo(r)),r},lo=e=>{let t=(0,d.toLower)((0,d.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},io=e=>({type:lo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),On=({value:e})=>({type:lo(e),const:e}),Rn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=mt(e,r)),i.length&&(a.required=i),a},An=()=>({type:"null"}),Pn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:ao}}),Cn=({},e)=>((0,Q.default)(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:ao}}),In=({},e)=>Q.default.fail(new z({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"}),wn=()=>({type:"integer",format:"bigint"}),En=e=>e.every(t=>t instanceof S.z.ZodLiteral),Zn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=mt(S.z.object((0,d.fromPairs)((0,d.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:mt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&En(e.options)){let o=(0,d.map)(i=>`${i.value}`,e.options),n=(0,d.fromPairs)((0,d.xprod)(o,[t]));return{type:"object",properties:mt(S.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},vn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},jn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Ln=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),j=u?u.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,T={type:"string"},M={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:l,emoji:c};for(let C in M)if(M[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),j&&(T.pattern=j.source),T},Nn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(y=>y.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(y=>y.kind==="max"),l=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=l:m.exclusiveMaximum=l,m},mt=({shape:e},t)=>(0,d.map)(t,e),kn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return pn?.[t]},mo=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Mn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,q.isSchemaObject)(o)){let i=Xe(e,kn(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.z.any())}if(!t&&n.type==="preprocess"&&(0,q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Un=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Hn=(e,{next:t})=>t(e.unwrap()),Dn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},Fn=(e,{next:t})=>t(e.unwrap().shape.raw),uo=e=>e.length?(0,d.fromPairs)((0,d.zip)((0,d.range)(1,e.length+1).map(t=>`example${t}`),(0,d.map)((0,d.objOf)("value"),e))):void 0,fo=(e,t,r=[])=>(0,d.pipe)(K,(0,d.map)((0,d.when)(o=>(0,d.type)(o)==="Object",(0,d.omit)(r))),uo)({schema:e,variant:t?"parsed":"original",validate:!0}),Kn=(e,t)=>(0,d.pipe)(K,(0,d.filter)((0,d.has)(t)),(0,d.pluck)(t),uo)({schema:e,variant:"original",validate:!0}),de=e=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?de(e.unwrap()):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(t=>de(t)).reduce((t,r)=>t.merge(r.partial()),S.z.object({})):e instanceof S.z.ZodEffects?de(e._def.schema):e instanceof S.z.ZodPipeline?de(e._def.in):de(e._def.left).merge(de(e._def.right)),yo=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=de(r),y=cn(e),u=o.includes("query"),x=o.includes("params"),j=o.includes("headers"),T=b=>x&&y.includes(b),M=b=>j&&Ct(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":M(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:Ze})=>{let V=ce(m[b],{rules:{...l,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),X=p==="components"?a(N(c,b),V):V;return{name:b,in:Ze,required:!m[b].isOptional(),description:V.description||c,schema:X,examples:Kn(r,b)}})},Dt={ZodString:Ln,ZodNumber:Nn,ZodBigInt:wn,ZodBoolean:zn,ZodNull:An,ZodArray:vn,ZodTuple:jn,ZodRecord:Zn,ZodObject:Rn,ZodLiteral:On,ZodIntersection:xn,ZodUnion:yn,ZodAny:mn,ZodDefault:dn,ZodEnum:io,ZodNativeEnum:io,ZodEffects:Mn,ZodOptional:bn,ZodNullable:Tn,ZodDiscriminatedUnion:gn,ZodBranded:Hn,ZodDate:In,ZodCatch:ln,ZodPipeline:Un,ZodLazy:Dn,ZodReadonly:Sn,[Y]:fn,[De]:un,[qe]:Cn,[Be]:Pn,[se]:Fn},Ft=(e,{isResponse:t,prev:r})=>{if((0,q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof S.z.ZodLazy,i=r.type!==void 0,a=t&&Ue(e),p=!n&&i&&!a&&e.isNullable(),l=n?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=mo(r)),l.length&&(c.examples=l.slice()),c},Kt=(e,t)=>Q.default.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Ht=(e,t)=>{if((0,q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,d.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,d.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ht(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ht(o,t))),r},go=e=>(0,q.isReferenceObject)(e)?e:(0,d.omit)(["examples"],e),ho=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:l,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${zt(n)} response ${c?m:""}`.trim()})=>{let x=go(ce(r,{rules:{...y,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),j={schema:l==="components"?p(N(u),x):x,examples:fo(r,!0)};return{description:u,content:(0,d.fromPairs)((0,d.xprod)(o,[j]))}},Bn=()=>({type:"http",scheme:"basic"}),qn=({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},Vn=({name:e})=>({type:"apiKey",in:"header",name:e}),Gn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),_n=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Yn=({flows:e={}})=>({type:"oauth2",flows:(0,d.map)(t=>({...t,scopes:t.scopes||{}}),(0,d.reject)(d.isNil,e))}),xo=(e,t)=>{let r={basic:Bn,bearer:qn,input:$n,header:Vn,cookie:Gn,openid:_n,oauth2:Yn};return nt(e,o=>r[o.type](o,t))},ut=e=>"or"in e?e.or.map(t=>"and"in t?(0,d.mergeAll)((0,d.map)(({name:r,scopes:o})=>(0,d.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?ut(Zt(e)):ut({or:[e]}),bo=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,paramNames:c,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=go(Ht(ce(r,{rules:{...l,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),u={schema:p==="components"?a(N(m),y):y,examples:fo(r,!1,c)};return{description:m,content:(0,d.fromPairs)((0,d.xprod)(o,[u]))}},So=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}),Bt=e=>e.length<=so?e:e.slice(0,so-1)+"\u2026";var ft=class extends Oo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=(0,yt.keys)(ae);makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||N(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&To.default.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:l=!0,composition:c="inline",serializer:m=We}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});pe({routing:t,onEndpoint:(u,x,j)=>{let T=j,M={path:x,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),Ze=C?Bt(C):l&&b?Bt(b):void 0,V=u.getTags(),X=r.inputSources?.[T]||At[T],me=this.ensureUniqOperationId(x,T,u.getOperationId(T)),ve=yo({...M,inputSources:X,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:me})}),Ve={};for(let D of this.responseVariants){let ee=u.getResponses(D);for(let{mimeTypes:je,schema:R,statusCodes:A}of ee)for(let I of A)Ve[I]=ho({...M,variant:D,schema:R,mimeTypes:je,statusCode:I,hasMultipleStatusCodes:ee.length>1||A.length>1,description:a?.[`${D}Response`]?.call(null,{method:T,path:x,operationId:me,statusCode:I})})}let Rt=X.includes("body")?bo({...M,paramNames:(0,yt.pluck)("name",ve),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:me})}):void 0,Ge=ut(nt(xo(u.getSecurity(),X),D=>{let ee=this.ensureUniqSecuritySchemaName(D),je=["oauth2","openIdConnect"].includes(D.type)?u.getScopes().slice():[];return this.addSecurityScheme(ee,D),{name:ee,scopes:je}}));this.addPath(co(x),{[T]:{operationId:me,summary:Ze,description:b,tags:V.length>0?V:void 0,parameters:ve.length>0?ve:void 0,requestBody:Rt,security:Ge.length>0?Ge:void 0,responses:Ve}})}}),this.rootDoc.tags=r.tags?So(r.tags):[]}};var gt=require("node-mocks-http"),Qn=e=>(0,gt.createRequest)({...e,headers:{"content-type":w.json,...e?.headers}}),Jn=e=>(0,gt.createResponse)(e),Wn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:wr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Ro=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Qn(e),i=Jn({req:n,...t});i.req=t?.req||n,n.res=i;let a=Wn(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Ao=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Ro(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Po=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:i,configMock:a}=Ro(r),p=Je(o,a.inputSources),l=await e.execute({request:o,response:n,logger:i,input:p,options:t});return{requestMock:o,responseMock:n,loggerMock:i,output:l}};var v=O(require("typescript"),1);var H=O(require("typescript"),1),ze=require("ramda"),s=H.default.factory,J=[s.createModifier(H.default.SyntaxKind.ExportKeyword)],Xn=[s.createModifier(H.default.SyntaxKind.AsyncKeyword)],es=[s.createModifier(H.default.SyntaxKind.PublicKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Co=[s.createModifier(H.default.SyntaxKind.ProtectedKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],qt=s.createTemplateHead(""),we=s.createTemplateTail(""),$t=s.createTemplateMiddle(" "),Vt=e=>s.createTemplateLiteralType(qt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?we:$t))),Gt=Vt(["M","P"]),ht=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),xt=(e,t)=>(0,ze.chain)(([r,o])=>[ht(s.createIdentifier(r),o,t)],(0,ze.toPairs)(e)),_t=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Io=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),zo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),W=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],H.default.NodeFlags.Const),Yt=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),bt=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,t),wo=(e,t,r)=>s.createPropertyDeclaration(es,e,void 0,t,r),Eo=(e,t,r)=>s.createClassDeclaration(J,e,void 0,void 0,[t,...r]),Zo=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),vo=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(H.default.SyntaxKind.AnyKeyword)]),jo=(e,t,r)=>s.createInterfaceDeclaration(J,e,void 0,t,r),ts=(0,ze.chain)(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),Lo=e=>ts((0,ze.toPairs)(e)),Qt=(e,t,r)=>s.createArrowFunction(r?Xn:void 0,void 0,e.map(o=>ht(o)),void 0,void 0,t),Jt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,xt({acc:void 0,key:void 0}),void 0,void 0,t),r]),No=(...e)=>`"${e.join(" ")}"`;var ko=["get","post","put","delete","patch"];var g=O(require("typescript"),1),Tt=require("zod");var $=O(require("typescript"),1),{factory:St}=$.default,Wt=(e,t)=>{$.default.addSyntheticLeadingComment(e,$.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ee=(e,t,r)=>{let o=St.createTypeAliasDeclaration(void 0,St.createIdentifier(t),void 0,e);return r&&Wt(o,r),o},Xt=(e,t)=>{let r=$.default.createSourceFile("print.ts","",$.default.ScriptTarget.Latest,!1,$.default.ScriptKind.TS);return $.default.createPrinter(t).printNode($.default.EmitHint.Unspecified,e,r)},rs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Mo=e=>rs.test(e)?St.createIdentifier(e):St.createStringLiteral(e);var{factory:f}=g.default,os={[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},ns=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),ss=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Ue(a)?a instanceof Tt.z.ZodOptional:a.isOptional(),l=f.createPropertySignature(void 0,Mo(i),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Wt(l,a.description),l});return f.createTypeLiteralNode(n)},is=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),as=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Uo=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),ps=e=>os?.[e.kind],cs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Xe(e,ps(o)),i={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(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},ds=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ls=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},ms=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),us=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),fs=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),ys=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),gs=({_def:e},{next:t})=>t(e.innerType),le=e=>()=>f.createKeywordTypeNode(e),hs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t})=>t(e.unwrap()),bs=({_def:e},{next:t})=>t(e.innerType),Ss=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ts=()=>f.createLiteralTypeNode(f.createNull()),Os=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,f.createLiteralTypeNode(f.createNull())),r(i,o(e)))},Rs=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof Tt.z.ZodString?r:t instanceof Tt.z.ZodUnion?n:o},As=(e,{next:t})=>t(e.unwrap().shape.raw),Ps={ZodString:le(g.default.SyntaxKind.StringKeyword),ZodNumber:le(g.default.SyntaxKind.NumberKeyword),ZodBigInt:le(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:le(g.default.SyntaxKind.BooleanKeyword),ZodAny:le(g.default.SyntaxKind.AnyKeyword),[Be]:le(g.default.SyntaxKind.StringKeyword),[qe]:le(g.default.SyntaxKind.StringKeyword),ZodNull:Ts,ZodArray:is,ZodTuple:us,ZodRecord:fs,ZodObject:ss,ZodLiteral:ns,ZodIntersection:ys,ZodUnion:Uo,ZodDefault:gs,ZodEnum:as,ZodNativeEnum:ds,ZodEffects:cs,ZodOptional:ls,ZodNullable:ms,ZodDiscriminatedUnion:Uo,ZodBranded:hs,ZodCatch:bs,ZodPipeline:Ss,ZodLazy:Os,ZodReadonly:xs,[Y]:Rs,[se]:As},$e=(e,{brandHandling:t,ctx:r})=>ce(e,{rules:{...t,...Ps},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var Ot=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ee(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=We,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){pe({routing:t,onEndpoint:(R,A,I)=>{let ue={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Le=N(I,A,"input"),Ne=$e(R.getSchema("input"),{brandHandling:r,ctx:{...ue,isResponse:!1}}),L=i?N(I,A,"positive.response"):void 0,er=R.getSchema("positive"),tr=i?$e(er,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,ke=i?N(I,A,"negative.response"):void 0,rr=R.getSchema("negative"),or=i?$e(rr,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,nr=N(I,A,"response"),Do=L&&ke?s.createUnionTypeNode([s.createTypeReferenceNode(L),s.createTypeReferenceNode(ke)]):$e(er.or(rr),{brandHandling:r,ctx:{...ue,isResponse:!0}});this.program.push(Ee(Ne,Le)),tr&&L&&this.program.push(Ee(tr,L)),or&&ke&&this.program.push(Ee(or,ke)),this.program.push(Ee(Do,nr)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Le,positive:L,negative:ke,response:nr,isJson:R.getMimeTypes("positive").includes(w.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Yt(this.ids.pathType,this.paths)),this.program.push(Yt(this.ids.methodType,ko)),this.program.push(bt(this.ids.methodPathType,Vt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(v.default.SyntaxKind.ExtendsKeyword,[_t(this.ids.methodPathType,v.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let l=[],c=[];for(let[{method:R,path:A},{isJson:I,tags:ue,...Le}]of this.registry){let Ne=No(R,A);for(let L of this.interfaces)L.kind in Le&&L.props.push(zo(Ne,Le[L.kind]));o!=="types"&&(I&&l.push(s.createPropertyAssignment(Ne,s.createTrue())),c.push(s.createPropertyAssignment(Ne,s.createArrayLiteralExpression(ue.map(L=>s.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(jo(R,p,A));if(o==="types")return;let m=s.createVariableStatement(J,W(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),y=s.createVariableStatement(J,W(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),u=bt(this.ids.providerType,s.createFunctionTypeNode(Lo({M:this.ids.methodType,P:this.ids.pathType}),xt({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Gt)}),Zo(this.ids.responseInterface,Gt))),x=bt(this.ids.implementationType,s.createFunctionTypeNode(void 0,xt({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(v.default.SyntaxKind.StringKeyword),params:_t(v.default.SyntaxKind.StringKeyword,v.default.SyntaxKind.AnyKeyword)}),vo())),j=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,we)]),T=Jt(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[j,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),M=Jt(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[j]),v.default.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),C=Eo(this.ids.clientClass,Io([ht(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Co)]),[wo(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,M]),!0))]);this.program.push(m,y,u,x,C);let b=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ze=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),V=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),X=s.createVariableStatement(void 0,W(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,we)]),s.createObjectLiteralExpression([b,Ze,V])])))),me=s.createVariableStatement(void 0,W(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=s.createVariableStatement(void 0,W(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),we)])))),[Ve,Rt]=["json","text"].map(R=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Ge=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(qt,[s.createTemplateSpan(this.ids.methodParameter,$t),s.createTemplateSpan(this.ids.pathParameter,we)]),v.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ve])),D=s.createVariableStatement(J,W(this.ids.exampleImplementationConst,Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([me,ve,X,Ge,Rt]),!0),s.createTypeReferenceNode(this.ids.implementationType))),ee=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),je=s.createVariableStatement(void 0,W(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(D,je,ee)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
|
|
22
22
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&v.default.addSyntheticLeadingComment(v.default.addSyntheticLeadingComment(s.createEmptyStatement(),v.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),v.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
23
23
|
${r}`);return this.program.concat(o||[]).map((n,i)=>Xt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
24
24
|
|
|
25
|
-
`)}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 n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var
|
|
25
|
+
`)}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 n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var Ho={dateIn:ro,dateOut:no,file:rt,upload:yr,raw:ur};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint,testMiddleware});
|
package/dist/index.d.cts
CHANGED
|
@@ -896,6 +896,32 @@ declare const testEndpoint: <LOG extends FlatObject, REQ extends RequestOptions>
|
|
|
896
896
|
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
897
897
|
};
|
|
898
898
|
}>;
|
|
899
|
+
declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOptions>({ middleware, options, ...rest }: TestingProps<REQ, LOG> & {
|
|
900
|
+
/** @desc The middleware to test */
|
|
901
|
+
middleware: AbstractMiddleware;
|
|
902
|
+
/** @desc The aggregated output from previously executed middlewares */
|
|
903
|
+
options?: FlatObject;
|
|
904
|
+
}) => Promise<{
|
|
905
|
+
requestMock: Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>> & {
|
|
906
|
+
[key: string]: any;
|
|
907
|
+
_setParameter: (key: string, value?: string) => void;
|
|
908
|
+
_setSessionVariable: (variable: string, value?: string) => void;
|
|
909
|
+
_setCookiesVariable: (variable: string, value?: string) => void;
|
|
910
|
+
_setSignedCookiesVariable: (variable: string, value?: string) => void;
|
|
911
|
+
_setHeadersCookiesVariable: (variable: string, value: string) => void;
|
|
912
|
+
_setFilesCookiesVariable: (variable: string, value?: string) => void;
|
|
913
|
+
_setMethod: (method?: string) => void;
|
|
914
|
+
_setURL: (value?: string) => void;
|
|
915
|
+
_setOriginalUrl: (value?: string) => void;
|
|
916
|
+
_setBody: (body?: node_mocks_http.Body) => void;
|
|
917
|
+
_addBody: (key: string, value?: any) => void;
|
|
918
|
+
} & REQ;
|
|
919
|
+
responseMock: node_mocks_http.MockResponse<Response<any, Record<string, any>>>;
|
|
920
|
+
loggerMock: AbstractLogger & LOG & {
|
|
921
|
+
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
922
|
+
};
|
|
923
|
+
output: FlatObject;
|
|
924
|
+
}>;
|
|
899
925
|
|
|
900
926
|
interface ZTSContext extends FlatObject {
|
|
901
927
|
isResponse: boolean;
|
|
@@ -1016,4 +1042,4 @@ declare class Integration {
|
|
|
1016
1042
|
printFormatted({ printerOptions, format: userDefined, }?: FormattedPrintingOptions): Promise<string>;
|
|
1017
1043
|
}
|
|
1018
1044
|
|
|
1019
|
-
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
|
|
1045
|
+
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint, testMiddleware };
|
package/dist/index.d.ts
CHANGED
|
@@ -896,6 +896,32 @@ declare const testEndpoint: <LOG extends FlatObject, REQ extends RequestOptions>
|
|
|
896
896
|
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
897
897
|
};
|
|
898
898
|
}>;
|
|
899
|
+
declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOptions>({ middleware, options, ...rest }: TestingProps<REQ, LOG> & {
|
|
900
|
+
/** @desc The middleware to test */
|
|
901
|
+
middleware: AbstractMiddleware;
|
|
902
|
+
/** @desc The aggregated output from previously executed middlewares */
|
|
903
|
+
options?: FlatObject;
|
|
904
|
+
}) => Promise<{
|
|
905
|
+
requestMock: Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>> & {
|
|
906
|
+
[key: string]: any;
|
|
907
|
+
_setParameter: (key: string, value?: string) => void;
|
|
908
|
+
_setSessionVariable: (variable: string, value?: string) => void;
|
|
909
|
+
_setCookiesVariable: (variable: string, value?: string) => void;
|
|
910
|
+
_setSignedCookiesVariable: (variable: string, value?: string) => void;
|
|
911
|
+
_setHeadersCookiesVariable: (variable: string, value: string) => void;
|
|
912
|
+
_setFilesCookiesVariable: (variable: string, value?: string) => void;
|
|
913
|
+
_setMethod: (method?: string) => void;
|
|
914
|
+
_setURL: (value?: string) => void;
|
|
915
|
+
_setOriginalUrl: (value?: string) => void;
|
|
916
|
+
_setBody: (body?: node_mocks_http.Body) => void;
|
|
917
|
+
_addBody: (key: string, value?: any) => void;
|
|
918
|
+
} & REQ;
|
|
919
|
+
responseMock: node_mocks_http.MockResponse<Response<any, Record<string, any>>>;
|
|
920
|
+
loggerMock: AbstractLogger & LOG & {
|
|
921
|
+
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
922
|
+
};
|
|
923
|
+
output: FlatObject;
|
|
924
|
+
}>;
|
|
899
925
|
|
|
900
926
|
interface ZTSContext extends FlatObject {
|
|
901
927
|
isResponse: boolean;
|
|
@@ -1016,4 +1042,4 @@ declare class Integration {
|
|
|
1016
1042
|
printFormatted({ printerOptions, format: userDefined, }?: FormattedPrintingOptions): Promise<string>;
|
|
1017
1043
|
}
|
|
1018
1044
|
|
|
1019
|
-
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
|
|
1045
|
+
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint, testMiddleware };
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{clone as Yt,fromPairs as
|
|
2
|
-
Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},He=class extends Error{name="IOSchemaError"},G=class extends He{constructor(r){super(U(r));this.originalError=r}name="OutputValidationError"},L=class extends He{constructor(r){super(U(r));this.originalError=r}name="InputValidationError"},M=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},Oe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var P={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var
|
|
1
|
+
import{clone as Yt,fromPairs as Co,map as Io,pipe as zo,toPairs as wo,pair as Eo}from"ramda";import{z as pe}from"zod";import{isHttpError as go}from"http-errors";import{createHash as ho}from"node:crypto";import{pickBy as xo,xprod as bo}from"ramda";import{z as So}from"zod";var ie=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
|
|
2
|
+
Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},He=class extends Error{name="IOSchemaError"},G=class extends He{constructor(r){super(U(r));this.originalError=r}name="OutputValidationError"},L=class extends He{constructor(r){super(U(r));this.originalError=r}name="InputValidationError"},M=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},Oe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var P={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var To=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(P.upload);return"files"in e&&r},lt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Oo=["body","query","params"],mt=e=>e.method.toLowerCase(),ut=e=>e.startsWith("x-"),Ro=e=>xo((t,r)=>ut(r),e),De=(e,t={})=>{let r=mt(e);return r==="options"?{}:(t[r]||lt[r]||Oo).filter(o=>o==="files"?To(e):!0).map(o=>o==="headers"?Ro(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},ae=e=>e instanceof Error?e:new Error(String(e)),U=e=>e instanceof So.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Fe=e=>go(e)?e.statusCode:e instanceof L?400:500,ft=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},_=(e,t,r)=>e.length&&t.length?
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};import{chain as Do}from"ramda";var J=e=>Y(e)&&"or"in e,de=e=>Y(e)&&"and"in e,ht=e=>({and:Do(t=>de(t)?t.and:[t],e)}),Ge=(e,t)=>de(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),xt=e=>e.and.reduce((t,r)=>({or:_(t.or,J(r)?r.or:[r],ht)}),{or:[]}),ce=(e,t)=>de(e)?J(t)?ce(xt(e),t):ht([e,t]):J(e)?de(t)?ce(t,e):J(t)?{or:_(e.or,t.or,ht)}:ce(e,{and:[t]}):de(t)||J(t)?ce(t,e):{and:[e,t]};import{z as or}from"zod";var bt=class{},F=class extends bt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof or.ZodError?new L(o):o}}},le=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:or.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,d)?.catch(d)})})}};var Pe=class{},_e=class extends Pe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:f}){super(),this.#a=n,this.#p=i,this.#r=d,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:l,short:f},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=tr(r)?"upload":rr(r)?"raw":"json",this.#i={input:Object.freeze([P[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:m})=>m))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?ce(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof nr.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof le))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof nr.ZodError?new L(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(d){Ve({logger:n,response:o,error:new M(ae(d).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=lt(t),p={},d=null,c=null;if(n.cors){let f=this.#m(i);typeof n.cors=="function"&&(f=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=ut(t,n.inputSources);try{if(await this.#f({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.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=ae(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};var sr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>_t(i,n),o)};import{z as v}from"zod";var W={positive:200,negative:400};import Fo from"node:assert/strict";import{z as Ko}from"zod";var Ye=(e,t)=>typeof e=="function"?Ye(e(...t.arguments),t):e instanceof Ko.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&Fo(e.length,new M(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var St=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Ce=class extends St{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Ye(this.#e,{variant:"positive",arguments:[t],statusCodes:[W.positive],mimeTypes:[P.json]})}getNegativeResponse(){return Ye(this.#t,{variant:"negative",arguments:[],statusCodes:[W.negative],mimeTypes:[P.json]})}},Ie=new Ce({positive:e=>{let t=H({schema:e}),r=v.object({status:v.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:v.object({status:v.literal("error"),error:v.object({message:v.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(W.positive).json({status:"success",data:r});return}let a=De(e);ft({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:U(e)}})}}),Tt=new Ce({positive:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.ZodArray?e.shape.items:v.array(v.any());return t.reduce((o,n)=>Y(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:v.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=De(r);ft({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(W.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var ze=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 instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({input:Bo.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new _e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:h,methods:l,getOperationId:f,description:n,shortDescription:i,inputSchema:sr(d,t)})}},qo=new ze(Ie),$o=new ze(Tt);import{Ansis as Go,blue as _o,cyanBright as Yo,green as Qo,hex as Jo,red as Wo}from"ansis";import{inspect as Xo}from"node:util";import{performance as mr}from"node:perf_hooks";var Je={debug:10,info:20,warn:30,error:40},ar=e=>Y(e)&&Object.keys(Je).some(t=>t in e),pr=e=>e in Je,cr=(e,t)=>Je[e]<Je[t],dr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),Qe=dr(),ir=dr(2),Vo=e=>e<1e-6?["picosecond",e/1e-9,Qe]:e<.001?["nanosecond",e/1e-6,Qe]:e<1?["microsecond",e/.001,Qe]:e<1e3?["millisecond",e,Qe]:e<6e4?["second",e/1e3,ir]:["minute",e/6e4,ir],lr=e=>{let[t,r,o]=Vo(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var we=class e{constructor(t){this.config=t;let{color:r=new Go().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:_o,info:Qo,warn:Jo("#FFA500"),error:Wo};prettyPrint(t){let{depth:r=2}=this.config;return Xo(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||cr(t,this.config.level))return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?Yo(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=mr.now();return()=>{let o=mr.now()-r,{message:n,severity:i="debug",formatter:a=lr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as en,tail as tn,toPairs as rn}from"ramda";var Ee=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(rn(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=en(this.pairs)?.[1],this.siblingMethods=Object.freeze(tn(this.pairs).map(([r])=>r))}};import on from"express";var Ze=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,on.static(...this.params))}};import Rt from"express";import ln from"node:http";import mn from"node:https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Oe(e)};import ur from"node:assert/strict";var X=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){ur.doesNotMatch(a,/\//,new ie(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Pe){let c=p.getMethods().slice();n&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Ze)r&&p.apply(d,r);else if(p instanceof Ee){for(let[c,l]of p.pairs)ur(l.getMethods().includes(c),new ie(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else X({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var Ot=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>X({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,d)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,l)=>i.execute({request:c,response:l,logger:t(c),config:r,siblingMethods:d}))},onStatic:(i,a)=>{e.use(i,a)}});import Sr,{isHttpError as sn}from"http-errors";import{setInterval as nn}from"node:timers/promises";var fr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,hr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),xr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var br=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(fr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let l of["connection","secureConnection"])c.on(l,p);let d=async()=>{for(let c of e)c.on("request",hr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(gr(c)||yr(c))&&a(c);for await(let c of nn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(xr))};return{sockets:n,shutdown:()=>o??=d()}};var Tr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:sn(r)?r:Sr(400,ae(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Or=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=Sr(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){Ve({response:o,logger:i,error:new M(ae(a).message,n)})}},an=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},pn=e=>({log:e.debug.bind(e)}),Rr=async({getChildLogger:e,config:t})=>{let r=await me("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=e(p);try{await n?.({request:p,logger:l})}catch(f){return c(f)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:pn(l)})(p,d,c)}),o&&a.push(an(o)),a},Ar=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Pr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:i}),n()},Cr=e=>t=>t.res?.locals[g]?.logger||e,Ir=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
6
|
-
`).slice(1))),zr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=br(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as
|
|
4
|
+
`,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},_=(e,t,r)=>e.length&&t.length?bo(e,t).map(r):e.concat(t),Re=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,yt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),w=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(yt).join(""),Ke=e=>ho("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Be=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Y=e=>typeof e=="object"&&e!==null;import{clone as Ao,mergeDeepRight as Po}from"ramda";var g=Symbol.for("express-zod-api"),qe=e=>{let t=e.describe(e.description);return t._def[g]=Ao(t._def[g])||{examples:[]},t},_t=(e,t)=>{if(!(g in e._def))return t;let r=qe(t);return r._def[g].examples=_(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Po({...o},{...n}):n),r};var Zo=function(e){let t=qe(this);return t._def[g].examples.push(e),t},vo=function(e){let t=qe(this);return t._def[g].defaultLabel=e,t},jo=function(e){return new pe.ZodBranded({typeName:pe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...Yt(this._def[g]),brand:e}})},Lo=function(e){let t=typeof e=="function"?e:zo(wo,Io(([n,i])=>Eo(e[String(n)]||n,i)),Co),r=t(Yt(this.shape)),o=pe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(pe.ZodType.prototype,{example:{get(){return Zo.bind(this)}},brand:{set(){},get(){return jo.bind(this)}}}),Object.defineProperty(pe.ZodDefault.prototype,"label",{get(){return vo.bind(this)}}),Object.defineProperty(pe.ZodObject.prototype,"remap",{get(){return Lo.bind(this)}}));function No(e){return e}import{z as qo}from"zod";import{z as nr}from"zod";import{z as Mo}from"zod";import{z as $e}from"zod";var D=Symbol("File"),Qt=$e.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),ko={buffer:()=>Qt.brand(D),string:()=>$e.string().brand(D),binary:()=>Qt.or($e.string()).brand(D),base64:()=>$e.string().base64().brand(D)};function Ve(e){return ko[e||"string"]()}var Q=Symbol("Raw"),Jt=(e={})=>Mo.object({raw:Ve("buffer")}).extend(e).brand(Q);import{z as Uo}from"zod";var Ae=Symbol("Upload"),Wt=()=>Uo.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ae);var Xt=(e,{next:t})=>e.options.some(t),Ho=({_def:e},{next:t})=>[e.left,e.right].some(t),er=(e,{next:t})=>t(e.unwrap()),Do={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Xt,ZodDiscriminatedUnion:Xt,ZodIntersection:Ho,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:er,ZodNullable:er,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=Do,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},tr=e=>gt(e,{condition:t=>t._def[g]?.brand===Ae}),rr=e=>gt(e,{condition:t=>t._def[g]?.brand===Q,maxDepth:3});var Ge=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
5
|
+
Original error: ${e.originalError.message}.`:""))};import{chain as Fo}from"ramda";var J=e=>Y(e)&&"or"in e,de=e=>Y(e)&&"and"in e,ht=e=>({and:Fo(t=>de(t)?t.and:[t],e)}),_e=(e,t)=>de(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),xt=e=>e.and.reduce((t,r)=>({or:_(t.or,J(r)?r.or:[r],ht)}),{or:[]}),ce=(e,t)=>de(e)?J(t)?ce(xt(e),t):ht([e,t]):J(e)?de(t)?ce(t,e):J(t)?{or:_(e.or,t.or,ht)}:ce(e,{and:[t]}):de(t)||J(t)?ce(t,e):{and:[e,t]};import{z as or}from"zod";var bt=class{},F=class extends bt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof or.ZodError?new L(o):o}}},le=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:or.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,d)?.catch(d)})})}};var Pe=class{},Ye=class extends Pe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:f}){super(),this.#a=n,this.#p=i,this.#r=d,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:l,short:f},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=tr(r)?"upload":rr(r)?"raw":"json",this.#i={input:Object.freeze([P[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:m})=>m))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?ce(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof nr.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof le))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof nr.ZodError?new L(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(d){Ge({logger:n,response:o,error:new M(ae(d).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=mt(t),p={},d=null,c=null;if(n.cors){let f=this.#m(i);typeof n.cors=="function"&&(f=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=De(t,n.inputSources);try{if(await this.#f({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.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=ae(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};var sr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>_t(i,n),o)};import{z as v}from"zod";var W={positive:200,negative:400};import Ko from"node:assert/strict";import{z as Bo}from"zod";var Qe=(e,t)=>typeof e=="function"?Qe(e(...t.arguments),t):e instanceof Bo.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&Ko(e.length,new M(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var St=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Ce=class extends St{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Qe(this.#e,{variant:"positive",arguments:[t],statusCodes:[W.positive],mimeTypes:[P.json]})}getNegativeResponse(){return Qe(this.#t,{variant:"negative",arguments:[],statusCodes:[W.negative],mimeTypes:[P.json]})}},Ie=new Ce({positive:e=>{let t=H({schema:e}),r=v.object({status:v.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:v.object({status:v.literal("error"),error:v.object({message:v.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(W.positive).json({status:"success",data:r});return}let a=Fe(e);ft({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:U(e)}})}}),Tt=new Ce({positive:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.ZodArray?e.shape.items:v.array(v.any());return t.reduce((o,n)=>Y(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:v.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Fe(r);ft({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(W.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var ze=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 instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({input:qo.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Ye({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:h,methods:l,getOperationId:f,description:n,shortDescription:i,inputSchema:sr(d,t)})}},$o=new ze(Ie),Vo=new ze(Tt);import{Ansis as _o,blue as Yo,cyanBright as Qo,green as Jo,hex as Wo,red as Xo}from"ansis";import{inspect as en}from"node:util";import{performance as mr}from"node:perf_hooks";var We={debug:10,info:20,warn:30,error:40},ar=e=>Y(e)&&Object.keys(We).some(t=>t in e),pr=e=>e in We,cr=(e,t)=>We[e]<We[t],dr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),Je=dr(),ir=dr(2),Go=e=>e<1e-6?["picosecond",e/1e-9,Je]:e<.001?["nanosecond",e/1e-6,Je]:e<1?["microsecond",e/.001,Je]:e<1e3?["millisecond",e,Je]:e<6e4?["second",e/1e3,ir]:["minute",e/6e4,ir],lr=e=>{let[t,r,o]=Go(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var we=class e{constructor(t){this.config=t;let{color:r=new _o().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:Yo,info:Jo,warn:Wo("#FFA500"),error:Xo};prettyPrint(t){let{depth:r=2}=this.config;return en(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||cr(t,this.config.level))return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?Qo(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=mr.now();return()=>{let o=mr.now()-r,{message:n,severity:i="debug",formatter:a=lr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as tn,tail as rn,toPairs as on}from"ramda";var Ee=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(on(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=tn(this.pairs)?.[1],this.siblingMethods=Object.freeze(rn(this.pairs).map(([r])=>r))}};import nn from"express";var Ze=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,nn.static(...this.params))}};import Rt from"express";import mn from"node:http";import un from"node:https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Oe(e)};import ur from"node:assert/strict";var X=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){ur.doesNotMatch(a,/\//,new ie(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Pe){let c=p.getMethods().slice();n&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Ze)r&&p.apply(d,r);else if(p instanceof Ee){for(let[c,l]of p.pairs)ur(l.getMethods().includes(c),new ie(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else X({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var Ot=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>X({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,d)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,l)=>i.execute({request:c,response:l,logger:t(c),config:r,siblingMethods:d}))},onStatic:(i,a)=>{e.use(i,a)}});import Sr,{isHttpError as an}from"http-errors";import{setInterval as sn}from"node:timers/promises";var fr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,hr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),xr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var br=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(fr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let l of["connection","secureConnection"])c.on(l,p);let d=async()=>{for(let c of e)c.on("request",hr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(gr(c)||yr(c))&&a(c);for await(let c of sn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(xr))};return{sockets:n,shutdown:()=>o??=d()}};var Tr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:an(r)?r:Sr(400,ae(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Or=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=Sr(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){Ge({response:o,logger:i,error:new M(ae(a).message,n)})}},pn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},cn=e=>({log:e.debug.bind(e)}),Rr=async({getChildLogger:e,config:t})=>{let r=await me("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=e(p);try{await n?.({request:p,logger:l})}catch(f){return c(f)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:cn(l)})(p,d,c)}),o&&a.push(pn(o)),a},Ar=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Pr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:i}),n()},Cr=e=>t=>t.res?.locals[g]?.logger||e,Ir=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
6
|
+
`).slice(1))),zr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=br(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as dn,hex as wr,italic as Xe,whiteBright as ln}from"ansis";var Er=()=>{let e=Xe("Proudly supports transgender community.".padStart(109)),t=Xe("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=Xe("Thank you for choosing Express Zod API for your project.".padStart(132)),o=Xe("for Zoey".padEnd(20)),n=wr("#F5A9B8"),i=wr("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(ln,5,7).fill(n,7,9).fill(i,9,12).fill(dn,12,13);return`
|
|
7
7
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
8
8
|
888 d88P 888 d88888 888 Y88b 888
|
|
9
9
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -18,8 +18,8 @@ ${o}888${t}
|
|
|
18
18
|
${r}
|
|
19
19
|
`.split(`
|
|
20
20
|
`).map((d,c)=>a[c]?a[c](d):d).join(`
|
|
21
|
-
`)};var Zr=e=>{e.startupLogo!==!1&&console.log(Er());let t=e.errorHandler||Ie,r=ar(e.logger)?e.logger:new we(e.logger);r.debug("Running","v20.14.2 (ESM)"),Ir(r);let o=Pr({rootLogger:r,config:e}),i={getChildLogger:Cr(r),errorHandler:t},a=Or(i),p=Tr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},un=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Zr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},fn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Zr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Ar],upload:e.server.upload?await Rr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=ln.createServer(p),f=e.https&&mn.createServer(e.https.options,p);return e.gracefulShutdown&&zr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import xs from"node:assert/strict";import{OpenApiBuilder as bs}from"openapi3-ts/oas31";import{keys as Ss,pluck as Ts}from"ramda";import re from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as tt}from"openapi3-ts/oas31";import{concat as gn,type as kr,filter as hn,fromPairs as Ne,has as xn,isNil as bn,map as ue,mergeAll as Sn,mergeDeepRight as Tn,mergeDeepWith as On,objOf as Mr,omit as rt,pipe as Ur,pluck as Rn,range as An,reject as Pn,toLower as Cn,union as In,when as zn,xprod as ot,zip as wn}from"ramda";import{z as S}from"zod";import{z as ve}from"zod";var Xe=e=>!isNaN(e.getTime());var je=Symbol("DateIn"),vr=()=>ve.union([ve.string().date(),ve.string().datetime(),ve.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ve.date().refine(Xe)).brand(je);import{z as yn}from"zod";var Le=Symbol("DateOut"),jr=()=>yn.date().refine(Xe).transform(e=>e.toISOString()).brand(Le);var ee=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>ee(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var Lr=50,Hr="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:[]},Dr=/:([A-Za-z0-9_]+)/g,Zn=e=>e.match(Dr)?.map(t=>t.slice(1))||[],Fr=e=>e.replace(Dr,t=>`{${t.slice(1)}}`),vn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),jn=({_def:{innerType:e}},{next:t})=>t(e),Ln=()=>({format:"any"}),Nn=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),kn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Mn=({options:e},{next:t})=>({oneOf:e.map(t)}),Un=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Hn=e=>{let[t,r]=e.filter(tt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));re(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=On((n,i)=>Array.isArray(n)&&Array.isArray(i)?gn(n,i):n===i?i:re.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=In(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>Tn(n,i))),o},Dn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Hn(o)}catch{}return{allOf:o}},Fn=(e,{next:t})=>t(e.unwrap()),Kn=(e,{next:t})=>t(e.unwrap()),Bn=(e,{next:t})=>{let r=t(e.unwrap());return tt(r)&&(r.type=Br(r)),r},Kr=e=>{let t=Cn(kr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Nr=e=>({type:Kr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),qn=({value:e})=>({type:Kr(e),const:e}),$n=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=et(e,r)),i.length&&(a.required=i),a},Vn=()=>({type:"null"}),Gn=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Hr}}),_n=({},e)=>(re(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Hr}}),Yn=({},e)=>re.fail(new z({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})),Qn=()=>({type:"boolean"}),Jn=()=>({type:"integer",format:"bigint"}),Wn=e=>e.every(t=>t instanceof S.ZodLiteral),Xn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=et(S.object(Ne(ot(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:et(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Wn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=Ne(ot(o,[t]));return{type:"object",properties:et(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},es=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},ts=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),rs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.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,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},os=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},et=({shape:e},t)=>ue(t,e),ns=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return En?.[t]},Br=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},ss=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&tt(o)){let i=Ke(e,ns(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&tt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},is=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),as=(e,{next:t})=>t(e.unwrap()),ps=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},cs=(e,{next:t})=>t(e.unwrap().shape.raw),qr=e=>e.length?Ne(wn(An(1,e.length+1).map(t=>`example${t}`),ue(Mr("value"),e))):void 0,$r=(e,t,r=[])=>Ur(H,ue(zn(o=>kr(o)==="Object",rt(r))),qr)({schema:e,variant:t?"parsed":"original",validate:!0}),ds=(e,t)=>Ur(H,hn(xn(t)),Rn(t),qr)({schema:e,variant:"original",validate:!0}),te=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?te(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>te(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?te(e._def.schema):e instanceof S.ZodPipeline?te(e._def.in):te(e._def.left).merge(te(e._def.right)),Vr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=te(r),f=Zn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&mt(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=ee(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ds(r,x)}})},Ct={ZodString:rs,ZodNumber:os,ZodBigInt:Jn,ZodBoolean:Qn,ZodNull:Vn,ZodArray:es,ZodTuple:ts,ZodRecord:Xn,ZodObject:$n,ZodLiteral:qn,ZodIntersection:Dn,ZodUnion:Mn,ZodAny:Ln,ZodDefault:vn,ZodEnum:Nr,ZodNativeEnum:Nr,ZodEffects:ss,ZodOptional:Fn,ZodNullable:Bn,ZodDiscriminatedUnion:Un,ZodBranded:as,ZodDate:Yn,ZodCatch:jn,ZodPipeline:is,ZodLazy:ps,ZodReadonly:Kn,[D]:kn,[Ae]:Nn,[Le]:_n,[je]:Gn,[Q]:cs},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Br(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>re.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=rt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>rt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},Gr=e=>Pt(e)?e:rt(["examples"],e),_r=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=Gr(ee(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:$r(r,!0)};return{description:m,content:Ne(ot(o,[C]))}},ls=()=>({type:"http",scheme:"basic"}),ms=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},us=({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},fs=({name:e})=>({type:"apiKey",in:"header",name:e}),ys=({name:e})=>({type:"apiKey",in:"cookie",name:e}),gs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),hs=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Pn(bn,e))}),Yr=(e,t)=>{let r={basic:ls,bearer:ms,input:us,header:fs,cookie:ys,openid:gs,oauth2:hs};return Ge(e,o=>r[o.type](o,t))},nt=e=>"or"in e?e.or.map(t=>"and"in t?Sn(ue(({name:r,scopes:o})=>Mr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?nt(xt(e)):nt({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=Gr(At(ee(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:$r(r,!1,c)};return{description:l,content:Ne(ot(o,[m]))}},Jr=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}),wt=e=>e.length<=Lr?e:e.slice(0,Lr-1)+"\u2026";var Et=class extends bs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=Ss(W);makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&xs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=Fe}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});X({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||dt[b],ne=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=Vr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:ne})}),Me={};for(let j of this.responseVariants){let V=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of V)for(let A of O)Me[A]=_r({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:V.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:ne,statusCode:A})})}let ct=$.includes("body")?Qr({...Z,paramNames:Ts("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:ne})}):void 0,Ue=nt(Ge(Yr(m.getSecurity(),$),j=>{let V=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(V,j),{name:V,scopes:xe}}));this.addPath(Fr(h),{[b]:{operationId:ne,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:ct,security:Ue.length>0?Ue:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Jr(r.tags):[]}};import{createRequest as Os,createResponse as Rs}from"node-mocks-http";var As=e=>Os({...e,headers:{"content-type":P.json,...e?.headers}}),Ps=e=>Rs(e),Cs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:pr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Is=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),i=Ps({req:n,...t});i.req=t?.req||n,n.res=i;let a=Cs(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Is(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};import E from"typescript";import N from"typescript";import{chain as Wr,toPairs as Xr}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],ws=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Es=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],eo=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),st=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),it=(e,t)=>Wr(([r,o])=>[st(s.createIdentifier(r),o,t)],Xr(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),to=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),ro=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),at=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),oo=(e,t,r)=>s.createPropertyDeclaration(Es,e,void 0,t,r),no=(e,t,r)=>s.createClassDeclaration(K,e,void 0,void 0,[t,...r]),so=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),io=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(N.SyntaxKind.AnyKeyword)]),ao=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),Zs=Wr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),po=e=>Zs(Xr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?ws:void 0,void 0,e.map(o=>st(o)),void 0,void 0,t),Ut=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,it({acc:void 0,key:void 0}),void 0,void 0,t),r]),co=(...e)=>`"${e.join(" ")}"`;var lo=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:pt}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=pt.createTypeAliasDeclaration(void 0,pt.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},vs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mo=e=>vs.test(e)?pt.createIdentifier(e):pt.createStringLiteral(e);var{factory:u}=y,js={[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},Ls=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Ns=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,mo(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},ks=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ms=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),uo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Us=e=>js?.[e.kind],Hs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ke(e,Us(o)),i={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(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Ds=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Ks=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Bs=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),qs=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),$s=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Vs=({_def:e},{next:t})=>t(e.innerType),oe=e=>()=>u.createKeywordTypeNode(e),Gs=(e,{next:t})=>t(e.unwrap()),_s=(e,{next:t})=>t(e.unwrap()),Ys=({_def:e},{next:t})=>t(e.innerType),Qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Js=()=>u.createLiteralTypeNode(u.createNull()),Ws=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},Xs=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},ei=(e,{next:t})=>t(e.unwrap().shape.raw),ti={ZodString:oe(y.SyntaxKind.StringKeyword),ZodNumber:oe(y.SyntaxKind.NumberKeyword),ZodBigInt:oe(y.SyntaxKind.BigIntKeyword),ZodBoolean:oe(y.SyntaxKind.BooleanKeyword),ZodAny:oe(y.SyntaxKind.AnyKeyword),[je]:oe(y.SyntaxKind.StringKeyword),[Le]:oe(y.SyntaxKind.StringKeyword),ZodNull:Js,ZodArray:ks,ZodTuple:Bs,ZodRecord:qs,ZodObject:Ns,ZodLiteral:Ls,ZodIntersection:$s,ZodUnion:uo,ZodDefault:Vs,ZodEnum:Ms,ZodNativeEnum:Ds,ZodEffects:Hs,ZodOptional:Fs,ZodNullable:Ks,ZodDiscriminatedUnion:uo,ZodBranded:Gs,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:Ws,ZodReadonly:_s,[D]:Xs,[Q]:ei},ke=(e,{brandHandling:t,ctx:r})=>ee(e,{rules:{...t,...ti},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Fe,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){X({routing:t,onEndpoint:(T,O,A)=>{let se={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=ke(T.getSchema("input"),{brandHandling:r,ctx:{...se,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?ke(Bt,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Vt=i?ke($t,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Gt=w(A,O,"response"),fo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):ke(Bt.or($t),{brandHandling:r,ctx:{...se,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Vt&&Te&&this.program.push(ye(Vt,Te)),this.program.push(ye(fo,Gt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Gt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,lo)),this.program.push(at(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:se,...be}]of this.registry){let Se=co(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(ro(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(se.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(ao(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=at(this.ids.providerType,s.createFunctionTypeNode(po({M:this.ids.methodType,P:this.ids.pathType}),it({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),so(this.ids.responseInterface,Lt))),h=at(this.ids.implementationType,s.createFunctionTypeNode(void 0,it({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),io())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),R=no(this.ids.clientClass,to([st(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),eo)]),[oo(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),$=s.createVariableStatement(void 0,B(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),ne=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),fe)])))),[Me,ct]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),Ue=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Me])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([ne,he,$,Ue,ct]),!0),s.createTypeReferenceNode(this.ids.implementationType))),V=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,V)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
|
|
21
|
+
`)};var Zr=e=>{e.startupLogo!==!1&&console.log(Er());let t=e.errorHandler||Ie,r=ar(e.logger)?e.logger:new we(e.logger);r.debug("Running","v20.14.3 (ESM)"),Ir(r);let o=Pr({rootLogger:r,config:e}),i={getChildLogger:Cr(r),errorHandler:t},a=Or(i),p=Tr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},fn=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Zr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},yn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Zr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Ar],upload:e.server.upload?await Rr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=mn.createServer(p),f=e.https&&un.createServer(e.https.options,p);return e.gracefulShutdown&&zr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import bs from"node:assert/strict";import{OpenApiBuilder as Ss}from"openapi3-ts/oas31";import{keys as Ts,pluck as Os}from"ramda";import re from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as rt}from"openapi3-ts/oas31";import{concat as hn,type as kr,filter as xn,fromPairs as Ne,has as bn,isNil as Sn,map as ue,mergeAll as Tn,mergeDeepRight as On,mergeDeepWith as Rn,objOf as Mr,omit as ot,pipe as Ur,pluck as An,range as Pn,reject as Cn,toLower as In,union as zn,when as wn,xprod as nt,zip as En}from"ramda";import{z as S}from"zod";import{z as ve}from"zod";var et=e=>!isNaN(e.getTime());var je=Symbol("DateIn"),vr=()=>ve.union([ve.string().date(),ve.string().datetime(),ve.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ve.date().refine(et)).brand(je);import{z as gn}from"zod";var Le=Symbol("DateOut"),jr=()=>gn.date().refine(et).transform(e=>e.toISOString()).brand(Le);var ee=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>ee(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var Lr=50,Hr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Dr=/:([A-Za-z0-9_]+)/g,vn=e=>e.match(Dr)?.map(t=>t.slice(1))||[],Fr=e=>e.replace(Dr,t=>`{${t.slice(1)}}`),jn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Ln=({_def:{innerType:e}},{next:t})=>t(e),Nn=()=>({format:"any"}),kn=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Mn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Un=({options:e},{next:t})=>({oneOf:e.map(t)}),Hn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Dn=e=>{let[t,r]=e.filter(rt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));re(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Rn((n,i)=>Array.isArray(n)&&Array.isArray(i)?hn(n,i):n===i?i:re.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=zn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>On(n,i))),o},Fn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Dn(o)}catch{}return{allOf:o}},Kn=(e,{next:t})=>t(e.unwrap()),Bn=(e,{next:t})=>t(e.unwrap()),qn=(e,{next:t})=>{let r=t(e.unwrap());return rt(r)&&(r.type=Br(r)),r},Kr=e=>{let t=In(kr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Nr=e=>({type:Kr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),$n=({value:e})=>({type:Kr(e),const:e}),Vn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=tt(e,r)),i.length&&(a.required=i),a},Gn=()=>({type:"null"}),_n=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Hr}}),Yn=({},e)=>(re(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Hr}}),Qn=({},e)=>re.fail(new z({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})),Jn=()=>({type:"boolean"}),Wn=()=>({type:"integer",format:"bigint"}),Xn=e=>e.every(t=>t instanceof S.ZodLiteral),es=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=tt(S.object(Ne(nt(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:tt(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Xn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=Ne(nt(o,[t]));return{type:"object",properties:tt(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ts=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},rs=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),os=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.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,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},ns=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},tt=({shape:e},t)=>ue(t,e),ss=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Zn?.[t]},Br=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},is=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&rt(o)){let i=Be(e,ss(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&rt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},as=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ps=(e,{next:t})=>t(e.unwrap()),cs=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},ds=(e,{next:t})=>t(e.unwrap().shape.raw),qr=e=>e.length?Ne(En(Pn(1,e.length+1).map(t=>`example${t}`),ue(Mr("value"),e))):void 0,$r=(e,t,r=[])=>Ur(H,ue(wn(o=>kr(o)==="Object",ot(r))),qr)({schema:e,variant:t?"parsed":"original",validate:!0}),ls=(e,t)=>Ur(H,xn(bn(t)),An(t),qr)({schema:e,variant:"original",validate:!0}),te=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?te(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>te(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?te(e._def.schema):e instanceof S.ZodPipeline?te(e._def.in):te(e._def.left).merge(te(e._def.right)),Vr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=te(r),f=vn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&ut(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=ee(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ls(r,x)}})},Ct={ZodString:os,ZodNumber:ns,ZodBigInt:Wn,ZodBoolean:Jn,ZodNull:Gn,ZodArray:ts,ZodTuple:rs,ZodRecord:es,ZodObject:Vn,ZodLiteral:$n,ZodIntersection:Fn,ZodUnion:Un,ZodAny:Nn,ZodDefault:jn,ZodEnum:Nr,ZodNativeEnum:Nr,ZodEffects:is,ZodOptional:Kn,ZodNullable:qn,ZodDiscriminatedUnion:Hn,ZodBranded:ps,ZodDate:Qn,ZodCatch:Ln,ZodPipeline:as,ZodLazy:cs,ZodReadonly:Bn,[D]:Mn,[Ae]:kn,[Le]:Yn,[je]:_n,[Q]:ds},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Br(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>re.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=ot(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>ot(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},Gr=e=>Pt(e)?e:ot(["examples"],e),_r=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=Gr(ee(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:$r(r,!0)};return{description:m,content:Ne(nt(o,[C]))}},ms=()=>({type:"http",scheme:"basic"}),us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},fs=({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},ys=({name:e})=>({type:"apiKey",in:"header",name:e}),gs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),hs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),xs=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Cn(Sn,e))}),Yr=(e,t)=>{let r={basic:ms,bearer:us,input:fs,header:ys,cookie:gs,openid:hs,oauth2:xs};return _e(e,o=>r[o.type](o,t))},st=e=>"or"in e?e.or.map(t=>"and"in t?Tn(ue(({name:r,scopes:o})=>Mr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?st(xt(e)):st({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=Gr(At(ee(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:$r(r,!1,c)};return{description:l,content:Ne(nt(o,[m]))}},Jr=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}),wt=e=>e.length<=Lr?e:e.slice(0,Lr-1)+"\u2026";var Et=class extends Ss{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=Ts(W);makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&bs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=Ke}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});X({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||lt[b],ne=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=Vr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:ne})}),Me={};for(let j of this.responseVariants){let V=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of V)for(let A of O)Me[A]=_r({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:V.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:ne,statusCode:A})})}let dt=$.includes("body")?Qr({...Z,paramNames:Os("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:ne})}):void 0,Ue=st(_e(Yr(m.getSecurity(),$),j=>{let V=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(V,j),{name:V,scopes:xe}}));this.addPath(Fr(h),{[b]:{operationId:ne,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:dt,security:Ue.length>0?Ue:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Jr(r.tags):[]}};import{createRequest as Rs,createResponse as As}from"node-mocks-http";var Ps=e=>Rs({...e,headers:{"content-type":P.json,...e?.headers}}),Cs=e=>As(e),Is=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:pr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Wr=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ps(e),i=Cs({req:n,...t});i.req=t?.req||n,n.res=i;let a=Is(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Wr(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},ws=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:i,configMock:a}=Wr(r),p=De(o,a.inputSources),d=await e.execute({request:o,response:n,logger:i,input:p,options:t});return{requestMock:o,responseMock:n,loggerMock:i,output:d}};import E from"typescript";import N from"typescript";import{chain as Xr,toPairs as eo}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],Es=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Zs=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],to=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),it=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),at=(e,t)=>Xr(([r,o])=>[it(s.createIdentifier(r),o,t)],eo(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),ro=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),oo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),pt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),no=(e,t,r)=>s.createPropertyDeclaration(Zs,e,void 0,t,r),so=(e,t,r)=>s.createClassDeclaration(K,e,void 0,void 0,[t,...r]),io=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),ao=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(N.SyntaxKind.AnyKeyword)]),po=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),vs=Xr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),co=e=>vs(eo(e)),Mt=(e,t,r)=>s.createArrowFunction(r?Es:void 0,void 0,e.map(o=>it(o)),void 0,void 0,t),Ut=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,at({acc:void 0,key:void 0}),void 0,void 0,t),r]),lo=(...e)=>`"${e.join(" ")}"`;var mo=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:ct}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=ct.createTypeAliasDeclaration(void 0,ct.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},js=/^[A-Za-z_$][A-Za-z0-9_$]*$/,uo=e=>js.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:u}=y,Ls={[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},Ns=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),ks=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,uo(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},Ms=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Us=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),fo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Hs=e=>Ls?.[e.kind],Ds=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Be(e,Hs(o)),i={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(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Fs=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Ks=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Bs=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),qs=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),$s=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Vs=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Gs=({_def:e},{next:t})=>t(e.innerType),oe=e=>()=>u.createKeywordTypeNode(e),_s=(e,{next:t})=>t(e.unwrap()),Ys=(e,{next:t})=>t(e.unwrap()),Qs=({_def:e},{next:t})=>t(e.innerType),Js=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ws=()=>u.createLiteralTypeNode(u.createNull()),Xs=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},ei=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},ti=(e,{next:t})=>t(e.unwrap().shape.raw),ri={ZodString:oe(y.SyntaxKind.StringKeyword),ZodNumber:oe(y.SyntaxKind.NumberKeyword),ZodBigInt:oe(y.SyntaxKind.BigIntKeyword),ZodBoolean:oe(y.SyntaxKind.BooleanKeyword),ZodAny:oe(y.SyntaxKind.AnyKeyword),[je]:oe(y.SyntaxKind.StringKeyword),[Le]:oe(y.SyntaxKind.StringKeyword),ZodNull:Ws,ZodArray:Ms,ZodTuple:qs,ZodRecord:$s,ZodObject:ks,ZodLiteral:Ns,ZodIntersection:Vs,ZodUnion:fo,ZodDefault:Gs,ZodEnum:Us,ZodNativeEnum:Fs,ZodEffects:Ds,ZodOptional:Ks,ZodNullable:Bs,ZodDiscriminatedUnion:fo,ZodBranded:_s,ZodCatch:Qs,ZodPipeline:Js,ZodLazy:Xs,ZodReadonly:Ys,[D]:ei,[Q]:ti},ke=(e,{brandHandling:t,ctx:r})=>ee(e,{rules:{...t,...ri},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Ke,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){X({routing:t,onEndpoint:(T,O,A)=>{let se={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=ke(T.getSchema("input"),{brandHandling:r,ctx:{...se,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?ke(Bt,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Vt=i?ke($t,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Gt=w(A,O,"response"),yo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):ke(Bt.or($t),{brandHandling:r,ctx:{...se,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Vt&&Te&&this.program.push(ye(Vt,Te)),this.program.push(ye(yo,Gt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Gt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,mo)),this.program.push(pt(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:se,...be}]of this.registry){let Se=lo(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(oo(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(se.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(po(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=pt(this.ids.providerType,s.createFunctionTypeNode(co({M:this.ids.methodType,P:this.ids.pathType}),at({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),io(this.ids.responseInterface,Lt))),h=pt(this.ids.implementationType,s.createFunctionTypeNode(void 0,at({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),ao())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),R=so(this.ids.clientClass,ro([it(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),to)]),[no(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),$=s.createVariableStatement(void 0,B(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),ne=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),fe)])))),[Me,dt]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),Ue=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Me])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([ne,he,$,Ue,dt]),!0),s.createTypeReferenceNode(this.ids.implementationType))),V=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,V)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
|
|
22
22
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&E.addSyntheticLeadingComment(E.addSyntheticLeadingComment(s.createEmptyStatement(),E.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.SyntaxKind.MultiLineCommentTrivia,`
|
|
23
23
|
${r}`);return this.program.concat(o||[]).map((n,i)=>Dt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
24
24
|
|
|
25
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await me("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var
|
|
25
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await me("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var oi={dateIn:vr,dateOut:jr,file:Ve,upload:Wt,raw:Jt};export{we as BuiltinLogger,Ee as DependsOnMethod,Et as Documentation,z as DocumentationError,ze as EndpointsFactory,L as InputValidationError,Kt as Integration,F as Middleware,Oe as MissingPeerError,G as OutputValidationError,Ce as ResultHandler,ie as RoutingError,Ze as ServeStatic,Vo as arrayEndpointsFactory,Tt as arrayResultHandler,fn as attachRouting,No as createConfig,yn as createServer,$o as defaultEndpointsFactory,Ie as defaultResultHandler,oi as ez,H as getExamples,U as getMessageFromError,Fe as getStatusCodeFromError,zs as testEndpoint,ws as testMiddleware};
|
package/package.json
CHANGED