express-zod-api 22.8.0 → 22.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.md +31 -4
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +26 -11
- package/dist/index.d.ts +26 -11
- package/dist/index.js +8 -8
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,34 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 22
|
|
4
4
|
|
|
5
|
+
### v22.9.0
|
|
6
|
+
|
|
7
|
+
- Featuring Deprecations:
|
|
8
|
+
- You can deprecate all usage of an `Endpoint` using `EndpointsFactory::build({ deprecated: true })`;
|
|
9
|
+
- You can deprecate a route using the assigned `Endpoint::deprecated()` or `DependsOnMethod::deprecated()`;
|
|
10
|
+
- You can deprecate a schema using `ZodType::deprecated()`;
|
|
11
|
+
- All `.deprecated()` methods are immutable — they create a new copy of the subject;
|
|
12
|
+
- Deprecated schemas and endpoints are reflected in the generated `Documentation` and `Integration`;
|
|
13
|
+
- The feature suggested by [@mlms13](https://github.com/mlms13).
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Routing, DependsOnMethod } from "express-zod-api";
|
|
17
|
+
import { z } from "zod";
|
|
18
|
+
|
|
19
|
+
const someEndpoint = factory.build({
|
|
20
|
+
deprecated: true, // deprecates all routes the endpoint assigned to
|
|
21
|
+
input: z.object({
|
|
22
|
+
prop: z.string().deprecated(), // deprecates the property or a path parameter
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const routing: Routing = {
|
|
27
|
+
v1: oldEndpoint.deprecated(), // deprecates the /v1 path
|
|
28
|
+
v2: new DependsOnMethod({ get: oldEndpoint }).deprecated(), // deprecates the /v2 path
|
|
29
|
+
v3: someEndpoint, // the path is assigned with initially deprecated endpoint (also deprecated)
|
|
30
|
+
};
|
|
31
|
+
```
|
|
32
|
+
|
|
5
33
|
### v22.8.0
|
|
6
34
|
|
|
7
35
|
- Feature: warning about the endpoint input scheme ignoring the parameters of the route to which it is assigned:
|
package/README.md
CHANGED
|
@@ -57,7 +57,8 @@ Start your API server with I/O schema validation and custom middlewares in minut
|
|
|
57
57
|
2. [Generating a Frontend Client](#generating-a-frontend-client)
|
|
58
58
|
3. [Creating a documentation](#creating-a-documentation)
|
|
59
59
|
4. [Tagging the endpoints](#tagging-the-endpoints)
|
|
60
|
-
5. [
|
|
60
|
+
5. [Deprecated schemas and routes](#deprecated-schemas-and-routes)
|
|
61
|
+
6. [Customizable brands handling](#customizable-brands-handling)
|
|
61
62
|
8. [Caveats](#caveats)
|
|
62
63
|
1. [Coercive schema of Zod](#coercive-schema-of-zod)
|
|
63
64
|
2. [Excessive properties in endpoint output](#excessive-properties-in-endpoint-output)
|
|
@@ -86,6 +87,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
|
|
|
86
87
|
|
|
87
88
|
These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
|
|
88
89
|
|
|
90
|
+
[<img src="https://github.com/mlms13.png" alt="@mlms13" width="50px" />](https://github.com/mlms13)
|
|
89
91
|
[<img src="https://github.com/bobgubko.png" alt="@bobgubko" width="50px" />](https://github.com/bobgubko)
|
|
90
92
|
[<img src="https://github.com/LucWag.png" alt="@LucWag" width="50px" />](https://github.com/LucWag)
|
|
91
93
|
[<img src="https://github.com/HenriJ.png" alt="@HenriJ" width="50px" />](https://github.com/HenriJ)
|
|
@@ -689,9 +691,9 @@ done(); // error: expensive operation '555.55ms'
|
|
|
689
691
|
## Enabling compression
|
|
690
692
|
|
|
691
693
|
According to [Express.js best practices guide](http://expressjs.com/en/advanced/best-practice-performance.html)
|
|
692
|
-
it might be a good idea to enable GZIP compression
|
|
694
|
+
it might be a good idea to enable GZIP and Brotli compression for your API responses.
|
|
693
695
|
|
|
694
|
-
Install
|
|
696
|
+
Install `compression` (version 1.8 supports Brotli) and `@types/compression`, and enable or configure compression:
|
|
695
697
|
|
|
696
698
|
```typescript
|
|
697
699
|
import { createConfig } from "express-zod-api";
|
|
@@ -703,7 +705,7 @@ const config = createConfig({
|
|
|
703
705
|
```
|
|
704
706
|
|
|
705
707
|
In order to receive a compressed response the client should include the following header in the request:
|
|
706
|
-
`Accept-Encoding: gzip, deflate`. Only responses with compressible content types are subject to compression.
|
|
708
|
+
`Accept-Encoding: br, gzip, deflate`. Only responses with compressible content types are subject to compression.
|
|
707
709
|
|
|
708
710
|
# Advanced features
|
|
709
711
|
|
|
@@ -1236,6 +1238,7 @@ framework, [Zod Sockets](https://github.com/RobinTail/zod-sockets), which has si
|
|
|
1236
1238
|
Express Zod API acts as a plugin for Zod, extending its functionality once you import anything from `express-zod-api`:
|
|
1237
1239
|
|
|
1238
1240
|
- Adds `.example()` method to all Zod schemas for storing examples and reflecting them in the generated documentation;
|
|
1241
|
+
- Adds `.deprecated()` method to all schemas for marking properties and request parameters as deprecated;
|
|
1239
1242
|
- Adds `.label()` method to `ZodDefault` for replacing the default value in documentation with a label;
|
|
1240
1243
|
- Adds `.remap()` method to `ZodObject` for renaming object properties in a suitable way for making documentation;
|
|
1241
1244
|
- Alters the `.brand()` method on all Zod schemas by making the assigned brand available in runtime.
|
|
@@ -1340,6 +1343,30 @@ new Documentation({
|
|
|
1340
1343
|
});
|
|
1341
1344
|
```
|
|
1342
1345
|
|
|
1346
|
+
## Deprecated schemas and routes
|
|
1347
|
+
|
|
1348
|
+
As your API evolves, you may need to mark some parameters or routes as deprecated before deleting them. For this
|
|
1349
|
+
purpose, the `.deprecated()` method is available on each schema, `Endpoint` and `DependsOnMethod`, it's immutable.
|
|
1350
|
+
You can also deprecate all routes the `Endpoint` assigned to by setting `EndpointsFactory::build({ deprecated: true })`.
|
|
1351
|
+
|
|
1352
|
+
```ts
|
|
1353
|
+
import { Routing, DependsOnMethod } from "express-zod-api";
|
|
1354
|
+
import { z } from "zod";
|
|
1355
|
+
|
|
1356
|
+
const someEndpoint = factory.build({
|
|
1357
|
+
deprecated: true, // deprecates all routes the endpoint assigned to
|
|
1358
|
+
input: z.object({
|
|
1359
|
+
prop: z.string().deprecated(), // deprecates the property or a path parameter
|
|
1360
|
+
}),
|
|
1361
|
+
});
|
|
1362
|
+
|
|
1363
|
+
const routing: Routing = {
|
|
1364
|
+
v1: oldEndpoint.deprecated(), // deprecates the /v1 path
|
|
1365
|
+
v2: new DependsOnMethod({ get: oldEndpoint }).deprecated(), // deprecates the /v2 path
|
|
1366
|
+
v3: someEndpoint, // the path is assigned with initially deprecated endpoint (also deprecated)
|
|
1367
|
+
};
|
|
1368
|
+
```
|
|
1369
|
+
|
|
1343
1370
|
## Customizable brands handling
|
|
1344
1371
|
|
|
1345
1372
|
You can customize handling rules for your schemas in Documentation and Integration. Use the `.brand()` method on your
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:(0,ht.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var _t=require("zod");var Gt=class{},V=class extends Gt{#e;#t;#r;constructor({input:t=_t.z.object({}),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 _t.z.ZodError?new Y(o):o}}},Ce=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var je=class{nest(t){return Object.assign(t,{"":this})}};var Qe=class extends je{},bt=class extends Qe{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:l,shortDescription:g}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:l,short:g},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Nr(r)?"upload":Lr(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof Jt.z.ZodError?new se(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof Ce))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof Jt.z.ZodError?new Y(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){xt({...r,error:new ie(pe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=qt(t),a={},c=null,d=null,p=pt(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(l){d=pe(l)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var me=require("zod");var Hr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Pr(s,n),o)},_=e=>e instanceof me.z.ZodObject?e:e instanceof me.z.ZodBranded?_(e.unwrap()):e instanceof me.z.ZodUnion||e instanceof me.z.ZodDiscriminatedUnion?e.options.map(t=>_(t)).reduce((t,r)=>t.merge(r.partial()),me.z.object({})):e instanceof me.z.ZodEffects?_(e._def.schema):e instanceof me.z.ZodPipeline?_(e._def.in):_(e._def.left).merge(_(e._def.right));var G=require("zod");var Ne={positive:200,negative:400},Le=Object.keys(Ne);var Wt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},le=class extends Wt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Vt(this.#e,{variant:"positive",args:[t],statusCodes:[Ne.positive],mimeTypes:[I.json]})}getNegativeResponse(){return Vt(this.#t,{variant:"negative",args:[],statusCodes:[Ne.negative],mimeTypes:[I.json]})}},Me=new le({positive:e=>{let t=re({schema:e,pullProps:!0}),r=G.z.object({status:G.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:G.z.object({status:G.z.literal("error"),error:G.z.object({message:G.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Re(e);return Ye(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Pe(a)}})}n.status(Ne.positive).json({status:"success",data:r})}}),St=new le({positive:e=>{let t=re({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof G.z.ZodArray?e.shape.items:G.z.array(G.z.any());return t.reduce((o,n)=>be(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:G.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Re(r);return Ye(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Pe(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Ne.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ue=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ce(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=Yt.z.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:l,resultHandler:g}=this,b=typeof p=="string"?[p]:p,f=typeof a=="function"?a:()=>a,R=typeof c=="string"?[c]:c||[],O=typeof d=="string"?[d]:d||[];return new bt({handler:r,middlewares:l,outputSchema:o,resultHandler:g,scopes:R,tags:O,methods:b,getOperationId:f,description:n,shortDescription:s,inputSchema:Hr(l,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Yt.z.object({}),handler:async o=>(await t(o),{})})}},Kr=new ue(Me),Dr=new ue(St);var _r=C(require("ansis"),1),Gr=require("node:util"),Xt=require("node:perf_hooks");var X=require("ansis"),Fr=require("ramda");var Qt={debug:X.blue,info:X.green,warn:(0,X.hex)("#FFA500"),error:X.red,ctx:X.cyanBright},Tt={debug:10,info:20,warn:30,error:40},qr=e=>be(e)&&Object.keys(Tt).some(t=>t in e),Br=e=>e in Tt,$r=(e,t)=>Tt[e]<Tt[t],bn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ue=(0,Fr.memoizeWith)((e,t)=>`${e}${t}`,bn),Vr=e=>e<1e-6?Ue("nanosecond",3).format(e/1e-6):e<.001?Ue("nanosecond").format(e/1e-6):e<1?Ue("microsecond").format(e/.001):e<1e3?Ue("millisecond").format(e):e<6e4?Ue("second",2).format(e/1e3):Ue("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=_r.default.isSupported(),level:r=ve()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return(0,Gr.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||$r(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Qt.ctx(s):s),d.push(c?`${Qt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.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})}get ctx(){return this.config.ctx}profile(t){let r=Xt.performance.now();return()=>{let o=Xt.performance.now()-r,{message:n,severity:s="debug",formatter:a=Vr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var De=require("ramda");var Ke=class extends je{entries;constructor(t){super();let r=[],o=(0,De.keys)(t);for(let n of o){let s=t[n];s&&r.push([n,s,(0,De.reject)((0,De.equals)(n),o)])}this.entries=Object.freeze(r)}};var Jr=C(require("express"),1),Fe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Jr.default.static(...this.params))}};var Rt=C(require("express"),1),go=C(require("node:http"),1),ho=C(require("node:https"),1);var qe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>C(require(e))))[t]}catch{}throw new Ie(e)};var Qr=C(require("http-errors"),1);var Wr=require("ramda");var Ot=class{constructor(t){this.logger=t;this.#e=(0,Wr.tryCatch)(Mr)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Le){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(I.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=at(t);if(s.length===0)return;let a=n?.shape||_(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Yr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new he(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Be=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Yr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Qe){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Fe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new he(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Yr(s,n))}};var Sn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,Qr.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},er=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new Ot(t()),a=new Map;if(Be({routing:o,onEndpoint:(d,p,l,g)=>{ve()||(s?.checkJsonCompat(d,{path:p,method:l}),s?.checkPathParams(p,d,{method:l}));let b=n?.[d.getRequestType()]||[],f=async(R,O)=>{let L=t(R);if(r.cors){let E={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...g||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:R,endpoint:d,logger:L,defaultHeaders:E}):E;for(let U in v)O.set(U,v[U])}return d.execute({request:R,response:O,logger:L,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...b,f),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...b,f)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,Sn(p))};var Xe=C(require("http-errors"),1);var no=require("node:timers/promises");var Xr=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",eo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",to=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ro=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),oo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var so=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Xr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let d=async()=>{for(let p of e)p.on("request",ro);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(to(p)||eo(p))&&a(p);for await(let p of(0,no.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(oo))};return{sockets:n,shutdown:()=>o??=d()}};var io=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,Xe.isHttpError)(r)?r:(0,Xe.default)(400,pe(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),ao=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Xe.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){xt({response:o,logger:s,error:new ie(pe(a),n)})}},Tn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},On=e=>({log:e.debug.bind(e)}),po=async({getLogger:e,config:t})=>{let r=await qe("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(g){return p(g)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:On(l)})(c,d,p)}),o&&a.push(Tn(o)),a},co=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},mo=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[x]={logger:s}),n()},lo=e=>t=>t?.res?.locals[x]?.logger||e,uo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),yo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=
|
|
1
|
+
"use strict";var on=Object.create;var at=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty;var cn=(e,t)=>{for(var r in t)at(e,r,{get:t[r],enumerable:!0})},Pr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of sn(t))!pn.call(e,n)&&n!==r&&at(e,n,{get:()=>t[n],enumerable:!(o=nn(t,n))||o.enumerable});return e};var k=(e,t,r)=>(r=e!=null?on(an(e)):{},Pr(t||!e||!e.__esModule?at(r,"default",{value:e,enumerable:!0}):r,e)),dn=e=>Pr(at({},"__esModule",{value:!0}),e);var Ys={};cn(Ys,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>wt,DocumentationError:()=>q,EndpointsFactory:()=>ye,EventStreamFactory:()=>Mt,InputValidationError:()=>Y,Integration:()=>Lt,Middleware:()=>_,MissingPeerError:()=>Ze,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>xe,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Fr,arrayResultHandler:()=>St,attachRouting:()=>So,createConfig:()=>wr,createServer:()=>To,defaultEndpointsFactory:()=>Kr,defaultResultHandler:()=>Ue,ensureHttpError:()=>Pe,ez:()=>rn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>Bo,testMiddleware:()=>$o});module.exports=dn(Ys);var U=require("ramda"),Te=require("zod");var oe=require("ramda"),Kt=require("zod");var I={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var xe=class extends Error{name="RoutingError"},q=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},pt=class extends Error{name="IOSchemaError"},ae=class extends pt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},Y=class extends pt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(ce(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ze=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ft=/:([A-Za-z0-9_]+)/g,ct=e=>e.match(Ft)?.map(t=>t.slice(1))||[],mn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(I.upload);return"files"in e&&r},qt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},ln=["body","query","params"],Bt=e=>e.method.toLowerCase(),dt=(e,t={})=>{let r=Bt(e);return r==="options"?{}:(t[r]||qt[r]||ln).filter(o=>o==="files"?mn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof Kt.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ae?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,un=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return be(t,(n[g]?.examples||[]).map((0,oe.objOf)(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[g]?.examples||[];if(!n.length&&o&&e instanceof Kt.z.ZodObject&&(n=un(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},be=(e,t,r)=>e.length&&t.length?(0,oe.xprod)(e,t).map(r):e.concat(t),We=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,$t=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=(0,oe.chain)(o=>o.split(/[^A-Z0-9]/gi),e);return(0,oe.chain)(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map($t).join("")},mt=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Se=e=>typeof e=="object"&&e!==null,ve=(0,oe.memoizeWith)(()=>"static",()=>process.env.NODE_ENV==="production");var lt=require("ramda"),g=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[g]=(0,lt.clone)(t._def[g])||{examples:[]},t},Ar=(e,t)=>{if(!(g in e._def))return t;let r=Ye(t);return r._def[g].examples=be(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?(0,lt.mergeDeepRight)({...o},{...n}):n),r};var fn=function(e){let t=Ye(this);return t._def[g].examples.push(e),t},yn=function(){let e=Ye(this);return e._def[g].isDeprecated=!0,e},gn=function(e){let t=Ye(this);return t._def[g].defaultLabel=e,t},hn=function(e){return new Te.z.ZodBranded({typeName:Te.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...(0,U.clone)(this._def[g]),brand:e}})},xn=function(e){let t=typeof e=="function"?e:(0,U.pipe)(U.toPairs,(0,U.map)(([n,s])=>(0,U.pair)(e[String(n)]||n,s)),U.fromPairs),r=t((0,U.clone)(this.shape)),o=Te.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Te.z.ZodType.prototype,{example:{get(){return fn.bind(this)}},deprecated:{get(){return yn.bind(this)}},brand:{set(){},get(){return hn.bind(this)}}}),Object.defineProperty(Te.z.ZodDefault.prototype,"label",{get(){return gn.bind(this)}}),Object.defineProperty(Te.z.ZodObject.prototype,"remap",{get(){return xn.bind(this)}}));function wr(e){return e}var Qt=require("zod");var Wt=require("zod");var C=require("node:assert/strict");var ke=require("zod");var ut=e=>!isNaN(e.getTime());var Oe=Symbol("DateIn"),Er=()=>ke.z.union([ke.z.string().date(),ke.z.string().datetime(),ke.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ke.z.date().refine(ut)).brand(Oe);var zr=require("zod");var Re=Symbol("DateOut"),Ir=()=>zr.z.date().refine(ut).transform(e=>e.toISOString()).brand(Re);var Qe=require("zod"),Q=Symbol("File"),Zr=Qe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),bn={buffer:()=>Zr.brand(Q),string:()=>Qe.z.string().brand(Q),binary:()=>Zr.or(Qe.z.string()).brand(Q),base64:()=>Qe.z.string().base64().brand(Q)};function ft(e){return bn[e||"string"]()}var vr=require("zod");var le=Symbol("Raw"),kr=(e={})=>vr.z.object({raw:ft("buffer")}).extend(e).brand(le);var Cr=require("zod"),Ce=Symbol("Upload"),jr=()=>Cr.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(Ce);var Nr=(e,{next:t})=>e.options.some(t),Sn=({_def:e},{next:t})=>[e.left,e.right].some(t),yt=(e,{next:t})=>t(e.unwrap()),_t={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Nr,ZodDiscriminatedUnion:Nr,ZodIntersection:Sn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:yt,ZodNullable:yt,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=_t,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Lr=e=>gt(e,{condition:t=>t._def[g]?.brand===Ce}),Mr=e=>gt(e,{condition:t=>t._def[g]?.brand===le,maxDepth:3}),Ur=(e,t)=>{let r=new WeakSet;return gt(e,{maxDepth:300,rules:{..._t,ZodBranded:yt,ZodReadonly:yt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:_t.ZodEffects}[t],ZodNaN:()=>(0,C.fail)("z.nan()"),ZodSymbol:()=>(0,C.fail)("z.symbol()"),ZodFunction:()=>(0,C.fail)("z.function()"),ZodMap:()=>(0,C.fail)("z.map()"),ZodSet:()=>(0,C.fail)("z.set()"),ZodBigInt:()=>(0,C.fail)("z.bigint()"),ZodVoid:()=>(0,C.fail)("z.void()"),ZodPromise:()=>(0,C.fail)("z.promise()"),ZodNever:()=>(0,C.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,C.fail)("z.date()"),[Re]:()=>t==="in"&&(0,C.fail)("ez.dateOut()"),[Oe]:()=>t==="out"&&(0,C.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,C.fail)("ez.raw()"),[Ce]:()=>t==="out"&&(0,C.fail)("ez.upload()"),[Q]:()=>!1}})};var ht=k(require("http-errors"),1);var Xe=k(require("http-errors"),1),Dr=require("zod");var Vt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Dr.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},et=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Pe=e=>(0,Xe.isHttpError)(e)?e:(0,Xe.default)(e instanceof Y?400:500,ce(e),{cause:e.cause||e}),Ae=e=>ve()&&!e.expose?(0,Xe.default)(e.statusCode).message:e.message;var xt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ae((0,ht.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:(0,ht.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Gt=require("zod");var Jt=class{},_=class extends Jt{#e;#t;#r;constructor({input:t=Gt.z.object({}),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 Gt.z.ZodError?new Y(o):o}}},je=class extends _{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Ne=class{nest(t){return Object.assign(t,{"":this})}};var tt=class extends Ne{},bt=class e extends tt{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Lr(this.#e.inputSchema)?"upload":Mr(this.#e.inputSchema)?"raw":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Wt.z.ZodError?new ae(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof je))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Wt.z.ZodError?new Y(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){xt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Bt(t),a={},c=null,d=null,p=dt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){d=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var ue=require("zod");var Hr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ar(s,n),o)},V=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?V(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>V(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?V(e._def.schema):e instanceof ue.z.ZodPipeline?V(e._def.in):V(e._def.left).merge(V(e._def.right));var G=require("zod");var Le={positive:200,negative:400},Me=Object.keys(Le);var Yt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends Yt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Vt(this.#e,{variant:"positive",args:[t],statusCodes:[Le.positive],mimeTypes:[I.json]})}getNegativeResponse(){return Vt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[I.json]})}},Ue=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=G.z.object({status:G.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:G.z.object({status:G.z.literal("error"),error:G.z.object({message:G.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Pe(e);return et(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.positive).json({status:"success",data:r})}}),St=new fe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof G.z.ZodArray?e.shape.items:G.z.array(G.z.any());return t.reduce((o,n)=>Se(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:G.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Pe(r);return et(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof _?t:new _(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new je(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new _({handler:t})),this.resultHandler)}build({input:t=Qt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:d,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,S=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new bt({...c,middlewares:d,outputSchema:r,resultHandler:p,scopes:S,tags:y,methods:l,getOperationId:b,inputSchema:Hr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Qt.z.object({}),handler:async o=>(await t(o),{})})}},Kr=new ye(Ue),Fr=new ye(St);var Gr=k(require("ansis"),1),Jr=require("node:util"),er=require("node:perf_hooks");var X=require("ansis"),qr=require("ramda");var Xt={debug:X.blue,info:X.green,warn:(0,X.hex)("#FFA500"),error:X.red,ctx:X.cyanBright},Tt={debug:10,info:20,warn:30,error:40},Br=e=>Se(e)&&Object.keys(Tt).some(t=>t in e),$r=e=>e in Tt,_r=(e,t)=>Tt[e]<Tt[t],Tn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=(0,qr.memoizeWith)((e,t)=>`${e}${t}`,Tn),Vr=e=>e<1e-6?De("nanosecond",3).format(e/1e-6):e<.001?De("nanosecond").format(e/1e-6):e<1?De("microsecond").format(e/.001):e<1e3?De("millisecond").format(e):e<6e4?De("second",2).format(e/1e3):De("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=Gr.default.isSupported(),level:r=ve()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return(0,Jr.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||_r(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Xt.ctx(s):s),d.push(c?`${Xt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.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})}get ctx(){return this.config.ctx}profile(t){let r=er.performance.now();return()=>{let o=er.performance.now()-r,{message:n,severity:s="debug",formatter:a=Vr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Fe=require("ramda");var Ke=class e extends Ne{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=(0,Fe.keys)(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,(0,Fe.reject)((0,Fe.equals)(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var Wr=k(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Wr.default.static(...this.params))}};var Rt=k(require("express"),1),ho=k(require("node:http"),1),xo=k(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>k(require(e))))[t]}catch{}throw new Ze(e)};var Xr=k(require("http-errors"),1);var Yr=require("ramda");var Ot=class{constructor(t){this.logger=t;this.#e=(0,Yr.tryCatch)(Ur)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Me){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(I.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=ct(t);if(s.length===0)return;let a=n?.shape||V(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Qr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new xe(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),$e=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Qr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof tt){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof qe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new xe(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Qr(s,n))}};var On=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,Xr.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},tr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new Ot(t()),a=new Map;if($e({routing:o,onEndpoint:(d,p,l,b)=>{ve()||(s?.checkJsonCompat(d,{path:p,method:l}),s?.checkPathParams(p,d,{method:l}));let S=n?.[d.getRequestType()]||[],y=async(w,A)=>{let N=t(w);if(r.cors){let Z={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},E=typeof r.cors=="function"?await r.cors({request:w,endpoint:d,logger:N,defaultHeaders:Z}):Z;for(let v in E)A.set(v,E[v])}return d.execute({request:w,response:A,logger:N,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...S,y),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...S,y)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,On(p))};var rt=k(require("http-errors"),1);var so=require("node:timers/promises");var eo=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",to=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",ro=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,oo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),no=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var io=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(eo(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let d=async()=>{for(let p of e)p.on("request",oo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(ro(p)||to(p))&&a(p);for await(let p of(0,so.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(no))};return{sockets:n,shutdown:()=>o??=d()}};var ao=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,rt.isHttpError)(r)?r:(0,rt.default)(400,de(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),po=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,rt.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){xt({response:o,logger:s,error:new pe(de(a),n)})}},Rn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Pn=e=>({log:e.debug.bind(e)}),co=async({getLogger:e,config:t})=>{let r=await Be("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Pn(l)})(c,d,p)}),o&&a.push(Rn(o)),a},mo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},lo=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},uo=e=>t=>t?.res?.locals[g]?.logger||e,fo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),yo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=io(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var B=require("ansis"),go=e=>{if(e.columns<132)return;let t=(0,B.italic)("Proudly supports transgender community.".padStart(109)),r=(0,B.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,B.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,B.italic)("for Tai".padEnd(20)),s=(0,B.hex)("#F5A9B8"),a=(0,B.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(B.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill(B.gray,12,13),d=`
|
|
4
4
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
5
5
|
888 d88P 888 d88888 888 Y88b 888
|
|
6
6
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -15,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,l)=>c[l]?c[l](p):p).join(`
|
|
18
|
-
`))};var xo=e=>{e.startupLogo!==!1&&fo(process.stdout);let t=e.errorHandler||Me,r=qr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.8.0 (CJS)",env:process.env.NODE_ENV||"development"}),uo(r);let o=mo({logger:r,config:e}),s={getLogger:lo(r),errorHandler:t},a=ao(s),c=io(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},bo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=xo(e);return er({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},So=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=xo(e),c=(0,Rt.default)().disable("x-powered-by").use(a);if(e.compression){let b=await qe("compression");c.use(b(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Rt.default.json()],raw:[e.rawParser||Rt.default.raw(),co],upload:e.upload?await po({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),er({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],l=(b,f)=>()=>b.listen(f,()=>r.info("Listening",f)),g=[];if(e.http){let b=go.default.createServer(c);p.push(b),g.push(l(b,e.http.listen))}if(e.https){let b=ho.default.createServer(e.https.options,c);p.push(b),g.push(l(b,e.https.listen))}return e.gracefulShutdown&&yo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:g.map(b=>b())}};var Ko=require("openapi3-ts/oas31"),Do=require("ramda");var T=require("ramda");var To=e=>be(e)&&"or"in e,Oo=e=>be(e)&&"and"in e,tr=e=>!Oo(e)&&!To(e),Ro=e=>{let t=(0,T.filter)(tr,e),r=(0,T.chain)((0,T.prop)("and"),(0,T.filter)(Oo,e)),[o,n]=(0,T.partition)(tr,r),s=(0,T.concat)(t,o),a=(0,T.filter)(To,e);return(0,T.map)((0,T.prop)("or"),(0,T.concat)(a,n)).reduce((d,p)=>xe(d,(0,T.map)(l=>tr(l)?[l]:l.and,p),([l,g])=>(0,T.concat)(l,g)),(0,T.reject)(T.isEmpty,[s]))};var oe=require("openapi3-ts/oas31"),m=require("ramda"),D=require("zod");var Ae=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[x]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>Ae(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var Po=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var Ao=50,Eo="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:[]},An=/^\d{4}-\d{2}-\d{2}$/,wn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,En=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,zo=e=>e.replace(Dt,t=>`{${t.slice(1)}}`),zn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),In=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),Zn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},kn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof D.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Cn=({options:e},{next:t})=>({oneOf:e.map(t)}),jn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Nn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Ln=e=>{let[t,r]=e.filter(oe.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Nn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=xe(t.examples||[],r.examples||[],([n,s])=>(0,m.mergeDeepRight)(n,s))),o},Mn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ln(o)}catch{}return{allOf:o}},Un=(e,{next:t})=>t(e.unwrap()),Hn=(e,{next:t})=>t(e.unwrap()),Kn=(e,{next:t})=>{let r=t(e.unwrap());return(0,oe.isSchemaObject)(r)&&(r.type=vo(r)),r},Io=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},wo=e=>({type:Io(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Dn=({value:e})=>({type:Io(e),const:e}),Fn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ge(c)?c instanceof D.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Pt(e,r)),s.length&&(a.required=s),a},qn=()=>({type:"null"}),Bn=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{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:Eo}}},$n=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Eo}}},Vn=({},e)=>{throw new q(`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)},_n=()=>({type:"boolean"}),Gn=()=>({type:"integer",format:"bigint"}),Jn=e=>e.every(t=>t instanceof D.z.ZodLiteral),Wn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof D.z.ZodEnum||e instanceof D.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Pt(D.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof D.z.ZodLiteral)return{type:"object",properties:Pt(D.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof D.z.ZodUnion&&Jn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:Pt(D.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Yn=({_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},Qn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Xn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:g,isDate:b,isTime:f,isBase64:R,isNANOID:O,isBase64url:L,isDuration:M,_def:{checks:S}})=>{let E=S.find(k=>k.kind==="regex"),v=S.find(k=>k.kind==="datetime"),U=S.some(k=>k.kind==="jwt"),Z=S.find(k=>k.kind==="length"),z={type:"string"},fe={"date-time":l,byte:R,base64url:L,date:b,time:f,duration:M,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:O,jwt:U,ip:d,cidr:g,emoji:p};for(let k in fe)if(fe[k]){z.format=k;break}return Z&&([z.minLength,z.maxLength]=[Z.value,Z.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),b&&(z.pattern=An.source),f&&(z.pattern=wn.source),l&&(z.pattern=En(v?.offset).source),E&&(z.pattern=E.regex.source),z},es=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(g=>g.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(g=>g.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,p?l.maximum=d:l.exclusiveMaximum=d,l},Pt=({shape:e},t)=>(0,m.map)(t,e),ts=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Pn?.[t]},vo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",rs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,oe.isSchemaObject)(o)){let s=ct(e,ts(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(D.z.any())}if(!t&&n.type==="preprocess"&&(0,oe.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},os=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ns=(e,{next:t})=>t(e.unwrap()),ss=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),is=(e,{next:t})=>t(e.unwrap().shape.raw),Zo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,ko=(e,t,r=[])=>(0,m.pipe)(re,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),Zo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),as=(e,t)=>(0,m.pipe)(re,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),Zo)({schema:e,variant:"original",validate:!0,pullProps:!0}),ps=(e,t)=>t?.includes(e)||e.startsWith("x-")||Po.includes(e),Co=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let l=_(r),g=at(e),b=o.includes("query"),f=o.includes("params"),R=o.includes("headers"),O=S=>f&&g.includes(S),L=(0,m.chain)((0,m.filter)(S=>S.type==="header"),d??[]).map(({name:S})=>S),M=S=>R&&(c?.(S,t,e)??ps(S,L));return Object.entries(l.shape).reduce((S,[E,v])=>{let U=O(E)?"path":M(E)?"header":b?"query":void 0;if(!U)return S;let Z=Ae(v,{rules:{...a,...or},onEach:nr,onMissing:sr,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),z=s==="components"?n(v,Z,ce(p,E)):Z;return S.concat({name:E,in:U,required:!v.isOptional(),description:Z.description||p,schema:z,examples:as(l,E)})},[])},or={ZodString:Xn,ZodNumber:es,ZodBigInt:Gn,ZodBoolean:_n,ZodNull:qn,ZodArray:Yn,ZodTuple:Qn,ZodRecord:Wn,ZodObject:Fn,ZodLiteral:Dn,ZodIntersection:Mn,ZodUnion:Cn,ZodAny:vn,ZodDefault:zn,ZodEnum:wo,ZodNativeEnum:wo,ZodEffects:rs,ZodOptional:Un,ZodNullable:Kn,ZodDiscriminatedUnion:jn,ZodBranded:ns,ZodDate:Vn,ZodCatch:In,ZodPipeline:os,ZodLazy:ss,ZodReadonly:Hn,[Q]:kn,[ke]:Zn,[Oe]:$n,[Te]:Bn,[de]:is},nr=(e,{isResponse:t,prev:r})=>{if((0,oe.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof D.z.ZodLazy,s=r.type!==void 0,a=t&&Ge(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=vo(r)),!n){let p=re({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},sr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},rr=(e,t)=>{if((0,oe.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>rr(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>rr(o,t))),r},jo=e=>(0,oe.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),No=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${Bt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let g=jo(Ae(r,{rules:{...p,...or},onEach:nr,onMissing:sr,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b={schema:a==="components"?s(r,g,ce(l)):g,examples:ko(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[b]))}},cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ds=({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},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),ls=({name:e})=>({type:"apiKey",in:"cookie",name:e}),us=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ys=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Lo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?cs(o):o.type==="input"?ds(o,t):o.type==="header"?ms(o):o.type==="cookie"?ls(o):o.type==="openid"?us(o):ys(o);return e.map(o=>o.map(r))},Mo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Uo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=jo(rr(Ae(r,{rules:{...a,...or},onEach:nr,onMissing:sr,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:s==="components"?n(r,p,ce(d)):p,examples:ko(_(r),!1,c)};return{description:d,content:{[o]:l}}},Ho=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),ir=e=>e.length<=Ao?e:e.slice(0,Ao-1)+"\u2026";var At=class extends Ko.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||ce(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});Be({routing:t,onEndpoint:(f,R,O)=>{let L={path:R,method:O,endpoint:f,composition:g,brandHandling:c,makeRef:this.makeRef.bind(this)},[M,S]=["short","long"].map(f.getDescription.bind(f)),E=M?ir(M):l&&S?ir(S):void 0,v=r.inputSources?.[O]||Ft[O],U=this.ensureUniqOperationId(R,O,f.getOperationId(O)),Z=Ro(f.getSecurity()),z=Co({...L,inputSources:v,isHeader:p,security:Z,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:R,operationId:U})}),fe={};for(let ne of Le){let ge=f.getResponses(ne);for(let{mimeTypes:Ut,schema:ot,statusCodes:nt}of ge)for(let Ht of nt)fe[Ht]=No({...L,variant:ne,schema:ot,mimeTypes:Ut,statusCode:Ht,hasMultipleStatusCodes:ge.length>1||nt.length>1,description:a?.[`${ne}Response`]?.call(null,{method:O,path:R,operationId:U,statusCode:Ht})})}let k=v.includes("body")?Uo({...L,paramNames:(0,Do.pluck)("name",z),schema:f.getSchema("input"),mimeType:I[f.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:R,operationId:U})}):void 0,Mt=Mo(Lo(Z,v),f.getScopes(),ne=>{let ge=this.ensureUniqSecuritySchemaName(ne);return this.addSecurityScheme(ge,ne),ge});this.addPath(zo(R),{[O]:{operationId:U,summary:E,description:S,tags:dt(f.getTags()),parameters:dt(z),requestBody:k,security:dt(Mt),responses:fe}})}}),d&&(this.rootDoc.tags=Ho(d))}};var wt=require("node-mocks-http"),fs=e=>(0,wt.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),gs=e=>(0,wt.createResponse)(e),hs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Br(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Fo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=fs(e),s=gs({req:n,...t});s.req=t?.req||n,n.res=s;let a=hs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},qo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Fo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Bo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Fo(o),d=pt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(pe(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var Yo=require("ramda"),rt=C(require("typescript"),1),Qo=require("zod");var Jo=require("ramda"),W=C(require("typescript"),1);var $o=["get","post","put","delete","patch"];var $e=require("ramda"),u=C(require("typescript"),1),i=u.default.factory,Et=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],xs=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],et={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ar=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),pr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,cr=e=>typeof e=="string"&&bs.test(e)?i.createIdentifier(e):w(e),zt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),It=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?y(t):void 0,o),Ve=e=>Object.entries(e).map(([t,r])=>It(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),dr=(e,t=[])=>i.createConstructorDeclaration(et.public,e,i.createBlock(t)),y=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&(0,$e.map)(y,t)):e,mr=y("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),we=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,cr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,y(t));return o?ar(n,o):n},lr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),ur=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),N=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Et,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?y(r):void 0,t)],u.default.NodeFlags.Const)),yr=(e,t)=>ee(e,i.createUnionTypeNode((0,$e.map)(F,t)),{expose:!0}),ee=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Et:void 0,e,n&&xr(n),t);return o?ar(s,o):s},Vo=(e,t)=>i.createPropertyDeclaration(et.public,e,void 0,y(t),void 0),fr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(et.public,void 0,e,void 0,o&&xr(o),t,n,i.createBlock(r)),gr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Et,e,r&&xr(r),void 0,t),hr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,y(e)),vt=e=>y(Promise.name,[e]),Zt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Et:void 0,e,void 0,void 0,t);return o?ar(n,o):n},xr=e=>(Array.isArray(e)?e.map(t=>(0,$e.pair)(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?y(o):void 0,n?y(n):void 0)}),Ee=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?(0,$e.map)(It,e):Ve(e),void 0,void 0,t),P=e=>e,tt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),_e=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),kt=(e,t)=>y("Extract",[e,t]),br=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),J=(e,t)=>i.createIndexedAccessTypeNode(y(e),y(t)),_o=e=>i.createUnionTypeNode([y(e),vt(e)]),Sr=(e,t)=>i.createFunctionTypeNode(void 0,Ve(e),y(t)),w=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(w(e)),Ss=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],Go=e=>Ss.includes(e.kind);var Ct=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=yr("Method",$o);someOfType=ee("SomeOf",J("T",hr("T")),{params:["T"]});requestType=ee("Request",hr(this.interfaces.input),{expose:!0});someOf=({name:t})=>y(this.someOfType.name,[t]);makePathType=()=>yr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Zt(this.interfaces[t],Array.from(this.registry).map(([r,o])=>we(r,o[t])),{expose:!0}));makeEndpointTags=()=>N("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(cr(t),i.createArrayLiteralExpression((0,Jo.map)(w,r))))),{expose:!0});makeImplementationType=()=>ee(this.ids.implementationType,Sr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:mr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},vt(W.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:W.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.ids.parseRequestFn,Ee({[this.ids.requestParameter.text]:W.default.SyntaxKind.StringKeyword},i.createAsExpression(A(this.ids.requestParameter,P("split"))(i.createRegularExpressionLiteral("/ (.+)/"),w(2)),i.createTupleTypeNode([y(this.methodType.name),y(this.ids.pathType)]))));makeSubstituteFn=()=>N(this.ids.substituteFn,Ee({[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:mr},i.createBlock([N(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],W.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([br(this.ids.pathParameter,A(this.ids.pathParameter,P("replace"))(zt(":",[this.ids.keyParameter]),Ee([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),y("const")))])));makeProvider=()=>fr(this.ids.provideMethod,Ve({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:J(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[N(ur(this.ids.methodParameter,this.ids.pathParameter),A(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(A(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(A(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:vt(J(this.interfaces.response,"K"))});makeClientClass=t=>gr(t,[dr([It(this.ids.implementationArgument,{type:y(this.ids.implementationType,["T"]),mod:et.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>zt("?",[_e(URLSearchParams.name,t)]);makeFetchURL=()=>_e(URL.name,zt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(P("method"),A(this.ids.methodParameter,P("toUpperCase"))()),r=i.createPropertyAssignment(P("headers"),tt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(w("Content-Type"),w(I.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(P("body"),tt(this.ids.hasBodyConst,A(JSON[Symbol.toStringTag],P("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=N(this.ids.responseConst,i.createAwaitExpression(A(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=N(this.ids.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([w("get"),w("delete")]),P("includes"))(this.ids.methodParameter))),a=N(this.ids.searchParamsConst,tt(this.ids.hasBodyConst,w(""),this.makeSearchParams(this.ids.paramsArgument))),c=N(this.ids.contentTypeConst,A(this.ids.responseConst,P("headers"),P("get"))(w("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(W.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=N(this.ids.isJsonConst,A(this.ids.contentTypeConst,P("startsWith"))(w(I.json))),l=i.createReturnStatement(A(this.ids.responseConst,tt(this.ids.isJsonConst,w(P("json")),w(P("text"))))());return N(this.ids.defaultImplementationConst,Ee([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>dr(Ve({request:"K",params:J(this.interfaces.input,"K")}),[N(ur(this.ids.pathParameter,this.ids.restConst),A(this.ids.substituteFn)(i.createElementAccessExpression(A(this.ids.parseRequestFn)(this.ids.requestParameter),w(1)),this.ids.paramsArgument)),N(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),br(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),_e("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([we(P("event"),t)]);makeOnMethod=()=>fr(this.ids.onMethod,Ve({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Sr({[this.ids.dataParameter.text]:J(kt("R",lr(this.makeEventNarrow("E"))),F(P("data")))},_o(W.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.ids.sourceProp,P("addEventListener"))(this.ids.eventParameter,Ee([this.ids.msgParameter],A(this.ids.handlerParameter)(A(JSON[Symbol.toStringTag],P("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,y(MessageEvent.name))),P("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:J("R",F(P("event")))}});makeSubscriptionClass=t=>gr(t,[Vo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:kt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(y(W.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:kt(J(this.interfaces.positive,"K"),lr(this.makeEventNarrow(W.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.ids.clientConst,_e(t)),A(this.ids.clientConst,this.ids.provideMethod)(w("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",w("10"))])),A(_e(r,w("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(w("time"),Ee(["time"],i.createBlock([])))]};var H=require("ramda"),h=C(require("typescript"),1),jt=require("zod");var{factory:$}=h.default,Ts={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Tr={name:(0,H.path)(["name","text"]),type:(0,H.path)(["type"]),optional:(0,H.path)(["questionToken"])},Os=({value:e})=>F(e),Rs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&Ge(a)?a instanceof jt.z.ZodOptional:a.isOptional();return we(s,r(a),{isOptional:c&&o,comment:a.description})});return $.createTypeLiteralNode(n)},Ps=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),As=({options:e})=>$.createUnionTypeNode(e.map(F)),Wo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Go(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},ws=e=>Ts?.[e.kind],Es=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ct(e,ws(o)),s={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return y(n&&s[n]||h.default.SyntaxKind.AnyKeyword)}return o},zs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),Is=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,y(h.default.SyntaxKind.UndefinedKeyword)]):o},vs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),Zs=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),ks=({keySchema:e,valueSchema:t},{next:r})=>y("Record",[e,t].map(r)),Cs=e=>{if(!e.every(h.default.isTypeLiteralNode))throw new Error("Not objects");let r=(0,H.chain)((0,H.prop)("members"),e),o=(0,H.uniqWith)((...n)=>{if(!(0,H.eqBy)(Tr.name,...n))return!1;if((0,H.eqBy)(Tr.type,...n)&&(0,H.eqBy)(Tr.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return $.createTypeLiteralNode(o)},js=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Cs(o)}catch{}return $.createIntersectionTypeNode(o)},Ns=({_def:e},{next:t})=>t(e.innerType),ye=e=>()=>y(e),Ls=(e,{next:t})=>t(e.unwrap()),Ms=(e,{next:t})=>t(e.unwrap()),Us=({_def:e},{next:t})=>t(e.innerType),Hs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ks=()=>F(null),Ds=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Fs=e=>{let t=e.unwrap(),r=y(h.default.SyntaxKind.StringKeyword),o=y("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof jt.z.ZodString?r:t instanceof jt.z.ZodUnion?n:o},qs=(e,{next:t})=>t(e.unwrap().shape.raw),Bs={ZodString:ye(h.default.SyntaxKind.StringKeyword),ZodNumber:ye(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ye(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ye(h.default.SyntaxKind.BooleanKeyword),ZodAny:ye(h.default.SyntaxKind.AnyKeyword),ZodUndefined:ye(h.default.SyntaxKind.UndefinedKeyword),[Te]:ye(h.default.SyntaxKind.StringKeyword),[Oe]:ye(h.default.SyntaxKind.StringKeyword),ZodNull:Ks,ZodArray:Ps,ZodTuple:Zs,ZodRecord:ks,ZodObject:Rs,ZodLiteral:Os,ZodIntersection:js,ZodUnion:Wo,ZodDefault:Ns,ZodEnum:As,ZodNativeEnum:zs,ZodEffects:Es,ZodOptional:Is,ZodNullable:vs,ZodDiscriminatedUnion:Wo,ZodBranded:Ls,ZodCatch:Us,ZodPipeline:Hs,ZodLazy:Ds,ZodReadonly:Ms,[Q]:Fs,[de]:qs},Or=(e,{brandHandling:t,ctx:r})=>Ae(e,{rules:{...t,...Bs},onMissing:()=>y(h.default.SyntaxKind.AnyKeyword),ctx:r});var Nt=class extends Ct{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=F(null);this.aliases.set(t,ee(o,n)),this.aliases.set(t,ee(o,r()))}return y(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Qo.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},g={brandHandling:r,ctx:{...p,isResponse:!0}};Be({routing:t,onEndpoint:(f,R,O)=>{let L=ce.bind(null,O,R),M=`${O} ${R}`,S=ee(L("input"),Or(f.getSchema("input"),l),{comment:M});this.program.push(S);let E=Le.reduce((U,Z)=>{let z=f.getResponses(Z),fe=(0,Yo.chain)(([Mt,{schema:ne,mimeTypes:ge,statusCodes:Ut}])=>{let ot=ee(L(Z,"variant",`${Mt+1}`),Or(ge?ne:d,g),{comment:M});return this.program.push(ot),Ut.map(nt=>we(nt,ot.name))},Array.from(z.entries())),k=Zt(L(Z,"response","variants"),fe,{comment:M});return this.program.push(k),Object.assign(U,{[Z]:k})},{});this.paths.add(R);let v=F(M);this.registry.set(M,{input:y(S.name),positive:this.someOf(E.positive),negative:this.someOf(E.negative),response:i.createUnionTypeNode([J(this.interfaces.positive,v),J(this.interfaces.negative,v)]),encoded:i.createIntersectionTypeNode([y(E.positive.name),y(E.negative.name)])}),this.tags.set(M,f.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:pr(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((n,s)=>
|
|
18
|
+
`))};var bo=e=>{e.startupLogo!==!1&&go(process.stdout);let t=e.errorHandler||Ue,r=Br(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.9.0 (CJS)",env:process.env.NODE_ENV||"development"}),fo(r);let o=lo({logger:r,config:e}),s={getLogger:uo(r),errorHandler:t},a=po(s),c=ao(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},So=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=bo(e);return tr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},To=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=bo(e),c=(0,Rt.default)().disable("x-powered-by").use(a);if(e.compression){let S=await Be("compression");c.use(S(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Rt.default.json()],raw:[e.rawParser||Rt.default.raw(),mo],upload:e.upload?await co({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),tr({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],l=(S,y)=>()=>S.listen(y,()=>r.info("Listening",y)),b=[];if(e.http){let S=ho.default.createServer(c);p.push(S),b.push(l(S,e.http.listen))}if(e.https){let S=xo.default.createServer(e.https.options,c);p.push(S),b.push(l(S,e.https.listen))}return e.gracefulShutdown&&yo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(S=>S())}};var Ko=require("openapi3-ts/oas31"),Fo=require("ramda");var T=require("ramda");var Oo=e=>Se(e)&&"or"in e,Ro=e=>Se(e)&&"and"in e,rr=e=>!Ro(e)&&!Oo(e),Po=e=>{let t=(0,T.filter)(rr,e),r=(0,T.chain)((0,T.prop)("and"),(0,T.filter)(Ro,e)),[o,n]=(0,T.partition)(rr,r),s=(0,T.concat)(t,o),a=(0,T.filter)(Oo,e);return(0,T.map)((0,T.prop)("or"),(0,T.concat)(a,n)).reduce((d,p)=>be(d,(0,T.map)(l=>rr(l)?[l]:l.and,p),([l,b])=>(0,T.concat)(l,b)),(0,T.reject)(T.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),m=require("ramda"),D=require("zod");var we=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>we(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var Ao=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var wo=50,zo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",wn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},En=/^\d{4}-\d{2}-\d{2}$/,zn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,In=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Io=e=>e.replace(Ft,t=>`{${t.slice(1)}}`),Zn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),vn=({_def:{innerType:e}},{next:t})=>t(e),kn=()=>({format:"any"}),Cn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},jn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof D.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Nn=({options:e},{next:t})=>({oneOf:e.map(t)}),Ln=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Un=e=>{let[t,r]=e.filter(se.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Mn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=be(t.examples||[],r.examples||[],([n,s])=>(0,m.mergeDeepRight)(n,s))),o},Dn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Un(o)}catch{}return{allOf:o}},Hn=(e,{next:t})=>t(e.unwrap()),Kn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=vo(r)),r},Zo=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Eo=e=>({type:Zo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),qn=({value:e})=>({type:Zo(e),const:e}),Bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&We(c)?c instanceof D.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Pt(e,r)),s.length&&(a.required=s),a},$n=()=>({type:"null"}),_n=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{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:zo}}},Vn=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:zo}}},Gn=({},e)=>{throw new q(`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"}),Yn=e=>e.every(t=>t instanceof D.z.ZodLiteral),Qn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof D.z.ZodEnum||e instanceof D.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Pt(D.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof D.z.ZodLiteral)return{type:"object",properties:Pt(D.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof D.z.ZodUnion&&Yn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:Pt(D.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Xn=({_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},es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ts=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:b,isDate:S,isTime:y,isBase64:w,isNANOID:A,isBase64url:N,isDuration:re,_def:{checks:h}})=>{let Z=h.find(L=>L.kind==="regex"),E=h.find(L=>L.kind==="datetime"),v=h.some(L=>L.kind==="jwt"),K=h.find(L=>L.kind==="length"),z={type:"string"},F={"date-time":l,byte:w,base64url:N,date:S,time:y,duration:re,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:A,jwt:v,ip:d,cidr:b,emoji:p};for(let L in F)if(F[L]){z.format=L;break}return K&&([z.minLength,z.maxLength]=[K.value,K.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),S&&(z.pattern=En.source),y&&(z.pattern=zn.source),l&&(z.pattern=In(E?.offset).source),Z&&(z.pattern=Z.regex.source),z},rs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(b=>b.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(b=>b.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,p?l.maximum=d:l.exclusiveMaximum=d,l},Pt=({shape:e},t)=>(0,m.map)(t,e),os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return wn?.[t]},vo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ns=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=mt(e,os(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(D.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ss=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),is=(e,{next:t})=>t(e.unwrap()),as=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ps=(e,{next:t})=>t(e.unwrap().shape.raw),ko=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,Co=(e,t,r=[])=>(0,m.pipe)(ne,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),ko)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),cs=(e,t)=>(0,m.pipe)(ne,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),ko)({schema:e,variant:"original",validate:!0,pullProps:!0}),ds=(e,t)=>t?.includes(e)||e.startsWith("x-")||Ao.includes(e),jo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let l=V(r),b=ct(e),S=o.includes("query"),y=o.includes("params"),w=o.includes("headers"),A=h=>y&&b.includes(h),N=(0,m.chain)((0,m.filter)(h=>h.type==="header"),d??[]).map(({name:h})=>h),re=h=>w&&(c?.(h,t,e)??ds(h,N));return Object.entries(l.shape).reduce((h,[Z,E])=>{let v=A(Z)?"path":re(Z)?"header":S?"query":void 0;if(!v)return h;let K=we(E,{rules:{...a,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),z=s==="components"?n(E,K,me(p,Z)):K,{_def:F}=E;return h.concat({name:Z,in:v,deprecated:F[g]?.isDeprecated,required:!E.isOptional(),description:K.description||p,schema:z,examples:cs(l,Z)})},[])},nr={ZodString:ts,ZodNumber:rs,ZodBigInt:Wn,ZodBoolean:Jn,ZodNull:$n,ZodArray:Xn,ZodTuple:es,ZodRecord:Qn,ZodObject:Bn,ZodLiteral:qn,ZodIntersection:Dn,ZodUnion:Nn,ZodAny:kn,ZodDefault:Zn,ZodEnum:Eo,ZodNativeEnum:Eo,ZodEffects:ns,ZodOptional:Hn,ZodNullable:Fn,ZodDiscriminatedUnion:Ln,ZodBranded:is,ZodDate:Gn,ZodCatch:vn,ZodPipeline:ss,ZodLazy:as,ZodReadonly:Kn,[Q]:jn,[Ce]:Cn,[Re]:Vn,[Oe]:_n,[le]:ps},sr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof D.z.ZodLazy,a=r.type!==void 0,c=t&&We(e),d=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[g]?.isDeprecated&&(p.deprecated=!0),d&&(p.type=vo(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},ir=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},or=(e,t)=>{if((0,se.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>or(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>or(o,t))),r},No=e=>(0,se.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),Lo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${$t(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let b=No(we(r,{rules:{...p,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),S={schema:a==="components"?s(r,b,me(l)):b,examples:Co(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[S]))}},ms=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({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},us=({name:e})=>({type:"apiKey",in:"header",name:e}),fs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ys=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),gs=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Mo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ms(o):o.type==="input"?ls(o,t):o.type==="header"?us(o):o.type==="cookie"?fs(o):o.type==="openid"?ys(o):gs(o);return e.map(o=>o.map(r))},Uo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Do=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=No(or(we(r,{rules:{...a,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:s==="components"?n(r,p,me(d)):p,examples:Co(V(r),!1,c)};return{description:d,content:{[o]:l}}},Ho=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),ar=e=>e.length<=wo?e:e.slice(0,wo-1)+"\u2026",At=e=>e.length?e.slice():void 0;var wt=class extends Ko.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||me(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:b="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});$e({routing:t,onEndpoint:(y,w,A)=>{let N={path:w,method:A,endpoint:y,composition:b,brandHandling:c,makeRef:this.makeRef.bind(this)},[re,h]=["short","long"].map(y.getDescription.bind(y)),Z=re?ar(re):l&&h?ar(h):void 0,E=r.inputSources?.[A]||qt[A],v=this.ensureUniqOperationId(w,A,y.getOperationId(A)),K=Po(y.getSecurity()),z=jo({...N,inputSources:E,isHeader:p,security:K,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:A,path:w,operationId:v})}),F={};for(let ie of Me){let he=y.getResponses(ie);for(let{mimeTypes:Dt,schema:Ht,statusCodes:Ge}of he)for(let Je of Ge)F[Je]=Lo({...N,variant:ie,schema:Ht,mimeTypes:Dt,statusCode:Je,hasMultipleStatusCodes:he.length>1||Ge.length>1,description:a?.[`${ie}Response`]?.call(null,{method:A,path:w,operationId:v,statusCode:Je})})}let L=E.includes("body")?Do({...N,paramNames:(0,Fo.pluck)("name",z),schema:y.getSchema("input"),mimeType:I[y.getRequestType()],description:a?.requestBody?.call(null,{method:A,path:w,operationId:v})}):void 0,Ut=Uo(Mo(K,E),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),it={operationId:v,summary:Z,description:h,deprecated:y.isDeprecated||void 0,tags:At(y.getTags()),parameters:At(z),requestBody:L,security:At(Ut),responses:F};this.addPath(Io(w),{[A]:it})}}),d&&(this.rootDoc.tags=Ho(d))}};var Et=require("node-mocks-http"),hs=e=>(0,Et.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),xs=e=>(0,Et.createResponse)(e),bs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:$r(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},qo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=hs(e),s=xs({req:n,...t});s.req=t?.req||n,n.res=s;let a=bs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Bo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=qo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},$o=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=qo(o),d=dt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(de(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var Qo=require("ramda"),st=k(require("typescript"),1),Xo=require("zod");var Wo=require("ramda"),W=k(require("typescript"),1);var _o=["get","post","put","delete","patch"];var ee=require("ramda"),u=k(require("typescript"),1),i=u.default.factory,zt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Ss=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],ot={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},pr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e=="string"&&Ts.test(e)?i.createIdentifier(e):P(e),It=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Zt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),_e=e=>Object.entries(e).map(([t,r])=>Zt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),mr=(e,t=[])=>i.createConstructorDeclaration(ot.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&(0,ee.map)(f,t)):e,lr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ee=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,dr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=(0,ee.reject)(ee.isNil,[o?"@deprecated":void 0,n]);return a.length?pr(s,a.join(" ")):s},ur=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),fr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&zt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),yr=(e,t)=>te(e,i.createUnionTypeNode((0,ee.map)(H,t)),{expose:!0}),te=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?zt:void 0,e,n&&br(n),t);return o?pr(s,o):s},Vo=(e,t)=>i.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),gr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(ot.public,void 0,e,void 0,o&&br(o),t,n,i.createBlock(r)),hr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(zt,e,r&&br(r),void 0,t),xr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),vt=e=>f(Promise.name,[e]),kt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?zt:void 0,e,void 0,void 0,t);return o?pr(n,o):n},br=e=>(Array.isArray(e)?e.map(t=>(0,ee.pair)(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ze=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ss:void 0,void 0,Array.isArray(e)?(0,ee.map)(Zt,e):_e(e),void 0,void 0,t),O=e=>e,nt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ve=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),Sr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),J=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Go=e=>i.createUnionTypeNode([f(e),vt(e)]),Tr=(e,t)=>i.createFunctionTypeNode(void 0,_e(e),f(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),H=e=>i.createLiteralTypeNode(P(e)),Os=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],Jo=e=>Os.includes(e.kind);var jt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=yr("Method",_o);someOfType=te("SomeOf",J("T",xr("T")),{params:["T"]});requestType=te("Request",xr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>yr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>kt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ee(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(dr(t),i.createArrayLiteralExpression((0,Wo.map)(P,r))))),{expose:!0});makeImplementationType=()=>te(this.ids.implementationType,Tr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:lr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},vt(W.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:W.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.ids.parseRequestFn,ze({[this.ids.requestParameter.text]:W.default.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>j(this.ids.substituteFn,ze({[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:lr},i.createBlock([j(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],W.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([Sr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(It(":",[this.ids.keyParameter]),ze([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),f("const")))])));makeProvider=()=>gr(this.ids.provideMethod,_e({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:J(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[j(fr(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:vt(J(this.interfaces.response,"K"))});makeClientClass=t=>hr(t,[mr([Zt(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:ot.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>It("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,It("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),nt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(I.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),nt(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=j(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=j(this.ids.searchParamsConst,nt(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=j(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(W.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=j(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(I.json))),l=i.createReturnStatement(R(this.ids.responseConst,nt(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return j(this.ids.defaultImplementationConst,ze([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>mr(_e({request:"K",params:J(this.interfaces.input,"K")}),[j(fr(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),j(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),Sr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([Ee(O("event"),t)]);makeOnMethod=()=>gr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Tr({[this.ids.dataParameter.text]:J(Ct("R",ur(this.makeEventNarrow("E"))),H(O("data")))},Go(W.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,ze([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:J("R",H(O("event")))}});makeSubscriptionClass=t=>hr(t,[Vo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:Ct(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(W.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ct(J(this.interfaces.positive,"K"),ur(this.makeEventNarrow(W.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.ids.clientConst,Ve(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(Ve(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),ze(["time"],i.createBlock([])))]};var M=require("ramda"),x=k(require("typescript"),1),Nt=require("zod");var{factory:$}=x.default,Rs={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Or={name:(0,M.path)(["name","text"]),type:(0,M.path)(["type"]),optional:(0,M.path)(["questionToken"])},Ps=({value:e})=>H(e),As=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:d}=a,p=t&&We(a)?a instanceof Nt.z.ZodOptional:a.isOptional();return Ee(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:d[g]?.isDeprecated})});return $.createTypeLiteralNode(n)},ws=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Es=({options:e})=>$.createUnionTypeNode(e.map(H)),Yo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Jo(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},zs=e=>Rs?.[e.kind],Is=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=mt(e,zs(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Zs=e=>$.createUnionTypeNode(Object.values(e.enum).map(H)),vs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},ks=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),H(null)]),Cs=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),js=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Ns=e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let r=(0,M.chain)((0,M.prop)("members"),e),o=(0,M.uniqWith)((...n)=>{if(!(0,M.eqBy)(Or.name,...n))return!1;if((0,M.eqBy)(Or.type,...n)&&(0,M.eqBy)(Or.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return $.createTypeLiteralNode(o)},Ls=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ns(o)}catch{}return $.createIntersectionTypeNode(o)},Ms=({_def:e},{next:t})=>t(e.innerType),ge=e=>()=>f(e),Us=(e,{next:t})=>t(e.unwrap()),Ds=(e,{next:t})=>t(e.unwrap()),Hs=({_def:e},{next:t})=>t(e.innerType),Ks=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Fs=()=>H(null),qs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Bs=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Nt.z.ZodString?r:t instanceof Nt.z.ZodUnion?n:o},$s=(e,{next:t})=>t(e.unwrap().shape.raw),_s={ZodString:ge(x.default.SyntaxKind.StringKeyword),ZodNumber:ge(x.default.SyntaxKind.NumberKeyword),ZodBigInt:ge(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:ge(x.default.SyntaxKind.BooleanKeyword),ZodAny:ge(x.default.SyntaxKind.AnyKeyword),ZodUndefined:ge(x.default.SyntaxKind.UndefinedKeyword),[Oe]:ge(x.default.SyntaxKind.StringKeyword),[Re]:ge(x.default.SyntaxKind.StringKeyword),ZodNull:Fs,ZodArray:ws,ZodTuple:Cs,ZodRecord:js,ZodObject:As,ZodLiteral:Ps,ZodIntersection:Ls,ZodUnion:Yo,ZodDefault:Ms,ZodEnum:Es,ZodNativeEnum:Zs,ZodEffects:Is,ZodOptional:vs,ZodNullable:ks,ZodDiscriminatedUnion:Yo,ZodBranded:Us,ZodCatch:Hs,ZodPipeline:Ks,ZodLazy:qs,ZodReadonly:Ds,[Q]:Bs,[le]:$s},Rr=(e,{brandHandling:t,ctx:r})=>we(e,{rules:{...t,..._s},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Lt=class extends jt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=H(null);this.aliases.set(t,te(o,n)),this.aliases.set(t,te(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Xo.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};$e({routing:t,onEndpoint:(y,w,A)=>{let N=me.bind(null,A,w),{isDeprecated:re}=y,h=`${A} ${w}`,Z=te(N("input"),Rr(y.getSchema("input"),l),{comment:h});this.program.push(Z);let E=Me.reduce((z,F)=>{let L=y.getResponses(F),Ut=(0,Qo.chain)(([ie,{schema:he,mimeTypes:Dt,statusCodes:Ht}])=>{let Ge=te(N(F,"variant",`${ie+1}`),Rr(Dt?he:d,b),{comment:h});return this.program.push(Ge),Ht.map(Je=>Ee(Je,Ge.name))},Array.from(L.entries())),it=kt(N(F,"response","variants"),Ut,{comment:h});return this.program.push(it),Object.assign(z,{[F]:it})},{});this.paths.add(w);let v=H(h),K={input:f(Z.name),positive:this.someOf(E.positive),negative:this.someOf(E.negative),response:i.createUnionTypeNode([J(this.interfaces.positive,v),J(this.interfaces.negative,v)]),encoded:i.createIntersectionTypeNode([f(E.positive.name),f(E.negative.name)])};this.registry.set(h,{isDeprecated:re,store:K}),this.tags.set(h,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:cr(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&st.default.addSyntheticLeadingComment(st.default.addSyntheticLeadingComment(i.createEmptyStatement(),st.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),st.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>cr(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Be("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};var Ie=require("zod");var tn=(e,t)=>Ie.z.object({data:t,event:Ie.z.literal(e),id:Ie.z.string().optional(),retry:Ie.z.number().int().positive().optional()}),Vs=(e,t,r)=>tn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Gs=1e4,en=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":I.sse,"cache-control":"no-cache"}),Js=e=>new _({handler:async({response:t})=>setTimeout(()=>en(t),Gs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{en(t),t.write(Vs(e,r,o),"utf-8"),t.flush?.()}}}),Ws=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>tn(o,n));return{mimeType:I.sse,schema:r.length?Ie.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ie.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Pe(r);et(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(Ae(a),"utf-8")}t.end()}}),Mt=class extends ye{constructor(t){super(Ws(t)),this.middlewares=[Js(t)]}};var rn={dateIn:Er,dateOut:Ir,file:ft,upload:jr,raw:kr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
|
package/dist/index.d.cts
CHANGED
|
@@ -276,10 +276,12 @@ declare const contentTypes: {
|
|
|
276
276
|
};
|
|
277
277
|
type ContentType = keyof typeof contentTypes;
|
|
278
278
|
|
|
279
|
-
declare class DependsOnMethod extends
|
|
280
|
-
|
|
281
|
-
readonly entries: ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
279
|
+
declare class DependsOnMethod extends Routable {
|
|
280
|
+
#private;
|
|
282
281
|
constructor(endpoints: Partial<Record<Method, AbstractEndpoint>>);
|
|
282
|
+
/** @desc [method, endpoint, siblingMethods] */
|
|
283
|
+
get entries(): ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
284
|
+
deprecated(): this;
|
|
283
285
|
}
|
|
284
286
|
|
|
285
287
|
type OriginalStatic = typeof express__default.static;
|
|
@@ -374,7 +376,9 @@ interface Routing {
|
|
|
374
376
|
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
|
|
375
377
|
}
|
|
376
378
|
|
|
377
|
-
declare abstract class
|
|
379
|
+
declare abstract class Routable {
|
|
380
|
+
/** @desc Marks the route as deprecated (makes a copy of the endpoint) */
|
|
381
|
+
abstract deprecated(): this;
|
|
378
382
|
/** @desc Enables nested routes within the path assigned to the subject */
|
|
379
383
|
nest(routing: Routing): Routing;
|
|
380
384
|
}
|
|
@@ -386,7 +390,7 @@ type Handler<IN, OUT, OPT> = (params: {
|
|
|
386
390
|
}) => Promise<OUT>;
|
|
387
391
|
type DescriptionVariant = "short" | "long";
|
|
388
392
|
type IOVariant = "input" | "output";
|
|
389
|
-
declare abstract class AbstractEndpoint extends
|
|
393
|
+
declare abstract class AbstractEndpoint extends Routable {
|
|
390
394
|
abstract execute(params: {
|
|
391
395
|
request: Request;
|
|
392
396
|
response: Response;
|
|
@@ -402,10 +406,12 @@ declare abstract class AbstractEndpoint extends Nesting {
|
|
|
402
406
|
abstract getTags(): ReadonlyArray<string>;
|
|
403
407
|
abstract getOperationId(method: Method): string | undefined;
|
|
404
408
|
abstract getRequestType(): ContentType;
|
|
409
|
+
abstract get isDeprecated(): boolean;
|
|
405
410
|
}
|
|
406
411
|
declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends FlatObject> extends AbstractEndpoint {
|
|
407
412
|
#private;
|
|
408
|
-
constructor(
|
|
413
|
+
constructor(def: {
|
|
414
|
+
deprecated?: boolean;
|
|
409
415
|
middlewares?: AbstractMiddleware[];
|
|
410
416
|
inputSchema: IN;
|
|
411
417
|
outputSchema: OUT;
|
|
@@ -418,11 +424,13 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
418
424
|
scopes?: string[];
|
|
419
425
|
tags?: string[];
|
|
420
426
|
});
|
|
427
|
+
deprecated(): this;
|
|
428
|
+
get isDeprecated(): boolean;
|
|
421
429
|
getDescription(variant: DescriptionVariant): string | undefined;
|
|
422
|
-
getMethods():
|
|
430
|
+
getMethods(): Readonly<("get" | "post" | "put" | "delete" | "patch")[] | undefined>;
|
|
423
431
|
getSchema(variant: "input"): IN;
|
|
424
432
|
getSchema(variant: "output"): OUT;
|
|
425
|
-
getRequestType(): "
|
|
433
|
+
getRequestType(): "json" | "upload" | "raw";
|
|
426
434
|
getResponses(variant: ResponseVariant): readonly NormalizedResponse[];
|
|
427
435
|
getSecurity(): LogicalContainer<Security>[];
|
|
428
436
|
getScopes(): readonly string[];
|
|
@@ -606,7 +614,7 @@ interface TagOverrides {
|
|
|
606
614
|
}
|
|
607
615
|
type Tag = NoNever<keyof TagOverrides, string>;
|
|
608
616
|
declare const getMessageFromError: (error: Error) => string;
|
|
609
|
-
declare const getExamples: <T extends z.
|
|
617
|
+
declare const getExamples: <T extends z.ZodType, V extends "original" | "parsed" | undefined>({ schema, variant, validate, pullProps, }: {
|
|
610
618
|
schema: T;
|
|
611
619
|
/**
|
|
612
620
|
* @desc examples variant: original or parsed
|
|
@@ -633,6 +641,7 @@ interface Metadata {
|
|
|
633
641
|
/** @override ZodDefault::_def.defaultValue() in depictDefault */
|
|
634
642
|
defaultLabel?: string;
|
|
635
643
|
brand?: string | number | symbol;
|
|
644
|
+
isDeprecated?: boolean;
|
|
636
645
|
}
|
|
637
646
|
|
|
638
647
|
/**
|
|
@@ -659,6 +668,7 @@ declare module "zod" {
|
|
|
659
668
|
interface ZodType {
|
|
660
669
|
/** @desc Add an example value (before any transformations, can be called multiple times) */
|
|
661
670
|
example(example: this["_input"]): this;
|
|
671
|
+
deprecated(): this;
|
|
662
672
|
}
|
|
663
673
|
interface ZodDefault<T extends z.ZodTypeAny> {
|
|
664
674
|
/** @desc Change the default value in the generated Documentation to a label */
|
|
@@ -683,6 +693,7 @@ interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN
|
|
|
683
693
|
method?: Method | [Method, ...Method[]];
|
|
684
694
|
scope?: SCO | SCO[];
|
|
685
695
|
tag?: Tag | Tag[];
|
|
696
|
+
deprecated?: boolean;
|
|
686
697
|
}
|
|
687
698
|
declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT extends FlatObject = EmptyObject, SCO extends string = string> {
|
|
688
699
|
#private;
|
|
@@ -696,7 +707,7 @@ declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT e
|
|
|
696
707
|
} | undefined) => EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
697
708
|
addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
698
709
|
addOptions<AOUT extends FlatObject>(getOptions: () => Promise<AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
699
|
-
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input,
|
|
710
|
+
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
|
|
700
711
|
/** @desc shorthand for returning {} while having output schema z.object({}) */
|
|
701
712
|
buildVoid<BIN extends IOSchema = EmptySchema>({ handler, ...rest }: Omit<BuildProps<BIN, z.ZodVoid, IN, OUT, SCO>, "output">): Endpoint<z.ZodIntersection<IN, BIN>, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, OUT>;
|
|
702
713
|
}
|
|
@@ -933,11 +944,15 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
933
944
|
type Typeable = ts.TypeNode | ts.Identifier | string | ts.KeywordTypeSyntaxKind;
|
|
934
945
|
|
|
935
946
|
type IOKind = "input" | "response" | ResponseVariant | "encoded";
|
|
947
|
+
type Store = Record<IOKind, ts.TypeNode>;
|
|
936
948
|
declare abstract class IntegrationBase {
|
|
937
949
|
private readonly serverUrl;
|
|
938
950
|
protected paths: Set<string>;
|
|
939
951
|
protected tags: Map<string, readonly string[]>;
|
|
940
|
-
protected registry: Map<string,
|
|
952
|
+
protected registry: Map<string, {
|
|
953
|
+
store: Store;
|
|
954
|
+
isDeprecated: boolean;
|
|
955
|
+
}>;
|
|
941
956
|
protected ids: {
|
|
942
957
|
pathType: ts.Identifier;
|
|
943
958
|
implementationType: ts.Identifier;
|
package/dist/index.d.ts
CHANGED
|
@@ -276,10 +276,12 @@ declare const contentTypes: {
|
|
|
276
276
|
};
|
|
277
277
|
type ContentType = keyof typeof contentTypes;
|
|
278
278
|
|
|
279
|
-
declare class DependsOnMethod extends
|
|
280
|
-
|
|
281
|
-
readonly entries: ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
279
|
+
declare class DependsOnMethod extends Routable {
|
|
280
|
+
#private;
|
|
282
281
|
constructor(endpoints: Partial<Record<Method, AbstractEndpoint>>);
|
|
282
|
+
/** @desc [method, endpoint, siblingMethods] */
|
|
283
|
+
get entries(): ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
284
|
+
deprecated(): this;
|
|
283
285
|
}
|
|
284
286
|
|
|
285
287
|
type OriginalStatic = typeof express__default.static;
|
|
@@ -374,7 +376,9 @@ interface Routing {
|
|
|
374
376
|
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
|
|
375
377
|
}
|
|
376
378
|
|
|
377
|
-
declare abstract class
|
|
379
|
+
declare abstract class Routable {
|
|
380
|
+
/** @desc Marks the route as deprecated (makes a copy of the endpoint) */
|
|
381
|
+
abstract deprecated(): this;
|
|
378
382
|
/** @desc Enables nested routes within the path assigned to the subject */
|
|
379
383
|
nest(routing: Routing): Routing;
|
|
380
384
|
}
|
|
@@ -386,7 +390,7 @@ type Handler<IN, OUT, OPT> = (params: {
|
|
|
386
390
|
}) => Promise<OUT>;
|
|
387
391
|
type DescriptionVariant = "short" | "long";
|
|
388
392
|
type IOVariant = "input" | "output";
|
|
389
|
-
declare abstract class AbstractEndpoint extends
|
|
393
|
+
declare abstract class AbstractEndpoint extends Routable {
|
|
390
394
|
abstract execute(params: {
|
|
391
395
|
request: Request;
|
|
392
396
|
response: Response;
|
|
@@ -402,10 +406,12 @@ declare abstract class AbstractEndpoint extends Nesting {
|
|
|
402
406
|
abstract getTags(): ReadonlyArray<string>;
|
|
403
407
|
abstract getOperationId(method: Method): string | undefined;
|
|
404
408
|
abstract getRequestType(): ContentType;
|
|
409
|
+
abstract get isDeprecated(): boolean;
|
|
405
410
|
}
|
|
406
411
|
declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends FlatObject> extends AbstractEndpoint {
|
|
407
412
|
#private;
|
|
408
|
-
constructor(
|
|
413
|
+
constructor(def: {
|
|
414
|
+
deprecated?: boolean;
|
|
409
415
|
middlewares?: AbstractMiddleware[];
|
|
410
416
|
inputSchema: IN;
|
|
411
417
|
outputSchema: OUT;
|
|
@@ -418,11 +424,13 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
418
424
|
scopes?: string[];
|
|
419
425
|
tags?: string[];
|
|
420
426
|
});
|
|
427
|
+
deprecated(): this;
|
|
428
|
+
get isDeprecated(): boolean;
|
|
421
429
|
getDescription(variant: DescriptionVariant): string | undefined;
|
|
422
|
-
getMethods():
|
|
430
|
+
getMethods(): Readonly<("get" | "post" | "put" | "delete" | "patch")[] | undefined>;
|
|
423
431
|
getSchema(variant: "input"): IN;
|
|
424
432
|
getSchema(variant: "output"): OUT;
|
|
425
|
-
getRequestType(): "
|
|
433
|
+
getRequestType(): "json" | "upload" | "raw";
|
|
426
434
|
getResponses(variant: ResponseVariant): readonly NormalizedResponse[];
|
|
427
435
|
getSecurity(): LogicalContainer<Security>[];
|
|
428
436
|
getScopes(): readonly string[];
|
|
@@ -606,7 +614,7 @@ interface TagOverrides {
|
|
|
606
614
|
}
|
|
607
615
|
type Tag = NoNever<keyof TagOverrides, string>;
|
|
608
616
|
declare const getMessageFromError: (error: Error) => string;
|
|
609
|
-
declare const getExamples: <T extends z.
|
|
617
|
+
declare const getExamples: <T extends z.ZodType, V extends "original" | "parsed" | undefined>({ schema, variant, validate, pullProps, }: {
|
|
610
618
|
schema: T;
|
|
611
619
|
/**
|
|
612
620
|
* @desc examples variant: original or parsed
|
|
@@ -633,6 +641,7 @@ interface Metadata {
|
|
|
633
641
|
/** @override ZodDefault::_def.defaultValue() in depictDefault */
|
|
634
642
|
defaultLabel?: string;
|
|
635
643
|
brand?: string | number | symbol;
|
|
644
|
+
isDeprecated?: boolean;
|
|
636
645
|
}
|
|
637
646
|
|
|
638
647
|
/**
|
|
@@ -659,6 +668,7 @@ declare module "zod" {
|
|
|
659
668
|
interface ZodType {
|
|
660
669
|
/** @desc Add an example value (before any transformations, can be called multiple times) */
|
|
661
670
|
example(example: this["_input"]): this;
|
|
671
|
+
deprecated(): this;
|
|
662
672
|
}
|
|
663
673
|
interface ZodDefault<T extends z.ZodTypeAny> {
|
|
664
674
|
/** @desc Change the default value in the generated Documentation to a label */
|
|
@@ -683,6 +693,7 @@ interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN
|
|
|
683
693
|
method?: Method | [Method, ...Method[]];
|
|
684
694
|
scope?: SCO | SCO[];
|
|
685
695
|
tag?: Tag | Tag[];
|
|
696
|
+
deprecated?: boolean;
|
|
686
697
|
}
|
|
687
698
|
declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT extends FlatObject = EmptyObject, SCO extends string = string> {
|
|
688
699
|
#private;
|
|
@@ -696,7 +707,7 @@ declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT e
|
|
|
696
707
|
} | undefined) => EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
697
708
|
addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
698
709
|
addOptions<AOUT extends FlatObject>(getOptions: () => Promise<AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
699
|
-
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input,
|
|
710
|
+
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
|
|
700
711
|
/** @desc shorthand for returning {} while having output schema z.object({}) */
|
|
701
712
|
buildVoid<BIN extends IOSchema = EmptySchema>({ handler, ...rest }: Omit<BuildProps<BIN, z.ZodVoid, IN, OUT, SCO>, "output">): Endpoint<z.ZodIntersection<IN, BIN>, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, OUT>;
|
|
702
713
|
}
|
|
@@ -933,11 +944,15 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
933
944
|
type Typeable = ts.TypeNode | ts.Identifier | string | ts.KeywordTypeSyntaxKind;
|
|
934
945
|
|
|
935
946
|
type IOKind = "input" | "response" | ResponseVariant | "encoded";
|
|
947
|
+
type Store = Record<IOKind, ts.TypeNode>;
|
|
936
948
|
declare abstract class IntegrationBase {
|
|
937
949
|
private readonly serverUrl;
|
|
938
950
|
protected paths: Set<string>;
|
|
939
951
|
protected tags: Map<string, readonly string[]>;
|
|
940
|
-
protected registry: Map<string,
|
|
952
|
+
protected registry: Map<string, {
|
|
953
|
+
store: Store;
|
|
954
|
+
isDeprecated: boolean;
|
|
955
|
+
}>;
|
|
941
956
|
protected ids: {
|
|
942
957
|
pathType: ts.Identifier;
|
|
943
958
|
implementationType: ts.Identifier;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{clone as
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:an(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Er}from"zod";var zt=class{},q=class extends zt{#e;#t;#r;constructor({input:t=Er.object({}),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 Er.ZodError?new _(o):o}}},Te=class extends q{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Oe=class{nest(t){return Object.assign(t,{"":this})}};var Ne=class extends Oe{},ot=class extends Ne{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:m,shortDescription:f}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:m,short:f},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Rr(r)?"upload":Pr(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof zr.ZodError?new oe(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof Te))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof zr.ZodError?new _(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){rt({...r,error:new J(W(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Pt(t),a={},c=null,d=null,p=_e(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(m){d=W(m)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};import{z as de}from"zod";var Ir=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>fr(s,n),o)},K=e=>e instanceof de.ZodObject?e:e instanceof de.ZodBranded?K(e.unwrap()):e instanceof de.ZodUnion||e instanceof de.ZodDiscriminatedUnion?e.options.map(t=>K(t)).reduce((t,r)=>t.merge(r.partial()),de.object({})):e instanceof de.ZodEffects?K(e._def.schema):e instanceof de.ZodPipeline?K(e._def.in):K(e._def.left).merge(K(e._def.right));import{z as B}from"zod";var Re={positive:200,negative:400},Pe=Object.keys(Re);var It=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},me=class extends It{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Et(this.#e,{variant:"positive",args:[t],statusCodes:[Re.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Et(this.#t,{variant:"negative",args:[],statusCodes:[Re.negative],mimeTypes:[E.json]})}},Le=new me({positive:e=>{let t=Y({schema:e,pullProps:!0}),r=B.object({status:B.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:B.object({status:B.literal("error"),error:B.object({message:B.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Se(e);return je(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ce(a)}})}n.status(Re.positive).json({status:"success",data:r})}}),vt=new me({positive:e=>{let t=Y({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof B.ZodArray?e.shape.items:B.array(B.any());return t.reduce((o,n)=>ie(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:B.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Se(r);return je(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ce(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Re.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var le=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Te(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new q({handler:t})),this.resultHandler)}build({input:t=vr.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:m,resultHandler:f}=this,x=typeof p=="string"?[p]:p,y=typeof a=="function"?a:()=>a,T=typeof c=="string"?[c]:c||[],S=typeof d=="string"?[d]:d||[];return new ot({handler:r,middlewares:m,outputSchema:o,resultHandler:f,scopes:T,tags:S,methods:x,getOperationId:y,description:n,shortDescription:s,inputSchema:Ir(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:vr.object({}),handler:async o=>(await t(o),{})})}},pn=new le(Le),cn=new le(vt);import hn from"ansis";import{inspect as xn}from"node:util";import{performance as Nr}from"node:perf_hooks";import{blue as dn,green as mn,hex as ln,red as un,cyanBright as yn}from"ansis";import{memoizeWith as fn}from"ramda";var Zt={debug:dn,info:mn,warn:ln("#FFA500"),error:un,ctx:yn},nt={debug:10,info:20,warn:30,error:40},Zr=e=>ie(e)&&Object.keys(nt).some(t=>t in e),kr=e=>e in nt,Cr=(e,t)=>nt[e]<nt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ae=fn((e,t)=>`${e}${t}`,gn),jr=e=>e<1e-6?Ae("nanosecond",3).format(e/1e-6):e<.001?Ae("nanosecond").format(e/1e-6):e<1?Ae("microsecond").format(e/.001):e<1e3?Ae("millisecond").format(e):e<6e4?Ae("second",2).format(e/1e3):Ae("minute",2).format(e/6e4);var Me=class e{config;constructor({color:t=hn.isSupported(),level:r=he()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return xn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Cr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Zt.ctx(s):s),d.push(c?`${Zt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.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})}get ctx(){return this.config.ctx}profile(t){let r=Nr.now();return()=>{let o=Nr.now()-r,{message:n,severity:s="debug",formatter:a=jr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import{keys as bn,reject as Sn,equals as Tn}from"ramda";var Ue=class extends Oe{entries;constructor(t){super();let r=[],o=bn(t);for(let n of o){let s=t[n];s&&r.push([n,s,Sn(Tn(n),o)])}this.entries=Object.freeze(r)}};import On from"express";var He=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,On.static(...this.params))}};import Ct from"express";import kn from"node:http";import Cn from"node:https";var we=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ze(e)};import Pn from"http-errors";import{tryCatch as Rn}from"ramda";var st=class{constructor(t){this.logger=t;this.#e=Rn(Ar)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Pe){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(E.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=Ve(t);if(s.length===0)return;let a=n?.shape||K(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Lr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new ge(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Ee=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Lr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Ne){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof He)r&&s.apply(n,r);else if(s instanceof Ue)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new ge(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Lr(s,n))}};var An=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=Pn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new st(t()),a=new Map;if(Ee({routing:o,onEndpoint:(d,p,m,f)=>{he()||(s?.checkJsonCompat(d,{path:p,method:m}),s?.checkPathParams(p,d,{method:m}));let x=n?.[d.getRequestType()]||[],y=async(T,S)=>{let k=t(T);if(r.cors){let A={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[m,...f||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},z=typeof r.cors=="function"?await r.cors({request:T,endpoint:d,logger:k,defaultHeaders:A}):A;for(let j in z)S.set(j,z[j])}return d.execute({request:T,response:S,logger:k,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...x,y),a.get(p)?.push("options"))),a.get(p)?.push(m),e[m](p,...x,y)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,An(p))};import qr,{isHttpError as En}from"http-errors";import{setInterval as wn}from"node:timers/promises";var Mr=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",Ur=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Hr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Kr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Dr=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,s=p=>void n.delete(p.destroy()),a=p=>void(Mr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let m of["connection","secureConnection"])p.on(m,c);let d=async()=>{for(let p of e)p.on("request",Kr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Hr(p)||Ur(p))&&a(p);for await(let p of wn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Dr))};return{sockets:n,shutdown:()=>o??=d()}};var Br=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:En(r)?r:qr(400,W(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),$r=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=qr(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){rt({response:o,logger:s,error:new J(W(a),n)})}},zn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},In=e=>({log:e.debug.bind(e)}),Vr=async({getLogger:e,config:t})=>{let r=await we("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let m=e(c);try{await n?.({request:c,logger:m})}catch(f){return p(f)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:In(m)})(c,d,p)}),o&&a.push(zn(o)),a},_r=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Gr=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},Jr=e=>t=>t?.res?.locals[g]?.logger||e,Wr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
import{clone as hr,fromPairs as qo,map as Bo,pipe as $o,toPairs as _o,pair as Vo}from"ramda";import{z as xe}from"zod";import{chain as fr,memoizeWith as No,objOf as Lo,xprod as Mo}from"ramda";import{z as yr}from"zod";var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var ge=class extends Error{name="RoutingError"},D=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Ve=class extends Error{name="IOSchemaError"},oe=class extends Ve{constructor(r){super(ne(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Ve{constructor(r){super(ne(r),{cause:r});this.cause=r}name="InputValidationError"},W=class extends Error{constructor(r,o){super(ne(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ce=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Rt=/:([A-Za-z0-9_]+)/g,Ge=e=>e.match(Rt)?.map(t=>t.slice(1))||[],Uo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Pt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Do=["body","query","params"],At=e=>e.method.toLowerCase(),Je=(e,t={})=>{let r=At(e);return r==="options"?{}:(t[r]||Pt[r]||Do).filter(o=>o==="files"?Uo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},Y=e=>e instanceof Error?e:new Error(String(e)),ne=e=>e instanceof yr.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof oe?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Ho=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return se(t,(n[y]?.examples||[]).map(Lo(r)),([s,a])=>({...s,...a}))},[]),Q=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof yr.ZodObject&&(n=Ho(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},se=(e,t,r)=>e.length&&t.length?Mo(e,t).map(r):e.concat(t),je=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,wt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),X=(...e)=>{let t=fr(o=>o.split(/[^A-Z0-9]/gi),e);return fr(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(wt).join("")},We=(e,t)=>{try{return typeof e.parse(t)}catch{return}},ie=e=>typeof e=="object"&&e!==null,he=No(()=>"static",()=>process.env.NODE_ENV==="production");import{clone as Ko,mergeDeepRight as Fo}from"ramda";var y=Symbol.for("express-zod-api"),Ne=e=>{let t=e.describe(e.description);return t._def[y]=Ko(t._def[y])||{examples:[]},t},gr=(e,t)=>{if(!(y in e._def))return t;let r=Ne(t);return r._def[y].examples=se(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Fo({...o},{...n}):n),r};var Go=function(e){let t=Ne(this);return t._def[y].examples.push(e),t},Jo=function(){let e=Ne(this);return e._def[y].isDeprecated=!0,e},Wo=function(e){let t=Ne(this);return t._def[y].defaultLabel=e,t},Yo=function(e){return new xe.ZodBranded({typeName:xe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...hr(this._def[y]),brand:e}})},Qo=function(e){let t=typeof e=="function"?e:$o(_o,Bo(([n,s])=>Vo(e[String(n)]||n,s)),qo),r=t(hr(this.shape)),o=xe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(xe.ZodType.prototype,{example:{get(){return Go.bind(this)}},deprecated:{get(){return Jo.bind(this)}},brand:{set(){},get(){return Yo.bind(this)}}}),Object.defineProperty(xe.ZodDefault.prototype,"label",{get(){return Wo.bind(this)}}),Object.defineProperty(xe.ZodObject.prototype,"remap",{get(){return Qo.bind(this)}}));function Xo(e){return e}import{z as vr}from"zod";import{z as Ir}from"zod";import{fail as C}from"node:assert/strict";import{z as Le}from"zod";var Ye=e=>!isNaN(e.getTime());var ae=Symbol("DateIn"),xr=()=>Le.union([Le.string().date(),Le.string().datetime(),Le.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Le.date().refine(Ye)).brand(ae);import{z as en}from"zod";var pe=Symbol("DateOut"),br=()=>en.date().refine(Ye).transform(e=>e.toISOString()).brand(pe);import{z as Qe}from"zod";var F=Symbol("File"),Sr=Qe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),tn={buffer:()=>Sr.brand(F),string:()=>Qe.string().brand(F),binary:()=>Sr.or(Qe.string()).brand(F),base64:()=>Qe.string().base64().brand(F)};function Xe(e){return tn[e||"string"]()}import{z as rn}from"zod";var ee=Symbol("Raw"),Tr=(e={})=>rn.object({raw:Xe("buffer")}).extend(e).brand(ee);import{z as on}from"zod";var be=Symbol("Upload"),Or=()=>on.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(be);var Rr=(e,{next:t})=>e.options.some(t),nn=({_def:e},{next:t})=>[e.left,e.right].some(t),et=(e,{next:t})=>t(e.unwrap()),Et={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Rr,ZodDiscriminatedUnion:Rr,ZodIntersection:nn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:et,ZodNullable:et,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},tt=(e,{condition:t,rules:r=Et,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>tt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Pr=e=>tt(e,{condition:t=>t._def[y]?.brand===be}),Ar=e=>tt(e,{condition:t=>t._def[y]?.brand===ee,maxDepth:3}),wr=(e,t)=>{let r=new WeakSet;return tt(e,{maxDepth:300,rules:{...Et,ZodBranded:et,ZodReadonly:et,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:Et.ZodEffects}[t],ZodNaN:()=>C("z.nan()"),ZodSymbol:()=>C("z.symbol()"),ZodFunction:()=>C("z.function()"),ZodMap:()=>C("z.map()"),ZodSet:()=>C("z.set()"),ZodBigInt:()=>C("z.bigint()"),ZodVoid:()=>C("z.void()"),ZodPromise:()=>C("z.promise()"),ZodNever:()=>C("z.never()"),ZodDate:()=>t==="in"&&C("z.date()"),[pe]:()=>t==="in"&&C("ez.dateOut()"),[ae]:()=>t==="out"&&C("ez.dateIn()"),[ee]:()=>t==="out"&&C("ez.raw()"),[be]:()=>t==="out"&&C("ez.upload()"),[F]:()=>!1}})};import pn,{isHttpError as cn}from"http-errors";import Er,{isHttpError as sn}from"http-errors";import{z as an}from"zod";var zt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof an.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new W(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},Me=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Se=e=>sn(e)?e:Er(e instanceof G?400:500,ne(e),{cause:e.cause||e}),ce=e=>he()&&!e.expose?Er(e.statusCode).message:e.message;var rt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ce(pn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:cn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as zr}from"zod";var It=class{},q=class extends It{#e;#t;#r;constructor({input:t=zr.object({}),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 zr.ZodError?new G(o):o}}},Te=class extends q{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Oe=class{nest(t){return Object.assign(t,{"":this})}};var Ue=class extends Oe{},ot=class e extends Ue{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Pr(this.#e.inputSchema)?"upload":Ar(this.#e.inputSchema)?"raw":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Ir.ZodError?new oe(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Te))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Ir.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){rt({...r,error:new W(Y(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=At(t),a={},c=null,d=null,p=Je(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(m){d=Y(m)}await this.#s({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};import{z as de}from"zod";var Zr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>gr(s,n),o)},H=e=>e instanceof de.ZodObject?e:e instanceof de.ZodBranded?H(e.unwrap()):e instanceof de.ZodUnion||e instanceof de.ZodDiscriminatedUnion?e.options.map(t=>H(t)).reduce((t,r)=>t.merge(r.partial()),de.object({})):e instanceof de.ZodEffects?H(e._def.schema):e instanceof de.ZodPipeline?H(e._def.in):H(e._def.left).merge(H(e._def.right));import{z as B}from"zod";var Re={positive:200,negative:400},Pe=Object.keys(Re);var Zt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},me=class extends Zt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return zt(this.#e,{variant:"positive",args:[t],statusCodes:[Re.positive],mimeTypes:[E.json]})}getNegativeResponse(){return zt(this.#t,{variant:"negative",args:[],statusCodes:[Re.negative],mimeTypes:[E.json]})}},De=new me({positive:e=>{let t=Q({schema:e,pullProps:!0}),r=B.object({status:B.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:B.object({status:B.literal("error"),error:B.object({message:B.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Se(e);return Me(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ce(a)}})}n.status(Re.positive).json({status:"success",data:r})}}),vt=new me({positive:e=>{let t=Q({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof B.ZodArray?e.shape.items:B.array(B.any());return t.reduce((o,n)=>ie(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:B.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Se(r);return Me(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ce(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Re.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var le=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Te(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new q({handler:t})),this.resultHandler)}build({input:t=vr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:d,resultHandler:p}=this,m=typeof a=="string"?[a]:a,x=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],f=typeof s=="string"?[s]:s||[];return new ot({...c,middlewares:d,outputSchema:r,resultHandler:p,scopes:b,tags:f,methods:m,getOperationId:x,inputSchema:Zr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:vr.object({}),handler:async o=>(await t(o),{})})}},dn=new le(De),mn=new le(vt);import bn from"ansis";import{inspect as Sn}from"node:util";import{performance as Lr}from"node:perf_hooks";import{blue as ln,green as un,hex as fn,red as yn,cyanBright as gn}from"ansis";import{memoizeWith as hn}from"ramda";var kt={debug:ln,info:un,warn:fn("#FFA500"),error:yn,ctx:gn},nt={debug:10,info:20,warn:30,error:40},kr=e=>ie(e)&&Object.keys(nt).some(t=>t in e),Cr=e=>e in nt,jr=(e,t)=>nt[e]<nt[t],xn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ae=hn((e,t)=>`${e}${t}`,xn),Nr=e=>e<1e-6?Ae("nanosecond",3).format(e/1e-6):e<.001?Ae("nanosecond").format(e/1e-6):e<1?Ae("microsecond").format(e/.001):e<1e3?Ae("millisecond").format(e):e<6e4?Ae("second",2).format(e/1e3):Ae("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=bn.isSupported(),level:r=he()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return Sn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||jr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?kt.ctx(s):s),d.push(c?`${kt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.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})}get ctx(){return this.config.ctx}profile(t){let r=Lr.now();return()=>{let o=Lr.now()-r,{message:n,severity:s="debug",formatter:a=Nr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import{keys as Tn,reject as On,equals as Rn}from"ramda";var Ke=class e extends Oe{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Tn(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,On(Rn(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import Pn from"express";var Fe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Pn.static(...this.params))}};import jt from"express";import jn from"node:http";import Nn from"node:https";var we=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ce(e)};import wn from"http-errors";import{tryCatch as An}from"ramda";var st=class{constructor(t){this.logger=t;this.#e=An(wr)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Pe){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(E.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=Ge(t);if(s.length===0)return;let a=n?.shape||H(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Mr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new ge(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Ee=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Mr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Ue){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Fe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new ge(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Mr(s,n))}};var En=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=wn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Ct=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new st(t()),a=new Map;if(Ee({routing:o,onEndpoint:(d,p,m,x)=>{he()||(s?.checkJsonCompat(d,{path:p,method:m}),s?.checkPathParams(p,d,{method:m}));let b=n?.[d.getRequestType()]||[],f=async(P,R)=>{let v=t(P);if(r.cors){let z={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[m,...x||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},A=typeof r.cors=="function"?await r.cors({request:P,endpoint:d,logger:v,defaultHeaders:z}):z;for(let I in A)R.set(I,A[I])}return d.execute({request:P,response:R,logger:v,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...b,f),a.get(p)?.push("options"))),a.get(p)?.push(m),e[m](p,...b,f)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,En(p))};import Br,{isHttpError as In}from"http-errors";import{setInterval as zn}from"node:timers/promises";var Ur=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",Dr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Hr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Kr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Fr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var qr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Ur(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let m of["connection","secureConnection"])p.on(m,c);let d=async()=>{for(let p of e)p.on("request",Kr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Hr(p)||Dr(p))&&a(p);for await(let p of zn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Fr))};return{sockets:n,shutdown:()=>o??=d()}};var $r=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:In(r)?r:Br(400,Y(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),_r=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Br(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){rt({response:o,logger:s,error:new W(Y(a),n)})}},Zn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},vn=e=>({log:e.debug.bind(e)}),Vr=async({getLogger:e,config:t})=>{let r=await we("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let m=e(c);try{await n?.({request:c,logger:m})}catch(x){return p(x)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:vn(m)})(c,d,p)}),o&&a.push(Zn(o)),a},Gr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Jr=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[y]={logger:s}),n()},Wr=e=>t=>t?.res?.locals[y]?.logger||e,Yr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),Qr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=qr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as kn,hex as Xr,italic as it,whiteBright as Cn}from"ansis";var eo=e=>{if(e.columns<132)return;let t=it("Proudly supports transgender community.".padStart(109)),r=it("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=it("Thank you for choosing Express Zod API for your project.".padStart(132)),n=it("for Tai".padEnd(20)),s=Xr("#F5A9B8"),a=Xr("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(Cn,5,7).fill(s,7,9).fill(a,9,12).fill(kn,12,13),d=`
|
|
4
4
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
5
5
|
888 d88P 888 d88888 888 Y88b 888
|
|
6
6
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -15,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,m)=>c[m]?c[m](p):p).join(`
|
|
18
|
-
`))};var eo=e=>{e.startupLogo!==!1&&Xr(process.stdout);let t=e.errorHandler||Le,r=Zr(e.logger)?e.logger:new Me(e.logger);r.debug("Running",{build:"v22.8.0 (ESM)",env:process.env.NODE_ENV||"development"}),Wr(r);let o=Gr({logger:r,config:e}),s={getLogger:Jr(r),errorHandler:t},a=$r(s),c=Br(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},jn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=eo(e);return kt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Nn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=eo(e),c=Ct().disable("x-powered-by").use(a);if(e.compression){let x=await we("compression");c.use(x(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Ct.json()],raw:[e.rawParser||Ct.raw(),_r],upload:e.upload?await Vr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),kt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let x=kn.createServer(c);p.push(x),f.push(m(x,e.http.listen))}if(e.https){let x=Cn.createServer(e.https.options,c);p.push(x),f.push(m(x,e.https.listen))}return e.gracefulShutdown&&Yr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(x=>x())}};import{OpenApiBuilder as Vs}from"openapi3-ts/oas31";import{pluck as _s}from"ramda";import{chain as Ln,isEmpty as Mn,map as to,partition as Un,prop as ro,reject as Hn,filter as jt,concat as Nt}from"ramda";var oo=e=>ie(e)&&"or"in e,no=e=>ie(e)&&"and"in e,Lt=e=>!no(e)&&!oo(e),so=e=>{let t=jt(Lt,e),r=Ln(ro("and"),jt(no,e)),[o,n]=Un(Lt,r),s=Nt(t,o),a=jt(oo,e);return to(ro("or"),Nt(a,n)).reduce((d,p)=>se(d,to(m=>Lt(m)?[m]:m.and,p),([m,f])=>Nt(m,f)),Hn(Mn,[s]))};import{isReferenceObject as Ht,isSchemaObject as pt}from"openapi3-ts/oas31";import{concat as Dn,chain as Fn,type as co,filter as mo,fromPairs as ct,has as qn,isNil as Bn,map as Ke,mergeDeepRight as $n,mergeDeepWith as Vn,objOf as _n,omit as dt,pipe as lo,pluck as Gn,reject as Jn,times as Wn,toLower as Yn,union as Qn,when as Xn,xprod as Mt,zip as es}from"ramda";import{z as M}from"zod";var ue=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>ue(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var io=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var ao=50,uo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",ts={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},rs=/^\d{4}-\d{2}-\d{2}$/,os=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,ns=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,yo=e=>e.replace(Ot,t=>`{${t.slice(1)}}`),ss=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),is=({_def:{innerType:e}},{next:t})=>t(e),as=()=>({format:"any"}),ps=({},e)=>{if(e.isResponse)throw new H("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},cs=e=>{let t=e.unwrap();return{type:"string",format:t instanceof M.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ds=({options:e},{next:t})=>({oneOf:e.map(t)}),ms=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ls=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Dn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},us=e=>{let[t,r]=e.filter(pt).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Vn(ls,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Qn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>$n(n,s))),o},ys=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return us(o)}catch{}return{allOf:o}},fs=(e,{next:t})=>t(e.unwrap()),gs=(e,{next:t})=>t(e.unwrap()),hs=(e,{next:t})=>{let r=t(e.unwrap());return pt(r)&&(r.type=go(r)),r},fo=e=>{let t=Yn(co(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},po=e=>({type:fo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),xs=({value:e})=>({type:fo(e),const:e}),bs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&ke(c)?c instanceof M.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=at(e,r)),s.length&&(a.required=s),a},Ss=()=>({type:"null"}),Ts=({},e)=>{if(e.isResponse)throw new H("Please use ez.dateOut() for output.",e);return{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:uo}}},Os=({},e)=>{if(!e.isResponse)throw new H("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:uo}}},Rs=({},e)=>{throw new H(`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)},Ps=()=>({type:"boolean"}),As=()=>({type:"integer",format:"bigint"}),ws=e=>e.every(t=>t instanceof M.ZodLiteral),Es=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof M.ZodEnum||e instanceof M.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=at(M.object(ct(Mt(o,[t]))),r),n.required=o),n}if(e instanceof M.ZodLiteral)return{type:"object",properties:at(M.object({[e.value]:t}),r),required:[e.value]};if(e instanceof M.ZodUnion&&ws(e.options)){let o=Ke(s=>`${s.value}`,e.options),n=ct(Mt(o,[t]));return{type:"object",properties:at(M.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},zs=({_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},Is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),vs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:x,isTime:y,isBase64:T,isNANOID:S,isBase64url:k,isDuration:C,_def:{checks:b}})=>{let A=b.find(v=>v.kind==="regex"),z=b.find(v=>v.kind==="datetime"),j=b.some(v=>v.kind==="jwt"),I=b.find(v=>v.kind==="length"),w={type:"string"},te={"date-time":m,byte:T,base64url:k,date:x,time:y,duration:C,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:S,jwt:j,ip:d,cidr:f,emoji:p};for(let v in te)if(te[v]){w.format=v;break}return I&&([w.minLength,w.maxLength]=[I.value,I.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),x&&(w.pattern=rs.source),y&&(w.pattern=os.source),m&&(w.pattern=ns(z?.offset).source),A&&(w.pattern=A.regex.source),w},Zs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},at=({shape:e},t)=>Ke(t,e),ks=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return ts?.[t]},go=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Cs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&pt(o)){let s=Ge(e,ks(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(M.any())}if(!t&&n.type==="preprocess"&&pt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},js=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ns=(e,{next:t})=>t(e.unwrap()),Ls=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ms=(e,{next:t})=>t(e.unwrap().shape.raw),ho=e=>e.length?ct(es(Wn(t=>`example${t+1}`,e.length),Ke(_n("value"),e))):void 0,xo=(e,t,r=[])=>lo(Y,Ke(Xn(o=>co(o)==="Object",dt(r))),ho)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Us=(e,t)=>lo(Y,mo(qn(t)),Gn(t),ho)({schema:e,variant:"original",validate:!0,pullProps:!0}),Hs=(e,t)=>t?.includes(e)||e.startsWith("x-")||io.includes(e),bo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=K(r),f=Ve(e),x=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=b=>y&&f.includes(b),k=Fn(mo(b=>b.type==="header"),d??[]).map(({name:b})=>b),C=b=>T&&(c?.(b,t,e)??Hs(b,k));return Object.entries(m.shape).reduce((b,[A,z])=>{let j=S(A)?"path":C(A)?"header":x?"query":void 0;if(!j)return b;let I=ue(z,{rules:{...a,...Kt},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),w=s==="components"?n(z,I,Q(p,A)):I;return b.concat({name:A,in:j,required:!z.isOptional(),description:I.description||p,schema:w,examples:Us(m,A)})},[])},Kt={ZodString:vs,ZodNumber:Zs,ZodBigInt:As,ZodBoolean:Ps,ZodNull:Ss,ZodArray:zs,ZodTuple:Is,ZodRecord:Es,ZodObject:bs,ZodLiteral:xs,ZodIntersection:ys,ZodUnion:ds,ZodAny:as,ZodDefault:ss,ZodEnum:po,ZodNativeEnum:po,ZodEffects:Cs,ZodOptional:fs,ZodNullable:hs,ZodDiscriminatedUnion:ms,ZodBranded:Ns,ZodDate:Rs,ZodCatch:is,ZodPipeline:js,ZodLazy:Ls,ZodReadonly:gs,[F]:cs,[be]:ps,[pe]:Os,[ae]:Ts,[X]:Ms},Dt=(e,{isResponse:t,prev:r})=>{if(Ht(r))return{};let{description:o}=e,n=e instanceof M.ZodLazy,s=r.type!==void 0,a=t&&ke(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=go(r)),!n){let p=Y({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Ft=(e,t)=>{throw new H(`Zod type ${e.constructor.name} is unsupported.`,t)},Ut=(e,t)=>{if(Ht(e))return e;let r={...e};return r.properties&&(r.properties=dt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>dt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ut(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ut(o,t))),r},So=e=>Ht(e)?e:dt(["examples"],e),To=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${At(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=So(ue(r,{rules:{...p,...Kt},onEach:Dt,onMissing:Ft,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x={schema:a==="components"?s(r,f,Q(m)):f,examples:xo(r,!0)};return{description:m,content:ct(Mt(o,[x]))}},Ks=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ds=({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}),qs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Bs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),$s=({flows:e={}})=>({type:"oauth2",flows:Ke(t=>({...t,scopes:t.scopes||{}}),Jn(Bn,e))}),Oo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Ks(o):o.type==="input"?Ds(o,t):o.type==="header"?Fs(o):o.type==="cookie"?qs(o):o.type==="openid"?Bs(o):$s(o);return e.map(o=>o.map(r))},Ro=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Po=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=So(Ut(ue(r,{rules:{...a,...Kt},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,Q(d)):p,examples:xo(K(r),!1,c)};return{description:d,content:{[o]:m}}},Ao=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),qt=e=>e.length<=ao?e:e.slice(0,ao-1)+"\u2026";var Bt=class extends Vs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||Q(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new H(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});Ee({routing:t,onEndpoint:(y,T,S)=>{let k={path:T,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(y.getDescription.bind(y)),A=C?qt(C):m&&b?qt(b):void 0,z=r.inputSources?.[S]||Rt[S],j=this.ensureUniqOperationId(T,S,y.getOperationId(S)),I=so(y.getSecurity()),w=bo({...k,inputSources:z,isHeader:p,security:I,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:T,operationId:j})}),te={};for(let G of Pe){let re=y.getResponses(G);for(let{mimeTypes:St,schema:qe,statusCodes:Be}of re)for(let Tt of Be)te[Tt]=To({...k,variant:G,schema:qe,mimeTypes:St,statusCode:Tt,hasMultipleStatusCodes:re.length>1||Be.length>1,description:a?.[`${G}Response`]?.call(null,{method:S,path:T,operationId:j,statusCode:Tt})})}let v=z.includes("body")?Po({...k,paramNames:_s("name",w),schema:y.getSchema("input"),mimeType:E[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:T,operationId:j})}):void 0,bt=Ro(Oo(I,z),y.getScopes(),G=>{let re=this.ensureUniqSecuritySchemaName(G);return this.addSecurityScheme(re,G),re});this.addPath(yo(T),{[S]:{operationId:j,summary:A,description:b,tags:Je(y.getTags()),parameters:Je(w),requestBody:v,security:Je(bt),responses:te}})}}),d&&(this.rootDoc.tags=Ao(d))}};import{createRequest as Gs,createResponse as Js}from"node-mocks-http";var Ws=e=>Gs({...e,headers:{"content-type":E.json,...e?.headers}}),Ys=e=>Js(e),Qs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:kr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},wo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ws(e),s=Ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=Qs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Xs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=wo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},ei=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=wo(o),d=_e(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(W(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Ci}from"ramda";import xt from"typescript";import{z as ji}from"zod";import{map as si}from"ramda";import V from"typescript";var Eo=["get","post","put","delete","patch"];import{map as $t,pair as ti}from"ramda";import l from"typescript";var i=l.factory,mt=[i.createModifier(l.SyntaxKind.ExportKeyword)],ri=[i.createModifier(l.SyntaxKind.AsyncKeyword)],De={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Vt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),_t=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},oi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gt=e=>typeof e=="string"&&oi.test(e)?i.createIdentifier(e):P(e),lt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),ut=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),ze=e=>Object.entries(e).map(([t,r])=>ut(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Jt=(e,t=[])=>i.createConstructorDeclaration(De.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&$t(u,t)):e,Wt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),ye=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,Gt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t));return o?Vt(n,o):n},Yt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Qt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),Z=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&mt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),Xt=(e,t)=>$(e,i.createUnionTypeNode($t(L,t)),{expose:!0}),$=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?mt:void 0,e,n&&or(n),t);return o?Vt(s,o):s},zo=(e,t)=>i.createPropertyDeclaration(De.public,e,void 0,u(t),void 0),er=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(De.public,void 0,e,void 0,o&&or(o),t,n,i.createBlock(r)),tr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(mt,e,r&&or(r),void 0,t),rr=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),yt=e=>u(Promise.name,[e]),ft=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?mt:void 0,e,void 0,void 0,t);return o?Vt(n,o):n},or=e=>(Array.isArray(e)?e.map(t=>ti(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?u(o):void 0,n?u(n):void 0)}),fe=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ri:void 0,void 0,Array.isArray(e)?$t(ut,e):ze(e),void 0,void 0,t),O=e=>e,Fe=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ie=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),gt=(e,t)=>u("Extract",[e,t]),nr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),D=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Io=e=>i.createUnionTypeNode([u(e),yt(e)]),sr=(e,t)=>i.createFunctionTypeNode(void 0,ze(e),u(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),L=e=>i.createLiteralTypeNode(P(e)),ni=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],vo=e=>ni.includes(e.kind);var ht=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Xt("Method",Eo);someOfType=$("SomeOf",D("T",rr("T")),{params:["T"]});requestType=$("Request",rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>Xt(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>ft(this.interfaces[t],Array.from(this.registry).map(([r,o])=>ye(r,o[t])),{expose:!0}));makeEndpointTags=()=>Z("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Gt(t),i.createArrayLiteralExpression(si(P,r))))),{expose:!0});makeImplementationType=()=>$(this.ids.implementationType,sr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Wt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},yt(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>Z(this.ids.parseRequestFn,fe({[this.ids.requestParameter.text]:V.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>Z(this.ids.substituteFn,fe({[this.ids.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Wt},i.createBlock([Z(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],V.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([nr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(lt(":",[this.ids.keyParameter]),fe([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>er(this.ids.provideMethod,ze({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:D(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[Z(Qt(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:yt(D(this.interfaces.response,"K"))});makeClientClass=t=>tr(t,[Jt([ut(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:De.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>lt("?",[Ie(URLSearchParams.name,t)]);makeFetchURL=()=>Ie(URL.name,lt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),Fe(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(E.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),Fe(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=Z(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=Z(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=Z(this.ids.searchParamsConst,Fe(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=Z(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=Z(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(E.json))),m=i.createReturnStatement(R(this.ids.responseConst,Fe(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return Z(this.ids.defaultImplementationConst,fe([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>Jt(ze({request:"K",params:D(this.interfaces.input,"K")}),[Z(Qt(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),Z(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),nr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ie("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ye(O("event"),t)]);makeOnMethod=()=>er(this.ids.onMethod,ze({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:sr({[this.ids.dataParameter.text]:D(gt("R",Yt(this.makeEventNarrow("E"))),L(O("data")))},Io(V.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,fe([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:D("R",L(O("event")))}});makeSubscriptionClass=t=>tr(t,[zo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:gt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u(V.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:gt(D(this.interfaces.positive,"K"),Yt(this.makeEventNarrow(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[Z(this.ids.clientConst,Ie(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(Ie(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),fe(["time"],i.createBlock([])))]};import{chain as ii,eqBy as ir,path as ar,prop as ai,uniqWith as pi}from"ramda";import h from"typescript";import{z as cr}from"zod";var{factory:U}=h,ci={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},pr={name:ar(["name","text"]),type:ar(["type"]),optional:ar(["questionToken"])},di=({value:e})=>L(e),mi=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&ke(a)?a instanceof cr.ZodOptional:a.isOptional();return ye(s,r(a),{isOptional:c&&o,comment:a.description})});return U.createTypeLiteralNode(n)},li=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),ui=({options:e})=>U.createUnionTypeNode(e.map(L)),Zo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(vo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},yi=e=>ci?.[e.kind],fi=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ge(e,yi(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},gi=e=>U.createUnionTypeNode(Object.values(e.enum).map(L)),hi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},xi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),L(null)]),bi=({items:e,_def:{rest:t}},{next:r})=>U.createTupleTypeNode(e.map(r).concat(t===null?[]:U.createRestTypeNode(r(t)))),Si=({keySchema:e,valueSchema:t},{next:r})=>u("Record",[e,t].map(r)),Ti=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=ii(ai("members"),e),o=pi((...n)=>{if(!ir(pr.name,...n))return!1;if(ir(pr.type,...n)&&ir(pr.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},Oi=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ti(o)}catch{}return U.createIntersectionTypeNode(o)},Ri=({_def:e},{next:t})=>t(e.innerType),ee=e=>()=>u(e),Pi=(e,{next:t})=>t(e.unwrap()),Ai=(e,{next:t})=>t(e.unwrap()),wi=({_def:e},{next:t})=>t(e.innerType),Ei=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),zi=()=>L(null),Ii=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),vi=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof cr.ZodString?r:t instanceof cr.ZodUnion?n:o},Zi=(e,{next:t})=>t(e.unwrap().shape.raw),ki={ZodString:ee(h.SyntaxKind.StringKeyword),ZodNumber:ee(h.SyntaxKind.NumberKeyword),ZodBigInt:ee(h.SyntaxKind.BigIntKeyword),ZodBoolean:ee(h.SyntaxKind.BooleanKeyword),ZodAny:ee(h.SyntaxKind.AnyKeyword),ZodUndefined:ee(h.SyntaxKind.UndefinedKeyword),[ae]:ee(h.SyntaxKind.StringKeyword),[pe]:ee(h.SyntaxKind.StringKeyword),ZodNull:zi,ZodArray:li,ZodTuple:bi,ZodRecord:Si,ZodObject:mi,ZodLiteral:di,ZodIntersection:Oi,ZodUnion:Zo,ZodDefault:Ri,ZodEnum:ui,ZodNativeEnum:gi,ZodEffects:fi,ZodOptional:hi,ZodNullable:xi,ZodDiscriminatedUnion:Zo,ZodBranded:Pi,ZodCatch:wi,ZodPipeline:Ei,ZodLazy:Ii,ZodReadonly:Ai,[F]:vi,[X]:Zi},dr=(e,{brandHandling:t,ctx:r})=>ue(e,{rules:{...t,...ki},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var mr=class extends ht{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=L(null);this.aliases.set(t,$(o,n)),this.aliases.set(t,$(o,r()))}return u(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=ji.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},f={brandHandling:r,ctx:{...p,isResponse:!0}};Ee({routing:t,onEndpoint:(y,T,S)=>{let k=Q.bind(null,S,T),C=`${S} ${T}`,b=$(k("input"),dr(y.getSchema("input"),m),{comment:C});this.program.push(b);let A=Pe.reduce((j,I)=>{let w=y.getResponses(I),te=Ci(([bt,{schema:G,mimeTypes:re,statusCodes:St}])=>{let qe=$(k(I,"variant",`${bt+1}`),dr(re?G:d,f),{comment:C});return this.program.push(qe),St.map(Be=>ye(Be,qe.name))},Array.from(w.entries())),v=ft(k(I,"response","variants"),te,{comment:C});return this.program.push(v),Object.assign(j,{[I]:v})},{});this.paths.add(T);let z=L(C);this.registry.set(C,{input:u(b.name),positive:this.someOf(A.positive),negative:this.someOf(A.negative),response:i.createUnionTypeNode([D(this.interfaces.positive,z),D(this.interfaces.negative,z)]),encoded:i.createIntersectionTypeNode([u(A.positive.name),u(A.negative.name)])}),this.tags.set(C,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((n,s)=>
|
|
18
|
+
`))};var to=e=>{e.startupLogo!==!1&&eo(process.stdout);let t=e.errorHandler||De,r=kr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.9.0 (ESM)",env:process.env.NODE_ENV||"development"}),Yr(r);let o=Jr({logger:r,config:e}),s={getLogger:Wr(r),errorHandler:t},a=_r(s),c=$r(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Ln=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=to(e);return Ct({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Mn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=to(e),c=jt().disable("x-powered-by").use(a);if(e.compression){let b=await we("compression");c.use(b(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||jt.json()],raw:[e.rawParser||jt.raw(),Gr],upload:e.upload?await Vr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Ct({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(b,f)=>()=>b.listen(f,()=>r.info("Listening",f)),x=[];if(e.http){let b=jn.createServer(c);p.push(b),x.push(m(b,e.http.listen))}if(e.https){let b=Nn.createServer(e.https.options,c);p.push(b),x.push(m(b,e.https.listen))}return e.gracefulShutdown&&Qr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:x.map(b=>b())}};import{OpenApiBuilder as Gs}from"openapi3-ts/oas31";import{pluck as Js}from"ramda";import{chain as Un,isEmpty as Dn,map as ro,partition as Hn,prop as oo,reject as Kn,filter as Nt,concat as Lt}from"ramda";var no=e=>ie(e)&&"or"in e,so=e=>ie(e)&&"and"in e,Mt=e=>!so(e)&&!no(e),io=e=>{let t=Nt(Mt,e),r=Un(oo("and"),Nt(so,e)),[o,n]=Hn(Mt,r),s=Lt(t,o),a=Nt(no,e);return ro(oo("or"),Lt(a,n)).reduce((d,p)=>se(d,ro(m=>Mt(m)?[m]:m.and,p),([m,x])=>Lt(m,x)),Kn(Dn,[s]))};import{isReferenceObject as Ht,isSchemaObject as pt}from"openapi3-ts/oas31";import{concat as qn,chain as Bn,type as mo,filter as lo,fromPairs as ct,has as $n,isNil as _n,map as qe,mergeDeepRight as Vn,mergeDeepWith as Gn,objOf as Jn,omit as dt,pipe as uo,pluck as Wn,reject as Yn,times as Qn,toLower as Xn,union as es,when as ts,xprod as Ut,zip as rs}from"ramda";import{z as M}from"zod";var ue=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>ue(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var ao=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var po=50,fo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",os={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},ns=/^\d{4}-\d{2}-\d{2}$/,ss=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,is=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,yo=e=>e.replace(Rt,t=>`{${t.slice(1)}}`),as=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),ps=({_def:{innerType:e}},{next:t})=>t(e),cs=()=>({format:"any"}),ds=({},e)=>{if(e.isResponse)throw new D("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},ms=e=>{let t=e.unwrap();return{type:"string",format:t instanceof M.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ls=({options:e},{next:t})=>({oneOf:e.map(t)}),us=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),fs=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return qn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},ys=e=>{let[t,r]=e.filter(pt).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Gn(fs,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=es(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>Vn(n,s))),o},gs=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return ys(o)}catch{}return{allOf:o}},hs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t})=>t(e.unwrap()),bs=(e,{next:t})=>{let r=t(e.unwrap());return pt(r)&&(r.type=ho(r)),r},go=e=>{let t=Xn(mo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},co=e=>({type:go(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Ss=({value:e})=>({type:go(e),const:e}),Ts=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&je(c)?c instanceof M.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=at(e,r)),s.length&&(a.required=s),a},Os=()=>({type:"null"}),Rs=({},e)=>{if(e.isResponse)throw new D("Please use ez.dateOut() for output.",e);return{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:fo}}},Ps=({},e)=>{if(!e.isResponse)throw new D("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:fo}}},As=({},e)=>{throw new D(`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)},ws=()=>({type:"boolean"}),Es=()=>({type:"integer",format:"bigint"}),zs=e=>e.every(t=>t instanceof M.ZodLiteral),Is=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof M.ZodEnum||e instanceof M.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=at(M.object(ct(Ut(o,[t]))),r),n.required=o),n}if(e instanceof M.ZodLiteral)return{type:"object",properties:at(M.object({[e.value]:t}),r),required:[e.value]};if(e instanceof M.ZodUnion&&zs(e.options)){let o=qe(s=>`${s.value}`,e.options),n=ct(Ut(o,[t]));return{type:"object",properties:at(M.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Zs=({_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},vs=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ks=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:x,isDate:b,isTime:f,isBase64:P,isNANOID:R,isBase64url:v,isDuration:V,_def:{checks:g}})=>{let z=g.find(k=>k.kind==="regex"),A=g.find(k=>k.kind==="datetime"),I=g.some(k=>k.kind==="jwt"),N=g.find(k=>k.kind==="length"),w={type:"string"},L={"date-time":m,byte:P,base64url:v,date:b,time:f,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:R,jwt:I,ip:d,cidr:x,emoji:p};for(let k in L)if(L[k]){w.format=k;break}return N&&([w.minLength,w.maxLength]=[N.value,N.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),b&&(w.pattern=ns.source),f&&(w.pattern=ss.source),m&&(w.pattern=is(A?.offset).source),z&&(w.pattern=z.regex.source),w},Cs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(x=>x.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(x=>x.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},at=({shape:e},t)=>qe(t,e),js=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return os?.[t]},ho=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Ns=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&pt(o)){let s=We(e,js(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(M.any())}if(!t&&n.type==="preprocess"&&pt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Ls=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ms=(e,{next:t})=>t(e.unwrap()),Us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ds=(e,{next:t})=>t(e.unwrap().shape.raw),xo=e=>e.length?ct(rs(Qn(t=>`example${t+1}`,e.length),qe(Jn("value"),e))):void 0,bo=(e,t,r=[])=>uo(Q,qe(ts(o=>mo(o)==="Object",dt(r))),xo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Hs=(e,t)=>uo(Q,lo($n(t)),Wn(t),xo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ks=(e,t)=>t?.includes(e)||e.startsWith("x-")||ao.includes(e),So=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=H(r),x=Ge(e),b=o.includes("query"),f=o.includes("params"),P=o.includes("headers"),R=g=>f&&x.includes(g),v=Bn(lo(g=>g.type==="header"),d??[]).map(({name:g})=>g),V=g=>P&&(c?.(g,t,e)??Ks(g,v));return Object.entries(m.shape).reduce((g,[z,A])=>{let I=R(z)?"path":V(z)?"header":b?"query":void 0;if(!I)return g;let N=ue(A,{rules:{...a,...Kt},onEach:Ft,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),w=s==="components"?n(A,N,X(p,z)):N,{_def:L}=A;return g.concat({name:z,in:I,deprecated:L[y]?.isDeprecated,required:!A.isOptional(),description:N.description||p,schema:w,examples:Hs(m,z)})},[])},Kt={ZodString:ks,ZodNumber:Cs,ZodBigInt:Es,ZodBoolean:ws,ZodNull:Os,ZodArray:Zs,ZodTuple:vs,ZodRecord:Is,ZodObject:Ts,ZodLiteral:Ss,ZodIntersection:gs,ZodUnion:ls,ZodAny:cs,ZodDefault:as,ZodEnum:co,ZodNativeEnum:co,ZodEffects:Ns,ZodOptional:hs,ZodNullable:bs,ZodDiscriminatedUnion:us,ZodBranded:Ms,ZodDate:As,ZodCatch:ps,ZodPipeline:Ls,ZodLazy:Us,ZodReadonly:xs,[F]:ms,[be]:ds,[pe]:Ps,[ae]:Rs,[ee]:Ds},Ft=(e,{isResponse:t,prev:r})=>{if(Ht(r))return{};let{description:o,_def:n}=e,s=e instanceof M.ZodLazy,a=r.type!==void 0,c=t&&je(e),d=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),d&&(p.type=ho(r)),!s){let m=Q({schema:e,variant:t?"parsed":"original",validate:!0});m.length&&(p.examples=m.slice())}return p},qt=(e,t)=>{throw new D(`Zod type ${e.constructor.name} is unsupported.`,t)},Dt=(e,t)=>{if(Ht(e))return e;let r={...e};return r.properties&&(r.properties=dt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>dt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Dt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Dt(o,t))),r},To=e=>Ht(e)?e:dt(["examples"],e),Oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${wt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let x=To(ue(r,{rules:{...p,...Kt},onEach:Ft,onMissing:qt,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b={schema:a==="components"?s(r,x,X(m)):x,examples:bo(r,!0)};return{description:m,content:ct(Ut(o,[b]))}},Fs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},qs=({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},Bs=({name:e})=>({type:"apiKey",in:"header",name:e}),$s=({name:e})=>({type:"apiKey",in:"cookie",name:e}),_s=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Vs=({flows:e={}})=>({type:"oauth2",flows:qe(t=>({...t,scopes:t.scopes||{}}),Yn(_n,e))}),Ro=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Fs(o):o.type==="input"?qs(o,t):o.type==="header"?Bs(o):o.type==="cookie"?$s(o):o.type==="openid"?_s(o):Vs(o);return e.map(o=>o.map(r))},Po=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Ao=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=To(Dt(ue(r,{rules:{...a,...Kt},onEach:Ft,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,X(d)):p,examples:bo(H(r),!1,c)};return{description:d,content:{[o]:m}}},wo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Bt=e=>e.length<=po?e:e.slice(0,po-1)+"\u2026",mt=e=>e.length?e.slice():void 0;var $t=class extends Gs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||X(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new D(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:x="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});Ee({routing:t,onEndpoint:(f,P,R)=>{let v={path:P,method:R,endpoint:f,composition:x,brandHandling:c,makeRef:this.makeRef.bind(this)},[V,g]=["short","long"].map(f.getDescription.bind(f)),z=V?Bt(V):m&&g?Bt(g):void 0,A=r.inputSources?.[R]||Pt[R],I=this.ensureUniqOperationId(P,R,f.getOperationId(R)),N=io(f.getSecurity()),w=So({...v,inputSources:A,isHeader:p,security:N,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:R,path:P,operationId:I})}),L={};for(let J of Pe){let re=f.getResponses(J);for(let{mimeTypes:Tt,schema:Ot,statusCodes:ve}of re)for(let ke of ve)L[ke]=Oo({...v,variant:J,schema:Ot,mimeTypes:Tt,statusCode:ke,hasMultipleStatusCodes:re.length>1||ve.length>1,description:a?.[`${J}Response`]?.call(null,{method:R,path:P,operationId:I,statusCode:ke})})}let k=A.includes("body")?Ao({...v,paramNames:Js("name",w),schema:f.getSchema("input"),mimeType:E[f.getRequestType()],description:a?.requestBody?.call(null,{method:R,path:P,operationId:I})}):void 0,St=Po(Ro(N,A),f.getScopes(),J=>{let re=this.ensureUniqSecuritySchemaName(J);return this.addSecurityScheme(re,J),re}),_e={operationId:I,summary:z,description:g,deprecated:f.isDeprecated||void 0,tags:mt(f.getTags()),parameters:mt(w),requestBody:k,security:mt(St),responses:L};this.addPath(yo(P),{[R]:_e})}}),d&&(this.rootDoc.tags=wo(d))}};import{createRequest as Ws,createResponse as Ys}from"node-mocks-http";var Qs=e=>Ws({...e,headers:{"content-type":E.json,...e?.headers}}),Xs=e=>Ys(e),ei=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Cr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Eo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Qs(e),s=Xs({req:n,...t});s.req=t?.req||n,n.res=s;let a=ei(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},ti=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Eo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},ri=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Eo(o),d=Je(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(Y(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Mi}from"ramda";import bt from"typescript";import{z as Ui}from"zod";import{map as ci}from"ramda";import _ from"typescript";var zo=["get","post","put","delete","patch"];import{isNil as oi,map as _t,pair as ni,reject as si}from"ramda";import l from"typescript";var i=l.factory,lt=[i.createModifier(l.SyntaxKind.ExportKeyword)],ii=[i.createModifier(l.SyntaxKind.AsyncKeyword)],Be={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Vt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Gt=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},ai=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Jt=e=>typeof e=="string"&&ai.test(e)?i.createIdentifier(e):O(e),ut=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),ft=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),ze=e=>Object.entries(e).map(([t,r])=>ft(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Wt=(e,t=[])=>i.createConstructorDeclaration(Be.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&_t(u,t)):e,Yt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),fe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,Jt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t)),a=si(oi,[o?"@deprecated":void 0,n]);return a.length?Vt(s,a.join(" ")):s},Qt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Xt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),Z=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&<,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),er=(e,t)=>$(e,i.createUnionTypeNode(_t(j,t)),{expose:!0}),$=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?lt:void 0,e,n&&nr(n),t);return o?Vt(s,o):s},Io=(e,t)=>i.createPropertyDeclaration(Be.public,e,void 0,u(t),void 0),tr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Be.public,void 0,e,void 0,o&&nr(o),t,n,i.createBlock(r)),rr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(lt,e,r&&nr(r),void 0,t),or=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),yt=e=>u(Promise.name,[e]),gt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?lt:void 0,e,void 0,void 0,t);return o?Vt(n,o):n},nr=e=>(Array.isArray(e)?e.map(t=>ni(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?u(o):void 0,n?u(n):void 0)}),ye=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ii:void 0,void 0,Array.isArray(e)?_t(ft,e):ze(e),void 0,void 0,t),S=e=>e,$e=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),T=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ie=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),ht=(e,t)=>u("Extract",[e,t]),sr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),K=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Zo=e=>i.createUnionTypeNode([u(e),yt(e)]),ir=(e,t)=>i.createFunctionTypeNode(void 0,ze(e),u(t)),O=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),j=e=>i.createLiteralTypeNode(O(e)),pi=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],vo=e=>pi.includes(e.kind);var xt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=er("Method",zo);someOfType=$("SomeOf",K("T",or("T")),{params:["T"]});requestType=$("Request",or(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>er(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>gt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>fe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>Z("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Jt(t),i.createArrayLiteralExpression(ci(O,r))))),{expose:!0});makeImplementationType=()=>$(this.ids.implementationType,ir({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Yt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},yt(_.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:_.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>Z(this.ids.parseRequestFn,ye({[this.ids.requestParameter.text]:_.SyntaxKind.StringKeyword},i.createAsExpression(T(this.ids.requestParameter,S("split"))(i.createRegularExpressionLiteral("/ (.+)/"),O(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>Z(this.ids.substituteFn,ye({[this.ids.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Yt},i.createBlock([Z(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],_.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([sr(this.ids.pathParameter,T(this.ids.pathParameter,S("replace"))(ut(":",[this.ids.keyParameter]),ye([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>tr(this.ids.provideMethod,ze({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:K(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[Z(Xt(this.ids.methodParameter,this.ids.pathParameter),T(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(T(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(T(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:yt(K(this.interfaces.response,"K"))});makeClientClass=t=>rr(t,[Wt([ft(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:Be.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>ut("?",[Ie(URLSearchParams.name,t)]);makeFetchURL=()=>Ie(URL.name,ut("",[this.ids.pathParameter],[this.ids.searchParamsConst]),O(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(S("method"),T(this.ids.methodParameter,S("toUpperCase"))()),r=i.createPropertyAssignment(S("headers"),$e(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(O("Content-Type"),O(E.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(S("body"),$e(this.ids.hasBodyConst,T(JSON[Symbol.toStringTag],S("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=Z(this.ids.responseConst,i.createAwaitExpression(T(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=Z(this.ids.hasBodyConst,i.createLogicalNot(T(i.createArrayLiteralExpression([O("get"),O("delete")]),S("includes"))(this.ids.methodParameter))),a=Z(this.ids.searchParamsConst,$e(this.ids.hasBodyConst,O(""),this.makeSearchParams(this.ids.paramsArgument))),c=Z(this.ids.contentTypeConst,T(this.ids.responseConst,S("headers"),S("get"))(O("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(_.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=Z(this.ids.isJsonConst,T(this.ids.contentTypeConst,S("startsWith"))(O(E.json))),m=i.createReturnStatement(T(this.ids.responseConst,$e(this.ids.isJsonConst,O(S("json")),O(S("text"))))());return Z(this.ids.defaultImplementationConst,ye([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>Wt(ze({request:"K",params:K(this.interfaces.input,"K")}),[Z(Xt(this.ids.pathParameter,this.ids.restConst),T(this.ids.substituteFn)(i.createElementAccessExpression(T(this.ids.parseRequestFn)(this.ids.requestParameter),O(1)),this.ids.paramsArgument)),Z(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),sr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ie("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([fe(S("event"),t)]);makeOnMethod=()=>tr(this.ids.onMethod,ze({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:ir({[this.ids.dataParameter.text]:K(ht("R",Qt(this.makeEventNarrow("E"))),j(S("data")))},Zo(_.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(T(i.createThis(),this.ids.sourceProp,S("addEventListener"))(this.ids.eventParameter,ye([this.ids.msgParameter],T(this.ids.handlerParameter)(T(JSON[Symbol.toStringTag],S("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),S("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:K("R",j(S("event")))}});makeSubscriptionClass=t=>rr(t,[Io(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:ht(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u(_.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:ht(K(this.interfaces.positive,"K"),Qt(this.makeEventNarrow(_.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[Z(this.ids.clientConst,Ie(t)),T(this.ids.clientConst,this.ids.provideMethod)(O("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",O("10"))])),T(Ie(r,O("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(O("time"),ye(["time"],i.createBlock([])))]};import{chain as di,eqBy as ar,path as pr,prop as mi,uniqWith as li}from"ramda";import h from"typescript";import{z as dr}from"zod";var{factory:U}=h,ui={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},cr={name:pr(["name","text"]),type:pr(["type"]),optional:pr(["questionToken"])},fi=({value:e})=>j(e),yi=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:d}=a,p=t&&je(a)?a instanceof dr.ZodOptional:a.isOptional();return fe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:d[y]?.isDeprecated})});return U.createTypeLiteralNode(n)},gi=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),hi=({options:e})=>U.createUnionTypeNode(e.map(j)),ko=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(vo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},xi=e=>ui?.[e.kind],bi=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=We(e,xi(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},Si=e=>U.createUnionTypeNode(Object.values(e.enum).map(j)),Ti=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},Oi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),j(null)]),Ri=({items:e,_def:{rest:t}},{next:r})=>U.createTupleTypeNode(e.map(r).concat(t===null?[]:U.createRestTypeNode(r(t)))),Pi=({keySchema:e,valueSchema:t},{next:r})=>u("Record",[e,t].map(r)),Ai=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=di(mi("members"),e),o=li((...n)=>{if(!ar(cr.name,...n))return!1;if(ar(cr.type,...n)&&ar(cr.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},wi=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ai(o)}catch{}return U.createIntersectionTypeNode(o)},Ei=({_def:e},{next:t})=>t(e.innerType),te=e=>()=>u(e),zi=(e,{next:t})=>t(e.unwrap()),Ii=(e,{next:t})=>t(e.unwrap()),Zi=({_def:e},{next:t})=>t(e.innerType),vi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ki=()=>j(null),Ci=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ji=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof dr.ZodString?r:t instanceof dr.ZodUnion?n:o},Ni=(e,{next:t})=>t(e.unwrap().shape.raw),Li={ZodString:te(h.SyntaxKind.StringKeyword),ZodNumber:te(h.SyntaxKind.NumberKeyword),ZodBigInt:te(h.SyntaxKind.BigIntKeyword),ZodBoolean:te(h.SyntaxKind.BooleanKeyword),ZodAny:te(h.SyntaxKind.AnyKeyword),ZodUndefined:te(h.SyntaxKind.UndefinedKeyword),[ae]:te(h.SyntaxKind.StringKeyword),[pe]:te(h.SyntaxKind.StringKeyword),ZodNull:ki,ZodArray:gi,ZodTuple:Ri,ZodRecord:Pi,ZodObject:yi,ZodLiteral:fi,ZodIntersection:wi,ZodUnion:ko,ZodDefault:Ei,ZodEnum:hi,ZodNativeEnum:Si,ZodEffects:bi,ZodOptional:Ti,ZodNullable:Oi,ZodDiscriminatedUnion:ko,ZodBranded:zi,ZodCatch:Zi,ZodPipeline:vi,ZodLazy:Ci,ZodReadonly:Ii,[F]:ji,[ee]:Ni},mr=(e,{brandHandling:t,ctx:r})=>ue(e,{rules:{...t,...Li},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var lr=class extends xt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=j(null);this.aliases.set(t,$(o,n)),this.aliases.set(t,$(o,r()))}return u(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Ui.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},x={brandHandling:r,ctx:{...p,isResponse:!0}};Ee({routing:t,onEndpoint:(f,P,R)=>{let v=X.bind(null,R,P),{isDeprecated:V}=f,g=`${R} ${P}`,z=$(v("input"),mr(f.getSchema("input"),m),{comment:g});this.program.push(z);let A=Pe.reduce((w,L)=>{let k=f.getResponses(L),St=Mi(([J,{schema:re,mimeTypes:Tt,statusCodes:Ot}])=>{let ve=$(v(L,"variant",`${J+1}`),mr(Tt?re:d,x),{comment:g});return this.program.push(ve),Ot.map(ke=>fe(ke,ve.name))},Array.from(k.entries())),_e=gt(v(L,"response","variants"),St,{comment:g});return this.program.push(_e),Object.assign(w,{[L]:_e})},{});this.paths.add(P);let I=j(g),N={input:u(z.name),positive:this.someOf(A.positive),negative:this.someOf(A.negative),response:i.createUnionTypeNode([K(this.interfaces.positive,I),K(this.interfaces.negative,I)]),encoded:i.createIntersectionTypeNode([u(A.positive.name),u(A.negative.name)])};this.registry.set(g,{isDeprecated:V,store:N}),this.tags.set(g,f.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Gt(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&bt.addSyntheticLeadingComment(bt.addSyntheticLeadingComment(i.createEmptyStatement(),bt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),bt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>Gt(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await we("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};import{z as
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await we("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};import{z as Ze}from"zod";var jo=(e,t)=>Ze.object({data:t,event:Ze.literal(e),id:Ze.string().optional(),retry:Ze.number().int().positive().optional()}),Di=(e,t,r)=>jo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Hi=1e4,Co=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Ki=e=>new q({handler:async({response:t})=>setTimeout(()=>Co(t),Hi)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Co(t),t.write(Di(e,r,o),"utf-8"),t.flush?.()}}}),Fi=e=>new me({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>jo(o,n));return{mimeType:E.sse,schema:r.length?Ze.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Se(r);Me(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ce(a),"utf-8")}t.end()}}),ur=class extends le{constructor(t){super(Fi(t)),this.middlewares=[Ki(t)]}};var qi={dateIn:xr,dateOut:br,file:Xe,upload:Or,raw:Tr};export{He as BuiltinLogger,Ke as DependsOnMethod,$t as Documentation,D as DocumentationError,le as EndpointsFactory,ur as EventStreamFactory,G as InputValidationError,lr as Integration,q as Middleware,Ce as MissingPeerError,oe as OutputValidationError,me as ResultHandler,ge as RoutingError,Fe as ServeStatic,mn as arrayEndpointsFactory,vt as arrayResultHandler,Ln as attachRouting,Xo as createConfig,Mn as createServer,dn as defaultEndpointsFactory,De as defaultResultHandler,Se as ensureHttpError,qi as ez,Q as getExamples,ne as getMessageFromError,ti as testEndpoint,ri as testMiddleware};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "22.
|
|
3
|
+
"version": "22.9.0",
|
|
4
4
|
"description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"node": "^20.9.0 || ^22.0.0"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"ansis": "^3.
|
|
64
|
+
"ansis": "^3.11.0",
|
|
65
65
|
"node-mocks-http": "^1.16.2",
|
|
66
66
|
"openapi3-ts": "^4.4.0",
|
|
67
67
|
"ramda": "^0.30.1"
|