express-zod-api 22.12.0-beta.1 → 22.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -1
- package/CONTRIBUTING.md +4 -4
- package/README.md +35 -24
- package/SECURITY.md +1 -1
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +16 -4
- package/dist/index.d.ts +16 -4
- package/dist/index.js +8 -8
- package/migration/index.cjs +2 -2
- package/migration/index.js +3 -3
- package/package.json +11 -9
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,39 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 22
|
|
4
4
|
|
|
5
|
+
### v22.12.0
|
|
6
|
+
|
|
7
|
+
- Featuring HTML forms support (URL Encoded request body):
|
|
8
|
+
- Introducing the new proprietary schema `ez.form()` accepting an object shape or a custom `z.object()` schema;
|
|
9
|
+
- Introducing the new config option `formParser` having `express.urlencoded()` as the default value;
|
|
10
|
+
- Requests to Endpoints having `input` schema assigned with `ez.form()` are parsed using `formParser`;
|
|
11
|
+
- Exception: requests to Endpoints having `ez.upload()` within `ez.form()` are still parsed by `express-fileupload`.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { defaultEndpointsFactory, ez } from "express-zod-api";
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
|
|
17
|
+
// The request content type should be "application/x-www-form-urlencoded"
|
|
18
|
+
export const submitFeedbackEndpoint = defaultEndpointsFactory.build({
|
|
19
|
+
method: "post",
|
|
20
|
+
input: ez.form({
|
|
21
|
+
name: z.string().min(1),
|
|
22
|
+
email: z.string().email(),
|
|
23
|
+
message: z.string().min(1),
|
|
24
|
+
}),
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### v22.11.2
|
|
29
|
+
|
|
30
|
+
- Fixed: allow future versions of Express 5:
|
|
31
|
+
- Incorrect condition for the peer dependency was introduced in v21.0.0.
|
|
32
|
+
|
|
33
|
+
```diff
|
|
34
|
+
- "express": "^4.21.1 || 5.0.1",
|
|
35
|
+
+ "express": "^4.21.1 || ^5.0.1",
|
|
36
|
+
```
|
|
37
|
+
|
|
5
38
|
### v22.11.1
|
|
6
39
|
|
|
7
40
|
- Simplified the type of `requestMock` returned from `testEndpoint` and `testMiddleware`.
|
|
@@ -714,7 +747,7 @@ const after: Routing = {
|
|
|
714
747
|
- Introducing `errorHandler` option for `testMiddleware()` method:
|
|
715
748
|
- If your middleware throws an error there was no ability to make assertions other than the thrown error;
|
|
716
749
|
- New option can be assigned with a function for transforming the error into response, so that `testMiddlware` itself
|
|
717
|
-
would not throw, enabling usage of all returned entities for
|
|
750
|
+
would not throw, enabling usage of all returned entities for multiple assertions in test;
|
|
718
751
|
- The feature suggested by [@williamgcampbell](https://github.com/williamgcampbell).
|
|
719
752
|
|
|
720
753
|
```ts
|
package/CONTRIBUTING.md
CHANGED
|
@@ -20,11 +20,11 @@ Which is highly appreciated as well. Consider these steps:
|
|
|
20
20
|
|
|
21
21
|
- Fork the repo,
|
|
22
22
|
- Create a new branch in your fork of the repo (don't change `master`),
|
|
23
|
-
- Install the dependencies using `
|
|
24
|
-
- Install the pre-commit hooks using `
|
|
23
|
+
- Install the dependencies using `yarn`,
|
|
24
|
+
- Install the pre-commit hooks using `yarn install_hooks`,
|
|
25
25
|
- Make changes,
|
|
26
|
-
- Run the tests using `
|
|
27
|
-
- In case you wanna run tests from `example` and `*-test` workspaces, run `
|
|
26
|
+
- Run the tests using `yarn test`,
|
|
27
|
+
- In case you wanna run tests from `example` and `*-test` workspaces, run `yarn build` first.
|
|
28
28
|
- Commit everything,
|
|
29
29
|
- Push your branch into your fork,
|
|
30
30
|
- Create a PR between the forks:
|
package/README.md
CHANGED
|
@@ -41,11 +41,12 @@ Start your API server with I/O schema validation and custom middlewares in minut
|
|
|
41
41
|
8. [Error handling](#error-handling)
|
|
42
42
|
9. [Production mode](#production-mode)
|
|
43
43
|
10. [Non-object response](#non-object-response) including file downloads
|
|
44
|
-
11. [
|
|
45
|
-
12. [
|
|
46
|
-
13. [
|
|
47
|
-
14. [
|
|
48
|
-
15. [Testing
|
|
44
|
+
11. [HTML Forms (URL encoded)](#html-forms-url-encoded)
|
|
45
|
+
12. [File uploads](#file-uploads)
|
|
46
|
+
13. [Serving static files](#serving-static-files)
|
|
47
|
+
14. [Connect to your own express app](#connect-to-your-own-express-app)
|
|
48
|
+
15. [Testing endpoints](#testing-endpoints)
|
|
49
|
+
16. [Testing middlewares](#testing-middlewares)
|
|
49
50
|
6. [Special needs](#special-needs)
|
|
50
51
|
1. [Different responses for different status codes](#different-responses-for-different-status-codes)
|
|
51
52
|
2. [Array response](#array-response) for migrating legacy APIs
|
|
@@ -166,8 +167,8 @@ Install the framework, its peer dependencies and type assistance packages using
|
|
|
166
167
|
|
|
167
168
|
```shell
|
|
168
169
|
# example for yarn and express 5 (recommended):
|
|
169
|
-
yarn add express-zod-api express
|
|
170
|
-
yarn add -D @types/express
|
|
170
|
+
yarn add express-zod-api express zod typescript http-errors
|
|
171
|
+
yarn add -D @types/express @types/node @types/http-errors
|
|
171
172
|
```
|
|
172
173
|
|
|
173
174
|
Ensure having the following options in your `tsconfig.json` file in order to make it work as expected:
|
|
@@ -964,43 +965,53 @@ const fileStreamingEndpointsFactory = new EndpointsFactory(
|
|
|
964
965
|
);
|
|
965
966
|
```
|
|
966
967
|
|
|
967
|
-
##
|
|
968
|
+
## HTML Forms (URL encoded)
|
|
968
969
|
|
|
969
|
-
|
|
970
|
-
|
|
970
|
+
Use the proprietary schema `ez.form()` with an object shape or a custom `z.object()` with form fields in order to
|
|
971
|
+
describe the `input` schema of an Endpoint. Requests to the Endpoint are parsed using the `formParser` config option,
|
|
972
|
+
which is `express.urlencoded()` by default. The request content type should be `application/x-www-form-urlencoded`
|
|
973
|
+
(default for HTML forms without uploads).
|
|
971
974
|
|
|
972
|
-
```
|
|
973
|
-
import {
|
|
975
|
+
```ts
|
|
976
|
+
import { defaultEndpointsFactory, ez } from "express-zod-api";
|
|
977
|
+
import { z } from "zod";
|
|
974
978
|
|
|
975
|
-
const
|
|
976
|
-
|
|
979
|
+
export const submitFeedbackEndpoint = defaultEndpointsFactory.build({
|
|
980
|
+
method: "post",
|
|
981
|
+
input: ez.form({
|
|
982
|
+
name: z.string().min(1),
|
|
983
|
+
email: z.string().email(),
|
|
984
|
+
message: z.string().min(1),
|
|
985
|
+
}),
|
|
977
986
|
});
|
|
978
987
|
```
|
|
979
988
|
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
989
|
+
_Hint: for unlisted extra fields use the following syntax: `ez.form( z.object({}).passthrough() )`._
|
|
990
|
+
|
|
991
|
+
## File uploads
|
|
992
|
+
|
|
993
|
+
Install the following additional packages: `express-fileupload` and `@types/express-fileupload`, and enable or
|
|
994
|
+
configure file uploads. Refer to [documentation](https://www.npmjs.com/package/express-fileupload#available-options) on
|
|
995
|
+
available options. The `limitHandler` option is replaced by the `limitError` one. You can also connect an additional
|
|
996
|
+
middleware for restricting the ability to upload using the `beforeUpload` option. So the configuration for the limited
|
|
997
|
+
and restricted upload might look this way:
|
|
986
998
|
|
|
987
999
|
```typescript
|
|
988
1000
|
import createHttpError from "http-errors";
|
|
989
1001
|
|
|
990
1002
|
const config = createConfig({
|
|
991
|
-
upload: {
|
|
1003
|
+
upload: /* true or options: */ {
|
|
992
1004
|
limits: { fileSize: 51200 }, // 50 KB
|
|
993
1005
|
limitError: createHttpError(413, "The file is too large"), // handled by errorHandler in config
|
|
994
1006
|
beforeUpload: ({ request, logger }) => {
|
|
995
1007
|
if (!canUpload(request)) throw createHttpError(403, "Not authorized");
|
|
996
1008
|
},
|
|
1009
|
+
debug: true, // default
|
|
997
1010
|
},
|
|
998
1011
|
});
|
|
999
1012
|
```
|
|
1000
1013
|
|
|
1001
|
-
Then
|
|
1002
|
-
using `ez.upload()` schema. Together with a corresponding configuration option, this makes it possible to handle file
|
|
1003
|
-
uploads. Here is a simplified example:
|
|
1014
|
+
Then use `ez.upload()` schema for a corresponding property. The request content type must be `multipart/form-data`:
|
|
1004
1015
|
|
|
1005
1016
|
```typescript
|
|
1006
1017
|
import { z } from "zod";
|
package/SECURITY.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
| 21.x.x | Kesaria | 11.2024 | :white_check_mark: |
|
|
9
9
|
| 20.x.x | Zoey | 06.2024 | :white_check_mark: |
|
|
10
10
|
| 19.x.x | Dime | 05.2024 | :white_check_mark: |
|
|
11
|
-
| 18.x.x | Victoria | 04.2024 |
|
|
11
|
+
| 18.x.x | Victoria | 04.2024 | :x: |
|
|
12
12
|
| 17.x.x | Tonya | 02.2024 | :x: |
|
|
13
13
|
| 16.x.x | Nina | 12.2023 | :x: |
|
|
14
14
|
| 15.x.x | Vika | 12.2023 | :x: |
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:(0,bt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Wt=require("zod");var Yt=class{},V=class extends Yt{#e;#t;#r;constructor({input:t=Wt.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 Wt.z.ZodError?new X(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 m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ne=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends Ne{},St=class e extends Xe{#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 Mr(this.#e.inputSchema)?"upload":ht(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 Qt.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 Qt.z.ZodError?new X(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=_t(t),a={},c=null,m=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){m=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,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 Xt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends Xt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Jt(this.#e,{variant:"positive",args:[t],statusCodes:[Le.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Jt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[C.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=we(e);return Qe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.positive).json({status:"success",data:r})}}),Rt=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=we(r);return Qe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof 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=er.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new St({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:x,methods:l,getOperationId:b,inputSchema:Hr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:er.z.object({}),handler:async o=>(await t(o),{})})}},Kr=new ye(Ue),Fr=new ye(Rt);var Gr=S(require("ansis"),1),Jr=require("node:util"),rr=require("node:perf_hooks");var te=require("ansis"),qr=S(require("ramda"),1);var tr={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},Tt={debug:10,info:20,warn:30,error:40},Br=e=>Se(e)&&Object.keys(Tt).some(t=>t in e),$r=e=>e in Tt,_r=(e,t)=>Tt[e]<Tt[t],On=(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}`,On),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 m=[new Date().toISOString()];s&&m.push(c?tr.ctx(s):s),m.push(c?`${tr[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.prettyPrint(o)),Object.keys(a).length>0&&m.push(this.prettyPrint(a)),console.log(m.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=rr.performance.now();return()=>{let o=rr.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=S(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=S(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Wr.default.static(...this.params))}};var Pt=S(require("express"),1),ho=S(require("node:http"),1),bo=S(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ve(e)};var Xr=S(require("http-errors"),1);var Yr=S(require("ramda"),1);var Ot=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(C.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 be(`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 Xe){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,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new be(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...Qr(s,n))}};var Pn=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)},or=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new Ot(t()),a=new Map;if($e({routing:o,onEndpoint:(m,p,l,b)=>{Re()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.getRequestType()]||[],x=async(y,j)=>{let P=t(y);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:P,defaultHeaders:T}):T;for(let N in v)j.set(N,v[N])}return m.execute({request:y,response:j,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,Pn(p))};var et=S(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 m=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??=m()}};var ao=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,et.isHttpError)(r)?r:(0,et.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,et.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await 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)})}},wn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},An=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,m,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:An(l)})(c,m,p)}),o&&a.push(wn(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[h]={logger:s}),n()},uo=e=>t=>t?.res?.locals[h]?.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))),
|
|
1
|
+
"use strict";var dn=Object.create;var ct=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var ln=Object.getOwnPropertyNames;var un=Object.getPrototypeOf,fn=Object.prototype.hasOwnProperty;var yn=(e,t)=>{for(var r in t)ct(e,r,{get:t[r],enumerable:!0})},Er=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ln(t))!fn.call(e,n)&&n!==r&&ct(e,n,{get:()=>t[n],enumerable:!(o=mn(t,n))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?dn(un(e)):{},Er(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),gn=e=>Er(ct({},"__esModule",{value:!0}),e);var ni={};yn(ni,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>It,DocumentationError:()=>B,EndpointsFactory:()=>ye,EventStreamFactory:()=>Ht,InputValidationError:()=>X,Integration:()=>Dt,Middleware:()=>V,MissingPeerError:()=>ve,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>be,ServeStatic:()=>qe,arrayEndpointsFactory:()=>_r,arrayResultHandler:()=>Pt,attachRouting:()=>Po,createConfig:()=>Ir,createServer:()=>wo,defaultEndpointsFactory:()=>$r,defaultResultHandler:()=>Ue,ensureHttpError:()=>we,ez:()=>cn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>Wo,testMiddleware:()=>Yo});module.exports=gn(ni);var H=S(require("ramda"),1),Te=require("zod");var D=S(require("ramda"),1),$t=require("zod");var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var be=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.`}},dt=class extends Error{name="IOSchemaError"},ae=class extends dt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends dt{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 _t=/:([A-Za-z0-9_]+)/g,mt=e=>e.match(_t)?.map(t=>t.slice(1))||[],hn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},Vt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},bn=["body","query","params"],Gt=e=>e.method.toLowerCase(),lt=(e,t={})=>{let r=Gt(e);return r==="options"?{}:(t[r]||Vt[r]||bn).filter(o=>o==="files"?hn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof $t.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,xn=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return xe(t,(n[g]?.examples||[]).map(D.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 $t.z.ZodObject&&(n=xn(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},xe=(e,t,r)=>e.length&&t.length?D.xprod(e,t).map(r):e.concat(t),Ge=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Jt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=D.chain(o=>o.split(/[^A-Z0-9]/gi),e);return D.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Jt).join("")},ut=D.tryCatch((e,t)=>typeof e.parse(t),D.always(void 0)),Se=e=>typeof e=="object"&&e!==null,Re=D.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ft=S(require("ramda"),1),g=Symbol.for("express-zod-api"),Je=e=>{let t=e.describe(e.description);return t._def[g]=ft.clone(t._def[g])||{examples:[]},t},zr=(e,t)=>{if(!(g in e._def))return t;let r=Je(t);return r._def[g].examples=xe(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?ft.mergeDeepRight({...o},{...n}):n),r};var Sn=function(e){let t=Je(this);return t._def[g].examples.push(e),t},Rn=function(){let e=Je(this);return e._def[g].isDeprecated=!0,e},Tn=function(e){let t=Je(this);return t._def[g].defaultLabel=e,t},On=function(e){return new Te.z.ZodBranded({typeName:Te.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...H.clone(this._def[g]),brand:e}})},Pn=function(e){let t=typeof e=="function"?e:H.pipe(H.toPairs,H.map(([n,s])=>H.pair(e[String(n)]||n,s)),H.fromPairs),r=t(H.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 Sn.bind(this)}},deprecated:{get(){return Rn.bind(this)}},brand:{set(){},get(){return On.bind(this)}}}),Object.defineProperty(Te.z.ZodDefault.prototype,"label",{get(){return Tn.bind(this)}}),Object.defineProperty(Te.z.ZodObject.prototype,"remap",{get(){return Pn.bind(this)}}));function Ir(e){return e}var rr=require("zod");var er=require("zod");var L=require("node:assert/strict");var ke=require("zod");var yt=e=>!isNaN(e.getTime());var Oe=Symbol("DateIn"),Zr=()=>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(yt)).brand(Oe);var vr=require("zod");var Pe=Symbol("DateOut"),kr=()=>vr.z.date().refine(yt).transform(e=>e.toISOString()).brand(Pe);var We=require("zod"),ee=Symbol("File"),Cr=We.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),wn={buffer:()=>Cr.brand(ee),string:()=>We.z.string().brand(ee),binary:()=>Cr.or(We.z.string()).brand(ee),base64:()=>We.z.string().base64().brand(ee)};function gt(e){return wn[e||"string"]()}var Wt=require("zod"),ht=Symbol("Form"),jr=e=>(e instanceof Wt.z.ZodObject?e:Wt.z.object(e)).brand(ht);var Nr=require("zod");var le=Symbol("Raw"),Lr=(e={})=>Nr.z.object({raw:gt("buffer")}).extend(e).brand(le);var Mr=require("zod"),Ce=Symbol("Upload"),Ur=()=>Mr.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 Dr=(e,{next:t})=>e.options.some(t),An=({_def:e},{next:t})=>[e.left,e.right].some(t),bt=(e,{next:t})=>t(e.unwrap()),xt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Dr,ZodDiscriminatedUnion:Dr,ZodIntersection:An,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:bt,ZodNullable:bt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Ye=(e,{condition:t,rules:r=xt,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=>Ye(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Hr=e=>Ye(e,{condition:t=>t._def[g]?.brand===Ce,rules:{...xt,[ht]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),St=e=>Ye(e,{condition:t=>t._def[g]?.brand===le,maxDepth:3}),Kr=e=>Ye(e,{condition:t=>t._def[g]?.brand===ht,maxDepth:3}),Fr=(e,t)=>{let r=new WeakSet;return Ye(e,{maxDepth:300,rules:{...xt,ZodBranded:bt,ZodReadonly:bt,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:xt.ZodEffects}[t],ZodNaN:()=>(0,L.fail)("z.nan()"),ZodSymbol:()=>(0,L.fail)("z.symbol()"),ZodFunction:()=>(0,L.fail)("z.function()"),ZodMap:()=>(0,L.fail)("z.map()"),ZodSet:()=>(0,L.fail)("z.set()"),ZodBigInt:()=>(0,L.fail)("z.bigint()"),ZodVoid:()=>(0,L.fail)("z.void()"),ZodPromise:()=>(0,L.fail)("z.promise()"),ZodNever:()=>(0,L.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,L.fail)("z.date()"),[Pe]:()=>t==="in"&&(0,L.fail)("ez.dateOut()"),[Oe]:()=>t==="out"&&(0,L.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,L.fail)("ez.raw()"),[Ce]:()=>t==="out"&&(0,L.fail)("ez.upload()"),[ee]:()=>!1}})};var Rt=S(require("http-errors"),1);var Qe=S(require("http-errors"),1),qr=require("zod");var Yt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof qr.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}))},Xe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>(0,Qe.isHttpError)(e)?e:(0,Qe.default)(e instanceof X?400:500,ce(e),{cause:e.cause||e}),Ae=e=>Re()&&!e.expose?(0,Qe.default)(e.statusCode).message:e.message;var Tt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ae((0,Rt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:(0,Rt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Qt=require("zod");var Xt=class{},V=class extends Xt{#e;#t;#r;constructor({input:t=Qt.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 Qt.z.ZodError?new X(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 m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ne=class{nest(t){return Object.assign(t,{"":this})}};var et=class extends Ne{},Ot=class e extends et{#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 Hr(this.#e.inputSchema)?"upload":St(this.#e.inputSchema)?"raw":Kr(this.#e.inputSchema)?"form":"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 er.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 er.z.ZodError?new X(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){Tt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Gt(t),a={},c=null,m=null,p=lt(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){m=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};var ue=require("zod");var Br=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>zr(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 tr=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends tr{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Yt(this.#e,{variant:"positive",args:[t],statusCodes:[Le.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Yt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[C.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=we(e);return Xe(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.positive).json({status:"success",data:r})}}),Pt=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=we(r);return Xe(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof 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=rr.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new Ot({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:h,tags:x,methods:l,getOperationId:b,inputSchema:Br(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:rr.z.object({}),handler:async o=>(await t(o),{})})}},$r=new ye(Ue),_r=new ye(Pt);var Qr=S(require("ansis"),1),Xr=require("node:util"),nr=require("node:perf_hooks");var te=require("ansis"),Vr=S(require("ramda"),1);var or={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},wt={debug:10,info:20,warn:30,error:40},Gr=e=>Se(e)&&Object.keys(wt).some(t=>t in e),Jr=e=>e in wt,Wr=(e,t)=>wt[e]<wt[t],En=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=Vr.memoizeWith((e,t)=>`${e}${t}`,En),Yr=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=Qr.default.isSupported(),level:r=Re()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,Xr.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"||Wr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?or.ctx(s):s),m.push(c?`${or[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.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.performance.now();return()=>{let o=nr.performance.now()-r,{message:n,severity:s="debug",formatter:a=Yr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Fe=S(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 eo=S(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,eo.default.static(...this.params))}};var rt=S(require("express"),1),Ro=S(require("node:http"),1),To=S(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>S(require(e))))[t]}catch{}throw new ve(e)};var oo=S(require("http-errors"),1);var to=S(require("ramda"),1);var At=class{constructor(t){this.logger=t}#e=to.tryCatch(Fr);#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(C.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=mt(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 ro=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new be(`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=ro(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof et){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,m]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new be(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...ro(s,n))}};var zn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,oo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},sr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new At(t()),a=new Map;if($e({routing:o,onEndpoint:(m,p,l,b)=>{Re()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let h=n?.[m.getRequestType()]||[],x=async(y,j)=>{let P=t(y);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:P,defaultHeaders:T}):T;for(let N in v)j.set(N,v[N])}return m.execute({request:y,response:j,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...h,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...h,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,zn(p))};var tt=S(require("http-errors"),1);var co=require("node:timers/promises");var no=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",so=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",io=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ao=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),po=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var mo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(no(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 m=async()=>{for(let p of e)p.on("request",ao);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(io(p)||so(p))&&a(p);for await(let p of(0,co.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(po))};return{sockets:n,shutdown:()=>o??=m()}};var lo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,tt.isHttpError)(r)?r:(0,tt.default)(400,de(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),uo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,tt.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){Tt({response:o,logger:s,error:new pe(de(a),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Zn=e=>({log:e.debug.bind(e)}),fo=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,m,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:Zn(l)})(c,m,p)}),o&&a.push(In(o)),a},yo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},go=({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()},ho=e=>t=>t?.res?.locals[g]?.logger||e,bo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),xo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=mo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var $=require("ansis"),So=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),m=`
|
|
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(m.split(`
|
|
17
17
|
`).map((p,l)=>c[l]?c[l](p):p).join(`
|
|
18
|
-
`))};var xo=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.12.0-beta.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}=xo(e);return or({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}=xo(e),c=(0,Pt.default)().disable("x-powered-by").use(a);if(e.compression){let g=await Be("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}let m={json:[e.jsonParser||Pt.default.json()],raw:[e.rawParser||Pt.default.raw(),mo],upload:e.upload?await co({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),or({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,x)=>()=>g.listen(x,()=>r.info("Listening",x)),b=[];if(e.http){let g=ho.default.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=bo.default.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&yo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};var qo=require("openapi3-ts/oas31"),Bo=S(require("ramda"),1);var O=S(require("ramda"),1);var To=e=>Se(e)&&"or"in e,Oo=e=>Se(e)&&"and"in e,nr=e=>!Oo(e)&&!To(e),Po=e=>{let t=O.filter(nr,e),r=O.chain(O.prop("and"),O.filter(Oo,e)),[o,n]=O.partition(nr,r),s=O.concat(t,o),a=O.filter(To,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>xe(m,O.map(l=>nr(l)?[l]:l.and,p),([l,b])=>O.concat(l,b)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=S(require("ramda"),1),K=require("zod");var Ee=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[h]?.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),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var wo=["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,zo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},In=/^\d{4}-\d{2}-\d{2}$/,Zn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,vn=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(Bt,t=>`{${t.slice(1)}}`),kn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),Cn=({_def:{innerType:e}},{next:t})=>t(e),jn=()=>({format:"any"}),Nn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Ln=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Mn=({options:e},{next:t})=>({oneOf:e.map(t)}),Un=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Dn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Zo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Dn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>xe(e,t,([r,o])=>d.mergeDeepRight(r,o))},Hn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Zo)),d.isEmpty)),Kn=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Hn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Zo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Fn=({_def:{left:e,right:t}},{next:r})=>Kn([e,t].map(r)),qn=(e,{next:t})=>t(e.unwrap()),Bn=(e,{next:t})=>t(e.unwrap()),$n=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=ko(r)),r},vo=e=>{let t=d.toLower(d.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:vo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),_n=({value:e})=>({type:vo(e),const:e}),Vn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ge(c)?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=wt(e,r)),s.length&&(a.required=s),a},Gn=()=>({type:"null"}),Jn=({},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}}},Wn=({},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}}},Yn=({},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)},Qn=()=>({type:"boolean"}),Xn=()=>({type:"integer",format:"bigint"}),es=e=>e.every(t=>t instanceof K.z.ZodLiteral),ts=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=wt(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:wt(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&es(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:wt(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},rs=({_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},os=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ns=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:x,isBase64:y,isNANOID:j,isBase64url:P,isDuration:Q,_def:{checks:Z}})=>{let T=Z.find(k=>k.kind==="regex"),v=Z.find(k=>k.kind==="datetime"),N=Z.some(k=>k.kind==="jwt"),U=Z.find(k=>k.kind==="length"),z={type:"string"},q={"date-time":l,byte:y,base64url:P,date:g,time:x,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:j,jwt:N,ip:m,cidr:b,emoji:p};for(let k in q)if(q[k]){z.format=k;break}return U&&([z.minLength,z.maxLength]=[U.value,U.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),g&&(z.pattern=In.source),x&&(z.pattern=Zn.source),l&&(z.pattern=vn(v?.offset).source),T&&(z.pattern=T.regex.source),z},ss=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(y=>y.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(y=>y.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,x={type:e?"integer":"number",format:e?"int64":"double"};return p?x.minimum=m:x.exclusiveMinimum=m,g?x.maximum=b:x.exclusiveMaximum=b,x},wt=({shape:e},t)=>d.map(t,e),is=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return zn?.[t]},ko=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",as=(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,is(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.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},ps=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),cs=(e,{next:t})=>t(e.unwrap()),ds=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ms=(e,{next:t})=>t(e.unwrap().shape.raw),Co=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,jo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Co)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ls=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Co)({schema:e,variant:"original",validate:!0,pullProps:!0}),us=(e,t)=>t?.includes(e)||e.startsWith("x-")||wo.includes(e),No=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=G(r),g=ct(e),x=o.includes("query"),y=o.includes("params"),j=o.includes("headers"),P=T=>y&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),Z=T=>j&&(c?.(T,t,e)??us(T,Q));return Object.entries(b.shape).reduce((T,[v,N])=>{let U=P(v)?"path":Z(v)?"header":x?"query":void 0;if(!U)return T;let z=Ee(N,{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(N,z,me(l,v)):z,{_def:k}=N;return T.concat({name:v,in:U,deprecated:k[h]?.isDeprecated,required:!N.isOptional(),description:z.description||l,schema:q,examples:ls(b,v)})},[])},sr={ZodString:ns,ZodNumber:ss,ZodBigInt:Xn,ZodBoolean:Qn,ZodNull:Gn,ZodArray:rs,ZodTuple:os,ZodRecord:ts,ZodObject:Vn,ZodLiteral:_n,ZodIntersection:Fn,ZodUnion:Mn,ZodAny:jn,ZodDefault:kn,ZodEnum:Eo,ZodNativeEnum:Eo,ZodEffects:as,ZodOptional:qn,ZodNullable:$n,ZodDiscriminatedUnion:Un,ZodBranded:cs,ZodDate:Yn,ZodCatch:Cn,ZodPipeline:ps,ZodLazy:ds,ZodReadonly:Bn,[ee]:Ln,[Ce]:Nn,[Pe]:Wn,[Oe]:Jn,[le]:ms},ir=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=t&&Ge(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[h]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=ko(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},ar=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Lo=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Lo(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},Mo=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Uo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Vt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=Mo(Ee(r,{rules:{...p,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,g,me(b)):g,examples:jo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},fs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ys=({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},gs=({name:e})=>({type:"apiKey",in:"header",name:e}),hs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),bs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),xs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Do=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?fs(o):o.type==="input"?ys(o,t):o.type==="header"?gs(o):o.type==="cookie"?hs(o):o.type==="openid"?bs(o):xs(o);return e.map(o=>o.map(r))},Ho=(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:[]})},{})),Ko=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Lo(Ee(r,{rules:{...a,...sr},onEach:ir,onMissing:ar,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=Mo(l),x={schema:s==="components"?n(r,g,me(p)):g,examples:jo(G(r),!1,c)},y={description:p,content:{[o]:x}};return(b||ht(r))&&(y.required=!0),y},Fo=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)},[]),pr=e=>e.length<=Ao?e:e.slice(0,Ao-1)+"\u2026",At=e=>e.length?e.slice():void 0;var Et=class extends qo.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:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="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,j,P)=>{let Q={path:j,method:P,endpoint:y,composition:g,brandHandling:c,numericRange:l,makeRef:this.makeRef.bind(this)},[Z,T]=["short","long"].map(y.getDescription.bind(y)),v=Z?pr(Z):b&&T?pr(T):void 0,N=r.inputSources?.[P]||$t[P],U=this.ensureUniqOperationId(j,P,y.getOperationId(P)),z=Po(y.getSecurity()),q=No({...Q,inputSources:N,isHeader:p,security:z,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:P,path:j,operationId:U})}),k={};for(let ie of Me){let he=y.getResponses(ie);for(let{mimeTypes:Kt,schema:st,statusCodes:it}of he)for(let Ft of it)k[Ft]=Uo({...Q,variant:ie,schema:st,mimeTypes:Kt,statusCode:Ft,hasMultipleStatusCodes:he.length>1||it.length>1,description:a?.[`${ie}Response`]?.call(null,{method:P,path:j,operationId:U,statusCode:Ft})})}let Dt=N.includes("body")?Ko({...Q,paramNames:Bo.pluck("name",q),schema:y.getSchema("input"),mimeType:C[y.getRequestType()],description:a?.requestBody?.call(null,{method:P,path:j,operationId:U})}):void 0,nt=Ho(Do(z,N),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),Ht={operationId:U,summary:v,description:T,deprecated:y.isDeprecated||void 0,tags:At(y.getTags()),parameters:At(q),requestBody:Dt,security:At(nt),responses:k};this.addPath(Io(j),{[P]:Ht})}}),m&&(this.rootDoc.tags=Fo(m))}};var zt=require("node-mocks-http"),Ss=e=>(0,zt.createRequest)({...e,headers:{"content-type":C.json,...e?.headers}}),Rs=e=>(0,zt.createResponse)(e),Ts=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)}})},$o=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ss(e),s=Rs({req:n,...t});s.req=t?.req||n,n.res=s;let a=Ts(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},_o=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=$o(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Vo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=$o(o),m=dt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:m,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 en=S(require("ramda"),1),ot=S(require("typescript"),1),tn=require("zod");var Qo=S(require("ramda"),1),Y=S(require("typescript"),1);var Go=["get","post","put","delete","patch"];var re=S(require("ramda"),1),u=S(require("typescript"),1),i=u.default.factory,It=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Os=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],tt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),dr=(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)},Ps=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mr=e=>typeof e=="string"&&Ps.test(e)?i.createIdentifier(e):E(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)))),vt=(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])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),lr=(e,t=[])=>i.createConstructorDeclaration(tt.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&&re.map(f,t)):e,ur=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,mr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?cr(s,a.join(" ")):s},fr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),yr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&It,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),gr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?It:void 0,e,n&&Sr(n),t);return o?cr(s,o):s},Jo=(e,t)=>i.createPropertyDeclaration(tt.public,e,void 0,f(t),void 0),hr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(tt.public,void 0,e,void 0,o&&Sr(o),t,n,i.createBlock(r)),br=(e,t,{typeParams:r}={})=>i.createClassDeclaration(It,e,r&&Sr(r),void 0,t),xr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),kt=e=>f(Promise.name,[e]),Ct=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?It:void 0,e,void 0,void 0,t);return o?cr(n,o):n},Sr=e=>(Array.isArray(e)?e.map(t=>re.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?Os:void 0,void 0,Array.isArray(e)?re.map(vt,e):_e(e),void 0,void 0,t),w=e=>e,rt=(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),Ve=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),jt=(e,t)=>f("Extract",[e,t]),Rr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Wo=e=>i.createUnionTypeNode([f(e),kt(e)]),Tr=(e,t)=>i.createFunctionTypeNode(void 0,_e(e),f(t)),E=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(E(e)),ws=[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],Yo=e=>ws.includes(e.kind);var Nt=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=gr("Method",Go);someOfType=oe("SomeOf",W("T",xr("T")),{params:["T"]});requestType=oe("Request",xr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>gr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ct(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>ze(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(mr(t),i.createArrayLiteralExpression(Qo.map(E,r))))),{expose:!0});makeImplementationType=()=>oe(this.ids.implementationType,Tr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:ur,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},kt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.ids.parseRequestFn,Ie({[this.ids.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(A(this.ids.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>M(this.ids.substituteFn,Ie({[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:ur},i.createBlock([M(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([Rr(this.ids.pathParameter,A(this.ids.pathParameter,w("replace"))(Zt(":",[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=()=>hr(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"}}),[M(yr(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:kt(W(this.interfaces.response,"K"))});makeClientClass=t=>br(t,[lr([vt(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:tt.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>Zt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,Zt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.ids.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),rt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(C.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(w("body"),rt(this.ids.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=M(this.ids.responseConst,i.createAwaitExpression(A(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=M(this.ids.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.ids.methodParameter))),a=M(this.ids.searchParamsConst,rt(this.ids.hasBodyConst,E(""),this.makeSearchParams(this.ids.paramsArgument))),c=M(this.ids.contentTypeConst,A(this.ids.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=M(this.ids.isJsonConst,A(this.ids.contentTypeConst,w("startsWith"))(E(C.json))),l=i.createReturnStatement(A(this.ids.responseConst,rt(this.ids.isJsonConst,E(w("json")),E(w("text"))))());return M(this.ids.defaultImplementationConst,Ie([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>lr(_e({request:"K",params:W(this.interfaces.input,"K")}),[M(yr(this.ids.pathParameter,this.ids.restConst),A(this.ids.substituteFn)(i.createElementAccessExpression(A(this.ids.parseRequestFn)(this.ids.requestParameter),E(1)),this.ids.paramsArgument)),M(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),Rr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ze(w("event"),t)]);makeOnMethod=()=>hr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Tr({[this.ids.dataParameter.text]:W(jt("R",fr(this.makeEventNarrow("E"))),F(w("data")))},Wo(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.ids.sourceProp,w("addEventListener"))(this.ids.eventParameter,Ie([this.ids.msgParameter],A(this.ids.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(w("event")))}});makeSubscriptionClass=t=>br(t,[Jo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:jt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:jt(W(this.interfaces.positive,"K"),fr(this.makeEventNarrow(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.ids.clientConst,Ve(t)),A(this.ids.clientConst,this.ids.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(Ve(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(E("time"),Ie(["time"],i.createBlock([])))]};var I=S(require("ramda"),1),R=S(require("typescript"),1),Lt=require("zod");var{factory:_}=R.default,As={[R.default.SyntaxKind.AnyKeyword]:"",[R.default.SyntaxKind.BigIntKeyword]:BigInt(0),[R.default.SyntaxKind.BooleanKeyword]:!1,[R.default.SyntaxKind.NumberKeyword]:0,[R.default.SyntaxKind.ObjectKeyword]:{},[R.default.SyntaxKind.StringKeyword]:"",[R.default.SyntaxKind.UndefinedKeyword]:void 0},Or={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Es=({value:e})=>F(e),zs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&Ge(a)?a instanceof Lt.z.ZodOptional:a.isOptional();return ze(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[h]?.isDeprecated})});return _.createTypeLiteralNode(n)},Is=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),Zs=({options:e})=>_.createUnionTypeNode(e.map(F)),Xo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Yo(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},vs=e=>As?.[e.kind],ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=mt(e,vs(o)),s={number:R.default.SyntaxKind.NumberKeyword,bigint:R.default.SyntaxKind.BigIntKeyword,boolean:R.default.SyntaxKind.BooleanKeyword,string:R.default.SyntaxKind.StringKeyword,undefined:R.default.SyntaxKind.UndefinedKeyword,object:R.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||R.default.SyntaxKind.AnyKeyword)}return o},Cs=e=>_.createUnionTypeNode(Object.values(e.enum).map(F)),js=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(R.default.SyntaxKind.UndefinedKeyword)]):o},Ns=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),F(null)]),Ls=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),Ms=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Us=I.tryCatch(e=>{if(!e.every(R.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(Or.name,...o))return!1;if(I.both(I.eqBy(Or.type),I.eqBy(Or.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),Ds=({_def:{left:e,right:t}},{next:r})=>Us([e,t].map(r)),Hs=({_def:e},{next:t})=>t(e.innerType),ge=e=>()=>f(e),Ks=(e,{next:t})=>t(e.unwrap()),Fs=(e,{next:t})=>t(e.unwrap()),qs=({_def:e},{next:t})=>t(e.innerType),Bs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),$s=()=>F(null),_s=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Vs=e=>{let t=e.unwrap(),r=f(R.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Lt.z.ZodString?r:t instanceof Lt.z.ZodUnion?n:o},Gs=(e,{next:t})=>t(e.unwrap().shape.raw),Js={ZodString:ge(R.default.SyntaxKind.StringKeyword),ZodNumber:ge(R.default.SyntaxKind.NumberKeyword),ZodBigInt:ge(R.default.SyntaxKind.BigIntKeyword),ZodBoolean:ge(R.default.SyntaxKind.BooleanKeyword),ZodAny:ge(R.default.SyntaxKind.AnyKeyword),ZodUndefined:ge(R.default.SyntaxKind.UndefinedKeyword),[Oe]:ge(R.default.SyntaxKind.StringKeyword),[Pe]:ge(R.default.SyntaxKind.StringKeyword),ZodNull:$s,ZodArray:Is,ZodTuple:Ls,ZodRecord:Ms,ZodObject:zs,ZodLiteral:Es,ZodIntersection:Ds,ZodUnion:Xo,ZodDefault:Hs,ZodEnum:Zs,ZodNativeEnum:Cs,ZodEffects:ks,ZodOptional:js,ZodNullable:Ns,ZodDiscriminatedUnion:Xo,ZodBranded:Ks,ZodCatch:qs,ZodPipeline:Bs,ZodLazy:_s,ZodReadonly:Fs,[ee]:Vs,[le]:Gs},Pr=(e,{brandHandling:t,ctx:r})=>Ee(e,{rules:{...t,...Js},onMissing:()=>f(R.default.SyntaxKind.AnyKeyword),ctx:r});var Mt=class extends Nt{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,oe(o,n)),this.aliases.set(t,oe(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:m=tn.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};$e({routing:t,onEndpoint:(x,y,j)=>{let P=me.bind(null,j,y),{isDeprecated:Q}=x,Z=`${j} ${y}`,T=oe(P("input"),Pr(x.getSchema("input"),l),{comment:Z});this.program.push(T);let v=Me.reduce((z,q)=>{let k=x.getResponses(q),Dt=en.chain(([Ht,{schema:ie,mimeTypes:he,statusCodes:Kt}])=>{let st=oe(P(q,"variant",`${Ht+1}`),Pr(he?ie:m,b),{comment:Z});return this.program.push(st),Kt.map(it=>ze(it,st.name))},Array.from(k.entries())),nt=Ct(P(q,"response","variants"),Dt,{comment:Z});return this.program.push(nt),Object.assign(z,{[q]:nt})},{});this.paths.add(y);let N=F(Z),U={input:f(T.name),positive:this.someOf(v.positive),negative:this.someOf(v.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,N),W(this.interfaces.negative,N)]),encoded:i.createIntersectionTypeNode([f(v.positive.name),f(v.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:U}),this.tags.set(Z,x.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:dr(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 Oo=e=>{e.startupLogo!==!1&&So(process.stdout);let t=e.errorHandler||Ue,r=Gr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.12.0 (CJS)",env:process.env.NODE_ENV||"development"}),bo(r);let o=go({logger:r,config:e}),s={getLogger:ho(r),errorHandler:t},a=uo(s),c=lo(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Po=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Oo(e);return sr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},wo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Oo(e),c=(0,rt.default)().disable("x-powered-by").use(a);if(e.compression){let h=await Be("compression");c.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||rt.default.json()],raw:[e.rawParser||rt.default.raw(),yo],form:[e.formParser||rt.default.urlencoded()],upload:e.upload?await fo({config:e,getLogger:o}):[]};sr({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(h,x)=>()=>h.listen(x,()=>r.info("Listening",x)),b=[];if(e.http){let h=Ro.default.createServer(c);p.push(h),b.push(l(h,e.http.listen))}if(e.https){let h=To.default.createServer(e.https.options,c);p.push(h),b.push(l(h,e.https.listen))}return e.gracefulShutdown&&xo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(h=>h())}};var Vo=require("openapi3-ts/oas31"),Go=S(require("ramda"),1);var O=S(require("ramda"),1);var Ao=e=>Se(e)&&"or"in e,Eo=e=>Se(e)&&"and"in e,ir=e=>!Eo(e)&&!Ao(e),zo=e=>{let t=O.filter(ir,e),r=O.chain(O.prop("and"),O.filter(Eo,e)),[o,n]=O.partition(ir,r),s=O.concat(t,o),a=O.filter(Ao,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>xe(m,O.map(l=>ir(l)?[l]:l.and,p),([l,b])=>O.concat(l,b)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=S(require("ramda"),1),K=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),m=t&&t(e,{prev:c,...n});return m?{...c,...m}: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","detached-jws","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 Zo=50,ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",kn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Cn=/^\d{4}-\d{2}-\d{2}$/,jn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Nn=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$/,Co=e=>e.replace(_t,t=>`{${t.slice(1)}}`),Ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Mn=({_def:{innerType:e}},{next:t})=>t(e),Un=()=>({format:"any"}),Dn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Fn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),qn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},jo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(qn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>xe(e,t,([r,o])=>d.mergeDeepRight(r,o))},Bn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(jo)),d.isEmpty)),$n=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Bn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,jo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),_n=({_def:{left:e,right:t}},{next:r})=>$n([e,t].map(r)),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>t(e.unwrap()),Jn=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Lo(r)),r},No=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},vo=e=>({type:No(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Wn=({value:e})=>({type:No(e),const:e}),Yn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ge(c)?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Et(e,r)),s.length&&(a.required=s),a},Qn=()=>({type:"null"}),Xn=({},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:ko}}},es=({},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:ko}}},ts=({},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)},rs=()=>({type:"boolean"}),os=()=>({type:"integer",format:"bigint"}),ns=e=>e.every(t=>t instanceof K.z.ZodLiteral),ss=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Et(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Et(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&ns(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Et(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},is=({_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},as=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ps=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:h,isTime:x,isBase64:y,isNANOID:j,isBase64url:P,isDuration:Q,_def:{checks:Z}})=>{let T=Z.find(k=>k.kind==="regex"),v=Z.find(k=>k.kind==="datetime"),N=Z.some(k=>k.kind==="jwt"),U=Z.find(k=>k.kind==="length"),z={type:"string"},q={"date-time":l,byte:y,base64url:P,date:h,time:x,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:j,jwt:N,ip:m,cidr:b,emoji:p};for(let k in q)if(q[k]){z.format=k;break}return U&&([z.minLength,z.maxLength]=[U.value,U.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),h&&(z.pattern=Cn.source),x&&(z.pattern=jn.source),l&&(z.pattern=Nn(v?.offset).source),T&&(z.pattern=T.regex.source),z},cs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(y=>y.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(y=>y.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,h=l?l.inclusive:!0,x={type:e?"integer":"number",format:e?"int64":"double"};return p?x.minimum=m:x.exclusiveMinimum=m,h?x.maximum=b:x.exclusiveMaximum=b,x},Et=({shape:e},t)=>d.map(t,e),ds=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return kn?.[t]},Lo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ms=(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=ut(e,ds(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.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},ls=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),us=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ys=(e,{next:t})=>t(e.unwrap().shape.raw),Mo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Uo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Mo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),gs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Mo)({schema:e,variant:"original",validate:!0,pullProps:!0}),hs=(e,t)=>t?.includes(e)||e.startsWith("x-")||Io.includes(e),Do=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=G(r),h=mt(e),x=o.includes("query"),y=o.includes("params"),j=o.includes("headers"),P=T=>y&&h.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),Z=T=>j&&(c?.(T,t,e)??hs(T,Q));return Object.entries(b.shape).reduce((T,[v,N])=>{let U=P(v)?"path":Z(v)?"header":x?"query":void 0;if(!U)return T;let z=Ee(N,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(N,z,me(l,v)):z,{_def:k}=N;return T.concat({name:v,in:U,deprecated:k[g]?.isDeprecated,required:!N.isOptional(),description:z.description||l,schema:q,examples:gs(b,v)})},[])},ar={ZodString:ps,ZodNumber:cs,ZodBigInt:os,ZodBoolean:rs,ZodNull:Qn,ZodArray:is,ZodTuple:as,ZodRecord:ss,ZodObject:Yn,ZodLiteral:Wn,ZodIntersection:_n,ZodUnion:Kn,ZodAny:Un,ZodDefault:Ln,ZodEnum:vo,ZodNativeEnum:vo,ZodEffects:ms,ZodOptional:Vn,ZodNullable:Jn,ZodDiscriminatedUnion:Fn,ZodBranded:us,ZodDate:ts,ZodCatch:Mn,ZodPipeline:ls,ZodLazy:fs,ZodReadonly:Gn,[ee]:Hn,[Ce]:Dn,[Pe]:es,[Oe]:Xn,[le]:ys},pr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=t&&Ge(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[g]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=Lo(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},cr=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Ho=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Ho(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},Ko=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Fo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Jt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let h=Ko(Ee(r,{rules:{...p,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,h,me(b)):h,examples:Uo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},bs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},xs=({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},Ss=({name:e})=>({type:"apiKey",in:"header",name:e}),Rs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ts=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Os=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),qo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?bs(o):o.type==="input"?xs(o,t):o.type==="header"?Ss(o):o.type==="cookie"?Rs(o):o.type==="openid"?Ts(o):Os(o);return e.map(o=>o.map(r))},Bo=(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:[]})},{})),$o=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Ho(Ee(r,{rules:{...a,...ar},onEach:pr,onMissing:cr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),h=Ko(l),x={schema:s==="components"?n(r,h,me(p)):h,examples:Uo(G(r),!1,c)},y={description:p,content:{[o]:x}};return(b||St(r))&&(y.required=!0),y},_o=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)},[]),dr=e=>e.length<=Zo?e:e.slice(0,Zo-1)+"\u2026",zt=e=>e.length?e.slice():void 0;var It=class extends Vo.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:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:h="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,j,P)=>{let Q={path:j,method:P,endpoint:y,composition:h,brandHandling:c,numericRange:l,makeRef:this.makeRef.bind(this)},[Z,T]=["short","long"].map(y.getDescription.bind(y)),v=Z?dr(Z):b&&T?dr(T):void 0,N=r.inputSources?.[P]||Vt[P],U=this.ensureUniqOperationId(j,P,y.getOperationId(P)),z=zo(y.getSecurity()),q=Do({...Q,inputSources:N,isHeader:p,security:z,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:P,path:j,operationId:U})}),k={};for(let ie of Me){let he=y.getResponses(ie);for(let{mimeTypes:qt,schema:at,statusCodes:pt}of he)for(let Bt of pt)k[Bt]=Fo({...Q,variant:ie,schema:at,mimeTypes:qt,statusCode:Bt,hasMultipleStatusCodes:he.length>1||pt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:P,path:j,operationId:U,statusCode:Bt})})}let Kt=N.includes("body")?$o({...Q,paramNames:Go.pluck("name",q),schema:y.getSchema("input"),mimeType:C[y.getRequestType()],description:a?.requestBody?.call(null,{method:P,path:j,operationId:U})}):void 0,it=Bo(qo(z,N),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),Ft={operationId:U,summary:v,description:T,deprecated:y.isDeprecated||void 0,tags:zt(y.getTags()),parameters:zt(q),requestBody:Kt,security:zt(it),responses:k};this.addPath(Co(j),{[P]:Ft})}}),m&&(this.rootDoc.tags=_o(m))}};var Zt=require("node-mocks-http"),Ps=e=>(0,Zt.createRequest)({...e,headers:{"content-type":C.json,...e?.headers}}),ws=e=>(0,Zt.createResponse)(e),As=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Jr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ps(e),s=ws({req:n,...t});s.req=t?.req||n,n.res=s;let a=As(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Wo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Yo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Jo(o),m=lt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:m,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 nn=S(require("ramda"),1),st=S(require("typescript"),1),sn=require("zod");var rn=S(require("ramda"),1),Y=S(require("typescript"),1);var Qo=["get","post","put","delete","patch"];var re=S(require("ramda"),1),u=S(require("typescript"),1),i=u.default.factory,vt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Es=[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)]},mr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),lr=(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)},zs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ur=e=>typeof e=="string"&&zs.test(e)?i.createIdentifier(e):E(e),kt=(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)))),Ct=(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])=>Ct(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),fr=(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&&re.map(f,t)):e,yr=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,ur(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?mr(s,a.join(" ")):s},gr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),hr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&vt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),br=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?vt:void 0,e,n&&Tr(n),t);return o?mr(s,o):s},Xo=(e,t)=>i.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),xr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(ot.public,void 0,e,void 0,o&&Tr(o),t,n,i.createBlock(r)),Sr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(vt,e,r&&Tr(r),void 0,t),Rr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),jt=e=>f(Promise.name,[e]),Nt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?mr(n,o):n},Tr=e=>(Array.isArray(e)?e.map(t=>re.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?Es:void 0,void 0,Array.isArray(e)?re.map(Ct,e):_e(e),void 0,void 0,t),w=e=>e,nt=(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),Ve=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Lt=(e,t)=>f("Extract",[e,t]),Or=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),en=e=>i.createUnionTypeNode([f(e),jt(e)]),Pr=(e,t)=>i.createFunctionTypeNode(void 0,_e(e),f(t)),E=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(E(e)),Is=[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],tn=e=>Is.includes(e.kind);var Mt=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=br("Method",Qo);someOfType=oe("SomeOf",W("T",Rr("T")),{params:["T"]});requestType=oe("Request",Rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>br(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Nt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>ze(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(ur(t),i.createArrayLiteralExpression(rn.map(E,r))))),{expose:!0});makeImplementationType=()=>oe(this.ids.implementationType,Pr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:yr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},jt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.ids.parseRequestFn,Ie({[this.ids.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(A(this.ids.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>M(this.ids.substituteFn,Ie({[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:yr},i.createBlock([M(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([Or(this.ids.pathParameter,A(this.ids.pathParameter,w("replace"))(kt(":",[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=()=>xr(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"}}),[M(hr(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:jt(W(this.interfaces.response,"K"))});makeClientClass=t=>Sr(t,[fr([Ct(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:ot.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>kt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,kt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.ids.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),nt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(C.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(w("body"),nt(this.ids.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=M(this.ids.responseConst,i.createAwaitExpression(A(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=M(this.ids.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.ids.methodParameter))),a=M(this.ids.searchParamsConst,nt(this.ids.hasBodyConst,E(""),this.makeSearchParams(this.ids.paramsArgument))),c=M(this.ids.contentTypeConst,A(this.ids.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=M(this.ids.isJsonConst,A(this.ids.contentTypeConst,w("startsWith"))(E(C.json))),l=i.createReturnStatement(A(this.ids.responseConst,nt(this.ids.isJsonConst,E(w("json")),E(w("text"))))());return M(this.ids.defaultImplementationConst,Ie([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>fr(_e({request:"K",params:W(this.interfaces.input,"K")}),[M(hr(this.ids.pathParameter,this.ids.restConst),A(this.ids.substituteFn)(i.createElementAccessExpression(A(this.ids.parseRequestFn)(this.ids.requestParameter),E(1)),this.ids.paramsArgument)),M(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),Or(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ze(w("event"),t)]);makeOnMethod=()=>xr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Pr({[this.ids.dataParameter.text]:W(Lt("R",gr(this.makeEventNarrow("E"))),F(w("data")))},en(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.ids.sourceProp,w("addEventListener"))(this.ids.eventParameter,Ie([this.ids.msgParameter],A(this.ids.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(w("event")))}});makeSubscriptionClass=t=>Sr(t,[Xo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:Lt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Lt(W(this.interfaces.positive,"K"),gr(this.makeEventNarrow(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.ids.clientConst,Ve(t)),A(this.ids.clientConst,this.ids.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(Ve(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(E("time"),Ie(["time"],i.createBlock([])))]};var I=S(require("ramda"),1),R=S(require("typescript"),1),Ut=require("zod");var{factory:_}=R.default,Zs={[R.default.SyntaxKind.AnyKeyword]:"",[R.default.SyntaxKind.BigIntKeyword]:BigInt(0),[R.default.SyntaxKind.BooleanKeyword]:!1,[R.default.SyntaxKind.NumberKeyword]:0,[R.default.SyntaxKind.ObjectKeyword]:{},[R.default.SyntaxKind.StringKeyword]:"",[R.default.SyntaxKind.UndefinedKeyword]:void 0},wr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},vs=({value:e})=>F(e),ks=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&Ge(a)?a instanceof Ut.z.ZodOptional:a.isOptional();return ze(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return _.createTypeLiteralNode(n)},Cs=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),js=({options:e})=>_.createUnionTypeNode(e.map(F)),on=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(tn(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},Ns=e=>Zs?.[e.kind],Ls=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ut(e,Ns(o)),s={number:R.default.SyntaxKind.NumberKeyword,bigint:R.default.SyntaxKind.BigIntKeyword,boolean:R.default.SyntaxKind.BooleanKeyword,string:R.default.SyntaxKind.StringKeyword,undefined:R.default.SyntaxKind.UndefinedKeyword,object:R.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||R.default.SyntaxKind.AnyKeyword)}return o},Ms=e=>_.createUnionTypeNode(Object.values(e.enum).map(F)),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(R.default.SyntaxKind.UndefinedKeyword)]):o},Ds=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),F(null)]),Hs=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),Ks=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Fs=I.tryCatch(e=>{if(!e.every(R.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(wr.name,...o))return!1;if(I.both(I.eqBy(wr.type),I.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),qs=({_def:{left:e,right:t}},{next:r})=>Fs([e,t].map(r)),Bs=({_def:e},{next:t})=>t(e.innerType),ge=e=>()=>f(e),$s=(e,{next:t})=>t(e.unwrap()),_s=(e,{next:t})=>t(e.unwrap()),Vs=({_def:e},{next:t})=>t(e.innerType),Gs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Js=()=>F(null),Ws=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ys=e=>{let t=e.unwrap(),r=f(R.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Ut.z.ZodString?r:t instanceof Ut.z.ZodUnion?n:o},Qs=(e,{next:t})=>t(e.unwrap().shape.raw),Xs={ZodString:ge(R.default.SyntaxKind.StringKeyword),ZodNumber:ge(R.default.SyntaxKind.NumberKeyword),ZodBigInt:ge(R.default.SyntaxKind.BigIntKeyword),ZodBoolean:ge(R.default.SyntaxKind.BooleanKeyword),ZodAny:ge(R.default.SyntaxKind.AnyKeyword),ZodUndefined:ge(R.default.SyntaxKind.UndefinedKeyword),[Oe]:ge(R.default.SyntaxKind.StringKeyword),[Pe]:ge(R.default.SyntaxKind.StringKeyword),ZodNull:Js,ZodArray:Cs,ZodTuple:Hs,ZodRecord:Ks,ZodObject:ks,ZodLiteral:vs,ZodIntersection:qs,ZodUnion:on,ZodDefault:Bs,ZodEnum:js,ZodNativeEnum:Ms,ZodEffects:Ls,ZodOptional:Us,ZodNullable:Ds,ZodDiscriminatedUnion:on,ZodBranded:$s,ZodCatch:Vs,ZodPipeline:Gs,ZodLazy:Ws,ZodReadonly:_s,[ee]:Ys,[le]:Qs},Ar=(e,{brandHandling:t,ctx:r})=>Ee(e,{rules:{...t,...Xs},onMissing:()=>f(R.default.SyntaxKind.AnyKeyword),ctx:r});var Dt=class extends Mt{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,oe(o,n)),this.aliases.set(t,oe(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:m=sn.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};$e({routing:t,onEndpoint:(x,y,j)=>{let P=me.bind(null,j,y),{isDeprecated:Q}=x,Z=`${j} ${y}`,T=oe(P("input"),Ar(x.getSchema("input"),l),{comment:Z});this.program.push(T);let v=Me.reduce((z,q)=>{let k=x.getResponses(q),Kt=nn.chain(([Ft,{schema:ie,mimeTypes:he,statusCodes:qt}])=>{let at=oe(P(q,"variant",`${Ft+1}`),Ar(he?ie:m,b),{comment:Z});return this.program.push(at),qt.map(pt=>ze(pt,at.name))},Array.from(k.entries())),it=Nt(P(q,"response","variants"),Kt,{comment:Z});return this.program.push(it),Object.assign(z,{[q]:it})},{});this.paths.add(y);let N=F(Z),U={input:f(T.name),positive:this.someOf(v.positive),negative:this.someOf(v.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,N),W(this.interfaces.negative,N)]),encoded:i.createIntersectionTypeNode([f(v.positive.name),f(v.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:U}),this.tags.set(Z,x.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:lr(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)=>lr(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 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
|
|
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 pn=(e,t)=>Ze.z.object({data:t,event:Ze.z.literal(e),id:Ze.z.string().optional(),retry:Ze.z.number().int().positive().optional()}),ei=(e,t,r)=>pn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),ti=1e4,an=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":C.sse,"cache-control":"no-cache"}),ri=e=>new V({handler:async({response:t})=>setTimeout(()=>an(t),ti)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{an(t),t.write(ei(e,r,o),"utf-8"),t.flush?.()}}}),oi=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>pn(o,n));return{mimeType:C.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=we(r);Xe(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(Ae(a),"utf-8")}t.end()}}),Ht=class extends ye{constructor(t){super(oi(t)),this.middlewares=[ri(t)]}};var cn={dateIn:Zr,dateOut:kr,form:jr,file:gt,upload:Ur,raw:Lr};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
|
@@ -69,7 +69,7 @@ declare class BuiltinLogger implements AbstractLogger {
|
|
|
69
69
|
protected readonly config: BuiltinLoggerConfig;
|
|
70
70
|
/** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
|
|
71
71
|
constructor({ color, level, depth, ctx, }?: Partial<BuiltinLoggerConfig>);
|
|
72
|
-
protected
|
|
72
|
+
protected format(subject: unknown): string;
|
|
73
73
|
protected print(method: Severity, message: string, meta?: unknown): void;
|
|
74
74
|
debug(message: string, meta?: unknown): void;
|
|
75
75
|
info(message: string, meta?: unknown): void;
|
|
@@ -116,6 +116,10 @@ interface NormalizedResponse {
|
|
|
116
116
|
mimeTypes: [string, ...string[]] | null;
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
+
/** @desc Accepts an object shape or a custom object schema */
|
|
120
|
+
declare const form: <S extends z.ZodRawShape>(base: S | z.ZodObject<S>) => z.ZodBranded<z.ZodObject<S, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<S>, any> extends infer T ? { [k in keyof T]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<S>, any>[k]; } : never, z.baseObjectInputType<S> extends infer T_1 ? { [k_1 in keyof T_1]: z.baseObjectInputType<S>[k_1]; } : never>, symbol>;
|
|
121
|
+
type FormSchema = ReturnType<typeof form>;
|
|
122
|
+
|
|
119
123
|
type LogicalOr<T> = {
|
|
120
124
|
or: T[];
|
|
121
125
|
};
|
|
@@ -263,7 +267,7 @@ type EffectsChain<U extends z.UnknownKeysParam> = ObjectBasedEffect<BaseObject<U
|
|
|
263
267
|
* @desc The type allowed on the top level of Middlewares and Endpoints
|
|
264
268
|
* @param U — only "strip" is allowed for Middlewares due to intersection issue (Zod) #600
|
|
265
269
|
* */
|
|
266
|
-
type IOSchema<U extends z.UnknownKeysParam = z.UnknownKeysParam> = BaseObject<U> | EffectsChain<U> | RawSchema | z.ZodUnion<[IOSchema<U>, ...IOSchema<U>[]]> | z.ZodIntersection<IOSchema<U>, IOSchema<U>> | z.ZodDiscriminatedUnion<string, BaseObject<U>[]> | z.ZodPipeline<ObjectBasedEffect<BaseObject<U>>, BaseObject<U>>;
|
|
270
|
+
type IOSchema<U extends z.UnknownKeysParam = z.UnknownKeysParam> = BaseObject<U> | EffectsChain<U> | RawSchema | FormSchema | z.ZodUnion<[IOSchema<U>, ...IOSchema<U>[]]> | z.ZodIntersection<IOSchema<U>, IOSchema<U>> | z.ZodDiscriminatedUnion<string, BaseObject<U>[]> | z.ZodPipeline<ObjectBasedEffect<BaseObject<U>>, BaseObject<U>>;
|
|
267
271
|
|
|
268
272
|
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
269
273
|
type Method = (typeof methods)[number];
|
|
@@ -273,6 +277,7 @@ declare const contentTypes: {
|
|
|
273
277
|
upload: string;
|
|
274
278
|
raw: string;
|
|
275
279
|
sse: string;
|
|
280
|
+
form: string;
|
|
276
281
|
};
|
|
277
282
|
type ContentType = keyof typeof contentTypes;
|
|
278
283
|
|
|
@@ -430,7 +435,7 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
430
435
|
getMethods(): Readonly<("get" | "post" | "put" | "delete" | "patch")[] | undefined>;
|
|
431
436
|
getSchema(variant: "input"): IN;
|
|
432
437
|
getSchema(variant: "output"): OUT;
|
|
433
|
-
getRequestType(): "json" | "upload" | "raw";
|
|
438
|
+
getRequestType(): "form" | "json" | "upload" | "raw";
|
|
434
439
|
getResponses(variant: ResponseVariant): readonly NormalizedResponse[];
|
|
435
440
|
getSecurity(): LogicalContainer<Security>[];
|
|
436
441
|
getScopes(): readonly string[];
|
|
@@ -578,6 +583,12 @@ interface ServerConfig extends CommonConfig {
|
|
|
578
583
|
* @link https://expressjs.com/en/4x/api.html#express.raw
|
|
579
584
|
* */
|
|
580
585
|
rawParser?: RequestHandler;
|
|
586
|
+
/**
|
|
587
|
+
* @desc Custom parser for URL Encoded requests used for submitting HTML forms
|
|
588
|
+
* @default express.urlencoded()
|
|
589
|
+
* @link https://expressjs.com/en/4x/api.html#express.urlencoded
|
|
590
|
+
* */
|
|
591
|
+
formParser?: RequestHandler;
|
|
581
592
|
/**
|
|
582
593
|
* @desc A code to execute before processing the Routing of your API (and before parsing).
|
|
583
594
|
* @desc This can be a good place for express middlewares establishing their own routes.
|
|
@@ -743,6 +754,7 @@ declare function file<K extends Variant>(variant: K): ReturnType<Variants[K]>;
|
|
|
743
754
|
declare const ez: {
|
|
744
755
|
dateIn: () => zod.ZodBranded<zod.ZodPipeline<zod.ZodEffects<zod.ZodUnion<[zod.ZodString, zod.ZodString, zod.ZodString]>, Date, string>, zod.ZodEffects<zod.ZodDate, Date, Date>>, symbol>;
|
|
745
756
|
dateOut: () => zod.ZodBranded<zod.ZodEffects<zod.ZodEffects<zod.ZodDate, Date, Date>, string, Date>, symbol>;
|
|
757
|
+
form: <S extends zod.ZodRawShape>(base: S | zod.ZodObject<S>) => zod.ZodBranded<zod.ZodObject<S, zod.UnknownKeysParam, zod.ZodTypeAny, zod.objectUtil.addQuestionMarks<zod.baseObjectOutputType<S>, any> extends infer T ? { [k in keyof T]: zod.objectUtil.addQuestionMarks<zod.baseObjectOutputType<S>, any>[k]; } : never, zod.baseObjectInputType<S> extends infer T_1 ? { [k_1 in keyof T_1]: zod.baseObjectInputType<S>[k_1]; } : never>, symbol>;
|
|
746
758
|
file: typeof file;
|
|
747
759
|
upload: () => zod.ZodBranded<zod.ZodType<express_fileupload.UploadedFile, zod.ZodTypeDef, express_fileupload.UploadedFile>, symbol>;
|
|
748
760
|
raw: <S extends zod.ZodRawShape>(extra?: S) => zod.ZodBranded<zod.ZodObject<zod.objectUtil.extendShape<{
|
|
@@ -1070,7 +1082,7 @@ type EventsMap = Record<string, z.ZodTypeAny>;
|
|
|
1070
1082
|
interface Emitter<E extends EventsMap> extends FlatObject {
|
|
1071
1083
|
/** @desc Returns true when the connection was closed or terminated */
|
|
1072
1084
|
isClosed: () => boolean;
|
|
1073
|
-
/** @desc Sends an event to the stream
|
|
1085
|
+
/** @desc Sends an event to the stream according to the declared schema */
|
|
1074
1086
|
emit: <K extends keyof E>(event: K, data: z.input<E[K]>) => void;
|
|
1075
1087
|
}
|
|
1076
1088
|
declare class EventStreamFactory<E extends EventsMap> extends EndpointsFactory<EmptySchema, Emitter<E>> {
|
package/dist/index.d.ts
CHANGED
|
@@ -69,7 +69,7 @@ declare class BuiltinLogger implements AbstractLogger {
|
|
|
69
69
|
protected readonly config: BuiltinLoggerConfig;
|
|
70
70
|
/** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
|
|
71
71
|
constructor({ color, level, depth, ctx, }?: Partial<BuiltinLoggerConfig>);
|
|
72
|
-
protected
|
|
72
|
+
protected format(subject: unknown): string;
|
|
73
73
|
protected print(method: Severity, message: string, meta?: unknown): void;
|
|
74
74
|
debug(message: string, meta?: unknown): void;
|
|
75
75
|
info(message: string, meta?: unknown): void;
|
|
@@ -116,6 +116,10 @@ interface NormalizedResponse {
|
|
|
116
116
|
mimeTypes: [string, ...string[]] | null;
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
+
/** @desc Accepts an object shape or a custom object schema */
|
|
120
|
+
declare const form: <S extends z.ZodRawShape>(base: S | z.ZodObject<S>) => z.ZodBranded<z.ZodObject<S, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<S>, any> extends infer T ? { [k in keyof T]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<S>, any>[k]; } : never, z.baseObjectInputType<S> extends infer T_1 ? { [k_1 in keyof T_1]: z.baseObjectInputType<S>[k_1]; } : never>, symbol>;
|
|
121
|
+
type FormSchema = ReturnType<typeof form>;
|
|
122
|
+
|
|
119
123
|
type LogicalOr<T> = {
|
|
120
124
|
or: T[];
|
|
121
125
|
};
|
|
@@ -263,7 +267,7 @@ type EffectsChain<U extends z.UnknownKeysParam> = ObjectBasedEffect<BaseObject<U
|
|
|
263
267
|
* @desc The type allowed on the top level of Middlewares and Endpoints
|
|
264
268
|
* @param U — only "strip" is allowed for Middlewares due to intersection issue (Zod) #600
|
|
265
269
|
* */
|
|
266
|
-
type IOSchema<U extends z.UnknownKeysParam = z.UnknownKeysParam> = BaseObject<U> | EffectsChain<U> | RawSchema | z.ZodUnion<[IOSchema<U>, ...IOSchema<U>[]]> | z.ZodIntersection<IOSchema<U>, IOSchema<U>> | z.ZodDiscriminatedUnion<string, BaseObject<U>[]> | z.ZodPipeline<ObjectBasedEffect<BaseObject<U>>, BaseObject<U>>;
|
|
270
|
+
type IOSchema<U extends z.UnknownKeysParam = z.UnknownKeysParam> = BaseObject<U> | EffectsChain<U> | RawSchema | FormSchema | z.ZodUnion<[IOSchema<U>, ...IOSchema<U>[]]> | z.ZodIntersection<IOSchema<U>, IOSchema<U>> | z.ZodDiscriminatedUnion<string, BaseObject<U>[]> | z.ZodPipeline<ObjectBasedEffect<BaseObject<U>>, BaseObject<U>>;
|
|
267
271
|
|
|
268
272
|
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
269
273
|
type Method = (typeof methods)[number];
|
|
@@ -273,6 +277,7 @@ declare const contentTypes: {
|
|
|
273
277
|
upload: string;
|
|
274
278
|
raw: string;
|
|
275
279
|
sse: string;
|
|
280
|
+
form: string;
|
|
276
281
|
};
|
|
277
282
|
type ContentType = keyof typeof contentTypes;
|
|
278
283
|
|
|
@@ -430,7 +435,7 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
430
435
|
getMethods(): Readonly<("get" | "post" | "put" | "delete" | "patch")[] | undefined>;
|
|
431
436
|
getSchema(variant: "input"): IN;
|
|
432
437
|
getSchema(variant: "output"): OUT;
|
|
433
|
-
getRequestType(): "json" | "upload" | "raw";
|
|
438
|
+
getRequestType(): "form" | "json" | "upload" | "raw";
|
|
434
439
|
getResponses(variant: ResponseVariant): readonly NormalizedResponse[];
|
|
435
440
|
getSecurity(): LogicalContainer<Security>[];
|
|
436
441
|
getScopes(): readonly string[];
|
|
@@ -578,6 +583,12 @@ interface ServerConfig extends CommonConfig {
|
|
|
578
583
|
* @link https://expressjs.com/en/4x/api.html#express.raw
|
|
579
584
|
* */
|
|
580
585
|
rawParser?: RequestHandler;
|
|
586
|
+
/**
|
|
587
|
+
* @desc Custom parser for URL Encoded requests used for submitting HTML forms
|
|
588
|
+
* @default express.urlencoded()
|
|
589
|
+
* @link https://expressjs.com/en/4x/api.html#express.urlencoded
|
|
590
|
+
* */
|
|
591
|
+
formParser?: RequestHandler;
|
|
581
592
|
/**
|
|
582
593
|
* @desc A code to execute before processing the Routing of your API (and before parsing).
|
|
583
594
|
* @desc This can be a good place for express middlewares establishing their own routes.
|
|
@@ -743,6 +754,7 @@ declare function file<K extends Variant>(variant: K): ReturnType<Variants[K]>;
|
|
|
743
754
|
declare const ez: {
|
|
744
755
|
dateIn: () => zod.ZodBranded<zod.ZodPipeline<zod.ZodEffects<zod.ZodUnion<[zod.ZodString, zod.ZodString, zod.ZodString]>, Date, string>, zod.ZodEffects<zod.ZodDate, Date, Date>>, symbol>;
|
|
745
756
|
dateOut: () => zod.ZodBranded<zod.ZodEffects<zod.ZodEffects<zod.ZodDate, Date, Date>, string, Date>, symbol>;
|
|
757
|
+
form: <S extends zod.ZodRawShape>(base: S | zod.ZodObject<S>) => zod.ZodBranded<zod.ZodObject<S, zod.UnknownKeysParam, zod.ZodTypeAny, zod.objectUtil.addQuestionMarks<zod.baseObjectOutputType<S>, any> extends infer T ? { [k in keyof T]: zod.objectUtil.addQuestionMarks<zod.baseObjectOutputType<S>, any>[k]; } : never, zod.baseObjectInputType<S> extends infer T_1 ? { [k_1 in keyof T_1]: zod.baseObjectInputType<S>[k_1]; } : never>, symbol>;
|
|
746
758
|
file: typeof file;
|
|
747
759
|
upload: () => zod.ZodBranded<zod.ZodType<express_fileupload.UploadedFile, zod.ZodTypeDef, express_fileupload.UploadedFile>, symbol>;
|
|
748
760
|
raw: <S extends zod.ZodRawShape>(extra?: S) => zod.ZodBranded<zod.ZodObject<zod.objectUtil.extendShape<{
|
|
@@ -1070,7 +1082,7 @@ type EventsMap = Record<string, z.ZodTypeAny>;
|
|
|
1070
1082
|
interface Emitter<E extends EventsMap> extends FlatObject {
|
|
1071
1083
|
/** @desc Returns true when the connection was closed or terminated */
|
|
1072
1084
|
isClosed: () => boolean;
|
|
1073
|
-
/** @desc Sends an event to the stream
|
|
1085
|
+
/** @desc Sends an event to the stream according to the declared schema */
|
|
1074
1086
|
emit: <K extends keyof E>(event: K, data: z.input<E[K]>) => void;
|
|
1075
1087
|
}
|
|
1076
1088
|
declare class EventStreamFactory<E extends EventsMap> extends EndpointsFactory<EmptySchema, Emitter<E>> {
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import*as D from"ramda";import{z as Pe}from"zod";import*as U from"ramda";import{z as
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:Yo(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as wr}from"zod";var Lt=class{},J=class extends Lt{#e;#t;#r;constructor({input:t=wr.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 wr.ZodError?new ee(o):o}}},Ee=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var ze=class{nest(t){return Object.assign(t,{"":this})}};var qe=class extends ze{},mt=class e extends qe{#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 Tr(this.#e.inputSchema)?"upload":ct(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 Ar.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 Ar.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){dt({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=kt(t),a={},c=null,m=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){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,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)=>yr(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 W}from"zod";var Ie={positive:200,negative:400},Ze=Object.keys(Ie);var Mt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Mt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Nt(this.#e,{variant:"positive",args:[t],statusCodes:[Ie.positive],mimeTypes:[k.json]})}getNegativeResponse(){return Nt(this.#t,{variant:"negative",args:[],statusCodes:[Ie.negative],mimeTypes:[k.json]})}},Be=new be({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.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 Fe(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})}}),Ut=new be({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>le(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.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 Fe(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 xe=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 J?t:new J(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 J({handler:t})),this.resultHandler)}build({input:t=zr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new mt({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:x,methods:l,getOperationId:b,inputSchema:Er(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:zr.object({}),handler:async o=>(await t(o),{})})}},Qo=new xe(Be),Xo=new xe(Ut);import an from"ansis";import{inspect as pn}from"node:util";import{performance as jr}from"node:perf_hooks";import{blue as en,green as tn,hex as rn,red as on,cyanBright as nn}from"ansis";import*as Ir from"ramda";var Dt={debug:en,info:tn,warn:rn("#FFA500"),error:on,ctx:nn},lt={debug:10,info:20,warn:30,error:40},Zr=e=>le(e)&&Object.keys(lt).some(t=>t in e),vr=e=>e in lt,kr=(e,t)=>lt[e]<lt[t],sn=(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}`,sn),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 $e=class e{config;constructor({color:t=an.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 pn(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 m=[new Date().toISOString()];s&&m.push(c?Dt.ctx(s):s),m.push(c?`${Dt[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.prettyPrint(o)),Object.keys(a).length>0&&m.push(this.prettyPrint(a)),console.log(m.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 _e=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 cn from"express";var Ve=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,cn.static(...this.params))}};import Kt from"express";import bn from"node:http";import xn from"node:https";var Ce=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ue(e)};import dn from"http-errors";import*as Nr from"ramda";var ut=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(k.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 qe){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Ve)r&&s.apply(n,r);else if(s instanceof _e)for(let[a,c,m]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,m)}else o.unshift(...Lr(s,n))}};var mn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=dn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Ht=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new ut(t()),a=new Map;if(je({routing:o,onEndpoint:(m,p,l,b)=>{ue()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.getRequestType()]||[],x=async(y,C)=>{let O=t(y);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:O,defaultHeaders:R}):R;for(let j in Z)C.set(j,Z[j])}return m.execute({request:y,response:C,logger:O,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,mn(p))};import qr,{isHttpError as un}from"http-errors";import{setInterval as ln}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 m=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 ln(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??=m()}};var Br=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:un(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{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){dt({response:o,logger:s,error:new re(oe(a),n)})}},fn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},yn=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,m,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:yn(l)})(c,m,p)}),o&&a.push(fn(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[h]={logger:s}),n()},Jr=e=>t=>t?.res?.locals[h]?.logger||e,Wr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
import*as D from"ramda";import{z as Pe}from"zod";import*as U from"ramda";import{z as yr}from"zod";var k={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};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.`}},et=class extends Error{name="IOSchemaError"},ce=class extends et{constructor(r){super(de(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends et{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"},Ue=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ct=/:([A-Za-z0-9_]+)/g,tt=e=>e.match(Ct)?.map(t=>t.slice(1))||[],Uo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(k.upload);return"files"in e&&r},jt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Do=["body","query","params"],Nt=e=>e.method.toLowerCase(),rt=(e,t={})=>{let r=Nt(e);return r==="options"?{}:(t[r]||jt[r]||Do).filter(o=>o==="files"?Uo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),de=e=>e instanceof yr.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,Ho=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return me(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 yr.ZodObject&&(n=Ho(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},me=(e,t,r)=>e.length&&t.length?U.xprod(e,t).map(r):e.concat(t),De=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Lt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...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(Lt).join("")},ot=U.tryCatch((e,t)=>typeof e.parse(t),U.always(void 0)),le=e=>typeof e=="object"&&e!==null,ue=U.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as nt from"ramda";var g=Symbol.for("express-zod-api"),He=e=>{let t=e.describe(e.description);return t._def[g]=nt.clone(t._def[g])||{examples:[]},t},gr=(e,t)=>{if(!(g in e._def))return t;let r=He(t);return r._def[g].examples=me(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?nt.mergeDeepRight({...o},{...n}):n),r};var Ko=function(e){let t=He(this);return t._def[g].examples.push(e),t},Fo=function(){let e=He(this);return e._def[g].isDeprecated=!0,e},qo=function(e){let t=He(this);return t._def[g].defaultLabel=e,t},Bo=function(e){return new Pe.ZodBranded({typeName:Pe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...D.clone(this._def[g]),brand:e}})},$o=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=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 Ko.bind(this)}},deprecated:{get(){return Fo.bind(this)}},brand:{set(){},get(){return Bo.bind(this)}}}),Object.defineProperty(Pe.ZodDefault.prototype,"label",{get(){return qo.bind(this)}}),Object.defineProperty(Pe.ZodObject.prototype,"remap",{get(){return $o.bind(this)}}));function _o(e){return e}import{z as kr}from"zod";import{z as Zr}from"zod";import{fail as L}from"node:assert/strict";import{z as Ke}from"zod";var st=e=>!isNaN(e.getTime());var fe=Symbol("DateIn"),hr=()=>Ke.union([Ke.string().date(),Ke.string().datetime(),Ke.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ke.date().refine(st)).brand(fe);import{z as Vo}from"zod";var ye=Symbol("DateOut"),br=()=>Vo.date().refine(st).transform(e=>e.toISOString()).brand(ye);import{z as it}from"zod";var G=Symbol("File"),xr=it.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Go={buffer:()=>xr.brand(G),string:()=>it.string().brand(G),binary:()=>xr.or(it.string()).brand(G),base64:()=>it.string().base64().brand(G)};function at(e){return Go[e||"string"]()}import{z as Sr}from"zod";var pt=Symbol("Form"),Rr=e=>(e instanceof Sr.ZodObject?e:Sr.object(e)).brand(pt);import{z as Jo}from"zod";var ie=Symbol("Raw"),Tr=(e={})=>Jo.object({raw:at("buffer")}).extend(e).brand(ie);import{z as Wo}from"zod";var we=Symbol("Upload"),Or=()=>Wo.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(we);var Pr=(e,{next:t})=>e.options.some(t),Yo=({_def:e},{next:t})=>[e.left,e.right].some(t),ct=(e,{next:t})=>t(e.unwrap()),dt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Pr,ZodDiscriminatedUnion:Pr,ZodIntersection:Yo,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:ct,ZodNullable:ct,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Fe=(e,{condition:t,rules:r=dt,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=>Fe(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},wr=e=>Fe(e,{condition:t=>t._def[g]?.brand===we,rules:{...dt,[pt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),mt=e=>Fe(e,{condition:t=>t._def[g]?.brand===ie,maxDepth:3}),Ar=e=>Fe(e,{condition:t=>t._def[g]?.brand===pt,maxDepth:3}),Er=(e,t)=>{let r=new WeakSet;return Fe(e,{maxDepth:300,rules:{...dt,ZodBranded:ct,ZodReadonly:ct,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:dt.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()"),[we]:()=>t==="out"&&L("ez.upload()"),[G]:()=>!1}})};import en,{isHttpError as tn}from"http-errors";import zr,{isHttpError as Qo}from"http-errors";import{z as Xo}from"zod";var Mt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Xo.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}))},qe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ae=e=>Qo(e)?e:zr(e instanceof ee?400:500,de(e),{cause:e.cause||e}),ge=e=>ue()&&!e.expose?zr(e.statusCode).message:e.message;var lt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ge(en(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:tn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ir}from"zod";var Ut=class{},J=class extends Ut{#e;#t;#r;constructor({input:t=Ir.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 Ir.ZodError?new ee(o):o}}},Ee=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var ze=class{nest(t){return Object.assign(t,{"":this})}};var Be=class extends ze{},ut=class e extends Be{#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 wr(this.#e.inputSchema)?"upload":mt(this.#e.inputSchema)?"raw":Ar(this.#e.inputSchema)?"form":"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 Zr.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 Zr.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){lt({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),a={},c=null,m=null,p=rt(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){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import{z as he}from"zod";var vr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>gr(s,n),o)},$=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 W}from"zod";var Ie={positive:200,negative:400},Ze=Object.keys(Ie);var Dt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Dt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Mt(this.#e,{variant:"positive",args:[t],statusCodes:[Ie.positive],mimeTypes:[k.json]})}getNegativeResponse(){return Mt(this.#t,{variant:"negative",args:[],statusCodes:[Ie.negative],mimeTypes:[k.json]})}},$e=new be({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.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 qe(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})}}),Ht=new be({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>le(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.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 qe(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 xe=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 J?t:new J(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 J({handler:t})),this.resultHandler)}build({input:t=kr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],x=typeof s=="string"?[s]:s||[];return new ut({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:h,tags:x,methods:l,getOperationId:b,inputSchema:vr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:kr.object({}),handler:async o=>(await t(o),{})})}},rn=new xe($e),on=new xe(Ht);import mn from"ansis";import{inspect as ln}from"node:util";import{performance as Ur}from"node:perf_hooks";import{blue as nn,green as sn,hex as an,red as pn,cyanBright as cn}from"ansis";import*as Cr from"ramda";var Kt={debug:nn,info:sn,warn:an("#FFA500"),error:pn,ctx:cn},ft={debug:10,info:20,warn:30,error:40},jr=e=>le(e)&&Object.keys(ft).some(t=>t in e),Nr=e=>e in ft,Lr=(e,t)=>ft[e]<ft[t],dn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),ve=Cr.memoizeWith((e,t)=>`${e}${t}`,dn),Mr=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 _e=class e{config;constructor({color:t=mn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return ln(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"||Lr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Kt.ctx(s):s),m.push(c?`${Kt[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.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=Ur.now();return()=>{let o=Ur.now()-r,{message:n,severity:s="debug",formatter:a=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as ke from"ramda";var Ve=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 un from"express";var Ge=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,un.static(...this.params))}};import ht from"express";import Tn from"node:http";import On from"node:https";var Ce=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ue(e)};import fn from"http-errors";import*as Dr from"ramda";var yt=class{constructor(t){this.logger=t}#e=Dr.tryCatch(Er);#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(k.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=tt(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 Hr=(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=Hr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Be){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Ge)r&&s.apply(n,r);else if(s instanceof Ve)for(let[a,c,m]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,m)}else o.unshift(...Hr(s,n))}};var yn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=fn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Ft=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new yt(t()),a=new Map;if(je({routing:o,onEndpoint:(m,p,l,b)=>{ue()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let h=n?.[m.getRequestType()]||[],x=async(y,C)=>{let O=t(y);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:y,endpoint:m,logger:O,defaultHeaders:R}):R;for(let j in Z)C.set(j,Z[j])}return m.execute({request:y,response:C,logger:O,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...h,x),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...h,x)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[m,p]of a.entries())e.all(m,yn(p))};import Vr,{isHttpError as hn}from"http-errors";import{setInterval as gn}from"node:timers/promises";var Kr=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",Fr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Br=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),$r=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var _r=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Kr(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 m=async()=>{for(let p of e)p.on("request",Br);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(qr(p)||Fr(p))&&a(p);for await(let p of gn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map($r))};return{sockets:n,shutdown:()=>o??=m()}};var Gr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:hn(r)?r:Vr(400,oe(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Jr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Vr(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){lt({response:o,logger:s,error:new re(oe(a),n)})}},bn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},xn=e=>({log:e.debug.bind(e)}),Wr=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,m,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:xn(l)})(c,m,p)}),o&&a.push(bn(o)),a},Yr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Qr=({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()},Xr=e=>t=>t?.res?.locals[g]?.logger||e,eo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),to=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=_r(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as Sn,hex as ro,italic as gt,whiteBright as Rn}from"ansis";var oo=e=>{if(e.columns<132)return;let t=gt("Proudly supports transgender community.".padStart(109)),r=gt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=gt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=gt("for Tai".padEnd(20)),s=ro("#F5A9B8"),a=ro("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(Rn,5,7).fill(s,7,9).fill(a,9,12).fill(Sn,12,13),m=`
|
|
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(m.split(`
|
|
17
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||Be,r=Zr(e.logger)?e.logger:new $e(e.logger);r.debug("Running",{build:"v22.12.0-beta.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}},Sn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=eo(e);return Ht({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Rn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=eo(e),c=Kt().disable("x-powered-by").use(a);if(e.compression){let g=await Ce("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}let m={json:[e.jsonParser||Kt.json()],raw:[e.rawParser||Kt.raw(),Vr],upload:e.upload?await _r({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Ht({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,x)=>()=>g.listen(x,()=>r.info("Listening",x)),b=[];if(e.http){let g=bn.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=xn.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&Yr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};import{OpenApiBuilder as ys}from"openapi3-ts/oas31";import*as Oo from"ramda";import*as T from"ramda";var to=e=>le(e)&&"or"in e,ro=e=>le(e)&&"and"in e,Ft=e=>!ro(e)&&!to(e),oo=e=>{let t=T.filter(Ft,e),r=T.chain(T.prop("and"),T.filter(ro,e)),[o,n]=T.partition(Ft,r),s=T.concat(t,o),a=T.filter(to,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>me(m,T.map(l=>Ft(l)?[l]:l.and,p),([l,b])=>T.concat(l,b)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as qt,isSchemaObject as gt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as F}from"zod";var Se=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[h]?.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),m=t&&t(e,{prev:c,...n});return m?{...c,...m}: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",On={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Pn=/^\d{4}-\d{2}-\d{2}$/,wn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,An=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)}}`),En=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),zn=({_def:{innerType:e}},{next:t})=>t(e),In=()=>({format:"any"}),Zn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},vn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof F.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Cn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),jn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},co={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(jn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>me(e,t,([r,o])=>d.mergeDeepRight(r,o))},Nn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(co)),d.isEmpty)),Ln=d.tryCatch(e=>{let[t,r]=e.filter(gt).filter(Nn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,co);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Mn=({_def:{left:e,right:t}},{next:r})=>Ln([e,t].map(r)),Un=(e,{next:t})=>t(e.unwrap()),Dn=(e,{next:t})=>t(e.unwrap()),Hn=(e,{next:t})=>{let r=t(e.unwrap());return gt(r)&&(r.type=lo(r)),r},mo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},io=e=>({type:mo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Kn=({value:e})=>({type:mo(e),const:e}),Fn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&De(c)?c instanceof F.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=yt(e,r)),s.length&&(a.required=s),a},qn=()=>({type:"null"}),Bn=({},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}}},$n=({},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}}},_n=({},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)},Vn=()=>({type:"boolean"}),Gn=()=>({type:"integer",format:"bigint"}),Jn=e=>e.every(t=>t instanceof F.ZodLiteral),Wn=({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=yt(F.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof F.ZodLiteral)return{type:"object",properties:yt(F.object({[e.value]:t}),r),required:[e.value]};if(e instanceof F.ZodUnion&&Jn(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:yt(F.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:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:x,isBase64:y,isNANOID:C,isBase64url:O,isDuration:V,_def:{checks:I}})=>{let R=I.find(v=>v.kind==="regex"),Z=I.find(v=>v.kind==="datetime"),j=I.some(v=>v.kind==="jwt"),M=I.find(v=>v.kind==="length"),E={type:"string"},K={"date-time":l,byte:y,base64url:O,date:g,time:x,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:j,ip:m,cidr:b,emoji:p};for(let v in K)if(K[v]){E.format=v;break}return M&&([E.minLength,E.maxLength]=[M.value,M.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),g&&(E.pattern=Pn.source),x&&(E.pattern=wn.source),l&&(E.pattern=An(Z?.offset).source),R&&(E.pattern=R.regex.source),E},es=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(y=>y.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(y=>y.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,x={type:e?"integer":"number",format:e?"int64":"double"};return p?x.minimum=m:x.exclusiveMinimum=m,g?x.maximum=b:x.exclusiveMaximum=b,x},yt=({shape:e},t)=>d.map(t,e),ts=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return On?.[t]},lo=({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"&>(o)){let s=rt(e,ts(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(F.any())}if(!t&&n.type==="preprocess"&>(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),uo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,fo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),uo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),as=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),uo)({schema:e,variant:"original",validate:!0,pullProps:!0}),ps=(e,t)=>t?.includes(e)||e.startsWith("x-")||no.includes(e),yo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=$(r),g=et(e),x=o.includes("query"),y=o.includes("params"),C=o.includes("headers"),O=R=>y&&g.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),I=R=>C&&(c?.(R,t,e)??ps(R,V));return Object.entries(b.shape).reduce((R,[Z,j])=>{let M=O(Z)?"path":I(Z)?"header":x?"query":void 0;if(!M)return R;let E=Se(j,{rules:{...a,...Bt},onEach:$t,onMissing:_t,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),K=s==="components"?n(j,E,se(l,Z)):E,{_def:v}=j;return R.concat({name:Z,in:M,deprecated:v[h]?.isDeprecated,required:!j.isOptional(),description:E.description||l,schema:K,examples:as(b,Z)})},[])},Bt={ZodString:Xn,ZodNumber:es,ZodBigInt:Gn,ZodBoolean:Vn,ZodNull:qn,ZodArray:Yn,ZodTuple:Qn,ZodRecord:Wn,ZodObject:Fn,ZodLiteral:Kn,ZodIntersection:Mn,ZodUnion:kn,ZodAny:In,ZodDefault:En,ZodEnum:io,ZodNativeEnum:io,ZodEffects:rs,ZodOptional:Un,ZodNullable:Hn,ZodDiscriminatedUnion:Cn,ZodBranded:ns,ZodDate:_n,ZodCatch:zn,ZodPipeline:os,ZodLazy:ss,ZodReadonly:Dn,[G]:vn,[we]:Zn,[ye]:$n,[fe]:Bn,[ie]:is},$t=(e,{isResponse:t,prev:r})=>{if(qt(r))return{};let{description:o,_def:n}=e,s=e instanceof F.ZodLazy,a=r.type!==void 0,c=t&&De(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[h]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=lo(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)},go=(e,t)=>{if(qt(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=go(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},ho=e=>qt(e)?e:d.omit(["examples"],e),bo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Ct(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=ho(Se(r,{rules:{...p,...Bt},onEach:$t,onMissing:_t,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,g,se(b)):g,examples:fo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},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}),fs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),xo=(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):fs(o);return e.map(o=>o.map(r))},So=(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:[]})},{})),Ro=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=go(Se(r,{rules:{...a,...Bt},onEach:$t,onMissing:_t,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=ho(l),x={schema:s==="components"?n(r,g,se(p)):g,examples:fo($(r),!1,c)},y={description:p,content:{[o]:x}};return(b||ct(r))&&(y.required=!0),y},To=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)},[]),Vt=e=>e.length<=so?e:e.slice(0,so-1)+"\u2026",ht=e=>e.length?e.slice():void 0;var Gt=class extends ys{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:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="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,C,O)=>{let V={path:C,method:O,endpoint:y,composition:g,brandHandling:c,numericRange:l,makeRef:this.makeRef.bind(this)},[I,R]=["short","long"].map(y.getDescription.bind(y)),Z=I?Vt(I):b&&R?Vt(R):void 0,j=r.inputSources?.[O]||vt[O],M=this.ensureUniqOperationId(C,O,y.getOperationId(O)),E=oo(y.getSecurity()),K=yo({...V,inputSources:j,isHeader:p,security:E,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:C,operationId:M})}),v={};for(let te of Ze){let pe=y.getResponses(te);for(let{mimeTypes:zt,schema:Ye,statusCodes:Qe}of pe)for(let It of Qe)v[It]=bo({...V,variant:te,schema:Ye,mimeTypes:zt,statusCode:It,hasMultipleStatusCodes:pe.length>1||Qe.length>1,description:a?.[`${te}Response`]?.call(null,{method:O,path:C,operationId:M,statusCode:It})})}let At=j.includes("body")?Ro({...V,paramNames:Oo.pluck("name",K),schema:y.getSchema("input"),mimeType:k[y.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:C,operationId:M})}):void 0,We=So(xo(E,j),y.getScopes(),te=>{let pe=this.ensureUniqSecuritySchemaName(te);return this.addSecurityScheme(pe,te),pe}),Et={operationId:M,summary:Z,description:R,deprecated:y.isDeprecated||void 0,tags:ht(y.getTags()),parameters:ht(K),requestBody:At,security:ht(We),responses:v};this.addPath(po(C),{[O]:Et})}}),m&&(this.rootDoc.tags=To(m))}};import{createRequest as gs,createResponse as hs}from"node-mocks-http";var bs=e=>gs({...e,headers:{"content-type":k.json,...e?.headers}}),xs=e=>hs(e),Ss=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)}})},Po=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=bs(e),s=xs({req:n,...t});s.req=t?.req||n,n.res=s;let a=Ss(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Rs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Po(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Ts=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Po(o),m=tt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:m,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 vo from"ramda";import wt from"typescript";import{z as Ws}from"zod";import*as Io from"ramda";import X from"typescript";var wo=["get","post","put","delete","patch"];import*as Y from"ramda";import u from"typescript";var i=u.factory,bt=[i.createModifier(u.SyntaxKind.ExportKeyword)],Os=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Ge={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Jt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Wt=(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)},Ps=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yt=e=>typeof e=="string"&&Ps.test(e)?i.createIdentifier(e):A(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)))),St=(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])=>St(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Qt=(e,t=[])=>i.createConstructorDeclaration(Ge.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,Xt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,Yt(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Jt(s,a.join(" ")):s},er=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),tr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),N=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&bt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),rr=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(H,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?bt:void 0,e,n&&ir(n),t);return o?Jt(s,o):s},Ao=(e,t)=>i.createPropertyDeclaration(Ge.public,e,void 0,f(t),void 0),or=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ge.public,void 0,e,void 0,o&&ir(o),t,n,i.createBlock(r)),nr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(bt,e,r&&ir(r),void 0,t),sr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Rt=e=>f(Promise.name,[e]),Tt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?bt:void 0,e,void 0,void 0,t);return o?Jt(n,o):n},ir=e=>(Array.isArray(e)?e.map(t=>Y.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?Os:void 0,void 0,Array.isArray(e)?Y.map(St,e):Ne(e),void 0,void 0,t),P=e=>e,Je=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),w=(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),Ot=(e,t)=>f("Extract",[e,t]),ar=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Eo=e=>i.createUnionTypeNode([f(e),Rt(e)]),pr=(e,t)=>i.createFunctionTypeNode(void 0,Ne(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),H=e=>i.createLiteralTypeNode(A(e)),ws=[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],zo=e=>ws.includes(e.kind);var Pt=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=rr("Method",wo);someOfType=Q("SomeOf",_("T",sr("T")),{params:["T"]});requestType=Q("Request",sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>rr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Tt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>N("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Yt(t),i.createArrayLiteralExpression(Io.map(A,r))))),{expose:!0});makeImplementationType=()=>Q(this.ids.implementationType,pr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Xt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},Rt(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.ids.parseRequestFn,Te({[this.ids.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(w(this.ids.requestParameter,P("split"))(i.createRegularExpressionLiteral("/ (.+)/"),A(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>N(this.ids.substituteFn,Te({[this.ids.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Xt},i.createBlock([N(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],X.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([ar(this.ids.pathParameter,w(this.ids.pathParameter,P("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=()=>or(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"}}),[N(tr(this.ids.methodParameter,this.ids.pathParameter),w(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(w(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(w(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Rt(_(this.interfaces.response,"K"))});makeClientClass=t=>nr(t,[Qt([St(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:Ge.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]),A(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(P("method"),w(this.ids.methodParameter,P("toUpperCase"))()),r=i.createPropertyAssignment(P("headers"),Je(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(A("Content-Type"),A(k.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(P("body"),Je(this.ids.hasBodyConst,w(JSON[Symbol.toStringTag],P("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=N(this.ids.responseConst,i.createAwaitExpression(w(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=N(this.ids.hasBodyConst,i.createLogicalNot(w(i.createArrayLiteralExpression([A("get"),A("delete")]),P("includes"))(this.ids.methodParameter))),a=N(this.ids.searchParamsConst,Je(this.ids.hasBodyConst,A(""),this.makeSearchParams(this.ids.paramsArgument))),c=N(this.ids.contentTypeConst,w(this.ids.responseConst,P("headers"),P("get"))(A("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=N(this.ids.isJsonConst,w(this.ids.contentTypeConst,P("startsWith"))(A(k.json))),l=i.createReturnStatement(w(this.ids.responseConst,Je(this.ids.isJsonConst,A(P("json")),A(P("text"))))());return N(this.ids.defaultImplementationConst,Te([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>Qt(Ne({request:"K",params:_(this.interfaces.input,"K")}),[N(tr(this.ids.pathParameter,this.ids.restConst),w(this.ids.substituteFn)(i.createElementAccessExpression(w(this.ids.parseRequestFn)(this.ids.requestParameter),A(1)),this.ids.paramsArgument)),N(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),ar(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Le("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([Re(P("event"),t)]);makeOnMethod=()=>or(this.ids.onMethod,Ne({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:pr({[this.ids.dataParameter.text]:_(Ot("R",er(this.makeEventNarrow("E"))),H(P("data")))},Eo(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(w(i.createThis(),this.ids.sourceProp,P("addEventListener"))(this.ids.eventParameter,Te([this.ids.msgParameter],w(this.ids.handlerParameter)(w(JSON[Symbol.toStringTag],P("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),P("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",H(P("event")))}});makeSubscriptionClass=t=>nr(t,[Ao(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:Ot(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ot(_(this.interfaces.positive,"K"),er(this.makeEventNarrow(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.ids.clientConst,Le(t)),w(this.ids.clientConst,this.ids.provideMethod)(A("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",A("10"))])),w(Le(r,A("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(A("time"),Te(["time"],i.createBlock([])))]};import*as z from"ramda";import S from"typescript";import{z as dr}from"zod";var{factory:q}=S,As={[S.SyntaxKind.AnyKeyword]:"",[S.SyntaxKind.BigIntKeyword]:BigInt(0),[S.SyntaxKind.BooleanKeyword]:!1,[S.SyntaxKind.NumberKeyword]:0,[S.SyntaxKind.ObjectKeyword]:{},[S.SyntaxKind.StringKeyword]:"",[S.SyntaxKind.UndefinedKeyword]:void 0},cr={name:z.path(["name","text"]),type:z.path(["type"]),optional:z.path(["questionToken"])},Es=({value:e})=>H(e),zs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&De(a)?a instanceof dr.ZodOptional:a.isOptional();return Re(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[h]?.isDeprecated})});return q.createTypeLiteralNode(n)},Is=({element:e},{next:t})=>q.createArrayTypeNode(t(e)),Zs=({options:e})=>q.createUnionTypeNode(e.map(H)),Zo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(zo(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},vs=e=>As?.[e.kind],ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=rt(e,vs(o)),s={number:S.SyntaxKind.NumberKeyword,bigint:S.SyntaxKind.BigIntKeyword,boolean:S.SyntaxKind.BooleanKeyword,string:S.SyntaxKind.StringKeyword,undefined:S.SyntaxKind.UndefinedKeyword,object:S.SyntaxKind.ObjectKeyword};return f(n&&s[n]||S.SyntaxKind.AnyKeyword)}return o},Cs=e=>q.createUnionTypeNode(Object.values(e.enum).map(H)),js=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?q.createUnionTypeNode([o,f(S.SyntaxKind.UndefinedKeyword)]):o},Ns=(e,{next:t})=>q.createUnionTypeNode([t(e.unwrap()),H(null)]),Ls=({items:e,_def:{rest:t}},{next:r})=>q.createTupleTypeNode(e.map(r).concat(t===null?[]:q.createRestTypeNode(r(t)))),Ms=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Us=z.tryCatch(e=>{if(!e.every(S.isTypeLiteralNode))throw new Error("Not objects");let t=z.chain(z.prop("members"),e),r=z.uniqWith((...o)=>{if(!z.eqBy(cr.name,...o))return!1;if(z.both(z.eqBy(cr.type),z.eqBy(cr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),Ds=({_def:{left:e,right:t}},{next:r})=>Us([e,t].map(r)),Hs=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),Ks=(e,{next:t})=>t(e.unwrap()),Fs=(e,{next:t})=>t(e.unwrap()),qs=({_def:e},{next:t})=>t(e.innerType),Bs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),$s=()=>H(null),_s=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Vs=e=>{let t=e.unwrap(),r=f(S.SyntaxKind.StringKeyword),o=f("Buffer"),n=q.createUnionTypeNode([r,o]);return t instanceof dr.ZodString?r:t instanceof dr.ZodUnion?n:o},Gs=(e,{next:t})=>t(e.unwrap().shape.raw),Js={ZodString:ae(S.SyntaxKind.StringKeyword),ZodNumber:ae(S.SyntaxKind.NumberKeyword),ZodBigInt:ae(S.SyntaxKind.BigIntKeyword),ZodBoolean:ae(S.SyntaxKind.BooleanKeyword),ZodAny:ae(S.SyntaxKind.AnyKeyword),ZodUndefined:ae(S.SyntaxKind.UndefinedKeyword),[fe]:ae(S.SyntaxKind.StringKeyword),[ye]:ae(S.SyntaxKind.StringKeyword),ZodNull:$s,ZodArray:Is,ZodTuple:Ls,ZodRecord:Ms,ZodObject:zs,ZodLiteral:Es,ZodIntersection:Ds,ZodUnion:Zo,ZodDefault:Hs,ZodEnum:Zs,ZodNativeEnum:Cs,ZodEffects:ks,ZodOptional:js,ZodNullable:Ns,ZodDiscriminatedUnion:Zo,ZodBranded:Ks,ZodCatch:qs,ZodPipeline:Bs,ZodLazy:_s,ZodReadonly:Fs,[G]:Vs,[ie]:Gs},mr=(e,{brandHandling:t,ctx:r})=>Se(e,{rules:{...t,...Js},onMissing:()=>f(S.SyntaxKind.AnyKeyword),ctx:r});var lr=class extends Pt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=H(null);this.aliases.set(t,Q(o,n)),this.aliases.set(t,Q(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:m=Ws.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:(x,y,C)=>{let O=se.bind(null,C,y),{isDeprecated:V}=x,I=`${C} ${y}`,R=Q(O("input"),mr(x.getSchema("input"),l),{comment:I});this.program.push(R);let Z=Ze.reduce((E,K)=>{let v=x.getResponses(K),At=vo.chain(([Et,{schema:te,mimeTypes:pe,statusCodes:zt}])=>{let Ye=Q(O(K,"variant",`${Et+1}`),mr(pe?te:m,b),{comment:I});return this.program.push(Ye),zt.map(Qe=>Re(Qe,Ye.name))},Array.from(v.entries())),We=Tt(O(K,"response","variants"),At,{comment:I});return this.program.push(We),Object.assign(E,{[K]:We})},{});this.paths.add(y);let j=H(I),M={input:f(R.name),positive:this.someOf(Z.positive),negative:this.someOf(Z.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,j),_(this.interfaces.negative,j)]),encoded:i.createIntersectionTypeNode([f(Z.positive.name),f(Z.negative.name)])};this.registry.set(I,{isDeprecated:V,store:M}),this.tags.set(I,x.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:Wt(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 no=e=>{e.startupLogo!==!1&&oo(process.stdout);let t=e.errorHandler||$e,r=jr(e.logger)?e.logger:new _e(e.logger);r.debug("Running",{build:"v22.12.0 (ESM)",env:process.env.NODE_ENV||"development"}),eo(r);let o=Qr({logger:r,config:e}),s={getLogger:Xr(r),errorHandler:t},a=Jr(s),c=Gr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Pn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=no(e);return Ft({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},wn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=no(e),c=ht().disable("x-powered-by").use(a);if(e.compression){let h=await Ce("compression");c.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ht.json()],raw:[e.rawParser||ht.raw(),Yr],form:[e.formParser||ht.urlencoded()],upload:e.upload?await Wr({config:e,getLogger:o}):[]};Ft({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(h,x)=>()=>h.listen(x,()=>r.info("Listening",x)),b=[];if(e.http){let h=Tn.createServer(c);p.push(h),b.push(l(h,e.http.listen))}if(e.https){let h=On.createServer(e.https.options,c);p.push(h),b.push(l(h,e.https.listen))}return e.gracefulShutdown&&to({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(h=>h())}};import{OpenApiBuilder as xs}from"openapi3-ts/oas31";import*as Eo from"ramda";import*as T from"ramda";var so=e=>le(e)&&"or"in e,io=e=>le(e)&&"and"in e,qt=e=>!io(e)&&!so(e),ao=e=>{let t=T.filter(qt,e),r=T.chain(T.prop("and"),T.filter(io,e)),[o,n]=T.partition(qt,r),s=T.concat(t,o),a=T.filter(so,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>me(m,T.map(l=>qt(l)?[l]:l.and,p),([l,b])=>T.concat(l,b)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as Bt,isSchemaObject as xt}from"openapi3-ts/oas31";import*as d 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),m=t&&t(e,{prev:c,...n});return m?{...c,...m}: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","detached-jws","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 co=50,lo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",En={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},zn=/^\d{4}-\d{2}-\d{2}$/,In=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Zn=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$/,uo=e=>e.replace(Ct,t=>`{${t.slice(1)}}`),vn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),kn=({_def:{innerType:e}},{next:t})=>t(e),Cn=()=>({format:"any"}),jn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Nn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof F.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Ln=({options:e},{next:t})=>({oneOf:e.map(t)}),Mn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Un=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},fo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Un,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>me(e,t,([r,o])=>d.mergeDeepRight(r,o))},Dn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(fo)),d.isEmpty)),Hn=d.tryCatch(e=>{let[t,r]=e.filter(xt).filter(Dn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,fo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Kn=({_def:{left:e,right:t}},{next:r})=>Hn([e,t].map(r)),Fn=(e,{next:t})=>t(e.unwrap()),qn=(e,{next:t})=>t(e.unwrap()),Bn=(e,{next:t})=>{let r=t(e.unwrap());return xt(r)&&(r.type=go(r)),r},yo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},mo=e=>({type:yo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),$n=({value:e})=>({type:yo(e),const:e}),_n=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&De(c)?c instanceof F.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=bt(e,r)),s.length&&(a.required=s),a},Vn=()=>({type:"null"}),Gn=({},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:lo}}},Jn=({},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:lo}}},Wn=({},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)},Yn=()=>({type:"boolean"}),Qn=()=>({type:"integer",format:"bigint"}),Xn=e=>e.every(t=>t instanceof F.ZodLiteral),es=({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=bt(F.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof F.ZodLiteral)return{type:"object",properties:bt(F.object({[e.value]:t}),r),required:[e.value]};if(e instanceof F.ZodUnion&&Xn(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:bt(F.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ts=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},rs=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),os=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:h,isTime:x,isBase64:y,isNANOID:C,isBase64url:O,isDuration:V,_def:{checks:I}})=>{let R=I.find(v=>v.kind==="regex"),Z=I.find(v=>v.kind==="datetime"),j=I.some(v=>v.kind==="jwt"),M=I.find(v=>v.kind==="length"),E={type:"string"},K={"date-time":l,byte:y,base64url:O,date:h,time:x,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:j,ip:m,cidr:b,emoji:p};for(let v in K)if(K[v]){E.format=v;break}return M&&([E.minLength,E.maxLength]=[M.value,M.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),h&&(E.pattern=zn.source),x&&(E.pattern=In.source),l&&(E.pattern=Zn(Z?.offset).source),R&&(E.pattern=R.regex.source),E},ns=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(y=>y.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(y=>y.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,h=l?l.inclusive:!0,x={type:e?"integer":"number",format:e?"int64":"double"};return p?x.minimum=m:x.exclusiveMinimum=m,h?x.maximum=b:x.exclusiveMaximum=b,x},bt=({shape:e},t)=>d.map(t,e),ss=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return En?.[t]},go=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",is=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&xt(o)){let s=ot(e,ss(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(F.any())}if(!t&&n.type==="preprocess"&&xt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},as=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ps=(e,{next:t})=>t(e.unwrap()),cs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ds=(e,{next:t})=>t(e.unwrap().shape.raw),ho=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,bo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),ho)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ms=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),ho)({schema:e,variant:"original",validate:!0,pullProps:!0}),ls=(e,t)=>t?.includes(e)||e.startsWith("x-")||po.includes(e),xo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=$(r),h=tt(e),x=o.includes("query"),y=o.includes("params"),C=o.includes("headers"),O=R=>y&&h.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),I=R=>C&&(c?.(R,t,e)??ls(R,V));return Object.entries(b.shape).reduce((R,[Z,j])=>{let M=O(Z)?"path":I(Z)?"header":x?"query":void 0;if(!M)return R;let E=Se(j,{rules:{...a,...$t},onEach:_t,onMissing:Vt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),K=s==="components"?n(j,E,se(l,Z)):E,{_def:v}=j;return R.concat({name:Z,in:M,deprecated:v[g]?.isDeprecated,required:!j.isOptional(),description:E.description||l,schema:K,examples:ms(b,Z)})},[])},$t={ZodString:os,ZodNumber:ns,ZodBigInt:Qn,ZodBoolean:Yn,ZodNull:Vn,ZodArray:ts,ZodTuple:rs,ZodRecord:es,ZodObject:_n,ZodLiteral:$n,ZodIntersection:Kn,ZodUnion:Ln,ZodAny:Cn,ZodDefault:vn,ZodEnum:mo,ZodNativeEnum:mo,ZodEffects:is,ZodOptional:Fn,ZodNullable:Bn,ZodDiscriminatedUnion:Mn,ZodBranded:ps,ZodDate:Wn,ZodCatch:kn,ZodPipeline:as,ZodLazy:cs,ZodReadonly:qn,[G]:Nn,[we]:jn,[ye]:Jn,[fe]:Gn,[ie]:ds},_t=(e,{isResponse:t,prev:r})=>{if(Bt(r))return{};let{description:o,_def:n}=e,s=e instanceof F.ZodLazy,a=r.type!==void 0,c=t&&De(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[g]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=go(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},Vt=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},So=(e,t)=>{if(Bt(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=So(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},Ro=e=>Bt(e)?e:d.omit(["examples"],e),To=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Lt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let h=Ro(Se(r,{rules:{...p,...$t},onEach:_t,onMissing:Vt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),x={schema:a==="components"?s(r,h,se(b)):h,examples:bo(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[x]))}},us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},fs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ys=({name:e})=>({type:"apiKey",in:"header",name:e}),gs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),hs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),bs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Oo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?us(o):o.type==="input"?fs(o,t):o.type==="header"?ys(o):o.type==="cookie"?gs(o):o.type==="openid"?hs(o):bs(o);return e.map(o=>o.map(r))},Po=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),wo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=So(Se(r,{rules:{...a,...$t},onEach:_t,onMissing:Vt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),h=Ro(l),x={schema:s==="components"?n(r,h,se(p)):h,examples:bo($(r),!1,c)},y={description:p,content:{[o]:x}};return(b||mt(r))&&(y.required=!0),y},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)},[]),Gt=e=>e.length<=co?e:e.slice(0,co-1)+"\u2026",St=e=>e.length?e.slice():void 0;var Jt=class extends xs{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:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:h="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,C,O)=>{let V={path:C,method:O,endpoint:y,composition:h,brandHandling:c,numericRange:l,makeRef:this.makeRef.bind(this)},[I,R]=["short","long"].map(y.getDescription.bind(y)),Z=I?Gt(I):b&&R?Gt(R):void 0,j=r.inputSources?.[O]||jt[O],M=this.ensureUniqOperationId(C,O,y.getOperationId(O)),E=ao(y.getSecurity()),K=xo({...V,inputSources:j,isHeader:p,security:E,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:C,operationId:M})}),v={};for(let te of Ze){let pe=y.getResponses(te);for(let{mimeTypes:vt,schema:Qe,statusCodes:Xe}of pe)for(let kt of Xe)v[kt]=To({...V,variant:te,schema:Qe,mimeTypes:vt,statusCode:kt,hasMultipleStatusCodes:pe.length>1||Xe.length>1,description:a?.[`${te}Response`]?.call(null,{method:O,path:C,operationId:M,statusCode:kt})})}let It=j.includes("body")?wo({...V,paramNames:Eo.pluck("name",K),schema:y.getSchema("input"),mimeType:k[y.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:C,operationId:M})}):void 0,Ye=Po(Oo(E,j),y.getScopes(),te=>{let pe=this.ensureUniqSecuritySchemaName(te);return this.addSecurityScheme(pe,te),pe}),Zt={operationId:M,summary:Z,description:R,deprecated:y.isDeprecated||void 0,tags:St(y.getTags()),parameters:St(K),requestBody:It,security:St(Ye),responses:v};this.addPath(uo(C),{[O]:Zt})}}),m&&(this.rootDoc.tags=Ao(m))}};import{createRequest as Ss,createResponse as Rs}from"node-mocks-http";var Ts=e=>Ss({...e,headers:{"content-type":k.json,...e?.headers}}),Os=e=>Rs(e),Ps=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Nr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},zo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ts(e),s=Os({req:n,...t});s.req=t?.req||n,n.res=s;let a=Ps(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},ws=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=zo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},As=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=zo(o),m=rt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:m,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 No from"ramda";import zt from"typescript";import{z as ei}from"zod";import*as Co from"ramda";import X from"typescript";var Io=["get","post","put","delete","patch"];import*as Y from"ramda";import u from"typescript";var i=u.factory,Rt=[i.createModifier(u.SyntaxKind.ExportKeyword)],Es=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Je={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Wt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Yt=(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)},zs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Qt=e=>typeof e=="string"&&zs.test(e)?i.createIdentifier(e):A(e),Tt=(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)))),Ot=(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])=>Ot(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Xt=(e,t=[])=>i.createConstructorDeclaration(Je.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,er=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,Qt(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Wt(s,a.join(" ")):s},tr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),rr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),N=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Rt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),or=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(H,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Rt:void 0,e,n&&ar(n),t);return o?Wt(s,o):s},Zo=(e,t)=>i.createPropertyDeclaration(Je.public,e,void 0,f(t),void 0),nr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Je.public,void 0,e,void 0,o&&ar(o),t,n,i.createBlock(r)),sr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Rt,e,r&&ar(r),void 0,t),ir=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Pt=e=>f(Promise.name,[e]),wt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Rt:void 0,e,void 0,void 0,t);return o?Wt(n,o):n},ar=e=>(Array.isArray(e)?e.map(t=>Y.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?Es:void 0,void 0,Array.isArray(e)?Y.map(Ot,e):Ne(e),void 0,void 0,t),P=e=>e,We=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),w=(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),At=(e,t)=>f("Extract",[e,t]),pr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),vo=e=>i.createUnionTypeNode([f(e),Pt(e)]),cr=(e,t)=>i.createFunctionTypeNode(void 0,Ne(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),H=e=>i.createLiteralTypeNode(A(e)),Is=[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],ko=e=>Is.includes(e.kind);var Et=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=or("Method",Io);someOfType=Q("SomeOf",_("T",ir("T")),{params:["T"]});requestType=Q("Request",ir(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>or(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>wt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>N("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Qt(t),i.createArrayLiteralExpression(Co.map(A,r))))),{expose:!0});makeImplementationType=()=>Q(this.ids.implementationType,cr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:er,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},Pt(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.ids.parseRequestFn,Te({[this.ids.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(w(this.ids.requestParameter,P("split"))(i.createRegularExpressionLiteral("/ (.+)/"),A(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>N(this.ids.substituteFn,Te({[this.ids.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:er},i.createBlock([N(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],X.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([pr(this.ids.pathParameter,w(this.ids.pathParameter,P("replace"))(Tt(":",[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=()=>nr(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"}}),[N(rr(this.ids.methodParameter,this.ids.pathParameter),w(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(w(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(w(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Pt(_(this.interfaces.response,"K"))});makeClientClass=t=>sr(t,[Xt([Ot(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:Je.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>Tt("?",[Le(URLSearchParams.name,t)]);makeFetchURL=()=>Le(URL.name,Tt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),A(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(P("method"),w(this.ids.methodParameter,P("toUpperCase"))()),r=i.createPropertyAssignment(P("headers"),We(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(A("Content-Type"),A(k.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(P("body"),We(this.ids.hasBodyConst,w(JSON[Symbol.toStringTag],P("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=N(this.ids.responseConst,i.createAwaitExpression(w(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=N(this.ids.hasBodyConst,i.createLogicalNot(w(i.createArrayLiteralExpression([A("get"),A("delete")]),P("includes"))(this.ids.methodParameter))),a=N(this.ids.searchParamsConst,We(this.ids.hasBodyConst,A(""),this.makeSearchParams(this.ids.paramsArgument))),c=N(this.ids.contentTypeConst,w(this.ids.responseConst,P("headers"),P("get"))(A("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=N(this.ids.isJsonConst,w(this.ids.contentTypeConst,P("startsWith"))(A(k.json))),l=i.createReturnStatement(w(this.ids.responseConst,We(this.ids.isJsonConst,A(P("json")),A(P("text"))))());return N(this.ids.defaultImplementationConst,Te([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>Xt(Ne({request:"K",params:_(this.interfaces.input,"K")}),[N(rr(this.ids.pathParameter,this.ids.restConst),w(this.ids.substituteFn)(i.createElementAccessExpression(w(this.ids.parseRequestFn)(this.ids.requestParameter),A(1)),this.ids.paramsArgument)),N(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),pr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Le("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([Re(P("event"),t)]);makeOnMethod=()=>nr(this.ids.onMethod,Ne({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:cr({[this.ids.dataParameter.text]:_(At("R",tr(this.makeEventNarrow("E"))),H(P("data")))},vo(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(w(i.createThis(),this.ids.sourceProp,P("addEventListener"))(this.ids.eventParameter,Te([this.ids.msgParameter],w(this.ids.handlerParameter)(w(JSON[Symbol.toStringTag],P("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),P("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",H(P("event")))}});makeSubscriptionClass=t=>sr(t,[Zo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:At(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:At(_(this.interfaces.positive,"K"),tr(this.makeEventNarrow(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.ids.clientConst,Le(t)),w(this.ids.clientConst,this.ids.provideMethod)(A("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",A("10"))])),w(Le(r,A("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(A("time"),Te(["time"],i.createBlock([])))]};import*as z from"ramda";import S from"typescript";import{z as mr}from"zod";var{factory:q}=S,Zs={[S.SyntaxKind.AnyKeyword]:"",[S.SyntaxKind.BigIntKeyword]:BigInt(0),[S.SyntaxKind.BooleanKeyword]:!1,[S.SyntaxKind.NumberKeyword]:0,[S.SyntaxKind.ObjectKeyword]:{},[S.SyntaxKind.StringKeyword]:"",[S.SyntaxKind.UndefinedKeyword]:void 0},dr={name:z.path(["name","text"]),type:z.path(["type"]),optional:z.path(["questionToken"])},vs=({value:e})=>H(e),ks=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&De(a)?a instanceof mr.ZodOptional:a.isOptional();return Re(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return q.createTypeLiteralNode(n)},Cs=({element:e},{next:t})=>q.createArrayTypeNode(t(e)),js=({options:e})=>q.createUnionTypeNode(e.map(H)),jo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(ko(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},Ns=e=>Zs?.[e.kind],Ls=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ot(e,Ns(o)),s={number:S.SyntaxKind.NumberKeyword,bigint:S.SyntaxKind.BigIntKeyword,boolean:S.SyntaxKind.BooleanKeyword,string:S.SyntaxKind.StringKeyword,undefined:S.SyntaxKind.UndefinedKeyword,object:S.SyntaxKind.ObjectKeyword};return f(n&&s[n]||S.SyntaxKind.AnyKeyword)}return o},Ms=e=>q.createUnionTypeNode(Object.values(e.enum).map(H)),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?q.createUnionTypeNode([o,f(S.SyntaxKind.UndefinedKeyword)]):o},Ds=(e,{next:t})=>q.createUnionTypeNode([t(e.unwrap()),H(null)]),Hs=({items:e,_def:{rest:t}},{next:r})=>q.createTupleTypeNode(e.map(r).concat(t===null?[]:q.createRestTypeNode(r(t)))),Ks=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Fs=z.tryCatch(e=>{if(!e.every(S.isTypeLiteralNode))throw new Error("Not objects");let t=z.chain(z.prop("members"),e),r=z.uniqWith((...o)=>{if(!z.eqBy(dr.name,...o))return!1;if(z.both(z.eqBy(dr.type),z.eqBy(dr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),qs=({_def:{left:e,right:t}},{next:r})=>Fs([e,t].map(r)),Bs=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),$s=(e,{next:t})=>t(e.unwrap()),_s=(e,{next:t})=>t(e.unwrap()),Vs=({_def:e},{next:t})=>t(e.innerType),Gs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Js=()=>H(null),Ws=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ys=e=>{let t=e.unwrap(),r=f(S.SyntaxKind.StringKeyword),o=f("Buffer"),n=q.createUnionTypeNode([r,o]);return t instanceof mr.ZodString?r:t instanceof mr.ZodUnion?n:o},Qs=(e,{next:t})=>t(e.unwrap().shape.raw),Xs={ZodString:ae(S.SyntaxKind.StringKeyword),ZodNumber:ae(S.SyntaxKind.NumberKeyword),ZodBigInt:ae(S.SyntaxKind.BigIntKeyword),ZodBoolean:ae(S.SyntaxKind.BooleanKeyword),ZodAny:ae(S.SyntaxKind.AnyKeyword),ZodUndefined:ae(S.SyntaxKind.UndefinedKeyword),[fe]:ae(S.SyntaxKind.StringKeyword),[ye]:ae(S.SyntaxKind.StringKeyword),ZodNull:Js,ZodArray:Cs,ZodTuple:Hs,ZodRecord:Ks,ZodObject:ks,ZodLiteral:vs,ZodIntersection:qs,ZodUnion:jo,ZodDefault:Bs,ZodEnum:js,ZodNativeEnum:Ms,ZodEffects:Ls,ZodOptional:Us,ZodNullable:Ds,ZodDiscriminatedUnion:jo,ZodBranded:$s,ZodCatch:Vs,ZodPipeline:Gs,ZodLazy:Ws,ZodReadonly:_s,[G]:Ys,[ie]:Qs},lr=(e,{brandHandling:t,ctx:r})=>Se(e,{rules:{...t,...Xs},onMissing:()=>f(S.SyntaxKind.AnyKeyword),ctx:r});var ur=class extends Et{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=H(null);this.aliases.set(t,Q(o,n)),this.aliases.set(t,Q(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:m=ei.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:(x,y,C)=>{let O=se.bind(null,C,y),{isDeprecated:V}=x,I=`${C} ${y}`,R=Q(O("input"),lr(x.getSchema("input"),l),{comment:I});this.program.push(R);let Z=Ze.reduce((E,K)=>{let v=x.getResponses(K),It=No.chain(([Zt,{schema:te,mimeTypes:pe,statusCodes:vt}])=>{let Qe=Q(O(K,"variant",`${Zt+1}`),lr(pe?te:m,b),{comment:I});return this.program.push(Qe),vt.map(Xe=>Re(Xe,Qe.name))},Array.from(v.entries())),Ye=wt(O(K,"response","variants"),It,{comment:I});return this.program.push(Ye),Object.assign(E,{[K]:Ye})},{});this.paths.add(y);let j=H(I),M={input:f(R.name),positive:this.someOf(Z.positive),negative:this.someOf(Z.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,j),_(this.interfaces.negative,j)]),encoded:i.createIntersectionTypeNode([f(Z.positive.name),f(Z.negative.name)])};this.registry.set(I,{isDeprecated:V,store:M}),this.tags.set(I,x.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:Yt(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&zt.addSyntheticLeadingComment(zt.addSyntheticLeadingComment(i.createEmptyStatement(),zt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),zt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>Yt(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 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
|
|
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 Mo=(e,t)=>Me.object({data:t,event:Me.literal(e),id:Me.string().optional(),retry:Me.number().int().positive().optional()}),ti=(e,t,r)=>Mo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),ri=1e4,Lo=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":k.sse,"cache-control":"no-cache"}),oi=e=>new J({handler:async({response:t})=>setTimeout(()=>Lo(t),ri)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Lo(t),t.write(ti(e,r,o),"utf-8"),t.flush?.()}}}),ni=e=>new be({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Mo(o,n));return{mimeType:k.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=Ae(r);qe(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ge(a),"utf-8")}t.end()}}),fr=class extends xe{constructor(t){super(ni(t)),this.middlewares=[oi(t)]}};var si={dateIn:hr,dateOut:br,form:Rr,file:at,upload:Or,raw:Tr};export{_e as BuiltinLogger,Ve as DependsOnMethod,Jt as Documentation,B as DocumentationError,xe as EndpointsFactory,fr as EventStreamFactory,ee as InputValidationError,ur as Integration,J as Middleware,Ue as MissingPeerError,ce as OutputValidationError,be as ResultHandler,Oe as RoutingError,Ge as ServeStatic,on as arrayEndpointsFactory,Ht as arrayResultHandler,Pn as attachRouting,_o as createConfig,wn as createServer,rn as defaultEndpointsFactory,$e as defaultResultHandler,Ae as ensureHttpError,si as ez,ne as getExamples,de as getMessageFromError,ws as testEndpoint,As as testMiddleware};
|
package/migration/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var a=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var u=(s,e)=>{for(var t in e)a(s,t,{get:e[t],enumerable:!0})},g=(s,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of m(e))!l.call(s,n)&&n!==t&&a(s,n,{get:()=>e[n],enumerable:!(o=c(e,n))||o.enumerable});return s};var y=s=>g(a({},"__esModule",{value:!0}),s);var E={};u(E,{default:()=>x});module.exports=y(E);var r=require("@typescript-eslint/utils");var i=["get","post","put","delete","patch"];var p="express-zod-api";var S={provide:`${r.AST_NODE_TYPES.CallExpression}[callee.property.name='provide'][arguments.length=3]:has(${r.AST_NODE_TYPES.Literal}[value=/^${i.join("|")}$/] + ${r.AST_NODE_TYPES.Literal} + ${r.AST_NODE_TYPES.ObjectExpression})`,splitResponse:`${r.AST_NODE_TYPES.NewExpression}[callee.name='Integration'] > ${r.AST_NODE_TYPES.ObjectExpression} > ${r.AST_NODE_TYPES.Property}[key.name='splitResponse']`,methodPath:`${r.AST_NODE_TYPES.ImportDeclaration} > ${r.AST_NODE_TYPES.ImportSpecifier}[imported.name='MethodPath']`,createConfig:`${r.AST_NODE_TYPES.CallExpression}[callee.name='createConfig'] > ${r.AST_NODE_TYPES.ObjectExpression} > ${r.AST_NODE_TYPES.Property}[key.name='tags'][value.type='ObjectExpression']`,newDocs:`${r.AST_NODE_TYPES.NewExpression}[callee.name='Documentation'] > ${r.AST_NODE_TYPES.ObjectExpression}[properties.length>0]:not(:has(>Property[key.name='tags']))`,newFactory:`${r.AST_NODE_TYPES.NewExpression}[callee.name='EndpointsFactory'] > ${r.AST_NODE_TYPES.ObjectExpression} > ${r.AST_NODE_TYPES.Property}[key.name='resultHandler']`,newSSE:`${r.AST_NODE_TYPES.NewExpression}[callee.name='EventStreamFactory'] > ${r.AST_NODE_TYPES.ObjectExpression} > ${r.AST_NODE_TYPES.Property}[key.name='events']`,newClient:`${r.AST_NODE_TYPES.NewExpression}[callee.name='ExpressZodAPIClient']`},h=s=>Object.keys(s).reduce((e,t)=>Object.assign(e,{[S[t]]:s[t]}),{}),T=r.ESLintUtils.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{add:"Add {{subject}} to {{to}}",change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:s=>h({provide:e=>{let{arguments:[t,o]}=e,n=`"${t.value} ${o.value}"`;s.report({messageId:"change",node:e,data:{subject:"arguments",from:`"${t.value}", "${o.value}"`,to:n},fix:d=>d.replaceTextRange([t.range[0],o.range[1]],n)})},splitResponse:e=>s.report({messageId:"remove",node:e,data:{subject:"property",name:e.key.name},fix:t=>t.remove(e)}),methodPath:e=>{let t="Request";s.report({messageId:"change",node:e.imported,data:{subject:"type",from:e.imported.name,to:t},fix:o=>o.replaceText(e.imported,t)})},createConfig:e=>{let t=e.value.properties.filter(o=>"key"in o&&"name"in o.key).map(o=>` "${o.key.name}": unknown,
|
|
2
2
|
`);s.report({messageId:"remove",node:e,data:{subject:"property",name:e.key.name},fix:o=>[o.remove(e),o.insertTextAfter(s.sourceCode.ast,`
|
|
3
3
|
// Declaring tag constraints
|
|
4
4
|
declare module "${p}" {
|
|
5
5
|
interface TagOverrides {
|
|
6
6
|
${t} }
|
|
7
|
-
}`)]})},newDocs:e=>s.report({messageId:"add",node:e,data:{subject:"tags",to:"Documentation"},fix:t=>t.insertTextBefore(e.properties[0],"tags: { /* move from createConfig() argument if any */ }, ")}),newFactory:e=>s.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"ResultHandler instance"},fix:t=>t.replaceText(e.parent,s.sourceCode.getText(e.value))}),newSSE:e=>s.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"events map"},fix:t=>t.replaceText(e.parent,s.sourceCode.getText(e.value))}),newClient:e=>{let t="Client";s.report({messageId:"change",node:e.callee,data:{subject:"class",from:"ExpressZodAPIClient",to:t},fix:o=>o.replaceText(e.callee,t)})}})}),
|
|
7
|
+
}`)]})},newDocs:e=>s.report({messageId:"add",node:e,data:{subject:"tags",to:"Documentation"},fix:t=>t.insertTextBefore(e.properties[0],"tags: { /* move from createConfig() argument if any */ }, ")}),newFactory:e=>s.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"ResultHandler instance"},fix:t=>t.replaceText(e.parent,s.sourceCode.getText(e.value))}),newSSE:e=>s.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"events map"},fix:t=>t.replaceText(e.parent,s.sourceCode.getText(e.value))}),newClient:e=>{let t="Client";s.report({messageId:"change",node:e.callee,data:{subject:"class",from:"ExpressZodAPIClient",to:t},fix:o=>o.replaceText(e.callee,t)})}})}),x={rules:{v22:T}};
|
package/migration/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{ESLintUtils as c,AST_NODE_TYPES as r}from"@typescript-eslint/utils";var
|
|
1
|
+
import{ESLintUtils as c,AST_NODE_TYPES as r}from"@typescript-eslint/utils";var a=["get","post","put","delete","patch"];var i="express-zod-api";var m={provide:`${r.CallExpression}[callee.property.name='provide'][arguments.length=3]:has(${r.Literal}[value=/^${a.join("|")}$/] + ${r.Literal} + ${r.ObjectExpression})`,splitResponse:`${r.NewExpression}[callee.name='Integration'] > ${r.ObjectExpression} > ${r.Property}[key.name='splitResponse']`,methodPath:`${r.ImportDeclaration} > ${r.ImportSpecifier}[imported.name='MethodPath']`,createConfig:`${r.CallExpression}[callee.name='createConfig'] > ${r.ObjectExpression} > ${r.Property}[key.name='tags'][value.type='ObjectExpression']`,newDocs:`${r.NewExpression}[callee.name='Documentation'] > ${r.ObjectExpression}[properties.length>0]:not(:has(>Property[key.name='tags']))`,newFactory:`${r.NewExpression}[callee.name='EndpointsFactory'] > ${r.ObjectExpression} > ${r.Property}[key.name='resultHandler']`,newSSE:`${r.NewExpression}[callee.name='EventStreamFactory'] > ${r.ObjectExpression} > ${r.Property}[key.name='events']`,newClient:`${r.NewExpression}[callee.name='ExpressZodAPIClient']`},l=o=>Object.keys(o).reduce((e,t)=>Object.assign(e,{[m[t]]:o[t]}),{}),u=c.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{add:"Add {{subject}} to {{to}}",change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:o=>l({provide:e=>{let{arguments:[t,s]}=e,n=`"${t.value} ${s.value}"`;o.report({messageId:"change",node:e,data:{subject:"arguments",from:`"${t.value}", "${s.value}"`,to:n},fix:p=>p.replaceTextRange([t.range[0],s.range[1]],n)})},splitResponse:e=>o.report({messageId:"remove",node:e,data:{subject:"property",name:e.key.name},fix:t=>t.remove(e)}),methodPath:e=>{let t="Request";o.report({messageId:"change",node:e.imported,data:{subject:"type",from:e.imported.name,to:t},fix:s=>s.replaceText(e.imported,t)})},createConfig:e=>{let t=e.value.properties.filter(s=>"key"in s&&"name"in s.key).map(s=>` "${s.key.name}": unknown,
|
|
2
2
|
`);o.report({messageId:"remove",node:e,data:{subject:"property",name:e.key.name},fix:s=>[s.remove(e),s.insertTextAfter(o.sourceCode.ast,`
|
|
3
3
|
// Declaring tag constraints
|
|
4
|
-
declare module "${
|
|
4
|
+
declare module "${i}" {
|
|
5
5
|
interface TagOverrides {
|
|
6
6
|
${t} }
|
|
7
|
-
}`)]})},newDocs:e=>o.report({messageId:"add",node:e,data:{subject:"tags",to:"Documentation"},fix:t=>t.insertTextBefore(e.properties[0],"tags: { /* move from createConfig() argument if any */ }, ")}),newFactory:e=>o.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"ResultHandler instance"},fix:t=>t.replaceText(e.parent,o.sourceCode.getText(e.value))}),newSSE:e=>o.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"events map"},fix:t=>t.replaceText(e.parent,o.sourceCode.getText(e.value))}),newClient:e=>{let t="Client";o.report({messageId:"change",node:e.callee,data:{subject:"class",from:"ExpressZodAPIClient",to:t},fix:s=>s.replaceText(e.callee,t)})}})}),
|
|
7
|
+
}`)]})},newDocs:e=>o.report({messageId:"add",node:e,data:{subject:"tags",to:"Documentation"},fix:t=>t.insertTextBefore(e.properties[0],"tags: { /* move from createConfig() argument if any */ }, ")}),newFactory:e=>o.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"ResultHandler instance"},fix:t=>t.replaceText(e.parent,o.sourceCode.getText(e.value))}),newSSE:e=>o.report({messageId:"change",node:e.parent,data:{subject:"argument",from:"object",to:"events map"},fix:t=>t.replaceText(e.parent,o.sourceCode.getText(e.value))}),newClient:e=>{let t="Client";o.report({messageId:"change",node:e.callee,data:{subject:"class",from:"ExpressZodAPIClient",to:t},fix:s=>s.replaceText(e.callee,t)})}})}),x={rules:{v22:u}};export{x as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "22.12.0
|
|
3
|
+
"version": "22.12.0",
|
|
4
4
|
"description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -17,12 +17,13 @@
|
|
|
17
17
|
"funding": "https://github.com/sponsors/RobinTail",
|
|
18
18
|
"scripts": {
|
|
19
19
|
"build": "tsup",
|
|
20
|
-
"postbuild": "attw
|
|
20
|
+
"postbuild": "yarn pack --filename release.tgz && attw release.tgz && rm release.tgz",
|
|
21
21
|
"pretest": "tsc --noEmit",
|
|
22
22
|
"test": "vitest run --coverage",
|
|
23
23
|
"bench": "vitest bench --run ./bench",
|
|
24
|
-
"prepublishOnly": "eslint &&
|
|
25
|
-
"prepack": "cp ../*.md ../LICENSE ./"
|
|
24
|
+
"prepublishOnly": "eslint && yarn test && yarn build",
|
|
25
|
+
"prepack": "cp ../*.md ../LICENSE ./",
|
|
26
|
+
"postversion": "git push && git push --tags"
|
|
26
27
|
},
|
|
27
28
|
"type": "module",
|
|
28
29
|
"sideEffects": true,
|
|
@@ -60,7 +61,7 @@
|
|
|
60
61
|
"node": "^20.9.0 || ^22.0.0"
|
|
61
62
|
},
|
|
62
63
|
"dependencies": {
|
|
63
|
-
"ansis": "^3.
|
|
64
|
+
"ansis": "^3.17.0",
|
|
64
65
|
"node-mocks-http": "^1.16.2",
|
|
65
66
|
"openapi3-ts": "^4.4.0",
|
|
66
67
|
"ramda": "^0.30.1"
|
|
@@ -71,7 +72,7 @@
|
|
|
71
72
|
"@types/express-fileupload": "^1.5.0",
|
|
72
73
|
"@types/http-errors": "^2.0.2",
|
|
73
74
|
"compression": "^1.7.4",
|
|
74
|
-
"express": "^4.21.1 || 5.0.1",
|
|
75
|
+
"express": "^4.21.1 || ^5.0.1",
|
|
75
76
|
"express-fileupload": "^1.5.0",
|
|
76
77
|
"http-errors": "^2.0.0",
|
|
77
78
|
"typescript": "^5.1.3",
|
|
@@ -103,14 +104,14 @@
|
|
|
103
104
|
"@types/depd": "^1.1.36",
|
|
104
105
|
"@types/node-forge": "^1.3.11",
|
|
105
106
|
"@types/ramda": "^0.30.0",
|
|
106
|
-
"@types/semver": "^7.
|
|
107
|
+
"@types/semver": "^7.7.0",
|
|
107
108
|
"camelize-ts": "^3.0.0",
|
|
108
109
|
"cors": "^2.8.5",
|
|
109
110
|
"depd": "^2.0.0",
|
|
110
111
|
"node-forge": "^1.3.1",
|
|
111
112
|
"semver": "^7.6.3",
|
|
112
113
|
"snakify-ts": "^2.3.0",
|
|
113
|
-
"tsup": "^8.
|
|
114
|
+
"tsup": "^8.4.0",
|
|
114
115
|
"undici": "^6.19.8"
|
|
115
116
|
},
|
|
116
117
|
"keywords": [
|
|
@@ -134,5 +135,6 @@
|
|
|
134
135
|
"swagger-documentation",
|
|
135
136
|
"zod",
|
|
136
137
|
"validation"
|
|
137
|
-
]
|
|
138
|
+
],
|
|
139
|
+
"packageManager": "yarn@1.22.22+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610"
|
|
138
140
|
}
|