express-zod-api 22.8.0 → 22.9.1
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 +32 -0
- package/README.md +31 -4
- package/SECURITY.md +24 -24
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +27 -12
- package/dist/index.d.ts +27 -12
- package/dist/index.js +9 -9
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,38 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 22
|
|
4
4
|
|
|
5
|
+
### v22.9.1
|
|
6
|
+
|
|
7
|
+
- Minor refactoring and optimizations.
|
|
8
|
+
|
|
9
|
+
### v22.9.0
|
|
10
|
+
|
|
11
|
+
- Featuring Deprecations:
|
|
12
|
+
- You can deprecate all usage of an `Endpoint` using `EndpointsFactory::build({ deprecated: true })`;
|
|
13
|
+
- You can deprecate a route using the assigned `Endpoint::deprecated()` or `DependsOnMethod::deprecated()`;
|
|
14
|
+
- You can deprecate a schema using `ZodType::deprecated()`;
|
|
15
|
+
- All `.deprecated()` methods are immutable — they create a new copy of the subject;
|
|
16
|
+
- Deprecated schemas and endpoints are reflected in the generated `Documentation` and `Integration`;
|
|
17
|
+
- The feature suggested by [@mlms13](https://github.com/mlms13).
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { Routing, DependsOnMethod } from "express-zod-api";
|
|
21
|
+
import { z } from "zod";
|
|
22
|
+
|
|
23
|
+
const someEndpoint = factory.build({
|
|
24
|
+
deprecated: true, // deprecates all routes the endpoint assigned to
|
|
25
|
+
input: z.object({
|
|
26
|
+
prop: z.string().deprecated(), // deprecates the property or a path parameter
|
|
27
|
+
}),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const routing: Routing = {
|
|
31
|
+
v1: oldEndpoint.deprecated(), // deprecates the /v1 path
|
|
32
|
+
v2: new DependsOnMethod({ get: oldEndpoint }).deprecated(), // deprecates the /v2 path
|
|
33
|
+
v3: someEndpoint, // the path is assigned with initially deprecated endpoint (also deprecated)
|
|
34
|
+
};
|
|
35
|
+
```
|
|
36
|
+
|
|
5
37
|
### v22.8.0
|
|
6
38
|
|
|
7
39
|
- 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/SECURITY.md
CHANGED
|
@@ -2,30 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
## Supported Versions
|
|
4
4
|
|
|
5
|
-
| Version | Release | Supported |
|
|
6
|
-
| ------: | :------ | :----------------: |
|
|
7
|
-
| 22.x.x | 01.2025 | :white_check_mark: |
|
|
8
|
-
| 21.x.x | 11.2024 | :white_check_mark: |
|
|
9
|
-
| 20.x.x | 06.2024 | :white_check_mark: |
|
|
10
|
-
| 19.x.x | 05.2024 | :white_check_mark: |
|
|
11
|
-
| 18.x.x | 04.2024 | :white_check_mark: |
|
|
12
|
-
| 17.x.x | 02.2024 | :x: |
|
|
13
|
-
| 16.x.x | 12.2023 | :x: |
|
|
14
|
-
| 15.x.x | 12.2023 | :x: |
|
|
15
|
-
| 14.x.x | 10.2023 | :x: |
|
|
16
|
-
| 12.x.x | 09.2023 | :x: |
|
|
17
|
-
| 11.x.x | 06.2023 | :x: |
|
|
18
|
-
| 10.x.x | 03.2023 | :x: |
|
|
19
|
-
| 9.x.x | 03.2023 | :x: |
|
|
20
|
-
| 8.x.x | 09.2022 | :x: |
|
|
21
|
-
| 7.x.x | 05.2022 | :x: |
|
|
22
|
-
| 6.x.x | 03.2022 | :x: |
|
|
23
|
-
| 5.x.x | 12.2021 | :x: |
|
|
24
|
-
| 4.x.x | 11.2021 | :x: |
|
|
25
|
-
| 3.x.x | 11.2021 | :x: |
|
|
26
|
-
| 2.x.x | 07.2021 | :x: |
|
|
27
|
-
| 1.x.x | 05.2021 | :x: |
|
|
28
|
-
| 0.x.x | 03.2021 | :x: |
|
|
5
|
+
| Version | Code name | Release | Supported |
|
|
6
|
+
| ------: | :------------ | :------ | :----------------: |
|
|
7
|
+
| 22.x.x | Tai | 01.2025 | :white_check_mark: |
|
|
8
|
+
| 21.x.x | Kesaria | 11.2024 | :white_check_mark: |
|
|
9
|
+
| 20.x.x | Zoey | 06.2024 | :white_check_mark: |
|
|
10
|
+
| 19.x.x | Dime | 05.2024 | :white_check_mark: |
|
|
11
|
+
| 18.x.x | Victoria | 04.2024 | :white_check_mark: |
|
|
12
|
+
| 17.x.x | Tonya | 02.2024 | :x: |
|
|
13
|
+
| 16.x.x | Nina | 12.2023 | :x: |
|
|
14
|
+
| 15.x.x | Vika | 12.2023 | :x: |
|
|
15
|
+
| 14.x.x | Katie | 10.2023 | :x: |
|
|
16
|
+
| 12.x.x | Adriana | 09.2023 | :x: |
|
|
17
|
+
| 11.x.x | trans sisters | 06.2023 | :x: |
|
|
18
|
+
| 10.x.x | Gisberta | 03.2023 | :x: |
|
|
19
|
+
| 9.x.x | Brianna | 03.2023 | :x: |
|
|
20
|
+
| 8.x.x | Ariyanna | 09.2022 | :x: |
|
|
21
|
+
| 7.x.x | Dmitry | 05.2022 | :x: |
|
|
22
|
+
| 6.x.x | Alice | 03.2022 | :x: |
|
|
23
|
+
| 5.x.x | Ella | 12.2021 | :x: |
|
|
24
|
+
| 4.x.x | Sharlie | 11.2021 | :x: |
|
|
25
|
+
| 3.x.x | Xiona | 11.2021 | :x: |
|
|
26
|
+
| 2.x.x | | 07.2021 | :x: |
|
|
27
|
+
| 1.x.x | | 05.2021 | :x: |
|
|
28
|
+
| 0.x.x | | 03.2021 | :x: |
|
|
29
29
|
|
|
30
30
|
## Reporting a Vulnerability
|
|
31
31
|
|
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 x=(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:()=>B,EndpointsFactory:()=>ye,EventStreamFactory:()=>Mt,InputValidationError:()=>Q,Integration:()=>Lt,Middleware:()=>V,MissingPeerError:()=>ve,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>xe,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Fr,arrayResultHandler:()=>St,attachRouting:()=>So,createConfig:()=>wr,createServer:()=>Ro,defaultEndpointsFactory:()=>Kr,defaultResultHandler:()=>Ue,ensureHttpError:()=>Ae,ez:()=>rn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>Bo,testMiddleware:()=>$o});module.exports=dn(Ys);var D=x(require("ramda"),1),Te=require("zod");var U=x(require("ramda"),1),Kt=require("zod");var v={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var xe=class extends Error{name="RoutingError"},B=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"},Q=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"},ve=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(v.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(U.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?U.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=U.chain(o=>o.split(/[^A-Z0-9]/gi),e);return U.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map($t).join("")},mt=U.tryCatch((e,t)=>typeof e.parse(t),U.always(void 0)),Se=e=>typeof e=="object"&&e!==null,Re=U.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var lt=x(require("ramda"),1),g=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[g]=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"?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:[],...D.clone(this._def[g]),brand:e}})},xn=function(e){let t=typeof e=="function"?e:D.pipe(D.toPairs,D.map(([n,s])=>D.pair(e[String(n)]||n,s)),D.fromPairs),r=t(D.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 j=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 Pe=Symbol("DateOut"),Ir=()=>zr.z.date().refine(ut).transform(e=>e.toISOString()).brand(Pe);var Qe=require("zod"),X=Symbol("File"),Zr=Qe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),bn={buffer:()=>Zr.brand(X),string:()=>Qe.z.string().brand(X),binary:()=>Zr.or(Qe.z.string()).brand(X),base64:()=>Qe.z.string().base64().brand(X)};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,j.fail)("z.nan()"),ZodSymbol:()=>(0,j.fail)("z.symbol()"),ZodFunction:()=>(0,j.fail)("z.function()"),ZodMap:()=>(0,j.fail)("z.map()"),ZodSet:()=>(0,j.fail)("z.set()"),ZodBigInt:()=>(0,j.fail)("z.bigint()"),ZodVoid:()=>(0,j.fail)("z.void()"),ZodPromise:()=>(0,j.fail)("z.promise()"),ZodNever:()=>(0,j.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,j.fail)("z.date()"),[Pe]:()=>t==="in"&&(0,j.fail)("ez.dateOut()"),[Oe]:()=>t==="out"&&(0,j.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,j.fail)("ez.raw()"),[Ce]:()=>t==="out"&&(0,j.fail)("ez.upload()"),[X]:()=>!1}})};var ht=x(require("http-errors"),1);var Xe=x(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}),Ae=e=>(0,Xe.isHttpError)(e)?e:(0,Xe.default)(e instanceof Q?400:500,ce(e),{cause:e.cause||e}),we=e=>Re()&&!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=we((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{},V=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 Q(o):o}}},je=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 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 Q(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)},G=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?G(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>G(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?G(e._def.schema):e instanceof ue.z.ZodPipeline?G(e._def.in):G(e._def.left).merge(G(e._def.right));var J=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:[v.json]})}getNegativeResponse(){return Vt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[v.json]})}},Ue=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.z.object({status:J.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.z.object({status:J.z.literal("error"),error:J.z.object({message:J.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=Ae(e);return et(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:we(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 J.z.ZodArray?e.shape.items:J.z.array(J.z.any());return t.reduce((o,n)=>Se(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ae(r);return et(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(we(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 V?t:new V(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 V({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,S=typeof o=="function"?o:()=>o,R=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new bt({...c,middlewares:d,outputSchema:r,resultHandler:p,scopes:R,tags:y,methods:l,getOperationId:S,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=x(require("ansis"),1),Jr=require("node:util"),er=require("node:perf_hooks");var ee=require("ansis"),qr=x(require("ramda"),1);var Xt={debug:ee.blue,info:ee.green,warn:(0,ee.hex)("#FFA500"),error:ee.red,ctx:ee.cyanBright},Rt={debug:10,info:20,warn:30,error:40},Br=e=>Se(e)&&Object.keys(Rt).some(t=>t in e),$r=e=>e in Rt,_r=(e,t)=>Rt[e]<Rt[t],Rn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=qr.memoizeWith((e,t)=>`${e}${t}`,Rn),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=Re()?"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=x(require("ramda"),1);var Ke=class e extends Ne{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Fe.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Fe.reject(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=x(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Wr.default.static(...this.params))}};var Ot=x(require("express"),1),ho=x(require("node:http"),1),xo=x(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>x(require(e))))[t]}catch{}throw new ve(e)};var Xr=x(require("http-errors"),1);var Yr=x(require("ramda"),1);var Tt=class{constructor(t){this.logger=t}#e=Yr.tryCatch(Ur);#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(v.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||G(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 Tn=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=Re()?void 0:new Tt(t()),a=new Map;if($e({routing:o,onEndpoint:(d,p,l,S)=>{Re()||(s?.checkJsonCompat(d,{path:p,method:l}),s?.checkPathParams(p,d,{method:l}));let R=n?.[d.getRequestType()]||[],y=async(E,w)=>{let L=t(E);if(r.cors){let k={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...S||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},z=typeof r.cors=="function"?await r.cors({request:E,endpoint:d,logger:L,defaultHeaders:k}):k;for(let C in z)w.set(C,z[C])}return d.execute({request:E,response:w,logger:L,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...R,y),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...R,y)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,Tn(p))};var rt=x(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)})}},On=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(S){return p(S)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Pn(l)})(c,d,p)}),o&&a.push(On(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 $=require("ansis"),go=e=>{if(e.columns<132)return;let t=(0,$.italic)("Proudly supports transgender community.".padStart(109)),r=(0,$.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,$.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,$.italic)("for Tai".padEnd(20)),s=(0,$.hex)("#F5A9B8"),a=(0,$.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill($.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill($.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.1 (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}},Ro=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=bo(e),c=(0,Ot.default)().disable("x-powered-by").use(a);if(e.compression){let R=await Be("compression");c.use(R(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Ot.default.json()],raw:[e.rawParser||Ot.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=(R,y)=>()=>R.listen(y,()=>r.info("Listening",y)),S=[];if(e.http){let R=ho.default.createServer(c);p.push(R),S.push(l(R,e.http.listen))}if(e.https){let R=xo.default.createServer(e.https.options,c);p.push(R),S.push(l(R,e.https.listen))}return e.gracefulShutdown&&yo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:S.map(R=>R())}};var Ko=require("openapi3-ts/oas31"),Fo=x(require("ramda"),1);var T=x(require("ramda"),1);var To=e=>Se(e)&&"or"in e,Oo=e=>Se(e)&&"and"in e,rr=e=>!Oo(e)&&!To(e),Po=e=>{let t=T.filter(rr,e),r=T.chain(T.prop("and"),T.filter(Oo,e)),[o,n]=T.partition(rr,r),s=T.concat(t,o),a=T.filter(To,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((d,p)=>be(d,T.map(l=>rr(l)?[l]:l.and,p),([l,S])=>T.concat(l,S)),T.reject(T.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),m=x(require("ramda"),1),H=require("zod");var Ee=(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=>Ee(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 B("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 H.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 m.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Un=m.tryCatch(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=m.mergeDeepWith(Mn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=m.union(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=be(t.examples||[],r.examples||[],([n,s])=>m.mergeDeepRight(n,s))),o},(e,t)=>({allOf:t})),Dn=({_def:{left:e,right:t}},{next:r})=>Un([e,t].map(r)),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=m.toLower(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 H.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 B("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 B("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 B(`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 H.z.ZodLiteral),Qn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof H.z.ZodEnum||e instanceof H.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Pt(H.z.object(m.fromPairs(m.xprod(o,[t]))),r),n.required=o),n}if(e instanceof H.z.ZodLiteral)return{type:"object",properties:Pt(H.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof H.z.ZodUnion&&Yn(e.options)){let o=m.map(s=>`${s.value}`,e.options),n=m.fromPairs(m.xprod(o,[t]));return{type:"object",properties:Pt(H.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:S,isDate:R,isTime:y,isBase64:E,isNANOID:w,isBase64url:L,isDuration:oe,_def:{checks:h}})=>{let k=h.find(M=>M.kind==="regex"),z=h.find(M=>M.kind==="datetime"),C=h.some(M=>M.kind==="jwt"),F=h.find(M=>M.kind==="length"),Z={type:"string"},q={"date-time":l,byte:E,base64url:L,date:R,time:y,duration:oe,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:w,jwt:C,ip:d,cidr:S,emoji:p};for(let M in q)if(q[M]){Z.format=M;break}return F&&([Z.minLength,Z.maxLength]=[F.value,F.value]),r!==null&&(Z.minLength=r),o!==null&&(Z.maxLength=o),R&&(Z.pattern=En.source),y&&(Z.pattern=zn.source),l&&(Z.pattern=In(z?.offset).source),k&&(Z.pattern=k.regex.source),Z},rs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(S=>S.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(S=>S.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)=>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(H.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?m.fromPairs(m.zip(m.times(t=>`example${t+1}`,e.length),m.map(m.objOf("value"),e))):void 0,Co=(e,t,r=[])=>m.pipe(ne,m.map(m.when(o=>m.type(o)==="Object",m.omit(r))),ko)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),cs=(e,t)=>m.pipe(ne,m.filter(m.has(t)),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=G(r),S=ct(e),R=o.includes("query"),y=o.includes("params"),E=o.includes("headers"),w=h=>y&&S.includes(h),L=m.chain(m.filter(h=>h.type==="header"),d??[]).map(({name:h})=>h),oe=h=>E&&(c?.(h,t,e)??ds(h,L));return Object.entries(l.shape).reduce((h,[k,z])=>{let C=w(k)?"path":oe(k)?"header":R?"query":void 0;if(!C)return h;let F=Ee(z,{rules:{...a,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),Z=s==="components"?n(z,F,me(p,k)):F,{_def:q}=z;return h.concat({name:k,in:C,deprecated:q[g]?.isDeprecated,required:!z.isOptional(),description:F.description||p,schema:Z,examples:cs(l,k)})},[])},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,[X]:jn,[Ce]:Cn,[Pe]: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 H.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 B(`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=m.omit(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>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: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 S=No(Ee(r,{rules:{...p,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),R={schema:a==="components"?s(r,S,me(l)):S,examples:Co(r,!0)};return{description:l,content:m.fromPairs(m.xprod(o,[R]))}},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:m.map(t=>({...t,scopes:t.scopes||{}}),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(Ee(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(G(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 B(`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:S="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,E,w)=>{let L={path:E,method:w,endpoint:y,composition:S,brandHandling:c,makeRef:this.makeRef.bind(this)},[oe,h]=["short","long"].map(y.getDescription.bind(y)),k=oe?ar(oe):l&&h?ar(h):void 0,z=r.inputSources?.[w]||qt[w],C=this.ensureUniqOperationId(E,w,y.getOperationId(w)),F=Po(y.getSecurity()),Z=jo({...L,inputSources:z,isHeader:p,security:F,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:w,path:E,operationId:C})}),q={};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)q[Je]=Lo({...L,variant:ie,schema:Ht,mimeTypes:Dt,statusCode:Je,hasMultipleStatusCodes:he.length>1||Ge.length>1,description:a?.[`${ie}Response`]?.call(null,{method:w,path:E,operationId:C,statusCode:Je})})}let M=z.includes("body")?Do({...L,paramNames:Fo.pluck("name",Z),schema:y.getSchema("input"),mimeType:v[y.getRequestType()],description:a?.requestBody?.call(null,{method:w,path:E,operationId:C})}):void 0,Ut=Uo(Mo(F,z),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),it={operationId:C,summary:k,description:h,deprecated:y.isDeprecated||void 0,tags:At(y.getTags()),parameters:At(Z),requestBody:M,security:At(Ut),responses:q};this.addPath(Io(E),{[w]:it})}}),d&&(this.rootDoc.tags=Ho(d))}};var Et=require("node-mocks-http"),hs=e=>(0,Et.createRequest)({...e,headers:{"content-type":v.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=x(require("ramda"),1),st=x(require("typescript"),1),Xo=require("zod");var Wo=x(require("ramda"),1),Y=x(require("typescript"),1);var _o=["get","post","put","delete","patch"];var te=x(require("ramda"),1),u=x(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)},Rs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e=="string"&&Rs.test(e)?i.createIdentifier(e):A(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&&te.map(f,t)):e,lr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),ze=(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=te.reject(te.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))),N=(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)=>re(e,i.createUnionTypeNode(te.map(K,t)),{expose:!0}),re=(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=>te.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)}),Ie=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ss:void 0,void 0,Array.isArray(e)?te.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),P=(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)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Go=e=>i.createUnionTypeNode([f(e),vt(e)]),Rr=(e,t)=>i.createFunctionTypeNode(void 0,_e(e),f(t)),A=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),K=e=>i.createLiteralTypeNode(A(e)),Ts=[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=>Ts.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=re("SomeOf",W("T",xr("T")),{params:["T"]});requestType=re("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}])=>ze(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>N("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(dr(t),i.createArrayLiteralExpression(Wo.map(A,r))))),{expose:!0});makeImplementationType=()=>re(this.ids.implementationType,Rr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:lr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},vt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.ids.parseRequestFn,Ie({[this.ids.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(P(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),A(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>N(this.ids.substituteFn,Ie({[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:lr},i.createBlock([N(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],Y.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([Sr(this.ids.pathParameter,P(this.ids.pathParameter,O("replace"))(It(":",[this.ids.keyParameter]),Ie([],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]:W(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[N(fr(this.ids.methodParameter,this.ids.pathParameter),P(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(P(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(P(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:vt(W(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]),A(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),P(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),nt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(A("Content-Type"),A(v.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),nt(this.ids.hasBodyConst,P(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=N(this.ids.responseConst,i.createAwaitExpression(P(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=N(this.ids.hasBodyConst,i.createLogicalNot(P(i.createArrayLiteralExpression([A("get"),A("delete")]),O("includes"))(this.ids.methodParameter))),a=N(this.ids.searchParamsConst,nt(this.ids.hasBodyConst,A(""),this.makeSearchParams(this.ids.paramsArgument))),c=N(this.ids.contentTypeConst,P(this.ids.responseConst,O("headers"),O("get"))(A("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=N(this.ids.isJsonConst,P(this.ids.contentTypeConst,O("startsWith"))(A(v.json))),l=i.createReturnStatement(P(this.ids.responseConst,nt(this.ids.isJsonConst,A(O("json")),A(O("text"))))());return N(this.ids.defaultImplementationConst,Ie([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:W(this.interfaces.input,"K")}),[N(fr(this.ids.pathParameter,this.ids.restConst),P(this.ids.substituteFn)(i.createElementAccessExpression(P(this.ids.parseRequestFn)(this.ids.requestParameter),A(1)),this.ids.paramsArgument)),N(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),Sr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ze(O("event"),t)]);makeOnMethod=()=>gr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Rr({[this.ids.dataParameter.text]:W(Ct("R",ur(this.makeEventNarrow("E"))),K(O("data")))},Go(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(P(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,Ie([this.ids.msgParameter],P(this.ids.handlerParameter)(P(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:W("R",K(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(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ct(W(this.interfaces.positive,"K"),ur(this.makeEventNarrow(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.ids.clientConst,Ve(t)),P(this.ids.clientConst,this.ids.provideMethod)(A("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",A("10"))])),P(Ve(r,A("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(A("time"),Ie(["time"],i.createBlock([])))]};var I=x(require("ramda"),1),b=x(require("typescript"),1),Nt=require("zod");var{factory:_}=b.default,Os={[b.default.SyntaxKind.AnyKeyword]:"",[b.default.SyntaxKind.BigIntKeyword]:BigInt(0),[b.default.SyntaxKind.BooleanKeyword]:!1,[b.default.SyntaxKind.NumberKeyword]:0,[b.default.SyntaxKind.ObjectKeyword]:{},[b.default.SyntaxKind.StringKeyword]:"",[b.default.SyntaxKind.UndefinedKeyword]:void 0},Tr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Ps=({value:e})=>K(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 ze(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(K)),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=>Os?.[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:b.default.SyntaxKind.NumberKeyword,bigint:b.default.SyntaxKind.BigIntKeyword,boolean:b.default.SyntaxKind.BooleanKeyword,string:b.default.SyntaxKind.StringKeyword,undefined:b.default.SyntaxKind.UndefinedKeyword,object:b.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||b.default.SyntaxKind.AnyKeyword)}return o},Zs=e=>_.createUnionTypeNode(Object.values(e.enum).map(K)),vs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(b.default.SyntaxKind.UndefinedKeyword)]):o},ks=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),K(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=I.tryCatch(e=>{if(!e.every(b.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(Tr.name,...o))return!1;if(I.both(I.eqBy(Tr.type),I.eqBy(Tr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),Ls=({_def:{left:e,right:t}},{next:r})=>Ns([e,t].map(r)),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=()=>K(null),qs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Bs=e=>{let t=e.unwrap(),r=f(b.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(b.default.SyntaxKind.StringKeyword),ZodNumber:ge(b.default.SyntaxKind.NumberKeyword),ZodBigInt:ge(b.default.SyntaxKind.BigIntKeyword),ZodBoolean:ge(b.default.SyntaxKind.BooleanKeyword),ZodAny:ge(b.default.SyntaxKind.AnyKeyword),ZodUndefined:ge(b.default.SyntaxKind.UndefinedKeyword),[Oe]:ge(b.default.SyntaxKind.StringKeyword),[Pe]:ge(b.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,[X]:Bs,[le]:$s},Or=(e,{brandHandling:t,ctx:r})=>Ee(e,{rules:{...t,..._s},onMissing:()=>f(b.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=K(null);this.aliases.set(t,re(o,n)),this.aliases.set(t,re(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}},S={brandHandling:r,ctx:{...p,isResponse:!0}};$e({routing:t,onEndpoint:(y,E,w)=>{let L=me.bind(null,w,E),{isDeprecated:oe}=y,h=`${w} ${E}`,k=re(L("input"),Or(y.getSchema("input"),l),{comment:h});this.program.push(k);let z=Me.reduce((Z,q)=>{let M=y.getResponses(q),Ut=Qo.chain(([ie,{schema:he,mimeTypes:Dt,statusCodes:Ht}])=>{let Ge=re(L(q,"variant",`${ie+1}`),Or(Dt?he:d,S),{comment:h});return this.program.push(Ge),Ht.map(Je=>ze(Je,Ge.name))},Array.from(M.entries())),it=kt(L(q,"response","variants"),Ut,{comment:h});return this.program.push(it),Object.assign(Z,{[q]:it})},{});this.paths.add(E);let C=K(h),F={input:f(k.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,C),W(this.interfaces.negative,C)]),encoded:i.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(h,{isDeprecated:oe,store:F}),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 Ze=require("zod");var tn=(e,t)=>Ze.z.object({data:t,event:Ze.z.literal(e),id:Ze.z.string().optional(),retry:Ze.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":v.sse,"cache-control":"no-cache"}),Js=e=>new V({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:v.sse,schema:r.length?Ze.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ae(r);et(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(we(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
|
}
|
|
@@ -906,7 +917,7 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
906
917
|
middleware: AbstractMiddleware;
|
|
907
918
|
/** @desc The aggregated output from previously executed middlewares */
|
|
908
919
|
options?: FlatObject;
|
|
909
|
-
/** @desc Enables transforming possible middleware errors into response, so that
|
|
920
|
+
/** @desc Enables transforming possible middleware errors into response, so that test Middleware does not throw */
|
|
910
921
|
errorHandler?: (error: Error, response: Response) => void;
|
|
911
922
|
}) => Promise<{
|
|
912
923
|
requestMock: Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>> & {
|
|
@@ -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
|
}
|
|
@@ -906,7 +917,7 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
906
917
|
middleware: AbstractMiddleware;
|
|
907
918
|
/** @desc The aggregated output from previously executed middlewares */
|
|
908
919
|
options?: FlatObject;
|
|
909
|
-
/** @desc Enables transforming possible middleware errors into response, so that
|
|
920
|
+
/** @desc Enables transforming possible middleware errors into response, so that test Middleware does not throw */
|
|
910
921
|
errorHandler?: (error: Error, response: Response) => void;
|
|
911
922
|
}) => Promise<{
|
|
912
923
|
requestMock: Request<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>> & {
|
|
@@ -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
|
|
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))),Yr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Fr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as
|
|
1
|
+
import*as U from"ramda";import{z as Pe}from"zod";import*as M from"ramda";import{z as ur}from"zod";var Z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var Oe=class extends Error{name="RoutingError"},B=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.`}},Xe=class extends Error{name="IOSchemaError"},ce=class extends Xe{constructor(r){super(de(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends Xe{constructor(r){super(de(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(de(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},He=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var zt=/:([A-Za-z0-9_]+)/g,et=e=>e.match(zt)?.map(t=>t.slice(1))||[],ko=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Z.upload);return"files"in e&&r},It={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Co=["body","query","params"],Zt=e=>e.method.toLowerCase(),tt=(e,t={})=>{let r=Zt(e);return r==="options"?{}:(t[r]||It[r]||Co).filter(o=>o==="files"?ko(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),de=e=>e instanceof ur.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ce?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,jo=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return me(t,(n[g]?.examples||[]).map(M.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 ur.ZodObject&&(n=jo(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},me=(e,t,r)=>e.length&&t.length?M.xprod(e,t).map(r):e.concat(t),Ke=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,vt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=M.chain(o=>o.split(/[^A-Z0-9]/gi),e);return M.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(vt).join("")},rt=M.tryCatch((e,t)=>typeof e.parse(t),M.always(void 0)),le=e=>typeof e=="object"&&e!==null,ue=M.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as ot from"ramda";var g=Symbol.for("express-zod-api"),Fe=e=>{let t=e.describe(e.description);return t._def[g]=ot.clone(t._def[g])||{examples:[]},t},fr=(e,t)=>{if(!(g in e._def))return t;let r=Fe(t);return r._def[g].examples=me(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?ot.mergeDeepRight({...o},{...n}):n),r};var No=function(e){let t=Fe(this);return t._def[g].examples.push(e),t},Lo=function(){let e=Fe(this);return e._def[g].isDeprecated=!0,e},Mo=function(e){let t=Fe(this);return t._def[g].defaultLabel=e,t},Uo=function(e){return new Pe.ZodBranded({typeName:Pe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...U.clone(this._def[g]),brand:e}})},Do=function(e){let t=typeof e=="function"?e:U.pipe(U.toPairs,U.map(([n,s])=>U.pair(e[String(n)]||n,s)),U.fromPairs),r=t(U.clone(this.shape)),o=Pe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Pe.ZodType.prototype,{example:{get(){return No.bind(this)}},deprecated:{get(){return Lo.bind(this)}},brand:{set(){},get(){return Uo.bind(this)}}}),Object.defineProperty(Pe.ZodDefault.prototype,"label",{get(){return Mo.bind(this)}}),Object.defineProperty(Pe.ZodObject.prototype,"remap",{get(){return Do.bind(this)}}));function Ho(e){return e}import{z as zr}from"zod";import{z as wr}from"zod";import{fail as L}from"node:assert/strict";import{z as qe}from"zod";var nt=e=>!isNaN(e.getTime());var fe=Symbol("DateIn"),yr=()=>qe.union([qe.string().date(),qe.string().datetime(),qe.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(qe.date().refine(nt)).brand(fe);import{z as Ko}from"zod";var ye=Symbol("DateOut"),gr=()=>Ko.date().refine(nt).transform(e=>e.toISOString()).brand(ye);import{z as st}from"zod";var V=Symbol("File"),hr=st.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Fo={buffer:()=>hr.brand(V),string:()=>st.string().brand(V),binary:()=>hr.or(st.string()).brand(V),base64:()=>st.string().base64().brand(V)};function it(e){return Fo[e||"string"]()}import{z as qo}from"zod";var ie=Symbol("Raw"),xr=(e={})=>qo.object({raw:it("buffer")}).extend(e).brand(ie);import{z as Bo}from"zod";var Ae=Symbol("Upload"),br=()=>Bo.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ae);var Sr=(e,{next:t})=>e.options.some(t),$o=({_def:e},{next:t})=>[e.left,e.right].some(t),at=(e,{next:t})=>t(e.unwrap()),kt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Sr,ZodDiscriminatedUnion:Sr,ZodIntersection:$o,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:at,ZodNullable:at,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},pt=(e,{condition:t,rules:r=kt,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=>pt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Rr=e=>pt(e,{condition:t=>t._def[g]?.brand===Ae}),Tr=e=>pt(e,{condition:t=>t._def[g]?.brand===ie,maxDepth:3}),Or=(e,t)=>{let r=new WeakSet;return pt(e,{maxDepth:300,rules:{...kt,ZodBranded:at,ZodReadonly:at,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:kt.ZodEffects}[t],ZodNaN:()=>L("z.nan()"),ZodSymbol:()=>L("z.symbol()"),ZodFunction:()=>L("z.function()"),ZodMap:()=>L("z.map()"),ZodSet:()=>L("z.set()"),ZodBigInt:()=>L("z.bigint()"),ZodVoid:()=>L("z.void()"),ZodPromise:()=>L("z.promise()"),ZodNever:()=>L("z.never()"),ZodDate:()=>t==="in"&&L("z.date()"),[ye]:()=>t==="in"&&L("ez.dateOut()"),[fe]:()=>t==="out"&&L("ez.dateIn()"),[ie]:()=>t==="out"&&L("ez.raw()"),[Ae]:()=>t==="out"&&L("ez.upload()"),[V]:()=>!1}})};import Go,{isHttpError as Jo}from"http-errors";import Pr,{isHttpError as _o}from"http-errors";import{z as Vo}from"zod";var Ct=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Vo.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(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}))},Be=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>_o(e)?e:Pr(e instanceof ee?400:500,de(e),{cause:e.cause||e}),ge=e=>ue()&&!e.expose?Pr(e.statusCode).message:e.message;var ct=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ge(Go(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:Jo(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ar}from"zod";var jt=class{},G=class extends jt{#e;#t;#r;constructor({input:t=Ar.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 Ar.ZodError?new ee(o):o}}},Ee=class extends G{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 ze=class{nest(t){return Object.assign(t,{"":this})}};var $e=class extends ze{},dt=class e extends $e{#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 Rr(this.#e.inputSchema)?"upload":Tr(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 wr.ZodError?new ce(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 Ee))&&(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 wr.ZodError?new ee(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){ct({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Zt(t),a={},c=null,d=null,p=tt(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=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};import{z as he}from"zod";var Er=(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)},$=e=>e instanceof he.ZodObject?e:e instanceof he.ZodBranded?$(e.unwrap()):e instanceof he.ZodUnion||e instanceof he.ZodDiscriminatedUnion?e.options.map(t=>$(t)).reduce((t,r)=>t.merge(r.partial()),he.object({})):e instanceof he.ZodEffects?$(e._def.schema):e instanceof he.ZodPipeline?$(e._def.in):$(e._def.left).merge($(e._def.right));import{z as J}from"zod";var Ie={positive:200,negative:400},Ze=Object.keys(Ie);var Nt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},xe=class extends Nt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Ct(this.#e,{variant:"positive",args:[t],statusCodes:[Ie.positive],mimeTypes:[Z.json]})}getNegativeResponse(){return Ct(this.#t,{variant:"negative",args:[],statusCodes:[Ie.negative],mimeTypes:[Z.json]})}},_e=new xe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.object({status:J.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.object({status:J.literal("error"),error:J.object({message:J.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=we(e);return Be(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ge(a)}})}n.status(Ie.positive).json({status:"success",data:r})}}),Lt=new xe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof J.ZodArray?e.shape.items:J.array(J.any());return t.reduce((o,n)=>le(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=we(r);return Be(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ge(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Ie.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var be=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 G?t:new G(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new G({handler:t})),this.resultHandler)}build({input:t=zr.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 dt({...c,middlewares:d,outputSchema:r,resultHandler:p,scopes:S,tags:y,methods:l,getOperationId:b,inputSchema:Er(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:zr.object({}),handler:async o=>(await t(o),{})})}},Wo=new be(_e),Yo=new be(Lt);import nn from"ansis";import{inspect as sn}from"node:util";import{performance as jr}from"node:perf_hooks";import{blue as Qo,green as Xo,hex as en,red as tn,cyanBright as rn}from"ansis";import*as Ir from"ramda";var Mt={debug:Qo,info:Xo,warn:en("#FFA500"),error:tn,ctx:rn},mt={debug:10,info:20,warn:30,error:40},Zr=e=>le(e)&&Object.keys(mt).some(t=>t in e),vr=e=>e in mt,kr=(e,t)=>mt[e]<mt[t],on=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),ve=Ir.memoizeWith((e,t)=>`${e}${t}`,on),Cr=e=>e<1e-6?ve("nanosecond",3).format(e/1e-6):e<.001?ve("nanosecond").format(e/1e-6):e<1?ve("microsecond").format(e/.001):e<1e3?ve("millisecond").format(e):e<6e4?ve("second",2).format(e/1e3):ve("minute",2).format(e/6e4);var Ve=class e{config;constructor({color:t=nn.isSupported(),level:r=ue()?"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"||kr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Mt.ctx(s):s),d.push(c?`${Mt[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=jr.now();return()=>{let o=jr.now()-r,{message:n,severity:s="debug",formatter:a=Cr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as ke from"ramda";var Ge=class e extends ze{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=ke.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,ke.reject(ke.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)}};import an from"express";var Je=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,an.static(...this.params))}};import Dt from"express";import gn from"node:http";import hn from"node:https";var Ce=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new He(e)};import pn from"http-errors";import*as Nr from"ramda";var lt=class{constructor(t){this.logger=t}#e=Nr.tryCatch(Or);#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 Ze){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(Z.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=et(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 Lr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new Oe(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Lr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof $e){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Je)r&&s.apply(n,r);else if(s instanceof Ge)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new Oe(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Lr(s,n))}};var cn=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)},Ut=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new lt(t()),a=new Map;if(je({routing:o,onEndpoint:(d,p,l,b)=>{ue()||(s?.checkJsonCompat(d,{path:p,method:l}),s?.checkPathParams(p,d,{method:l}));let S=n?.[d.getRequestType()]||[],y=async(w,A)=>{let j=t(w);if(r.cors){let v={"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:j,defaultHeaders:v}):v;for(let k in E)A.set(k,E[k])}return d.execute({request:w,response:A,logger:j,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,cn(p))};import qr,{isHttpError as mn}from"http-errors";import{setInterval as dn}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",Dr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Hr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Kr=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 l of["connection","secureConnection"])p.on(l,c);let d=async()=>{for(let p of e)p.on("request",Hr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Dr(p)||Ur(p))&&a(p);for await(let p of dn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Kr))};return{sockets:n,shutdown:()=>o??=d()}};var Br=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:mn(r)?r:qr(400,oe(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){ct({response:o,logger:s,error:new re(oe(a),n)})}},ln=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},un=e=>({log:e.debug.bind(e)}),_r=async({getLogger:e,config:t})=>{let r=await Ce("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:un(l)})(c,d,p)}),o&&a.push(ln(o)),a},Vr=(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))),Yr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Fr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as fn,hex as Qr,italic as ut,whiteBright as yn}from"ansis";var Xr=e=>{if(e.columns<132)return;let t=ut("Proudly supports transgender community.".padStart(109)),r=ut("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=ut("Thank you for choosing Express Zod API for your project.".padStart(132)),n=ut("for Tai".padEnd(20)),s=Qr("#F5A9B8"),a=Qr("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(yn,5,7).fill(s,7,9).fill(a,9,12).fill(fn,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
|
|
@@ -14,10 +14,10 @@ Original error: ${e.handled.message}.`:""),{expose:an(e.cause)?e.cause.expose:!1
|
|
|
14
14
|
${n}888${r}
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
|
-
`).map((p,
|
|
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)=>
|
|
17
|
+
`).map((p,l)=>c[l]?c[l](p):p).join(`
|
|
18
|
+
`))};var eo=e=>{e.startupLogo!==!1&&Xr(process.stdout);let t=e.errorHandler||_e,r=Zr(e.logger)?e.logger:new Ve(e.logger);r.debug("Running",{build:"v22.9.1 (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}},xn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=eo(e);return Ut({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},bn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=eo(e),c=Dt().disable("x-powered-by").use(a);if(e.compression){let S=await Ce("compression");c.use(S(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Dt.json()],raw:[e.rawParser||Dt.raw(),Vr],upload:e.upload?await _r({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Ut({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=gn.createServer(c);p.push(S),b.push(l(S,e.http.listen))}if(e.https){let S=hn.createServer(e.https.options,c);p.push(S),b.push(l(S,e.https.listen))}return e.gracefulShutdown&&Yr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(S=>S())}};import{OpenApiBuilder as ls}from"openapi3-ts/oas31";import*as Ro from"ramda";import*as R from"ramda";var to=e=>le(e)&&"or"in e,ro=e=>le(e)&&"and"in e,Ht=e=>!ro(e)&&!to(e),oo=e=>{let t=R.filter(Ht,e),r=R.chain(R.prop("and"),R.filter(ro,e)),[o,n]=R.partition(Ht,r),s=R.concat(t,o),a=R.filter(to,e);return R.map(R.prop("or"),R.concat(a,n)).reduce((d,p)=>me(d,R.map(l=>Ht(l)?[l]:l.and,p),([l,b])=>R.concat(l,b)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as Ft,isSchemaObject as yt}from"openapi3-ts/oas31";import*as m from"ramda";import{z as F}from"zod";var Se=(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=>Se(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 no=["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 so=50,ao="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Rn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Tn=/^\d{4}-\d{2}-\d{2}$/,On=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Pn=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$/,po=e=>e.replace(zt,t=>`{${t.slice(1)}}`),An=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),wn=({_def:{innerType:e}},{next:t})=>t(e),En=()=>({format:"any"}),zn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},In=e=>{let t=e.unwrap();return{type:"string",format:t instanceof F.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Zn=({options:e},{next:t})=>({oneOf:e.map(t)}),vn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),kn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return m.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Cn=m.tryCatch(e=>{let[t,r]=e.filter(yt).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=m.mergeDeepWith(kn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=m.union(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=me(t.examples||[],r.examples||[],([n,s])=>m.mergeDeepRight(n,s))),o},(e,t)=>({allOf:t})),jn=({_def:{left:e,right:t}},{next:r})=>Cn([e,t].map(r)),Nn=(e,{next:t})=>t(e.unwrap()),Ln=(e,{next:t})=>t(e.unwrap()),Mn=(e,{next:t})=>{let r=t(e.unwrap());return yt(r)&&(r.type=mo(r)),r},co=e=>{let t=m.toLower(m.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},io=e=>({type:co(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Un=({value:e})=>({type:co(e),const:e}),Dn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ke(c)?c instanceof F.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=ft(e,r)),s.length&&(a.required=s),a},Hn=()=>({type:"null"}),Kn=({},e)=>{if(e.isResponse)throw new B("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:ao}}},Fn=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:ao}}},qn=({},e)=>{throw new B(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Bn=()=>({type:"boolean"}),$n=()=>({type:"integer",format:"bigint"}),_n=e=>e.every(t=>t instanceof F.ZodLiteral),Vn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof F.ZodEnum||e instanceof F.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=ft(F.object(m.fromPairs(m.xprod(o,[t]))),r),n.required=o),n}if(e instanceof F.ZodLiteral)return{type:"object",properties:ft(F.object({[e.value]:t}),r),required:[e.value]};if(e instanceof F.ZodUnion&&_n(e.options)){let o=m.map(s=>`${s.value}`,e.options),n=m.fromPairs(m.xprod(o,[t]));return{type:"object",properties:ft(F.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Gn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Jn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Wn=({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:j,isDuration:X,_def:{checks:h}})=>{let v=h.find(N=>N.kind==="regex"),E=h.find(N=>N.kind==="datetime"),k=h.some(N=>N.kind==="jwt"),H=h.find(N=>N.kind==="length"),I={type:"string"},K={"date-time":l,byte:w,base64url:j,date:S,time:y,duration:X,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:A,jwt:k,ip:d,cidr:b,emoji:p};for(let N in K)if(K[N]){I.format=N;break}return H&&([I.minLength,I.maxLength]=[H.value,H.value]),r!==null&&(I.minLength=r),o!==null&&(I.maxLength=o),S&&(I.pattern=Tn.source),y&&(I.pattern=On.source),l&&(I.pattern=Pn(E?.offset).source),v&&(I.pattern=v.regex.source),I},Yn=({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},ft=({shape:e},t)=>m.map(t,e),Qn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Rn?.[t]},mo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Xn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&yt(o)){let s=rt(e,Qn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(F.any())}if(!t&&n.type==="preprocess"&&yt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},es=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ts=(e,{next:t})=>t(e.unwrap()),rs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),os=(e,{next:t})=>t(e.unwrap().shape.raw),lo=e=>e.length?m.fromPairs(m.zip(m.times(t=>`example${t+1}`,e.length),m.map(m.objOf("value"),e))):void 0,uo=(e,t,r=[])=>m.pipe(ne,m.map(m.when(o=>m.type(o)==="Object",m.omit(r))),lo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ns=(e,t)=>m.pipe(ne,m.filter(m.has(t)),m.pluck(t),lo)({schema:e,variant:"original",validate:!0,pullProps:!0}),ss=(e,t)=>t?.includes(e)||e.startsWith("x-")||no.includes(e),fo=({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),b=et(e),S=o.includes("query"),y=o.includes("params"),w=o.includes("headers"),A=h=>y&&b.includes(h),j=m.chain(m.filter(h=>h.type==="header"),d??[]).map(({name:h})=>h),X=h=>w&&(c?.(h,t,e)??ss(h,j));return Object.entries(l.shape).reduce((h,[v,E])=>{let k=A(v)?"path":X(v)?"header":S?"query":void 0;if(!k)return h;let H=Se(E,{rules:{...a,...qt},onEach:Bt,onMissing:$t,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),I=s==="components"?n(E,H,se(p,v)):H,{_def:K}=E;return h.concat({name:v,in:k,deprecated:K[g]?.isDeprecated,required:!E.isOptional(),description:H.description||p,schema:I,examples:ns(l,v)})},[])},qt={ZodString:Wn,ZodNumber:Yn,ZodBigInt:$n,ZodBoolean:Bn,ZodNull:Hn,ZodArray:Gn,ZodTuple:Jn,ZodRecord:Vn,ZodObject:Dn,ZodLiteral:Un,ZodIntersection:jn,ZodUnion:Zn,ZodAny:En,ZodDefault:An,ZodEnum:io,ZodNativeEnum:io,ZodEffects:Xn,ZodOptional:Nn,ZodNullable:Mn,ZodDiscriminatedUnion:vn,ZodBranded:ts,ZodDate:qn,ZodCatch:wn,ZodPipeline:es,ZodLazy:rs,ZodReadonly:Ln,[V]:In,[Ae]:zn,[ye]:Fn,[fe]:Kn,[ie]:os},Bt=(e,{isResponse:t,prev:r})=>{if(Ft(r))return{};let{description:o,_def:n}=e,s=e instanceof F.ZodLazy,a=r.type!==void 0,c=t&&Ke(e),d=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[g]?.isDeprecated&&(p.deprecated=!0),d&&(p.type=mo(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},$t=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Kt=(e,t)=>{if(Ft(e))return e;let r={...e};return r.properties&&(r.properties=m.omit(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>m.omit(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Kt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Kt(o,t))),r},yo=e=>Ft(e)?e:m.omit(["examples"],e),go=({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} ${vt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let b=yo(Se(r,{rules:{...p,...qt},onEach:Bt,onMissing:$t,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),S={schema:a==="components"?s(r,b,se(l)):b,examples:uo(r,!0)};return{description:l,content:m.fromPairs(m.xprod(o,[S]))}},is=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},as=({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},ps=({name:e})=>({type:"apiKey",in:"header",name:e}),cs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ds=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ms=({flows:e={}})=>({type:"oauth2",flows:m.map(t=>({...t,scopes:t.scopes||{}}),m.reject(m.isNil,e))}),ho=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?is(o):o.type==="input"?as(o,t):o.type==="header"?ps(o):o.type==="cookie"?cs(o):o.type==="openid"?ds(o):ms(o);return e.map(o=>o.map(r))},xo=(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:[]})},{})),bo=({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=yo(Kt(Se(r,{rules:{...a,...qt},onEach:Bt,onMissing:$t,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:s==="components"?n(r,p,se(d)):p,examples:uo($(r),!1,c)};return{description:d,content:{[o]:l}}},So=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)},[]),_t=e=>e.length<=so?e:e.slice(0,so-1)+"\u2026",gt=e=>e.length?e.slice():void 0;var Vt=class extends ls{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||se(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new B(`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});je({routing:t,onEndpoint:(y,w,A)=>{let j={path:w,method:A,endpoint:y,composition:b,brandHandling:c,makeRef:this.makeRef.bind(this)},[X,h]=["short","long"].map(y.getDescription.bind(y)),v=X?_t(X):l&&h?_t(h):void 0,E=r.inputSources?.[A]||It[A],k=this.ensureUniqOperationId(w,A,y.getOperationId(A)),H=oo(y.getSecurity()),I=fo({...j,inputSources:E,isHeader:p,security:H,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:A,path:w,operationId:k})}),K={};for(let te of Ze){let pe=y.getResponses(te);for(let{mimeTypes:wt,schema:Et,statusCodes:Ue}of pe)for(let De of Ue)K[De]=go({...j,variant:te,schema:Et,mimeTypes:wt,statusCode:De,hasMultipleStatusCodes:pe.length>1||Ue.length>1,description:a?.[`${te}Response`]?.call(null,{method:A,path:w,operationId:k,statusCode:De})})}let N=E.includes("body")?bo({...j,paramNames:Ro.pluck("name",I),schema:y.getSchema("input"),mimeType:Z[y.getRequestType()],description:a?.requestBody?.call(null,{method:A,path:w,operationId:k})}):void 0,At=xo(ho(H,E),y.getScopes(),te=>{let pe=this.ensureUniqSecuritySchemaName(te);return this.addSecurityScheme(pe,te),pe}),Qe={operationId:k,summary:v,description:h,deprecated:y.isDeprecated||void 0,tags:gt(y.getTags()),parameters:gt(I),requestBody:N,security:gt(At),responses:K};this.addPath(po(w),{[A]:Qe})}}),d&&(this.rootDoc.tags=So(d))}};import{createRequest as us,createResponse as fs}from"node-mocks-http";var ys=e=>us({...e,headers:{"content-type":Z.json,...e?.headers}}),gs=e=>fs(e),hs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:vr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},To=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ys(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}},xs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=To(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},bs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=To(o),d=tt(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(oe(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import*as Io from"ramda";import Pt from"typescript";import{z as Vs}from"zod";import*as Eo from"ramda";import Q from"typescript";var Oo=["get","post","put","delete","patch"];import*as W from"ramda";import u from"typescript";var i=u.factory,ht=[i.createModifier(u.SyntaxKind.ExportKeyword)],Ss=[i.createModifier(u.SyntaxKind.AsyncKeyword)],We={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Gt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Jt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},Rs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Wt=e=>typeof e=="string"&&Rs.test(e)?i.createIdentifier(e):P(e),xt=(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)))),bt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ne=e=>Object.entries(e).map(([t,r])=>bt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Yt=(e,t=[])=>i.createConstructorDeclaration(We.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&W.map(f,t)):e,Qt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,Wt(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=W.reject(W.isNil,[o?"@deprecated":void 0,n]);return a.length?Gt(s,a.join(" ")):s},Xt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),er=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),C=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&ht,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),tr=(e,t)=>Y(e,i.createUnionTypeNode(W.map(D,t)),{expose:!0}),Y=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?ht:void 0,e,n&&sr(n),t);return o?Gt(s,o):s},Po=(e,t)=>i.createPropertyDeclaration(We.public,e,void 0,f(t),void 0),rr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(We.public,void 0,e,void 0,o&&sr(o),t,n,i.createBlock(r)),or=(e,t,{typeParams:r}={})=>i.createClassDeclaration(ht,e,r&&sr(r),void 0,t),nr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),St=e=>f(Promise.name,[e]),Rt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?ht:void 0,e,void 0,void 0,t);return o?Gt(n,o):n},sr=e=>(Array.isArray(e)?e.map(t=>W.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)}),Te=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ss:void 0,void 0,Array.isArray(e)?W.map(bt,e):Ne(e),void 0,void 0,t),T=e=>e,Ye=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),O=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Le=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Tt=(e,t)=>f("Extract",[e,t]),ir=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Ao=e=>i.createUnionTypeNode([f(e),St(e)]),ar=(e,t)=>i.createFunctionTypeNode(void 0,Ne(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),D=e=>i.createLiteralTypeNode(P(e)),Ts=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],wo=e=>Ts.includes(e.kind);var Ot=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=tr("Method",Oo);someOfType=Y("SomeOf",_("T",nr("T")),{params:["T"]});requestType=Y("Request",nr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>tr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Rt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>C("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Wt(t),i.createArrayLiteralExpression(Eo.map(P,r))))),{expose:!0});makeImplementationType=()=>Y(this.ids.implementationType,ar({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Q.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Qt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},St(Q.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Q.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>C(this.ids.parseRequestFn,Te({[this.ids.requestParameter.text]:Q.SyntaxKind.StringKeyword},i.createAsExpression(O(this.ids.requestParameter,T("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>C(this.ids.substituteFn,Te({[this.ids.pathParameter.text]:Q.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Qt},i.createBlock([C(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],Q.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([ir(this.ids.pathParameter,O(this.ids.pathParameter,T("replace"))(xt(":",[this.ids.keyParameter]),Te([],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=()=>rr(this.ids.provideMethod,Ne({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:_(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[C(er(this.ids.methodParameter,this.ids.pathParameter),O(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(O(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(O(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:St(_(this.interfaces.response,"K"))});makeClientClass=t=>or(t,[Yt([bt(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:We.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>xt("?",[Le(URLSearchParams.name,t)]);makeFetchURL=()=>Le(URL.name,xt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(T("method"),O(this.ids.methodParameter,T("toUpperCase"))()),r=i.createPropertyAssignment(T("headers"),Ye(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(Z.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(T("body"),Ye(this.ids.hasBodyConst,O(JSON[Symbol.toStringTag],T("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=C(this.ids.responseConst,i.createAwaitExpression(O(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=C(this.ids.hasBodyConst,i.createLogicalNot(O(i.createArrayLiteralExpression([P("get"),P("delete")]),T("includes"))(this.ids.methodParameter))),a=C(this.ids.searchParamsConst,Ye(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=C(this.ids.contentTypeConst,O(this.ids.responseConst,T("headers"),T("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(Q.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=C(this.ids.isJsonConst,O(this.ids.contentTypeConst,T("startsWith"))(P(Z.json))),l=i.createReturnStatement(O(this.ids.responseConst,Ye(this.ids.isJsonConst,P(T("json")),P(T("text"))))());return C(this.ids.defaultImplementationConst,Te([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=()=>Yt(Ne({request:"K",params:_(this.interfaces.input,"K")}),[C(er(this.ids.pathParameter,this.ids.restConst),O(this.ids.substituteFn)(i.createElementAccessExpression(O(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),C(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),ir(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Le("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([Re(T("event"),t)]);makeOnMethod=()=>rr(this.ids.onMethod,Ne({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:ar({[this.ids.dataParameter.text]:_(Tt("R",Xt(this.makeEventNarrow("E"))),D(T("data")))},Ao(Q.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(O(i.createThis(),this.ids.sourceProp,T("addEventListener"))(this.ids.eventParameter,Te([this.ids.msgParameter],O(this.ids.handlerParameter)(O(JSON[Symbol.toStringTag],T("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),T("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",D(T("event")))}});makeSubscriptionClass=t=>or(t,[Po(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:Tt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Q.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Tt(_(this.interfaces.positive,"K"),Xt(this.makeEventNarrow(Q.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[C(this.ids.clientConst,Le(t)),O(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),O(Le(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),Te(["time"],i.createBlock([])))]};import*as z from"ramda";import x from"typescript";import{z as cr}from"zod";var{factory:q}=x,Os={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},pr={name:z.path(["name","text"]),type:z.path(["type"]),optional:z.path(["questionToken"])},Ps=({value:e})=>D(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&&Ke(a)?a instanceof cr.ZodOptional:a.isOptional();return Re(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:d[g]?.isDeprecated})});return q.createTypeLiteralNode(n)},ws=({element:e},{next:t})=>q.createArrayTypeNode(t(e)),Es=({options:e})=>q.createUnionTypeNode(e.map(D)),zo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(wo(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},zs=e=>Os?.[e.kind],Is=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=rt(e,zs(o)),s={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.SyntaxKind.AnyKeyword)}return o},Zs=e=>q.createUnionTypeNode(Object.values(e.enum).map(D)),vs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?q.createUnionTypeNode([o,f(x.SyntaxKind.UndefinedKeyword)]):o},ks=(e,{next:t})=>q.createUnionTypeNode([t(e.unwrap()),D(null)]),Cs=({items:e,_def:{rest:t}},{next:r})=>q.createTupleTypeNode(e.map(r).concat(t===null?[]:q.createRestTypeNode(r(t)))),js=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Ns=z.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=z.chain(z.prop("members"),e),r=z.uniqWith((...o)=>{if(!z.eqBy(pr.name,...o))return!1;if(z.both(z.eqBy(pr.type),z.eqBy(pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),Ls=({_def:{left:e,right:t}},{next:r})=>Ns([e,t].map(r)),Ms=({_def:e},{next:t})=>t(e.innerType),ae=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=()=>D(null),qs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Bs=e=>{let t=e.unwrap(),r=f(x.SyntaxKind.StringKeyword),o=f("Buffer"),n=q.createUnionTypeNode([r,o]);return t instanceof cr.ZodString?r:t instanceof cr.ZodUnion?n:o},$s=(e,{next:t})=>t(e.unwrap().shape.raw),_s={ZodString:ae(x.SyntaxKind.StringKeyword),ZodNumber:ae(x.SyntaxKind.NumberKeyword),ZodBigInt:ae(x.SyntaxKind.BigIntKeyword),ZodBoolean:ae(x.SyntaxKind.BooleanKeyword),ZodAny:ae(x.SyntaxKind.AnyKeyword),ZodUndefined:ae(x.SyntaxKind.UndefinedKeyword),[fe]:ae(x.SyntaxKind.StringKeyword),[ye]:ae(x.SyntaxKind.StringKeyword),ZodNull:Fs,ZodArray:ws,ZodTuple:Cs,ZodRecord:js,ZodObject:As,ZodLiteral:Ps,ZodIntersection:Ls,ZodUnion:zo,ZodDefault:Ms,ZodEnum:Es,ZodNativeEnum:Zs,ZodEffects:Is,ZodOptional:vs,ZodNullable:ks,ZodDiscriminatedUnion:zo,ZodBranded:Us,ZodCatch:Hs,ZodPipeline:Ks,ZodLazy:qs,ZodReadonly:Ds,[V]:Bs,[ie]:$s},dr=(e,{brandHandling:t,ctx:r})=>Se(e,{rules:{...t,..._s},onMissing:()=>f(x.SyntaxKind.AnyKeyword),ctx:r});var mr=class extends Ot{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=D(null);this.aliases.set(t,Y(o,n)),this.aliases.set(t,Y(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=Vs.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}};je({routing:t,onEndpoint:(y,w,A)=>{let j=se.bind(null,A,w),{isDeprecated:X}=y,h=`${A} ${w}`,v=Y(j("input"),dr(y.getSchema("input"),l),{comment:h});this.program.push(v);let E=Ze.reduce((I,K)=>{let N=y.getResponses(K),At=Io.chain(([te,{schema:pe,mimeTypes:wt,statusCodes:Et}])=>{let Ue=Y(j(K,"variant",`${te+1}`),dr(wt?pe:d,b),{comment:h});return this.program.push(Ue),Et.map(De=>Re(De,Ue.name))},Array.from(N.entries())),Qe=Rt(j(K,"response","variants"),At,{comment:h});return this.program.push(Qe),Object.assign(I,{[K]:Qe})},{});this.paths.add(w);let k=D(h),H={input:f(v.name),positive:this.someOf(E.positive),negative:this.someOf(E.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,k),_(this.interfaces.negative,k)]),encoded:i.createIntersectionTypeNode([f(E.positive.name),f(E.negative.name)])};this.registry.set(h,{isDeprecated:X,store:H}),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:Jt(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&Pt.addSyntheticLeadingComment(Pt.addSyntheticLeadingComment(i.createEmptyStatement(),Pt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Pt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>Jt(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 Ce("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 Me}from"zod";var vo=(e,t)=>Me.object({data:t,event:Me.literal(e),id:Me.string().optional(),retry:Me.number().int().positive().optional()}),Gs=(e,t,r)=>vo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Js=1e4,Zo=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":Z.sse,"cache-control":"no-cache"}),Ws=e=>new G({handler:async({response:t})=>setTimeout(()=>Zo(t),Js)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Zo(t),t.write(Gs(e,r,o),"utf-8"),t.flush?.()}}}),Ys=e=>new xe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>vo(o,n));return{mimeType:Z.sse,schema:r.length?Me.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Me.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=we(r);Be(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ge(a),"utf-8")}t.end()}}),lr=class extends be{constructor(t){super(Ys(t)),this.middlewares=[Ws(t)]}};var Qs={dateIn:yr,dateOut:gr,file:it,upload:br,raw:xr};export{Ve as BuiltinLogger,Ge as DependsOnMethod,Vt as Documentation,B as DocumentationError,be as EndpointsFactory,lr as EventStreamFactory,ee as InputValidationError,mr as Integration,G as Middleware,He as MissingPeerError,ce as OutputValidationError,xe as ResultHandler,Oe as RoutingError,Je as ServeStatic,Yo as arrayEndpointsFactory,Lt as arrayResultHandler,xn as attachRouting,Ho as createConfig,bn as createServer,Wo as defaultEndpointsFactory,_e as defaultResultHandler,we as ensureHttpError,Qs as ez,ne as getExamples,de as getMessageFromError,xs as testEndpoint,bs 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.1",
|
|
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.14.0",
|
|
65
65
|
"node-mocks-http": "^1.16.2",
|
|
66
66
|
"openapi3-ts": "^4.4.0",
|
|
67
67
|
"ramda": "^0.30.1"
|