express-zod-api 19.0.0 → 19.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/README.md +45 -0
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +108 -68
- package/dist/index.d.ts +108 -68
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,63 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 19
|
|
4
4
|
|
|
5
|
+
### v19.1.1
|
|
6
|
+
|
|
7
|
+
- Fixed a bug on duplicated or missing request header parameters in the generated Documentation:
|
|
8
|
+
- The issue corresponds to the "Headers as input source" opt-in feature;
|
|
9
|
+
- When `query` was not listed in the input sources:
|
|
10
|
+
- Headers used to be missing in the documented request parameters.
|
|
11
|
+
- When `body` was listed along with `query` in the input sources:
|
|
12
|
+
- Headers used to be duplicated into the documented request body.
|
|
13
|
+
- The issue was found and reported by [@boarush](https://github.com/boarush).
|
|
14
|
+
|
|
15
|
+
### v19.1.0
|
|
16
|
+
|
|
17
|
+
- Feature: customizable handling rules for your branded schemas in Documentation and Integration:
|
|
18
|
+
- You can make your schemas special by branding them using `.brand()` method;
|
|
19
|
+
- The library (being a Zod Plugin as well) distinguishes the branded schemas in runtime;
|
|
20
|
+
- The constructors of `Documentation` and `Integration` now accept new property `brandHandling` (object);
|
|
21
|
+
- Its keys should be the brands you want to handle in a special way;
|
|
22
|
+
- Its values are functions having your schema as the first argument and a context in the second place;
|
|
23
|
+
- In case you need to reuse a handling rule for multiple brands, use the exposed types `Depicter` and `Producer`.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import ts from "typescript";
|
|
27
|
+
import { z } from "zod";
|
|
28
|
+
import {
|
|
29
|
+
Documentation,
|
|
30
|
+
Integration,
|
|
31
|
+
Depicter,
|
|
32
|
+
Producer,
|
|
33
|
+
} from "express-zod-api";
|
|
34
|
+
|
|
35
|
+
const myBrand = Symbol("MamaToldMeImSpecial"); // I recommend to use symbols for this purpose
|
|
36
|
+
const myBrandedSchema = z.string().brand(myBrand);
|
|
37
|
+
|
|
38
|
+
const ruleForDocs: Depicter = (
|
|
39
|
+
schema: typeof myBrandedSchema, // you should assign type yourself
|
|
40
|
+
{ next, path, method, isResponse }, // handle a nested schema using next()
|
|
41
|
+
) => {
|
|
42
|
+
const defaultDepiction = next(schema.unwrap()); // { type: string }
|
|
43
|
+
return { summary: "Special type of data" };
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const ruleForClient: Producer = (
|
|
47
|
+
schema: typeof myBrandedSchema, // you should assign type yourself
|
|
48
|
+
{ next, isResponse, serializer }, // handle a nested schema using next()
|
|
49
|
+
) => ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
|
|
50
|
+
|
|
51
|
+
new Documentation({
|
|
52
|
+
/* config, routing, title, version */
|
|
53
|
+
brandHandling: { [myBrand]: ruleForDocs },
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
new Integration({
|
|
57
|
+
/* routing */
|
|
58
|
+
brandHandling: { [myBrand]: ruleForClient },
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
5
62
|
### v19.0.0
|
|
6
63
|
|
|
7
64
|
- **Breaking changes**:
|
package/README.md
CHANGED
|
@@ -58,6 +58,7 @@ Start your API server with I/O schema validation and custom middlewares in minut
|
|
|
58
58
|
2. [Generating a Frontend Client](#generating-a-frontend-client)
|
|
59
59
|
3. [Creating a documentation](#creating-a-documentation)
|
|
60
60
|
4. [Tagging the endpoints](#tagging-the-endpoints)
|
|
61
|
+
5. [Customizable brands handling](#customizable-brands-handling)
|
|
61
62
|
8. [Caveats](#caveats)
|
|
62
63
|
1. [Coercive schema of Zod](#coercive-schema-of-zod)
|
|
63
64
|
2. [Excessive properties in endpoint output](#excessive-properties-in-endpoint-output)
|
|
@@ -1170,6 +1171,50 @@ const exampleEndpoint = taggedEndpointsFactory.build({
|
|
|
1170
1171
|
});
|
|
1171
1172
|
```
|
|
1172
1173
|
|
|
1174
|
+
## Customizable brands handling
|
|
1175
|
+
|
|
1176
|
+
You can customize handling rules for your schemas in Documentation and Integration. Use the `.brand()` method on your
|
|
1177
|
+
schema to make it special and distinguishable for the library in runtime. Using symbols is recommended for branding.
|
|
1178
|
+
After that utilize the `brandHandling` feature of both constructors to declare your custom implementation. In case you
|
|
1179
|
+
need to reuse a handling rule for multiple brands, use the exposed types `Depicter` and `Producer`.
|
|
1180
|
+
|
|
1181
|
+
```ts
|
|
1182
|
+
import ts from "typescript";
|
|
1183
|
+
import { z } from "zod";
|
|
1184
|
+
import {
|
|
1185
|
+
Documentation,
|
|
1186
|
+
Integration,
|
|
1187
|
+
Depicter,
|
|
1188
|
+
Producer,
|
|
1189
|
+
} from "express-zod-api";
|
|
1190
|
+
|
|
1191
|
+
const myBrand = Symbol("MamaToldMeImSpecial"); // I recommend to use symbols for this purpose
|
|
1192
|
+
const myBrandedSchema = z.string().brand(myBrand);
|
|
1193
|
+
|
|
1194
|
+
const ruleForDocs: Depicter = (
|
|
1195
|
+
schema: typeof myBrandedSchema, // you should assign type yourself
|
|
1196
|
+
{ next, path, method, isResponse }, // handle a nested schema using next()
|
|
1197
|
+
) => {
|
|
1198
|
+
const defaultDepiction = next(schema.unwrap()); // { type: string }
|
|
1199
|
+
return { summary: "Special type of data" };
|
|
1200
|
+
};
|
|
1201
|
+
|
|
1202
|
+
const ruleForClient: Producer = (
|
|
1203
|
+
schema: typeof myBrandedSchema, // you should assign type yourself
|
|
1204
|
+
{ next, isResponse, serializer }, // handle a nested schema using next()
|
|
1205
|
+
) => ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
|
|
1206
|
+
|
|
1207
|
+
new Documentation({
|
|
1208
|
+
/* config, routing, title, version */
|
|
1209
|
+
brandHandling: { [myBrand]: ruleForDocs },
|
|
1210
|
+
});
|
|
1211
|
+
|
|
1212
|
+
new Integration({
|
|
1213
|
+
/* routing */
|
|
1214
|
+
brandHandling: { [myBrand]: ruleForClient },
|
|
1215
|
+
});
|
|
1216
|
+
```
|
|
1217
|
+
|
|
1173
1218
|
# Caveats
|
|
1174
1219
|
|
|
1175
1220
|
There are some well-known issues and limitations, or third party bugs that cannot be fixed in the usual way, but you
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},
|
|
1
|
+
"use strict";var Ao=Object.create;var $e=Object.defineProperty;var Po=Object.getOwnPropertyDescriptor;var Co=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,wo=Object.prototype.hasOwnProperty;var Eo=(e,t)=>{for(var r in t)$e(e,r,{get:t[r],enumerable:!0})},er=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Co(t))!wo.call(e,i)&&i!==r&&$e(e,i,{get:()=>t[i],enumerable:!(o=Po(t,i))||o.enumerable});return e};var R=(e,t,r)=>(r=e!=null?Ao(Io(e)):{},er(t||!e||!e.__esModule?$e(r,"default",{value:e,enumerable:!0}):r,e)),zo=e=>er($e({},"__esModule",{value:!0}),e);var ii={};Eo(ii,{AbstractEndpoint:()=>se,DependsOnMethod:()=>Te,Documentation:()=>lt,DocumentationError:()=>P,EndpointsFactory:()=>be,InputValidationError:()=>H,Integration:()=>ht,MissingPeerError:()=>re,OutputValidationError:()=>G,RoutingError:()=>ee,ServeStatic:()=>Re,arrayEndpointsFactory:()=>Or,arrayResultHandler:()=>it,attachRouting:()=>kr,createConfig:()=>ar,createLogger:()=>st,createMiddleware:()=>ot,createResultHandler:()=>nt,createServer:()=>Hr,defaultEndpointsFactory:()=>Rr,defaultResultHandler:()=>xe,ez:()=>Ro,getExamples:()=>F,getMessageFromError:()=>U,getStatusCodeFromError:()=>ve,testEndpoint:()=>ao});module.exports=zo(ii);var sr=require("ramda"),De=require("zod");var tr=require("http-errors"),rr=require("crypto"),ue=require("ramda"),or=require("zod");var ee=class extends Error{name="RoutingError"},P=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
|
|
2
|
+
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},V=class extends Error{name="IOSchemaError"},G=class extends V{name="OutputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},H=class extends V{name="InputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},te=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},re=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var N={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var Zo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(N.upload);return"files"in e&&r},bt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},No=["body","query","params"],Tt=e=>e.method.toLowerCase(),St=e=>e.startsWith("x-"),Mo=e=>(0,ue.pickBy)((0,ue.flip)(St),e),nr=(e,t={})=>{let r=Tt(e);return r==="options"?{}:(t[r]||bt[r]||No).filter(o=>o==="files"?Zo(e):!0).map(o=>o==="headers"?Mo(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},fe=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),U=e=>e instanceof or.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,ve=e=>(0,tr.isHttpError)(e)?e.statusCode:e instanceof H?400:500,Rt=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};var xr=require("ramda");var re=e=>F(e)&&"or"in e,fe=e=>F(e)&&"and"in e,Pt=e=>({and:(0,xr.chain)(t=>fe(t)?t.and:[t],e)}),Xe=(e,t)=>fe(e)?{and:e.and.map(r=>re(r)?{or:r.or.map(t)}:t(r))}:re(e)?{or:e.or.map(r=>fe(r)?{and:r.and.map(t)}:t(r))}:t(e),Ct=e=>e.and.reduce((t,r)=>({or:ee(t.or,re(r)?r.or:[r],Pt)}),{or:[]}),ue=(e,t)=>fe(e)?re(t)?ue(Ct(e),t):Pt([e,t]):re(e)?fe(t)?ue(t,e):re(t)?{or:ee(e.or,t.or,Pt)}:ue(e,{and:[t]}):fe(t)||re(t)?ue(t,e):{and:[e,t]};var oe=class{},tt=class extends oe{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:l=[],description:u,shortDescription:m}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(l),this.#e={long:u,short:m},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,It.default)(!Je(T),new q(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:Object.freeze(Ot(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[me.positive]})),negative:Object.freeze(Ot(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[me.negative]}))};for(let[y,T]of Object.entries(this.#t))(0,It.default)(T.length,new W(`ResultHandler must have at least one ${y} response schema specified.`));this.#i=gr(r)?"upload":hr(r)?"raw":"json",this.#s={input:Object.freeze([N[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:y})=>y)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:y})=>y))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ue(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof et.z.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(l){throw l instanceof et.z.ZodError?new j(l):l}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof et.z.ZodError?new j(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){We({logger:i,response:o,error:new W(le(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=bt(t),p={},d=null,l=null;if(i.cors){let m=this.#m(s);typeof i.cors=="function"&&(m=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:m}));for(let y in m)r.set(y,m[y])}let u=or(t,i.inputSources);try{if(await this.#f({method:a,input:u,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:u,logger:o,options:p}))}catch(m){l=le(m)}await this.#g({input:u,output:d,request:t,response:r,error:l,logger:o,options:p})}};var wt=require("zod");var br=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>nr(s,i),o)};var Tr=R(require("assert/strict"),1),rt=e=>((0,Tr.default)(!Je(e.input),new q("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var v=require("zod");var ot=e=>e,ye=ot({getPositiveResponse:e=>{let t=H({schema:e}),r=v.z.object({status:v.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>v.z.object({status:v.z.literal("error"),error:v.z.object({message:v.z.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(me.positive).json({status:"success",data:r});return}let a=Ze(e);St({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),nt=ot({getPositiveResponse:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.z.ZodArray?e.shape.items:v.z.array(v.z.any());return t.reduce((o,i)=>F(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>v.z.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Ze(r);St({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(me.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var ge=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:wt.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,l)=>{t(a,p,m=>{if(m&&m instanceof Error)return l(o(m));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(rt({input:wt.z.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:l}=this,u="methods"in p?p.methods:[p.method],m=typeof a=="function"?a:()=>a,y="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],T="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new tt({handler:r,middlewares:d,outputSchema:o,resultHandler:l,scopes:y,tags:T,methods:u,getOperationId:m,description:i,shortDescription:s,inputSchema:br(d,t)})}},Sr=new ge(ye),Rr=new ge(nt);var Or=require("util");var Ar=require("ramda"),L=require("ansis"),Et={debug:10,info:20,warn:30,error:40},Pr=e=>F(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),it=({level:e,color:t=new L.Ansis().isSupported(),depth:r=2})=>{let o={debug:L.blue,info:L.green,warn:(0,L.hex)("#FFA500"),error:L.red},i=e==="debug",s=e==="silent"?100:Et[e],a=(p,d,l)=>{if(Et[p]<s)return;let u=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];l!==void 0&&u.push((0,Or.inspect)(l,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Ar.mapObjIndexed)(({},p)=>(d,l)=>a(p,d,l),Et)};var xe=require("ramda"),he=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,xe.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,xe.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,xe.tail)(this.pairs).map(([r])=>r))}};var Cr=R(require("express"),1),be=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Cr.default.static(...this.params))}};var st=R(require("express"),1),vr=R(require("http"),1),Lr=R(require("https"),1);var ne=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>R(require(e))))[t]}catch{}throw new X(e)},Ir=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await ne(t,r)}catch{}throw new X(e.map(({moduleName:t})=>t))};var zt=R(require("assert/strict"),1);var ie=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){zt.default.doesNotMatch(a,/\//,new J(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof oe){let l=p.getMethods().slice();i&&l.push("options");for(let u of l)t(p,d,u)}else if(p instanceof be)r&&p.apply(d,r);else if(p instanceof he){for(let[l,u]of p.pairs)(0,zt.default)(u.getMethods().includes(l),new J(`Endpoint assigned to ${l} method of ${d} must support ${l} method.`)),t(u,d,l);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else ie({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Zt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>ie({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(l,u)=>s.execute({request:l,response:u,logger:u.locals[g]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});var De=R(require("http-errors"),1);var wr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:(0,De.isHttpError)(r)?r:(0,De.default)(400,le(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},Er=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,De.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){We({response:o,logger:s,error:new W(le(a).message,i)})}},Bo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},qo=e=>({log:e.debug.bind(e)}),zr=async({rootLogger:e,config:t})=>{let r=await ne("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,l)=>{let u=d.locals[g]?.logger||e;try{await i?.({request:p,logger:u})}catch(m){return l(m)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:qo(u)})(p,d,l)}),o&&a.push(Bo(o)),a},Zr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Nr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var E=require("ansis"),Mr=()=>{let e=(0,E.italic)("Proudly supports transgender community.".padStart(109)),t=(0,E.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,E.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,E.italic)("for Dime".padEnd(20)),i=(0,E.hex)("#F5A9B8"),s=(0,E.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(E.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(E.gray,12,13);return`
|
|
4
|
+
`,{url:t.url,payload:r})},F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},oe=(e,t,r)=>e.length&&t.length?(0,ue.xprod)(e,t).map(r):e.concat(t),Le=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Ot=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),M=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(Ot).join(""),Ve=e=>(0,rr.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ge=(e,t)=>{try{return typeof e.parse(t)}catch{return}},K=e=>typeof e=="object"&&e!==null;var _e=require("ramda"),g=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[g]=(0,_e.clone)(t._def[g])||{examples:[]},t},ir=(e,t)=>{if(!(g in e._def))return t;let r=Ye(t);return r._def[g].examples=oe(r._def[g].examples,e._def[g].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,_e.mergeDeepRight)({...o},{...i}):i),r};var vo=function(e){let t=Ye(this);return t._def[g].examples.push(e),t},Lo=function(e){let t=Ye(this);return t._def[g].defaultLabel=e,t},Do=function(e){return new De.z.ZodBranded({typeName:De.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...(0,sr.clone)(this._def[g]),brand:e}})};g in globalThis||(globalThis[g]=!0,Object.defineProperties(De.z.ZodType.prototype,{example:{get(){return vo.bind(this)}},brand:{set(){},get(){return Do.bind(this)}}}),Object.defineProperty(De.z.ZodDefault.prototype,"label",{get(){return Lo.bind(this)}}));function ar(e){return e}var wt=R(require("assert/strict"),1),tt=require("zod");var pr=require("zod"),ye={positive:200,negative:400},At=(e,t)=>e instanceof pr.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));var yr=require("zod");var cr=require("zod");var je=require("zod"),_=Symbol("File"),dr=je.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),jo={buffer:()=>dr.brand(_),string:()=>je.z.string().brand(_),binary:()=>dr.or(je.z.string()).brand(_),base64:()=>je.z.string().base64().brand(_)};function Qe(e){return jo[e||"string"]()}var ne=Symbol("Raw"),lr=(e={})=>cr.z.object({raw:Qe("buffer")}).extend(e).brand(ne);var mr=require("zod"),ke=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(ke);var Pt=(e,{next:t})=>e.options.some(t),gr=({_def:e},{next:t})=>[e.left,e.right].some(t),fr=(e,{next:t})=>t(e.unwrap()),ko={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Pt,ZodDiscriminatedUnion:Pt,ZodIntersection:gr,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:fr,ZodNullable:fr,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Je=(e,{condition:t,rules:r=ko,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s(e,{next:a=>Je(a,{condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},We=e=>Je(e,{maxDepth:3,rules:{ZodUnion:Pt,ZodIntersection:gr},condition:t=>t instanceof yr.z.ZodEffects&&t._def.effect.type!=="refinement"}),hr=e=>Je(e,{condition:t=>t._def[g]?.brand===ke}),xr=e=>Je(e,{condition:t=>t._def[g]?.brand===ne,maxDepth:3});var Xe=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
5
|
+
Original error: ${e.originalError.message}.`:""))};var br=require("ramda");var ie=e=>K(e)&&"or"in e,he=e=>K(e)&&"and"in e,Ct=e=>({and:(0,br.chain)(t=>he(t)?t.and:[t],e)}),et=(e,t)=>he(e)?{and:e.and.map(r=>ie(r)?{or:r.or.map(t)}:t(r))}:ie(e)?{or:e.or.map(r=>he(r)?{and:r.and.map(t)}:t(r))}:t(e),It=e=>e.and.reduce((t,r)=>({or:oe(t.or,ie(r)?r.or:[r],Ct)}),{or:[]}),ge=(e,t)=>he(e)?ie(t)?ge(It(e),t):Ct([e,t]):ie(e)?he(t)?ge(t,e):ie(t)?{or:oe(e.or,t.or,Ct)}:ge(e,{and:[t]}):he(t)||ie(t)?ge(t,e):{and:[e,t]};var se=class{},rt=class extends se{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:y}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:m,short:y},this.#r={input:r,output:o};for(let[u,x]of Object.entries(this.#r))(0,wt.default)(!We(x),new V(`Using transformations on the top level of endpoint ${u} schema is not allowed.`));this.#t={positive:Object.freeze(At(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[ye.positive]})),negative:Object.freeze(At(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[ye.negative]}))};for(let[u,x]of Object.entries(this.#t))(0,wt.default)(x.length,new te(`ResultHandler must have at least one ${u} response schema specified.`));this.#i=hr(r)?"upload":xr(r)?"raw":"json",this.#s={input:Object.freeze([N[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ge(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof tt.z.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof tt.z.ZodError?new H(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof tt.z.ZodError?new H(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Xe({logger:i,response:o,error:new te(fe(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=Tt(t),p={},d=null,c=null;if(i.cors){let y=this.#m(s);typeof i.cors=="function"&&(y=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let u in y)r.set(u,y[u])}let m=nr(t,i.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){c=fe(y)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};var Et=require("zod");var Tr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>ir(s,i),o)};var Sr=R(require("assert/strict"),1),ot=e=>((0,Sr.default)(!We(e.input),new V("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var v=require("zod");var nt=e=>e,xe=nt({getPositiveResponse:e=>{let t=F({schema:e}),r=v.z.object({status:v.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>v.z.object({status:v.z.literal("error"),error:v.z.object({message:v.z.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(ye.positive).json({status:"success",data:r});return}let a=ve(e);Rt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),it=nt({getPositiveResponse:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.z.ZodArray?e.shape.items:v.z.array(v.z.any());return t.reduce((o,i)=>K(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>v.z.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=ve(r);Rt({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ye.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var be=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:Et.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,y=>{if(y&&y instanceof Error)return c(o(y));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ot({input:Et.z.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],y=typeof a=="function"?a:()=>a,u="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],x="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new rt({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:u,tags:x,methods:m,getOperationId:y,description:i,shortDescription:s,inputSchema:Tr(d,t)})}},Rr=new be(xe),Or=new be(it);var Ar=require("util");var Pr=require("ramda"),D=require("ansis"),zt={debug:10,info:20,warn:30,error:40},Cr=e=>K(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),st=({level:e,color:t=new D.Ansis().isSupported(),depth:r=2})=>{let o={debug:D.blue,info:D.green,warn:(0,D.hex)("#FFA500"),error:D.red},i=e==="debug",s=e==="silent"?100:zt[e],a=(p,d,c)=>{if(zt[p]<s)return;let m=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&m.push((0,Ar.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(m.join(" "))};return(0,Pr.mapObjIndexed)(({},p)=>(d,c)=>a(p,d,c),zt)};var Se=require("ramda"),Te=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,Se.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,Se.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,Se.tail)(this.pairs).map(([r])=>r))}};var Ir=R(require("express"),1),Re=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Ir.default.static(...this.params))}};var at=R(require("express"),1),Lr=R(require("http"),1),Dr=R(require("https"),1);var ae=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>R(require(e))))[t]}catch{}throw new re(e)},wr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await ae(t,r)}catch{}throw new re(e.map(({moduleName:t})=>t))};var Zt=R(require("assert/strict"),1);var pe=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){Zt.default.doesNotMatch(a,/\//,new ee(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof se){let c=p.getMethods().slice();i&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof Re)r&&p.apply(d,r);else if(p instanceof Te){for(let[c,m]of p.pairs)(0,Zt.default)(m.getMethods().includes(c),new ee(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(m,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else pe({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Nt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>pe({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,m)=>s.execute({request:c,response:m,logger:m.locals[g]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});var He=R(require("http-errors"),1);var Er=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:(0,He.isHttpError)(r)?r:(0,He.default)(400,fe(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},zr=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,He.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){Xe({response:o,logger:s,error:new te(fe(a).message,i)})}},Ho=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Uo=e=>({log:e.debug.bind(e)}),Zr=async({rootLogger:e,config:t})=>{let r=await ae("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=d.locals[g]?.logger||e;try{await i?.({request:p,logger:m})}catch(y){return c(y)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Uo(m)})(p,d,c)}),o&&a.push(Ho(o)),a},Nr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Mr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var w=require("ansis"),vr=()=>{let e=(0,w.italic)("Proudly supports transgender community.".padStart(109)),t=(0,w.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,w.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,w.italic)("for Dime".padEnd(20)),i=(0,w.hex)("#F5A9B8"),s=(0,w.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(w.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(w.gray,12,13);return`
|
|
6
6
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
7
7
|
888 d88P 888 d88888 888 Y88b 888
|
|
8
8
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -16,9 +16,9 @@ Original error: ${e.originalError.message}.`:""))};var xr=require("ramda");var r
|
|
|
16
16
|
${o}888${t}
|
|
17
17
|
${r}
|
|
18
18
|
`.split(`
|
|
19
|
-
`).map((d,
|
|
20
|
-
`)};var Dr=e=>{e.startupLogo!==!1&&console.log(Mr());let t=e.errorHandler||ye,r=Pr(e.logger)?it(e.logger):e.logger;r.debug("Running","v19.0.0 (CJS)");let o=Nr({rootLogger:r,config:e}),i=Er({rootLogger:r,errorHandler:t}),s=wr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=Dr(e);return Zt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},jr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=Dr(e),a=(0,st.default)().disable("x-powered-by").use(s);if(e.server.compression){let u=await ne("compression");a.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||st.default.json()],raw:[e.server.rawParser||st.default.raw(),Zr],upload:e.server.upload?await zr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Zt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(u,m)=>u.listen(m,()=>{r.info("Listening",m)}),l={httpServer:d(vr.default.createServer(a),e.server.listen),httpsServer:e.https?d(Lr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...l,logger:r}};var no=R(require("assert/strict"),1),io=require("openapi3-ts/oas31");var K=R(require("assert/strict"),1),_=require("openapi3-ts/oas31"),c=require("ramda"),b=require("zod");var Te=require("zod");var at=e=>!isNaN(e.getTime());var ke=Symbol("DateIn"),Ur=()=>Te.z.union([Te.z.string().date(),Te.z.string().datetime(),Te.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Te.z.date().refine(at)).brand(ke);var Hr=require("zod");var je=Symbol("DateOut"),Fr=()=>Hr.z.date().refine(at).transform(e=>e.toISOString()).brand(je);var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:u=>se({schema:u,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),l=t&&t({schema:e,prev:d,...a});return l?{...d,...l}:d};var Kr=50,qr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Vo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vr=/:([A-Za-z0-9_]+)/g,$r=e=>e.match(Vr)?.map(t=>t.slice(1))||[],_r=e=>e.replace(Vr,t=>`{${t.slice(1)}}`),$o=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[g]?.defaultLabel||e._def.defaultValue()}),_o=({schema:{_def:{innerType:e}},next:t})=>t(e),Go=()=>({format:"any"}),Yo=e=>((0,K.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Qo=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof b.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Jo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Wo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Xo=e=>{let[t,r]=e.filter(i=>!(0,_.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,K.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:K.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},en=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Xo(o)}catch{}return{allOf:o}},tn=({schema:e,next:t})=>t(e.unwrap()),rn=({schema:e,next:t})=>t(e._def.innerType),on=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=Yr(r)),r},Gr=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Br=({schema:e})=>({type:Gr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),nn=({schema:{value:e}})=>({type:Gr(e),const:e}),sn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ne(p)?p instanceof b.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=pt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},an=()=>({type:"null"}),pn=e=>((0,K.default)(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:qr}}),dn=e=>((0,K.default)(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:qr}}),cn=e=>K.default.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),ln=()=>({type:"boolean"}),mn=()=>({type:"integer",format:"bigint"}),un=e=>e.every(t=>t instanceof b.z.ZodLiteral),fn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof b.z.ZodEnum||e instanceof b.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=pt({schema:b.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof b.z.ZodLiteral)return{type:"object",properties:pt({schema:b.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof b.z.ZodUnion&&un(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:pt({schema:b.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},yn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},gn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),hn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:l,isDatetime:u,_def:{checks:m}}})=>{let y=m.find(O=>O.kind==="regex"),T=m.find(O=>O.kind==="datetime"),S=y?y.regex:T?T.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,A={type:"string"},x={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:l};for(let O in x)if(x[O]){A.format=O;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),S&&(A.pattern=S.source),A},xn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},pt=({schema:{shape:e},next:t})=>(0,c.map)(t,e),bn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Vo?.[t]},Yr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Tn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=$e(e,bn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(b.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Sn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Rn=({schema:e,next:t})=>t(e.unwrap()),On=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},An=({next:e,schema:t})=>e(t.unwrap().shape.raw),Qr=e=>e.length?(0,c.fromPairs)((0,c.zip)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e))):void 0,Jr=(e,t,r=[])=>(0,c.pipe)(H,(0,c.map)((0,c.when)((0,c.both)(F,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),Qr)({schema:e,variant:t?"parsed":"original",validate:!0}),Pn=(e,t)=>(0,c.pipe)(H,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),Qr)({schema:e,variant:"original",validate:!0}),Se=(e,t)=>e instanceof b.z.ZodObject?e:e instanceof b.z.ZodBranded?Se(e.unwrap(),t):e instanceof b.z.ZodUnion||e instanceof b.z.ZodDiscriminatedUnion?e.options.map(r=>Se(r,t)).reduce((r,o)=>r.merge(o.partial()),b.z.object({})):e instanceof b.z.ZodEffects?((0,K.default)(e._def.effect.type==="refinement",t),Se(e._def.schema,t)):Se(e._def.left,t).merge(Se(e._def.right,t)),Wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=Se(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=$r(e),m=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=x=>y&&u.includes(x),A=x=>T&&Tt(x);return Object.keys(l).filter(x=>m||S(x)).map(x=>{let O=se({schema:l[x],isResponse:!1,rules:Mt,onEach:vt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Pe=p==="components"?a(M(d,x),O):O;return{name:x,in:S(x)?"path":A(x)?"header":"query",required:!l[x].isOptional(),description:O.description||d,schema:Pe,examples:Pn(r,x)}})},Mt={ZodString:hn,ZodNumber:xn,ZodBigInt:mn,ZodBoolean:ln,ZodNull:an,ZodArray:yn,ZodTuple:gn,ZodRecord:fn,ZodObject:sn,ZodLiteral:nn,ZodIntersection:en,ZodUnion:Jo,ZodAny:Go,ZodDefault:$o,ZodEnum:Br,ZodNativeEnum:Br,ZodEffects:Tn,ZodOptional:tn,ZodNullable:on,ZodDiscriminatedUnion:Wo,ZodBranded:Rn,ZodDate:cn,ZodCatch:_o,ZodPipeline:Sn,ZodLazy:On,ZodReadonly:rn,[$]:Qo,[Le]:Yo,[je]:dn,[ke]:pn,[te]:An},vt=({schema:e,isResponse:t,prev:r})=>{if((0,_.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof b.z.ZodLazy,s=r.type!==void 0,a=t&&Ne(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),l={};return o&&(l.description=o),p&&(l.type=Yr(r)),d.length&&(l.examples=d.slice()),l},Lt=({schema:e,...t})=>K.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Nt=(e,t)=>{if((0,_.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Nt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Nt(o,t))),r},Xr=e=>(0,_.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),eo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:l,statusCode:u,description:m=`${e.toUpperCase()} ${t} ${Rt(i)} response ${l?u:""}`.trim()})=>{let y=Xr(se({schema:r,isResponse:!0,rules:Mt,onEach:vt,onMissing:Lt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(M(m),y):y,examples:Jr(r,!0)};return{description:m,content:(0,c.fromPairs)((0,c.xprod)(o,[T]))}},Cn=()=>({type:"http",scheme:"basic"}),In=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},wn=({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},En=({name:e})=>({type:"apiKey",in:"header",name:e}),zn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Zn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Nn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),to=(e,t)=>{let r={basic:Cn,bearer:In,input:wn,header:En,cookie:zn,openid:Zn,oauth2:Nn};return Xe(e,o=>r[o.type](o,t))},dt=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?dt(Ct(e)):dt({or:[e]}),ro=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let l=$r(t),u=Xr(Nt(se({schema:r,isResponse:!1,rules:Mt,onEach:vt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),l)),m={schema:p==="components"?a(M(d),u):u,examples:Jr(r,!1,l)};return{description:d,content:(0,c.fromPairs)((0,c.xprod)(o,[m]))}},oo=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Dt=e=>e.length<=Kr?e:e.slice(0,Kr-1)+"\u2026";var ct=class extends io.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||M(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&no.default.fail(new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;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:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:l=Ve}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});ie({routing:t,onEndpoint:(m,y,T)=>{let S=T,A={path:y,method:S,endpoint:m,composition:d,serializer:l,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[x,O]=["short","long"].map(m.getDescription.bind(m)),Pe=x?Dt(x):p&&O?Dt(O):void 0,He=m.getTags(),Ce=r.inputSources?.[S]||xt[S],pe=this.ensureUniqOperationId(y,S,m.getOperationId(S)),Fe=Wr({...A,inputSources:Ce,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),Ke={};for(let k of["positive","negative"]){let Q=m.getResponses(k);for(let{mimeTypes:Ie,schema:P,statusCodes:C}of Q)for(let w of C)Ke[w]=eo({...A,variant:k,schema:P,mimeTypes:Ie,statusCode:w,hasMultipleStatusCodes:Q.length>1||C.length>1,description:a?.[`${k}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:w})})}let ht=Ce.includes("body")?ro({...A,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,Be=dt(Xe(to(m.getSecurity(),Ce),k=>{let Q=this.ensureUniqSecuritySchemaName(k),Ie=["oauth2","openIdConnect"].includes(k.type)?m.getScopes().slice():[];return this.addSecurityScheme(Q,k),{name:Q,scopes:Ie}}));this.addPath(_r(y),{[S]:{operationId:pe,summary:Pe,description:O,tags:He.length>0?He:void 0,parameters:Fe.length>0?Fe:void 0,requestBody:ht,security:Be.length>0?Be:void 0,responses:Ke}})}}),this.rootDoc.tags=r.tags?oo(r.tags):[]}};var kt=R(require("http"),1);var Mn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),vn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},Ln=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),so=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Ir([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Mn({fnMethod:a,requestProps:t}),d=vn({fnMethod:a,responseProps:r}),l=Ln({fnMethod:a,loggerProps:i}),u={cors:!1,logger:l,...o};return await e.execute({request:p,response:d,config:u,logger:l}),{requestMock:p,responseMock:d,loggerMock:l}};var z=R(require("typescript"),1);var D=R(require("typescript"),1),Re=require("ramda"),n=D.default.factory,G=[n.createModifier(D.default.SyntaxKind.ExportKeyword)],Dn=[n.createModifier(D.default.SyntaxKind.AsyncKeyword)],kn=[n.createModifier(D.default.SyntaxKind.PublicKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],ao=[n.createModifier(D.default.SyntaxKind.ProtectedKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],jt=n.createTemplateHead(""),Oe=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Ht=e=>n.createTemplateLiteralType(jt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Oe:Ut))),Ft=Ht(["M","P"]),lt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),mt=(e,t)=>(0,Re.chain)(([r,o])=>[lt(n.createIdentifier(r),o,t)],(0,Re.toPairs)(e)),Kt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),po=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),co=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Y=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.default.NodeFlags.Const),Bt=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ut=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,t),lo=(e,t,r)=>n.createPropertyDeclaration(kn,e,void 0,t,r),mo=(e,t,r)=>n.createClassDeclaration(G,e,void 0,void 0,[t,...r]),uo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),fo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.default.SyntaxKind.AnyKeyword)]),yo=(e,t,r)=>n.createInterfaceDeclaration(G,e,void 0,t,r),go=e=>(0,Re.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Re.toPairs)(e)),qt=(e,t,r)=>n.createArrowFunction(r?Dn:void 0,void 0,e.map(o=>lt(o)),void 0,void 0,t),Vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,mt({acc:void 0,key:void 0}),void 0,void 0,t),r]),ho=(...e)=>`"${e.join(" ")}"`;var xo=["get","post","put","delete","patch"];var h=R(require("typescript"),1),yt=require("zod");var B=R(require("typescript"),1),{factory:ft}=B.default,$t=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ae=(e,t,r)=>{let o=ft.createTypeAliasDeclaration(void 0,ft.createIdentifier(t),void 0,e);return r&&$t(o,r),o},_t=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},jn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,bo=e=>jn.test(e)?ft.createIdentifier(e):ft.createStringLiteral(e);var{factory:f}=h.default,Un={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Hn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),Fn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ne(a)?a instanceof yt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,bo(s),p&&o?f.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&$t(d,a.description),d});return f.createTypeLiteralNode(i)},Kn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Bn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),To=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),qn=e=>Un?.[e.kind],Vn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=$e(e,qn(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},$n=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),_n=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},Gn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Yn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Qn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Jn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Wn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),Xn=({next:e,schema:t})=>e(t.unwrap()),ei=({next:e,schema:t})=>e(t._def.innerType),ti=({next:e,schema:t})=>e(t._def.innerType),ri=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),oi=()=>f.createLiteralTypeNode(f.createNull()),ni=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},ii=({schema:e})=>{let t=e.unwrap(),r=f.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),i=f.createUnionTypeNode([r,o]);return t instanceof yt.z.ZodString?r:t instanceof yt.z.ZodUnion?i:o},si=({next:e,schema:t})=>e(t.unwrap().shape.raw),ai={ZodString:ae(h.default.SyntaxKind.StringKeyword),ZodNumber:ae(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(h.default.SyntaxKind.BooleanKeyword),ZodAny:ae(h.default.SyntaxKind.AnyKeyword),[ke]:ae(h.default.SyntaxKind.StringKeyword),[je]:ae(h.default.SyntaxKind.StringKeyword),ZodNull:oi,ZodArray:Kn,ZodTuple:Yn,ZodRecord:Qn,ZodObject:Fn,ZodLiteral:Hn,ZodIntersection:Jn,ZodUnion:To,ZodDefault:Wn,ZodEnum:Bn,ZodNativeEnum:$n,ZodEffects:Vn,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:To,ZodBranded:Xn,ZodCatch:ti,ZodPipeline:ri,ZodLazy:ni,ZodReadonly:ei,[$]:ii,[te]:si},Ue=({schema:e,...t})=>se({schema:e,rules:ai,onMissing:()=>f.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),...t});var gt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ae(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Ve,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(P,C,w)=>{let de={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},we=M(w,C,"input"),Ee=Ue({...de,schema:P.getSchema("input"),isResponse:!1}),Z=i?M(w,C,"positive.response"):void 0,Gt=P.getSchema("positive"),Yt=i?Ue({...de,isResponse:!0,schema:Gt}):void 0,ze=i?M(w,C,"negative.response"):void 0,Qt=P.getSchema("negative"),Jt=i?Ue({...de,isResponse:!0,schema:Qt}):void 0,Wt=M(w,C,"response"),Ro=Z&&ze?n.createUnionTypeNode([n.createTypeReferenceNode(Z),n.createTypeReferenceNode(ze)]):Ue({...de,isResponse:!0,schema:Gt.or(Qt)});this.program.push(Ae(Ee,we)),Yt&&Z&&this.program.push(Ae(Yt,Z)),Jt&&ze&&this.program.push(Ae(Jt,ze)),this.program.push(Ae(Ro,Wt)),w!=="options"&&(this.paths.push(C),this.registry.set({method:w,path:C},{input:we,positive:Z,negative:ze,response:Wt,isJson:P.getMimeTypes("positive").includes(N.json),tags:P.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Bt(this.ids.pathType,this.paths)),this.program.push(Bt(this.ids.methodType,xo)),this.program.push(ut(this.ids.methodPathType,Ht([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.default.SyntaxKind.ExtendsKeyword,[Kt(this.ids.methodPathType,z.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:P,path:C},{isJson:w,tags:de,...we}]of this.registry){let Ee=ho(P,C);for(let Z of this.interfaces)Z.kind in we&&Z.props.push(co(Ee,we[Z.kind]));r!=="types"&&(w&&p.push(n.createPropertyAssignment(Ee,n.createTrue())),d.push(n.createPropertyAssignment(Ee,n.createArrayLiteralExpression(de.map(Z=>n.createStringLiteral(Z))))))}for(let{id:P,props:C}of this.interfaces)this.program.push(yo(P,a,C));if(r==="types")return;let l=n.createVariableStatement(G,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),u=n.createVariableStatement(G,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),m=ut(this.ids.providerType,n.createFunctionTypeNode(go({M:this.ids.methodType,P:this.ids.pathType}),mt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ft)}),uo(this.ids.responseInterface,Ft))),y=ut(this.ids.implementationType,n.createFunctionTypeNode(void 0,mt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.default.SyntaxKind.StringKeyword),params:Kt(z.default.SyntaxKind.StringKeyword,z.default.SyntaxKind.AnyKeyword)}),fo())),T=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Oe)]),S=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[T,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),A=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[T]),z.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),x=mo(this.ids.clientClass,po([lt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),ao)]),[lo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,S,A]),!0))]);this.program.push(l,u,m,y,x);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Pe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),He=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),Ce=n.createVariableStatement(void 0,Y(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Oe)]),n.createObjectLiteralExpression([O,Pe,He])])))),pe=n.createVariableStatement(void 0,Y(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Fe=n.createVariableStatement(void 0,Y(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Oe)])))),[Ke,ht]=["json","text"].map(P=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,P),void 0,void 0))),Be=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(jt,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Oe)]),z.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Ke])),k=n.createVariableStatement(G,Y(this.ids.exampleImplementationConst,qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([pe,Fe,Ce,Be,ht]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Ie=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(k,Ie,Q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
|
|
21
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
19
|
+
`).map((d,c)=>a[c]?a[c](d):d).join(`
|
|
20
|
+
`)};var jr=e=>{e.startupLogo!==!1&&console.log(vr());let t=e.errorHandler||xe,r=Cr(e.logger)?st(e.logger):e.logger;r.debug("Running","v19.1.1 (CJS)");let o=Mr({rootLogger:r,config:e}),i=zr({rootLogger:r,errorHandler:t}),s=Er({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=jr(e);return Nt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Hr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=jr(e),a=(0,at.default)().disable("x-powered-by").use(s);if(e.server.compression){let m=await ae("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||at.default.json()],raw:[e.server.rawParser||at.default.raw(),Nr],upload:e.server.upload?await Zr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Nt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,y)=>m.listen(y,()=>{r.info("Listening",y)}),c={httpServer:d(Lr.default.createServer(a),e.server.listen),httpsServer:e.https?d(Dr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...c,logger:r}};var no=R(require("assert/strict"),1),io=require("openapi3-ts/oas31"),so=require("ramda");var B=R(require("assert/strict"),1),Y=require("openapi3-ts/oas31"),l=require("ramda"),S=require("zod");var Oe=require("zod");var pt=e=>!isNaN(e.getTime());var Ue=Symbol("DateIn"),Ur=()=>Oe.z.union([Oe.z.string().date(),Oe.z.string().datetime(),Oe.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Oe.z.date().refine(pt)).brand(Ue);var Fr=require("zod");var Fe=Symbol("DateOut"),Kr=()=>Fr.z.date().refine(pt).transform(e=>e.toISOString()).brand(Fe);var de=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:c=>de(c,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),d=t&&t(e,{prev:p,...i});return d?{...p,...d}:p};var Br=50,$r="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Fo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vr=/:([A-Za-z0-9_]+)/g,Ko=e=>e.match(Vr)?.map(t=>t.slice(1))||[],Gr=e=>e.replace(Vr,t=>`{${t.slice(1)}}`),Bo=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),qo=({_def:{innerType:e}},{next:t})=>t(e),$o=()=>({format:"any"}),Vo=({},e)=>((0,B.default)(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Go=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},_o=({options:e},{next:t})=>({oneOf:e.map(t)}),Yo=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Qo=e=>{let[t,r]=e.filter(i=>!(0,Y.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,B.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,l.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,l.concat)(i,s):i===s?s:B.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,l.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=oe(t.examples||[],r.examples||[],([i,s])=>(0,l.mergeDeepRight)(i,s))),o},Jo=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Qo(o)}catch{}return{allOf:o}},Wo=(e,{next:t})=>t(e.unwrap()),Xo=(e,{next:t})=>t(e.unwrap()),en=(e,{next:t})=>{let r=t(e.unwrap());return(0,Y.isReferenceObject)(r)||(r.type=Yr(r)),r},_r=e=>{let t=(0,l.toLower)((0,l.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},qr=e=>({type:_r(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),tn=({value:e})=>({type:_r(e),const:e}),rn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Le(p)?p instanceof S.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=dt(e,r)),s.length&&(a.required=s),a},on=()=>({type:"null"}),nn=({},e)=>((0,B.default)(!e.isResponse,new P({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:$r}}),sn=({},e)=>((0,B.default)(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:$r}}),an=({},e)=>B.default.fail(new P({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),pn=()=>({type:"boolean"}),dn=()=>({type:"integer",format:"bigint"}),cn=e=>e.every(t=>t instanceof S.z.ZodLiteral),ln=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=dt(S.z.object((0,l.fromPairs)((0,l.xprod)(o,[t]))),r),i.required=o),i}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:dt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&cn(e.options)){let o=(0,l.map)(s=>`${s.value}`,e.options),i=(0,l.fromPairs)((0,l.xprod)(o,[t]));return{type:"object",properties:dt(S.z.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},mn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},un=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),fn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),z=u?u.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,T={type:"string"},L={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let C in L)if(L[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),z&&(T.pattern=z.source),T},yn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(({kind:y})=>y==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(({kind:y})=>y==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,c?m.maximum=d:m.exclusiveMaximum=d,m},dt=({shape:e},t)=>(0,l.map)(t,e),gn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Fo?.[t]},Yr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},hn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,Y.isReferenceObject)(o)){let s=Ge(e,gn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.z.any())}if(!t&&i.type==="preprocess"&&!(0,Y.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},xn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bn=(e,{next:t})=>t(e.unwrap()),Tn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},Sn=(e,{next:t})=>t(e.unwrap().shape.raw),Qr=e=>e.length?(0,l.fromPairs)((0,l.zip)((0,l.range)(1,e.length+1).map(t=>`example${t}`),(0,l.map)((0,l.objOf)("value"),e))):void 0,Jr=(e,t,r=[])=>(0,l.pipe)(F,(0,l.map)((0,l.when)((0,l.both)(K,(0,l.complement)(Array.isArray)),(0,l.omit)(r))),Qr)({schema:e,variant:t?"parsed":"original",validate:!0}),Rn=(e,t)=>(0,l.pipe)(F,(0,l.filter)((0,l.has)(t)),(0,l.pluck)(t),Qr)({schema:e,variant:"original",validate:!0}),Ae=(e,t)=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?Ae(e.unwrap(),t):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(r=>Ae(r,t)).reduce((r,o)=>r.merge(o.partial()),S.z.object({})):e instanceof S.z.ZodEffects?((0,B.default)(e._def.effect.type==="refinement",t),Ae(e._def.schema,t)):Ae(e._def.left,t).merge(Ae(e._def.right,t)),Wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=Ae(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),y=Ko(e),u=o.includes("query"),x=o.includes("params"),z=o.includes("headers"),T=b=>x&&y.includes(b),L=b=>z&&St(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":L(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:we})=>{let $=de(m[b],{rules:{...d,...vt},onEach:Lt,onMissing:Dt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),W=p==="components"?a(M(c,b),$):$;return{name:b,in:we,required:!m[b].isOptional(),description:$.description||c,schema:W,examples:Rn(r,b)}})},vt={ZodString:fn,ZodNumber:yn,ZodBigInt:dn,ZodBoolean:pn,ZodNull:on,ZodArray:mn,ZodTuple:un,ZodRecord:ln,ZodObject:rn,ZodLiteral:tn,ZodIntersection:Jo,ZodUnion:_o,ZodAny:$o,ZodDefault:Bo,ZodEnum:qr,ZodNativeEnum:qr,ZodEffects:hn,ZodOptional:Wo,ZodNullable:en,ZodDiscriminatedUnion:Yo,ZodBranded:bn,ZodDate:an,ZodCatch:qo,ZodPipeline:xn,ZodLazy:Tn,ZodReadonly:Xo,[_]:Go,[ke]:Vo,[Fe]:sn,[Ue]:nn,[ne]:Sn},Lt=(e,{isResponse:t,prev:r})=>{if((0,Y.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof S.z.ZodLazy,s=r.type!==void 0,a=t&&Le(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Yr(r)),d.length&&(c.examples=d.slice()),c},Dt=(e,t)=>B.default.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Mt=(e,t)=>{if((0,Y.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,l.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,l.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Mt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Mt(o,t))),r},Xr=e=>(0,Y.isReferenceObject)(e)?e:(0,l.omit)(["examples"],e),eo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${Ot(i)} response ${c?m:""}`.trim()})=>{let x=Xr(de(r,{rules:{...y,...vt},onEach:Lt,onMissing:Dt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),z={schema:d==="components"?p(M(u),x):x,examples:Jr(r,!0)};return{description:u,content:(0,l.fromPairs)((0,l.xprod)(o,[z]))}},On=()=>({type:"http",scheme:"basic"}),An=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Pn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Cn=({name:e})=>({type:"apiKey",in:"header",name:e}),In=({name:e})=>({type:"apiKey",in:"cookie",name:e}),wn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),En=({flows:e={}})=>({type:"oauth2",flows:(0,l.map)(t=>({...t,scopes:t.scopes||{}}),(0,l.reject)(l.isNil,e))}),to=(e,t)=>{let r={basic:On,bearer:An,input:Pn,header:Cn,cookie:In,openid:wn,oauth2:En};return et(e,o=>r[o.type](o,t))},ct=e=>"or"in e?e.or.map(t=>"and"in t?(0,l.mergeAll)((0,l.map)(({name:r,scopes:o})=>(0,l.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?ct(It(e)):ct({or:[e]}),ro=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=Xr(Mt(de(r,{rules:{...d,...vt},onEach:Lt,onMissing:Dt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),c)),u={schema:p==="components"?a(M(m),y):y,examples:Jr(r,!1,c)};return{description:m,content:(0,l.fromPairs)((0,l.xprod)(o,[u]))}},oo=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),jt=e=>e.length<=Br?e:e.slice(0,Br-1)+"\u2026";var lt=class extends io.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||M(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&no.default.fail(new P({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;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:i,serverUrl:s,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:m=Ve}){super(),this.addInfo({title:o,version:i});for(let u of typeof s=="string"?[s]:s)this.addServer({url:u});pe({routing:t,onEndpoint:(u,x,z)=>{let T=z,L={path:x,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),we=C?jt(C):d&&b?jt(b):void 0,$=u.getTags(),W=r.inputSources?.[T]||bt[T],le=this.ensureUniqOperationId(x,T,u.getOperationId(T)),Ee=Wr({...L,inputSources:W,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:le})}),Be={};for(let k of["positive","negative"]){let X=u.getResponses(k);for(let{mimeTypes:ze,schema:O,statusCodes:A}of X)for(let I of A)Be[I]=eo({...L,variant:k,schema:O,mimeTypes:ze,statusCode:I,hasMultipleStatusCodes:X.length>1||A.length>1,description:a?.[`${k}Response`]?.call(null,{method:T,path:x,operationId:le,statusCode:I})})}let xt=W.includes("body")?ro({...L,paramNames:(0,so.pluck)("name",Ee),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:le})}):void 0,qe=ct(et(to(u.getSecurity(),W),k=>{let X=this.ensureUniqSecuritySchemaName(k),ze=["oauth2","openIdConnect"].includes(k.type)?u.getScopes().slice():[];return this.addSecurityScheme(X,k),{name:X,scopes:ze}}));this.addPath(Gr(x),{[T]:{operationId:le,summary:we,description:b,tags:$.length>0?$:void 0,parameters:Ee.length>0?Ee:void 0,requestBody:xt,security:qe.length>0?qe:void 0,responses:Be}})}}),this.rootDoc.tags=r.tags?oo(r.tags):[]}};var kt=R(require("http"),1);var zn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),Zn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},Nn=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ao=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await wr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=zn({fnMethod:a,requestProps:t}),d=Zn({fnMethod:a,responseProps:r}),c=Nn({fnMethod:a,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:m,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};var E=R(require("typescript"),1);var j=R(require("typescript"),1),Pe=require("ramda"),n=j.default.factory,Q=[n.createModifier(j.default.SyntaxKind.ExportKeyword)],Mn=[n.createModifier(j.default.SyntaxKind.AsyncKeyword)],vn=[n.createModifier(j.default.SyntaxKind.PublicKeyword),n.createModifier(j.default.SyntaxKind.ReadonlyKeyword)],po=[n.createModifier(j.default.SyntaxKind.ProtectedKeyword),n.createModifier(j.default.SyntaxKind.ReadonlyKeyword)],Ht=n.createTemplateHead(""),Ce=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Ft=e=>n.createTemplateLiteralType(Ht,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Ce:Ut))),Kt=Ft(["M","P"]),mt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ut=(e,t)=>(0,Pe.chain)(([r,o])=>[mt(n.createIdentifier(r),o,t)],(0,Pe.toPairs)(e)),Bt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),co=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),lo=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),J=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],j.default.NodeFlags.Const),qt=(e,t)=>n.createTypeAliasDeclaration(Q,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ft=(e,t)=>n.createTypeAliasDeclaration(Q,e,void 0,t),mo=(e,t,r)=>n.createPropertyDeclaration(vn,e,void 0,t,r),uo=(e,t,r)=>n.createClassDeclaration(Q,e,void 0,void 0,[t,...r]),fo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),yo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(j.default.SyntaxKind.AnyKeyword)]),go=(e,t,r)=>n.createInterfaceDeclaration(Q,e,void 0,t,r),ho=e=>(0,Pe.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Pe.toPairs)(e)),$t=(e,t,r)=>n.createArrowFunction(r?Mn:void 0,void 0,e.map(o=>mt(o)),void 0,void 0,t),Vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,ut({acc:void 0,key:void 0}),void 0,void 0,t),r]),xo=(...e)=>`"${e.join(" ")}"`;var bo=["get","post","put","delete","patch"];var h=R(require("typescript"),1),gt=require("zod");var q=R(require("typescript"),1),{factory:yt}=q.default,Gt=(e,t)=>{q.default.addSyntheticLeadingComment(e,q.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ie=(e,t,r)=>{let o=yt.createTypeAliasDeclaration(void 0,yt.createIdentifier(t),void 0,e);return r&&Gt(o,r),o},_t=(e,t)=>{let r=q.default.createSourceFile("print.ts","",q.default.ScriptTarget.Latest,!1,q.default.ScriptKind.TS);return q.default.createPrinter(t).printNode(q.default.EmitHint.Unspecified,e,r)},Ln=/^[A-Za-z_$][A-Za-z0-9_$]*$/,To=e=>Ln.test(e)?yt.createIdentifier(e):yt.createStringLiteral(e);var{factory:f}=h.default,Dn={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},jn=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),kn=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Le(a)?a instanceof gt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,To(s),p&&o?f.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Gt(d,a.description),d});return f.createTypeLiteralNode(i)},Hn=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),Un=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),So=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),Fn=e=>Dn?.[e.kind],Kn=(e,{next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Ge(e,Fn(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},Bn=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),qn=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},$n=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),Vn=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),Gn=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),_n=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),Yn=({_def:e},{next:t})=>t(e.innerType),ce=e=>()=>f.createKeywordTypeNode(e),Qn=(e,{next:t})=>t(e.unwrap()),Jn=(e,{next:t})=>t(e.unwrap()),Wn=({_def:e},{next:t})=>t(e.innerType),Xn=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ei=()=>f.createLiteralTypeNode(f.createNull()),ti=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,f.createLiteralTypeNode(f.createNull())),r(s,o(e)))},ri=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),i=f.createUnionTypeNode([r,o]);return t instanceof gt.z.ZodString?r:t instanceof gt.z.ZodUnion?i:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:ce(h.default.SyntaxKind.StringKeyword),ZodNumber:ce(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ce(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ce(h.default.SyntaxKind.BooleanKeyword),ZodAny:ce(h.default.SyntaxKind.AnyKeyword),[Ue]:ce(h.default.SyntaxKind.StringKeyword),[Fe]:ce(h.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Hn,ZodTuple:Vn,ZodRecord:Gn,ZodObject:kn,ZodLiteral:jn,ZodIntersection:_n,ZodUnion:So,ZodDefault:Yn,ZodEnum:Un,ZodNativeEnum:Bn,ZodEffects:Kn,ZodOptional:qn,ZodNullable:$n,ZodDiscriminatedUnion:So,ZodBranded:Qn,ZodCatch:Wn,ZodPipeline:Xn,ZodLazy:ti,ZodReadonly:Jn,[_]:ri,[ne]:oi},Ke=(e,{brandHandling:t,ctx:r})=>de(e,{rules:{...t,...ni},onMissing:()=>f.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),ctx:r});var ht=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ie(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=Ve,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){pe({routing:t,onEndpoint:(O,A,I)=>{let me={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Ze=M(I,A,"input"),Ne=Ke(O.getSchema("input"),{brandHandling:r,ctx:{...me,isResponse:!1}}),Z=s?M(I,A,"positive.response"):void 0,Yt=O.getSchema("positive"),Qt=s?Ke(Yt,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,Me=s?M(I,A,"negative.response"):void 0,Jt=O.getSchema("negative"),Wt=s?Ke(Jt,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,Xt=M(I,A,"response"),Oo=Z&&Me?n.createUnionTypeNode([n.createTypeReferenceNode(Z),n.createTypeReferenceNode(Me)]):Ke(Yt.or(Jt),{brandHandling:r,ctx:{...me,isResponse:!0}});this.program.push(Ie(Ne,Ze)),Qt&&Z&&this.program.push(Ie(Qt,Z)),Wt&&Me&&this.program.push(Ie(Wt,Me)),this.program.push(Ie(Oo,Xt)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Ze,positive:Z,negative:Me,response:Xt,isJson:O.getMimeTypes("positive").includes(N.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(qt(this.ids.pathType,this.paths)),this.program.push(qt(this.ids.methodType,bo)),this.program.push(ft(this.ids.methodPathType,Ft([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(E.default.SyntaxKind.ExtendsKeyword,[Bt(this.ids.methodPathType,E.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:O,path:A},{isJson:I,tags:me,...Ze}]of this.registry){let Ne=xo(O,A);for(let Z of this.interfaces)Z.kind in Ze&&Z.props.push(lo(Ne,Ze[Z.kind]));o!=="types"&&(I&&d.push(n.createPropertyAssignment(Ne,n.createTrue())),c.push(n.createPropertyAssignment(Ne,n.createArrayLiteralExpression(me.map(Z=>n.createStringLiteral(Z))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(go(O,p,A));if(o==="types")return;let m=n.createVariableStatement(Q,J(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(d))),y=n.createVariableStatement(Q,J(this.ids.endpointTagsConst,n.createObjectLiteralExpression(c))),u=ft(this.ids.providerType,n.createFunctionTypeNode(ho({M:this.ids.methodType,P:this.ids.pathType}),ut({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Kt)}),fo(this.ids.responseInterface,Kt))),x=ft(this.ids.implementationType,n.createFunctionTypeNode(void 0,ut({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(E.default.SyntaxKind.StringKeyword),params:Bt(E.default.SyntaxKind.StringKeyword,E.default.SyntaxKind.AnyKeyword)}),yo())),z=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Ce)]),T=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[z,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),L=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[z]),E.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),C=uo(this.ids.clientClass,co([mt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),po)]),[mo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,L]),!0))]);this.program.push(m,y,u,x,C);let b=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),we=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),$=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),W=n.createVariableStatement(void 0,J(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Ce)]),n.createObjectLiteralExpression([b,we,$])])))),le=n.createVariableStatement(void 0,J(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ee=n.createVariableStatement(void 0,J(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Ce)])))),[Be,xt]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),qe=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ht,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Ce)]),E.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Be])),k=n.createVariableStatement(Q,J(this.ids.exampleImplementationConst,$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([le,Ee,W,qe,xt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),X=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),ze=n.createVariableStatement(void 0,J(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(k,ze,X)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
|
|
21
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&E.default.addSyntheticLeadingComment(E.default.addSyntheticLeadingComment(n.createEmptyStatement(),E.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
22
22
|
${r}`);return this.program.concat(o||[]).map((i,s)=>_t(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
23
23
|
|
|
24
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
24
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await ae("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Ro={dateIn:Ur,dateOut:Kr,file:Qe,upload:ur,raw:lr};0&&(module.exports={AbstractEndpoint,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,MissingPeerError,OutputValidationError,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createLogger,createMiddleware,createResultHandler,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint});
|
package/dist/index.d.cts
CHANGED
|
@@ -10,7 +10,7 @@ import { ListenOptions } from 'node:net';
|
|
|
10
10
|
import * as qs from 'qs';
|
|
11
11
|
import * as express_serve_static_core from 'express-serve-static-core';
|
|
12
12
|
import http from 'node:http';
|
|
13
|
-
import {
|
|
13
|
+
import { ReferenceObject, SchemaObject, OpenApiBuilder, SecuritySchemeType, SecuritySchemeObject } from 'openapi3-ts/oas31';
|
|
14
14
|
import ts from 'typescript';
|
|
15
15
|
|
|
16
16
|
declare const metaSymbol: unique symbol;
|
|
@@ -590,41 +590,38 @@ declare const createServer: (config: ServerConfig, routing: Routing) => Promise<
|
|
|
590
590
|
app: express_serve_static_core.Express;
|
|
591
591
|
}>;
|
|
592
592
|
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
statusCode?: number;
|
|
597
|
-
}) => string;
|
|
598
|
-
interface DocumentationParams {
|
|
599
|
-
title: string;
|
|
600
|
-
version: string;
|
|
601
|
-
serverUrl: string | [string, ...string[]];
|
|
602
|
-
routing: Routing;
|
|
603
|
-
config: CommonConfig;
|
|
604
|
-
/**
|
|
605
|
-
* @desc Descriptions of various components based on their properties (method, path, operationId).
|
|
606
|
-
* @desc When composition set to "components", component name is generated from this description
|
|
607
|
-
* @default () => `${method} ${path} ${component}`
|
|
608
|
-
* */
|
|
609
|
-
descriptions?: Partial<Record<Component, Descriptor>>;
|
|
610
|
-
/** @default true */
|
|
611
|
-
hasSummaryFromDescription?: boolean;
|
|
612
|
-
/** @default inline */
|
|
613
|
-
composition?: "inline" | "components";
|
|
614
|
-
/**
|
|
615
|
-
* @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
|
|
616
|
-
* @default JSON.stringify() + SHA1 hash as a hex digest
|
|
617
|
-
* */
|
|
618
|
-
serializer?: (schema: z.ZodTypeAny) => string;
|
|
593
|
+
/** @desc An error related to the wrong Routing declaration */
|
|
594
|
+
declare class RoutingError extends Error {
|
|
595
|
+
name: string;
|
|
619
596
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
597
|
+
/**
|
|
598
|
+
* @desc An error related to the generating of the documentation
|
|
599
|
+
* */
|
|
600
|
+
declare class DocumentationError extends Error {
|
|
601
|
+
name: string;
|
|
602
|
+
constructor({ message, method, path, isResponse, }: {
|
|
603
|
+
message: string;
|
|
604
|
+
} & Pick<OpenAPIContext, "path" | "method" | "isResponse">);
|
|
605
|
+
}
|
|
606
|
+
/** @desc An error related to the input and output schemas declaration */
|
|
607
|
+
declare class IOSchemaError extends Error {
|
|
608
|
+
name: string;
|
|
609
|
+
}
|
|
610
|
+
/** @desc An error of validating the Endpoint handler's returns against the Endpoint output schema */
|
|
611
|
+
declare class OutputValidationError extends IOSchemaError {
|
|
612
|
+
name: string;
|
|
613
|
+
readonly originalError: ZodError;
|
|
614
|
+
constructor(originalError: ZodError);
|
|
615
|
+
}
|
|
616
|
+
/** @desc An error of validating the input sources against the Middleware or Endpoint input schema */
|
|
617
|
+
declare class InputValidationError extends IOSchemaError {
|
|
618
|
+
name: string;
|
|
619
|
+
readonly originalError: ZodError;
|
|
620
|
+
constructor(originalError: ZodError);
|
|
621
|
+
}
|
|
622
|
+
declare class MissingPeerError extends Error {
|
|
623
|
+
name: string;
|
|
624
|
+
constructor(module: string | string[]);
|
|
628
625
|
}
|
|
629
626
|
|
|
630
627
|
declare const variants: {
|
|
@@ -656,6 +653,19 @@ declare const ez: {
|
|
|
656
653
|
}, S>>[k_1]; } : never>, symbol>;
|
|
657
654
|
};
|
|
658
655
|
|
|
656
|
+
interface VariantDependingProps<U> {
|
|
657
|
+
regular: {
|
|
658
|
+
next: (schema: z.ZodTypeAny) => U;
|
|
659
|
+
};
|
|
660
|
+
each: {
|
|
661
|
+
prev: U;
|
|
662
|
+
};
|
|
663
|
+
last: {};
|
|
664
|
+
}
|
|
665
|
+
type HandlingVariant = keyof VariantDependingProps<unknown>;
|
|
666
|
+
type SchemaHandler<U, Context extends FlatObject = {}, Variant extends HandlingVariant = "regular"> = (schema: any, ctx: Context & VariantDependingProps<U>[Variant]) => U;
|
|
667
|
+
type HandlingRules<U, Context extends FlatObject = {}, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
|
|
668
|
+
|
|
659
669
|
interface OpenAPIContext extends FlatObject {
|
|
660
670
|
isResponse: boolean;
|
|
661
671
|
serializer: (schema: z.ZodTypeAny) => string;
|
|
@@ -664,39 +674,50 @@ interface OpenAPIContext extends FlatObject {
|
|
|
664
674
|
path: string;
|
|
665
675
|
method: Method;
|
|
666
676
|
}
|
|
677
|
+
type Depicter = SchemaHandler<SchemaObject | ReferenceObject, OpenAPIContext>;
|
|
667
678
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
/** @
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
679
|
+
type Component = "positiveResponse" | "negativeResponse" | "requestParameter" | "requestBody";
|
|
680
|
+
/** @desc user defined function that creates a component description from its properties */
|
|
681
|
+
type Descriptor = (props: Record<"method" | "path" | "operationId", string> & {
|
|
682
|
+
statusCode?: number;
|
|
683
|
+
}) => string;
|
|
684
|
+
interface DocumentationParams {
|
|
685
|
+
title: string;
|
|
686
|
+
version: string;
|
|
687
|
+
serverUrl: string | [string, ...string[]];
|
|
688
|
+
routing: Routing;
|
|
689
|
+
config: CommonConfig;
|
|
690
|
+
/**
|
|
691
|
+
* @desc Descriptions of various components based on their properties (method, path, operationId).
|
|
692
|
+
* @desc When composition set to "components", component name is generated from this description
|
|
693
|
+
* @default () => `${method} ${path} ${component}`
|
|
694
|
+
* */
|
|
695
|
+
descriptions?: Partial<Record<Component, Descriptor>>;
|
|
696
|
+
/** @default true */
|
|
697
|
+
hasSummaryFromDescription?: boolean;
|
|
698
|
+
/** @default inline */
|
|
699
|
+
composition?: "inline" | "components";
|
|
700
|
+
/**
|
|
701
|
+
* @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
|
|
702
|
+
* @default JSON.stringify() + SHA1 hash as a hex digest
|
|
703
|
+
* */
|
|
704
|
+
serializer?: (schema: z.ZodTypeAny) => string;
|
|
705
|
+
/**
|
|
706
|
+
* @desc Handling rules for your own branded schemas.
|
|
707
|
+
* @desc Keys: brands (recommended to use unique symbols).
|
|
708
|
+
* @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
|
|
709
|
+
* @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => ({ type: "object" })
|
|
710
|
+
*/
|
|
711
|
+
brandHandling?: HandlingRules<SchemaObject | ReferenceObject, OpenAPIContext>;
|
|
696
712
|
}
|
|
697
|
-
declare class
|
|
698
|
-
|
|
699
|
-
|
|
713
|
+
declare class Documentation extends OpenApiBuilder {
|
|
714
|
+
protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
|
|
715
|
+
protected lastOperationIdSuffixes: Map<string, number>;
|
|
716
|
+
protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
|
|
717
|
+
protected getRef(name: string): ReferenceObject | undefined;
|
|
718
|
+
protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
|
|
719
|
+
protected ensureUniqSecuritySchemaName(subject: SecuritySchemeObject): string;
|
|
720
|
+
constructor({ routing, config, title, version, serverUrl, descriptions, brandHandling, hasSummaryFromDescription, composition, serializer, }: DocumentationParams);
|
|
700
721
|
}
|
|
701
722
|
|
|
702
723
|
type LocalResponse = Response<unknown, {
|
|
@@ -758,6 +779,18 @@ declare const testEndpoint: <LOG extends Record<string, any>, REQ extends Record
|
|
|
758
779
|
loggerMock: Record<"error" | "info" | "debug" | "warn", MockOverrides> & LOG;
|
|
759
780
|
}>;
|
|
760
781
|
|
|
782
|
+
interface ZTSContext extends FlatObject {
|
|
783
|
+
isResponse: boolean;
|
|
784
|
+
getAlias: (name: string) => ts.TypeReferenceNode | undefined;
|
|
785
|
+
makeAlias: (name: string, type: ts.TypeNode) => ts.TypeReferenceNode;
|
|
786
|
+
serializer: (schema: z.ZodTypeAny) => string;
|
|
787
|
+
optionalPropStyle: {
|
|
788
|
+
withQuestionMark?: boolean;
|
|
789
|
+
withUndefined?: boolean;
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
|
|
793
|
+
|
|
761
794
|
type IOKind = "input" | "response" | "positive" | "negative";
|
|
762
795
|
interface IntegrationParams {
|
|
763
796
|
routing: Routing;
|
|
@@ -794,6 +827,13 @@ interface IntegrationParams {
|
|
|
794
827
|
*/
|
|
795
828
|
withUndefined?: boolean;
|
|
796
829
|
};
|
|
830
|
+
/**
|
|
831
|
+
* @desc Handling rules for your own branded schemas.
|
|
832
|
+
* @desc Keys: brands (recommended to use unique symbols).
|
|
833
|
+
* @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
|
|
834
|
+
* @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => createKeywordTypeNode(SyntaxKind.AnyKeyword)
|
|
835
|
+
*/
|
|
836
|
+
brandHandling?: HandlingRules<ts.TypeNode, ZTSContext>;
|
|
797
837
|
}
|
|
798
838
|
interface FormattedPrintingOptions {
|
|
799
839
|
/** @desc Typescript printer options */
|
|
@@ -852,10 +892,10 @@ declare class Integration {
|
|
|
852
892
|
}>;
|
|
853
893
|
protected getAlias(name: string): ts.TypeReferenceNode | undefined;
|
|
854
894
|
protected makeAlias(name: string, type: ts.TypeNode): ts.TypeReferenceNode;
|
|
855
|
-
constructor({ routing, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
|
|
895
|
+
constructor({ routing, brandHandling, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
|
|
856
896
|
protected printUsage(printerOptions?: ts.PrinterOptions): string | undefined;
|
|
857
897
|
print(printerOptions?: ts.PrinterOptions): string;
|
|
858
898
|
printFormatted({ printerOptions, format: userDefined, }?: FormattedPrintingOptions): Promise<string>;
|
|
859
899
|
}
|
|
860
900
|
|
|
861
|
-
export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
|
|
901
|
+
export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { ListenOptions } from 'node:net';
|
|
|
10
10
|
import * as qs from 'qs';
|
|
11
11
|
import * as express_serve_static_core from 'express-serve-static-core';
|
|
12
12
|
import http from 'node:http';
|
|
13
|
-
import {
|
|
13
|
+
import { ReferenceObject, SchemaObject, OpenApiBuilder, SecuritySchemeType, SecuritySchemeObject } from 'openapi3-ts/oas31';
|
|
14
14
|
import ts from 'typescript';
|
|
15
15
|
|
|
16
16
|
declare const metaSymbol: unique symbol;
|
|
@@ -590,41 +590,38 @@ declare const createServer: (config: ServerConfig, routing: Routing) => Promise<
|
|
|
590
590
|
app: express_serve_static_core.Express;
|
|
591
591
|
}>;
|
|
592
592
|
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
statusCode?: number;
|
|
597
|
-
}) => string;
|
|
598
|
-
interface DocumentationParams {
|
|
599
|
-
title: string;
|
|
600
|
-
version: string;
|
|
601
|
-
serverUrl: string | [string, ...string[]];
|
|
602
|
-
routing: Routing;
|
|
603
|
-
config: CommonConfig;
|
|
604
|
-
/**
|
|
605
|
-
* @desc Descriptions of various components based on their properties (method, path, operationId).
|
|
606
|
-
* @desc When composition set to "components", component name is generated from this description
|
|
607
|
-
* @default () => `${method} ${path} ${component}`
|
|
608
|
-
* */
|
|
609
|
-
descriptions?: Partial<Record<Component, Descriptor>>;
|
|
610
|
-
/** @default true */
|
|
611
|
-
hasSummaryFromDescription?: boolean;
|
|
612
|
-
/** @default inline */
|
|
613
|
-
composition?: "inline" | "components";
|
|
614
|
-
/**
|
|
615
|
-
* @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
|
|
616
|
-
* @default JSON.stringify() + SHA1 hash as a hex digest
|
|
617
|
-
* */
|
|
618
|
-
serializer?: (schema: z.ZodTypeAny) => string;
|
|
593
|
+
/** @desc An error related to the wrong Routing declaration */
|
|
594
|
+
declare class RoutingError extends Error {
|
|
595
|
+
name: string;
|
|
619
596
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
597
|
+
/**
|
|
598
|
+
* @desc An error related to the generating of the documentation
|
|
599
|
+
* */
|
|
600
|
+
declare class DocumentationError extends Error {
|
|
601
|
+
name: string;
|
|
602
|
+
constructor({ message, method, path, isResponse, }: {
|
|
603
|
+
message: string;
|
|
604
|
+
} & Pick<OpenAPIContext, "path" | "method" | "isResponse">);
|
|
605
|
+
}
|
|
606
|
+
/** @desc An error related to the input and output schemas declaration */
|
|
607
|
+
declare class IOSchemaError extends Error {
|
|
608
|
+
name: string;
|
|
609
|
+
}
|
|
610
|
+
/** @desc An error of validating the Endpoint handler's returns against the Endpoint output schema */
|
|
611
|
+
declare class OutputValidationError extends IOSchemaError {
|
|
612
|
+
name: string;
|
|
613
|
+
readonly originalError: ZodError;
|
|
614
|
+
constructor(originalError: ZodError);
|
|
615
|
+
}
|
|
616
|
+
/** @desc An error of validating the input sources against the Middleware or Endpoint input schema */
|
|
617
|
+
declare class InputValidationError extends IOSchemaError {
|
|
618
|
+
name: string;
|
|
619
|
+
readonly originalError: ZodError;
|
|
620
|
+
constructor(originalError: ZodError);
|
|
621
|
+
}
|
|
622
|
+
declare class MissingPeerError extends Error {
|
|
623
|
+
name: string;
|
|
624
|
+
constructor(module: string | string[]);
|
|
628
625
|
}
|
|
629
626
|
|
|
630
627
|
declare const variants: {
|
|
@@ -656,6 +653,19 @@ declare const ez: {
|
|
|
656
653
|
}, S>>[k_1]; } : never>, symbol>;
|
|
657
654
|
};
|
|
658
655
|
|
|
656
|
+
interface VariantDependingProps<U> {
|
|
657
|
+
regular: {
|
|
658
|
+
next: (schema: z.ZodTypeAny) => U;
|
|
659
|
+
};
|
|
660
|
+
each: {
|
|
661
|
+
prev: U;
|
|
662
|
+
};
|
|
663
|
+
last: {};
|
|
664
|
+
}
|
|
665
|
+
type HandlingVariant = keyof VariantDependingProps<unknown>;
|
|
666
|
+
type SchemaHandler<U, Context extends FlatObject = {}, Variant extends HandlingVariant = "regular"> = (schema: any, ctx: Context & VariantDependingProps<U>[Variant]) => U;
|
|
667
|
+
type HandlingRules<U, Context extends FlatObject = {}, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
|
|
668
|
+
|
|
659
669
|
interface OpenAPIContext extends FlatObject {
|
|
660
670
|
isResponse: boolean;
|
|
661
671
|
serializer: (schema: z.ZodTypeAny) => string;
|
|
@@ -664,39 +674,50 @@ interface OpenAPIContext extends FlatObject {
|
|
|
664
674
|
path: string;
|
|
665
675
|
method: Method;
|
|
666
676
|
}
|
|
677
|
+
type Depicter = SchemaHandler<SchemaObject | ReferenceObject, OpenAPIContext>;
|
|
667
678
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
/** @
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
679
|
+
type Component = "positiveResponse" | "negativeResponse" | "requestParameter" | "requestBody";
|
|
680
|
+
/** @desc user defined function that creates a component description from its properties */
|
|
681
|
+
type Descriptor = (props: Record<"method" | "path" | "operationId", string> & {
|
|
682
|
+
statusCode?: number;
|
|
683
|
+
}) => string;
|
|
684
|
+
interface DocumentationParams {
|
|
685
|
+
title: string;
|
|
686
|
+
version: string;
|
|
687
|
+
serverUrl: string | [string, ...string[]];
|
|
688
|
+
routing: Routing;
|
|
689
|
+
config: CommonConfig;
|
|
690
|
+
/**
|
|
691
|
+
* @desc Descriptions of various components based on their properties (method, path, operationId).
|
|
692
|
+
* @desc When composition set to "components", component name is generated from this description
|
|
693
|
+
* @default () => `${method} ${path} ${component}`
|
|
694
|
+
* */
|
|
695
|
+
descriptions?: Partial<Record<Component, Descriptor>>;
|
|
696
|
+
/** @default true */
|
|
697
|
+
hasSummaryFromDescription?: boolean;
|
|
698
|
+
/** @default inline */
|
|
699
|
+
composition?: "inline" | "components";
|
|
700
|
+
/**
|
|
701
|
+
* @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
|
|
702
|
+
* @default JSON.stringify() + SHA1 hash as a hex digest
|
|
703
|
+
* */
|
|
704
|
+
serializer?: (schema: z.ZodTypeAny) => string;
|
|
705
|
+
/**
|
|
706
|
+
* @desc Handling rules for your own branded schemas.
|
|
707
|
+
* @desc Keys: brands (recommended to use unique symbols).
|
|
708
|
+
* @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
|
|
709
|
+
* @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => ({ type: "object" })
|
|
710
|
+
*/
|
|
711
|
+
brandHandling?: HandlingRules<SchemaObject | ReferenceObject, OpenAPIContext>;
|
|
696
712
|
}
|
|
697
|
-
declare class
|
|
698
|
-
|
|
699
|
-
|
|
713
|
+
declare class Documentation extends OpenApiBuilder {
|
|
714
|
+
protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
|
|
715
|
+
protected lastOperationIdSuffixes: Map<string, number>;
|
|
716
|
+
protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
|
|
717
|
+
protected getRef(name: string): ReferenceObject | undefined;
|
|
718
|
+
protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
|
|
719
|
+
protected ensureUniqSecuritySchemaName(subject: SecuritySchemeObject): string;
|
|
720
|
+
constructor({ routing, config, title, version, serverUrl, descriptions, brandHandling, hasSummaryFromDescription, composition, serializer, }: DocumentationParams);
|
|
700
721
|
}
|
|
701
722
|
|
|
702
723
|
type LocalResponse = Response<unknown, {
|
|
@@ -758,6 +779,18 @@ declare const testEndpoint: <LOG extends Record<string, any>, REQ extends Record
|
|
|
758
779
|
loggerMock: Record<"error" | "info" | "debug" | "warn", MockOverrides> & LOG;
|
|
759
780
|
}>;
|
|
760
781
|
|
|
782
|
+
interface ZTSContext extends FlatObject {
|
|
783
|
+
isResponse: boolean;
|
|
784
|
+
getAlias: (name: string) => ts.TypeReferenceNode | undefined;
|
|
785
|
+
makeAlias: (name: string, type: ts.TypeNode) => ts.TypeReferenceNode;
|
|
786
|
+
serializer: (schema: z.ZodTypeAny) => string;
|
|
787
|
+
optionalPropStyle: {
|
|
788
|
+
withQuestionMark?: boolean;
|
|
789
|
+
withUndefined?: boolean;
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
|
|
793
|
+
|
|
761
794
|
type IOKind = "input" | "response" | "positive" | "negative";
|
|
762
795
|
interface IntegrationParams {
|
|
763
796
|
routing: Routing;
|
|
@@ -794,6 +827,13 @@ interface IntegrationParams {
|
|
|
794
827
|
*/
|
|
795
828
|
withUndefined?: boolean;
|
|
796
829
|
};
|
|
830
|
+
/**
|
|
831
|
+
* @desc Handling rules for your own branded schemas.
|
|
832
|
+
* @desc Keys: brands (recommended to use unique symbols).
|
|
833
|
+
* @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
|
|
834
|
+
* @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => createKeywordTypeNode(SyntaxKind.AnyKeyword)
|
|
835
|
+
*/
|
|
836
|
+
brandHandling?: HandlingRules<ts.TypeNode, ZTSContext>;
|
|
797
837
|
}
|
|
798
838
|
interface FormattedPrintingOptions {
|
|
799
839
|
/** @desc Typescript printer options */
|
|
@@ -852,10 +892,10 @@ declare class Integration {
|
|
|
852
892
|
}>;
|
|
853
893
|
protected getAlias(name: string): ts.TypeReferenceNode | undefined;
|
|
854
894
|
protected makeAlias(name: string, type: ts.TypeNode): ts.TypeReferenceNode;
|
|
855
|
-
constructor({ routing, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
|
|
895
|
+
constructor({ routing, brandHandling, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
|
|
856
896
|
protected printUsage(printerOptions?: ts.PrinterOptions): string | undefined;
|
|
857
897
|
print(printerOptions?: ts.PrinterOptions): string;
|
|
858
898
|
printFormatted({ printerOptions, format: userDefined, }?: FormattedPrintingOptions): Promise<string>;
|
|
859
899
|
}
|
|
860
900
|
|
|
861
|
-
export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
|
|
901
|
+
export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{clone as po}from"ramda";import{z as Ue}from"zod";import{isHttpError as Jr}from"http-errors";import{createHash as Wr}from"crypto";import{flip as Xr,pickBy as eo,xprod as to}from"ramda";import{z as ro}from"zod";var
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},
|
|
1
|
+
import{clone as po}from"ramda";import{z as Ue}from"zod";import{isHttpError as Jr}from"http-errors";import{createHash as Wr}from"crypto";import{flip as Xr,pickBy as eo,xprod as to}from"ramda";import{z as ro}from"zod";var se=class extends Error{name="RoutingError"},P=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
|
|
2
|
+
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},j=class extends Error{name="IOSchemaError"},_=class extends j{name="OutputValidationError";originalError;constructor(t){super(H(t)),this.originalError=t}},k=class extends j{name="InputValidationError";originalError;constructor(t){super(H(t)),this.originalError=t}},Y=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ae=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var oo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},it={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},no=["body","query","params"],st=e=>e.method.toLowerCase(),at=e=>e.startsWith("x-"),io=e=>eo(Xr(at),e),$t=(e,t={})=>{let r=st(e);return r==="options"?{}:(t[r]||it[r]||no).filter(o=>o==="files"?oo(e):!0).map(o=>o==="headers"?io(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},pe=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),H=e=>e instanceof ro.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof _?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,De=e=>Jr(e)?e.statusCode:e instanceof k?400:500,pt=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};import{chain as Po}from"ramda";var Y=e=>M(e)&&"or"in e,pe=e=>M(e)&&"and"in e,lt=e=>({and:Po(t=>pe(t)?t.and:[t],e)}),Ve=(e,t)=>pe(e)?{and:e.and.map(r=>Y(r)?{or:r.or.map(t)}:t(r))}:Y(e)?{or:e.or.map(r=>pe(r)?{and:r.and.map(t)}:t(r))}:t(e),mt=e=>e.and.reduce((t,r)=>({or:_(t.or,Y(r)?r.or:[r],lt)}),{or:[]}),ae=(e,t)=>pe(e)?Y(t)?ae(mt(e),t):lt([e,t]):Y(e)?pe(t)?ae(t,e):Y(t)?{or:_(e.or,t.or,lt)}:ae(e,{and:[t]}):pe(t)||Y(t)?ae(t,e):{and:[e,t]};var de=class{},$e=class extends de{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:l}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:m,short:l},this.#r={input:r,output:o};for(let[f,b]of Object.entries(this.#r))Xt(!Be(b),new L(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:Object.freeze(dt(s.getPositiveResponse(o),{mimeTypes:[w.json],statusCodes:[se.positive]})),negative:Object.freeze(dt(s.getNegativeResponse(),{mimeTypes:[w.json],statusCodes:[se.negative]}))};for(let[f,b]of Object.entries(this.#t))Xt(b.length,new $(`ResultHandler must have at least one ${f} response schema specified.`));this.#i=Jt(r)?"upload":Wt(r)?"raw":"json",this.#s={input:Object.freeze([w[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:f})=>f)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:f})=>f))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ae(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ut.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof ut.ZodError?new D(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ut.ZodError?new D(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){qe({logger:i,response:o,error:new $(ie(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=it(t),p={},d=null,c=null;if(i.cors){let l=this.#m(s);typeof i.cors=="function"&&(l=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let f in l)r.set(f,l[f])}let m=qt(t,i.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(l){c=ie(l)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as tr}from"zod";var er=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Vt(s,i),o)};import Co from"assert/strict";var ft=e=>(Co(!Be(e.input),new L("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as Z}from"zod";var yt=e=>e,Re=yt({getPositiveResponse:e=>{let t=j({schema:e}),r=Z.object({status:Z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>Z.object({status:Z.literal("error"),error:Z.object({message:Z.string()})}).example({status:"error",error:{message:k(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(se.positive).json({status:"success",data:r});return}let a=Le(e);at({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:k(e)}})}}),gt=yt({getPositiveResponse:e=>{let t=j({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof Z.ZodArray?e.shape.items:Z.array(Z.any());return t.reduce((o,i)=>M(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>Z.string().example(k(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);at({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(se.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Oe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:tr.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,l=>{if(l&&l instanceof Error)return c(o(l));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ft({input:tr.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],b="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new $e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:b,methods:m,getOperationId:l,description:i,shortDescription:s,inputSchema:er(d,t)})}},Io=new Oe(Re),wo=new Oe(gt);import{inspect as Eo}from"util";import{mapObjIndexed as zo}from"ramda";import{Ansis as Zo,blue as No,green as Mo,hex as vo,red as Lo}from"ansis";var ht={debug:10,info:20,warn:30,error:40},rr=e=>M(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),xt=({level:e,color:t=new Zo().isSupported(),depth:r=2})=>{let o={debug:No,info:Mo,warn:vo("#FFA500"),error:Lo},i=e==="debug",s=e==="silent"?100:ht[e],a=(p,d,c)=>{if(ht[p]<s)return;let m=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&m.push(Eo(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(m.join(" "))};return zo(({},p)=>(d,c)=>a(p,d,c),ht)};import{head as Do,tail as ko,toPairs as jo}from"ramda";var Ae=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(jo(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=Do(this.pairs)?.[1],this.siblingMethods=Object.freeze(ko(this.pairs).map(([r])=>r))}};import Uo from"express";var Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Uo.static(...this.params))}};import Tt from"express";import Vo from"http";import $o from"https";var Q=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new ne(e)},or=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await Q(t,r)}catch{}throw new ne(e.map(({moduleName:t})=>t))};import nr from"assert/strict";var J=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){nr.doesNotMatch(a,/\//,new oe(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof de){let c=p.getMethods().slice();i&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof Pe)r&&p.apply(d,r);else if(p instanceof Ae){for(let[c,m]of p.pairs)nr(m.getMethods().includes(c),new oe(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(m,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else J({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var bt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>J({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,m)=>s.execute({request:c,response:m,logger:m.locals[y]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});import ir,{isHttpError as Ho}from"http-errors";var sr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:Ho(r)?r:ir(400,ie(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[y]?.logger||t})},ar=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=ir(404,`Can not ${r.method} ${r.path}`),s=o.locals[y]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){qe({response:o,logger:s,error:new $(ie(a).message,i)})}},Fo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Ko=e=>({log:e.debug.bind(e)}),pr=async({rootLogger:e,config:t})=>{let r=await Q("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=d.locals[y]?.logger||e;try{await i?.({request:p,logger:m})}catch(l){return c(l)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Ko(m)})(p,d,c)}),o&&a.push(Fo(o)),a},dr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},cr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[y]={logger:s},i()};import{gray as Bo,hex as lr,italic as _e,whiteBright as qo}from"ansis";var mr=()=>{let e=_e("Proudly supports transgender community.".padStart(109)),t=_e("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=_e("Thank you for choosing Express Zod API for your project.".padStart(132)),o=_e("for Dime".padEnd(20)),i=lr("#F5A9B8"),s=lr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(qo,5,7).fill(i,7,9).fill(s,9,12).fill(Bo,12,13);return`
|
|
4
|
+
`,{url:t.url,payload:r})},U=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[y]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},Q=(e,t,r)=>e.length&&t.length?to(e,t).map(r):e.concat(t),Oe=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,dt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),E=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(dt).join(""),je=e=>Wr("sha1").update(JSON.stringify(e),"utf8").digest("hex"),ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},v=e=>typeof e=="object"&&e!==null;import{clone as so,mergeDeepRight as ao}from"ramda";var y=Symbol.for("express-zod-api"),He=e=>{let t=e.describe(e.description);return t._def[y]=so(t._def[y])||{examples:[]},t},Vt=(e,t)=>{if(!(y in e._def))return t;let r=He(t);return r._def[y].examples=Q(r._def[y].examples,e._def[y].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?ao({...o},{...i}):i),r};var co=function(e){let t=He(this);return t._def[y].examples.push(e),t},lo=function(e){let t=He(this);return t._def[y].defaultLabel=e,t},mo=function(e){return new Ue.ZodBranded({typeName:Ue.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...po(this._def[y]),brand:e}})};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ue.ZodType.prototype,{example:{get(){return co.bind(this)}},brand:{set(){},get(){return mo.bind(this)}}}),Object.defineProperty(Ue.ZodDefault.prototype,"label",{get(){return lo.bind(this)}}));function uo(e){return e}import er from"assert/strict";import{z as ft}from"zod";import{z as fo}from"zod";var de={positive:200,negative:400},ct=(e,t)=>e instanceof fo.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));import{z as xo}from"zod";import{z as go}from"zod";import{z as Fe}from"zod";var F=Symbol("File"),Gt=Fe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),yo={buffer:()=>Gt.brand(F),string:()=>Fe.string().brand(F),binary:()=>Gt.or(Fe.string()).brand(F),base64:()=>Fe.string().base64().brand(F)};function Ke(e){return yo[e||"string"]()}var J=Symbol("Raw"),_t=(e={})=>go.object({raw:Ke("buffer")}).extend(e).brand(J);import{z as ho}from"zod";var Ae=Symbol("Upload"),Yt=()=>ho.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ae);var lt=(e,{next:t})=>e.options.some(t),Jt=({_def:e},{next:t})=>[e.left,e.right].some(t),Qt=(e,{next:t})=>t(e.unwrap()),bo={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:lt,ZodDiscriminatedUnion:lt,ZodIntersection:Jt,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:Qt,ZodNullable:Qt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Be=(e,{condition:t,rules:r=bo,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s(e,{next:a=>Be(a,{condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},qe=e=>Be(e,{maxDepth:3,rules:{ZodUnion:lt,ZodIntersection:Jt},condition:t=>t instanceof xo.ZodEffects&&t._def.effect.type!=="refinement"}),Wt=e=>Be(e,{condition:t=>t._def[y]?.brand===Ae}),Xt=e=>Be(e,{condition:t=>t._def[y]?.brand===J,maxDepth:3});var $e=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
5
|
+
Original error: ${e.originalError.message}.`:""))};import{chain as To}from"ramda";var W=e=>v(e)&&"or"in e,le=e=>v(e)&&"and"in e,mt=e=>({and:To(t=>le(t)?t.and:[t],e)}),Ve=(e,t)=>le(e)?{and:e.and.map(r=>W(r)?{or:r.or.map(t)}:t(r))}:W(e)?{or:e.or.map(r=>le(r)?{and:r.and.map(t)}:t(r))}:t(e),ut=e=>e.and.reduce((t,r)=>({or:Q(t.or,W(r)?r.or:[r],mt)}),{or:[]}),ce=(e,t)=>le(e)?W(t)?ce(ut(e),t):mt([e,t]):W(e)?le(t)?ce(t,e):W(t)?{or:Q(e.or,t.or,mt)}:ce(e,{and:[t]}):le(t)||W(t)?ce(t,e):{and:[e,t]};var me=class{},Ge=class extends me{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:f}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:l,short:f},this.#r={input:r,output:o};for(let[m,h]of Object.entries(this.#r))er(!qe(h),new j(`Using transformations on the top level of endpoint ${m} schema is not allowed.`));this.#t={positive:Object.freeze(ct(s.getPositiveResponse(o),{mimeTypes:[w.json],statusCodes:[de.positive]})),negative:Object.freeze(ct(s.getNegativeResponse(),{mimeTypes:[w.json],statusCodes:[de.negative]}))};for(let[m,h]of Object.entries(this.#t))er(h.length,new Y(`ResultHandler must have at least one ${m} response schema specified.`));this.#i=Wt(r)?"upload":Xt(r)?"raw":"json",this.#s={input:Object.freeze([w[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:m})=>m))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ce(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ft.ZodError?new _(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof ft.ZodError?new k(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ft.ZodError?new k(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){$e({logger:i,response:o,error:new Y(pe(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=st(t),p={},d=null,c=null;if(i.cors){let f=this.#m(s);typeof i.cors=="function"&&(f=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=$t(t,i.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=pe(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as rr}from"zod";var tr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Vt(s,i),o)};import So from"assert/strict";var yt=e=>(So(!qe(e.input),new j("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as N}from"zod";var gt=e=>e,Pe=gt({getPositiveResponse:e=>{let t=U({schema:e}),r=N.object({status:N.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>N.object({status:N.literal("error"),error:N.object({message:N.string()})}).example({status:"error",error:{message:H(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(de.positive).json({status:"success",data:r});return}let a=De(e);pt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:H(e)}})}}),ht=gt({getPositiveResponse:e=>{let t=U({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof N.ZodArray?e.shape.items:N.array(N.any());return t.reduce((o,i)=>v(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>N.string().example(H(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=De(r);pt({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(de.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Ce=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:rr.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,f=>{if(f&&f instanceof Error)return c(o(f));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(yt({input:rr.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Ge({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:h,methods:l,getOperationId:f,description:i,shortDescription:s,inputSchema:tr(d,t)})}},Ro=new Ce(Pe),Oo=new Ce(ht);import{inspect as Ao}from"util";import{mapObjIndexed as Po}from"ramda";import{Ansis as Co,blue as Io,green as wo,hex as Eo,red as zo}from"ansis";var xt={debug:10,info:20,warn:30,error:40},or=e=>v(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),bt=({level:e,color:t=new Co().isSupported(),depth:r=2})=>{let o={debug:Io,info:wo,warn:Eo("#FFA500"),error:zo},i=e==="debug",s=e==="silent"?100:xt[e],a=(p,d,c)=>{if(xt[p]<s)return;let l=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&l.push(Ao(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(l.join(" "))};return Po(({},p)=>(d,c)=>a(p,d,c),xt)};import{head as Zo,tail as No,toPairs as Mo}from"ramda";var Ie=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(Mo(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=Zo(this.pairs)?.[1],this.siblingMethods=Object.freeze(No(this.pairs).map(([r])=>r))}};import vo from"express";var we=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,vo.static(...this.params))}};import St from"express";import Uo from"http";import Fo from"https";var X=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new ae(e)},nr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await X(t,r)}catch{}throw new ae(e.map(({moduleName:t})=>t))};import ir from"assert/strict";var ee=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){ir.doesNotMatch(a,/\//,new se(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof me){let c=p.getMethods().slice();i&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof we)r&&p.apply(d,r);else if(p instanceof Ie){for(let[c,l]of p.pairs)ir(l.getMethods().includes(c),new se(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else ee({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Tt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>ee({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,l)=>s.execute({request:c,response:l,logger:l.locals[y]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});import sr,{isHttpError as Lo}from"http-errors";var ar=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:Lo(r)?r:sr(400,pe(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[y]?.logger||t})},pr=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=sr(404,`Can not ${r.method} ${r.path}`),s=o.locals[y]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){$e({response:o,logger:s,error:new Y(pe(a).message,i)})}},Do=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},jo=e=>({log:e.debug.bind(e)}),dr=async({rootLogger:e,config:t})=>{let r=await X("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=d.locals[y]?.logger||e;try{await i?.({request:p,logger:l})}catch(f){return c(f)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:jo(l)})(p,d,c)}),o&&a.push(Do(o)),a},cr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},lr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[y]={logger:s},i()};import{gray as ko,hex as mr,italic as _e,whiteBright as Ho}from"ansis";var ur=()=>{let e=_e("Proudly supports transgender community.".padStart(109)),t=_e("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=_e("Thank you for choosing Express Zod API for your project.".padStart(132)),o=_e("for Dime".padEnd(20)),i=mr("#F5A9B8"),s=mr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(Ho,5,7).fill(i,7,9).fill(s,9,12).fill(ko,12,13);return`
|
|
6
6
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
7
7
|
888 d88P 888 d88888 888 Y88b 888
|
|
8
8
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -17,8 +17,8 @@ ${o}888${t}
|
|
|
17
17
|
${r}
|
|
18
18
|
`.split(`
|
|
19
19
|
`).map((d,c)=>a[c]?a[c](d):d).join(`
|
|
20
|
-
`)};var ur=e=>{e.startupLogo!==!1&&console.log(mr());let t=e.errorHandler||Re,r=rr(e.logger)?xt(e.logger):e.logger;r.debug("Running","v19.0.0 (ESM)");let o=cr({rootLogger:r,config:e}),i=ar({rootLogger:r,errorHandler:t}),s=sr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},_o=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=ur(e);return bt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Go=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=ur(e),a=Tt().disable("x-powered-by").use(s);if(e.server.compression){let m=await Q("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||Tt.json()],raw:[e.server.rawParser||Tt.raw(),dr],upload:e.server.upload?await pr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),bt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,l)=>m.listen(l,()=>{r.info("Listening",l)}),c={httpServer:d(Vo.createServer(a),e.server.listen),httpsServer:e.https?d($o.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...c,logger:r}};import ti from"assert/strict";import{OpenApiBuilder as ri}from"openapi3-ts/oas31";import H from"assert/strict";import{isReferenceObject as X}from"openapi3-ts/oas31";import{both as Qo,complement as Jo,concat as Wo,type as Xo,filter as en,fromPairs as Ee,has as tn,isNil as rn,map as le,mergeAll as on,mergeDeepRight as nn,mergeDeepWith as sn,objOf as xr,omit as Qe,pipe as br,pluck as an,range as pn,reject as dn,toLower as cn,union as ln,when as mn,xprod as Je,zip as un}from"ramda";import{z as x}from"zod";import{z as Ce}from"zod";var Ge=e=>!isNaN(e.getTime());var Ie=Symbol("DateIn"),fr=()=>Ce.union([Ce.string().date(),Ce.string().datetime(),Ce.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ce.date().refine(Ge)).brand(Ie);import{z as Yo}from"zod";var we=Symbol("DateOut"),yr=()=>Yo.date().refine(Ge).transform(e=>e.toISOString()).brand(we);var W=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:m=>W({schema:m,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),c=t&&t({schema:e,prev:d,...a});return c?{...d,...c}:d};var gr=50,Tr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",fn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Sr=/:([A-Za-z0-9_]+)/g,Rr=e=>e.match(Sr)?.map(t=>t.slice(1))||[],Or=e=>e.replace(Sr,t=>`{${t.slice(1)}}`),yn=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[y]?.defaultLabel||e._def.defaultValue()}),gn=({schema:{_def:{innerType:e}},next:t})=>t(e),hn=()=>({format:"any"}),xn=e=>(H(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),bn=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof x.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Tn=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Sn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Rn=e=>{let[t,r]=e.filter(i=>!X(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));H(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=sn((i,s)=>Array.isArray(i)&&Array.isArray(s)?Wo(i,s):i===s?s:H.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=ln(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([i,s])=>nn(i,s))),o},On=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Rn(o)}catch{}return{allOf:o}},An=({schema:e,next:t})=>t(e.unwrap()),Pn=({schema:e,next:t})=>t(e._def.innerType),Cn=({schema:e,next:t})=>{let r=t(e.unwrap());return X(r)||(r.type=Pr(r)),r},Ar=e=>{let t=cn(Xo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},hr=({schema:e})=>({type:Ar(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),In=({schema:{value:e}})=>({type:Ar(e),const:e}),wn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Te(p)?p instanceof x.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=Ye({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},En=()=>({type:"null"}),zn=e=>(H(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Tr}}),Zn=e=>(H(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Tr}}),Nn=e=>H.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Mn=()=>({type:"boolean"}),vn=()=>({type:"integer",format:"bigint"}),Ln=e=>e.every(t=>t instanceof x.ZodLiteral),Dn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=Ye({schema:x.object(Ee(Je(o,[t]))),...r}),i.required=o),i}if(e instanceof x.ZodLiteral)return{type:"object",properties:Ye({schema:x.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.ZodUnion&&Ln(e.options)){let o=le(s=>`${s.value}`,e.options),i=Ee(Je(o,[t]));return{type:"object",properties:Ye({schema:x.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},kn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},jn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Un=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}}})=>{let f=l.find(S=>S.kind==="regex"),b=l.find(S=>S.kind==="datetime"),T=f?f.regex:b?b.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,R={type:"string"},h={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let S in h)if(h[S]){R.format=S;break}return r!==null&&(R.minLength=r),o!==null&&(R.maxLength=o),T&&(R.pattern=T.source),R},Hn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},Ye=({schema:{shape:e},next:t})=>le(t,e),Fn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return fn?.[t]},Pr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Kn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!X(o)){let s=ke(e,Fn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(x.any())}if(!t&&i.type==="preprocess"&&!X(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Bn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),qn=({schema:e,next:t})=>t(e.unwrap()),Vn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},$n=({next:e,schema:t})=>e(t.unwrap().shape.raw),Cr=e=>e.length?Ee(un(pn(1,e.length+1).map(t=>`example${t}`),le(xr("value"),e))):void 0,Ir=(e,t,r=[])=>br(j,le(mn(Qo(M,Jo(Array.isArray)),Qe(r))),Cr)({schema:e,variant:t?"parsed":"original",validate:!0}),_n=(e,t)=>br(j,en(tn(t)),an(t),Cr)({schema:e,variant:"original",validate:!0}),ce=(e,t)=>e instanceof x.ZodObject?e:e instanceof x.ZodBranded?ce(e.unwrap(),t):e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion?e.options.map(r=>ce(r,t)).reduce((r,o)=>r.merge(o.partial()),x.object({})):e instanceof x.ZodEffects?(H(e._def.effect.type==="refinement",t),ce(e._def.schema,t)):ce(e._def.left,t).merge(ce(e._def.right,t)),wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=ce(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),m=Rr(e),l=o.includes("query"),f=o.includes("params"),b=o.includes("headers"),T=h=>f&&m.includes(h),R=h=>b&&st(h);return Object.keys(c).filter(h=>l||T(h)).map(h=>{let S=W({schema:c[h],isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:e,method:t}),fe=p==="components"?a(E(d,h),S):S;return{name:h,in:T(h)?"path":R(h)?"header":"query",required:!c[h].isOptional(),description:S.description||d,schema:fe,examples:_n(r,h)}})},Rt={ZodString:Un,ZodNumber:Hn,ZodBigInt:vn,ZodBoolean:Mn,ZodNull:En,ZodArray:kn,ZodTuple:jn,ZodRecord:Dn,ZodObject:wn,ZodLiteral:In,ZodIntersection:On,ZodUnion:Tn,ZodAny:hn,ZodDefault:yn,ZodEnum:hr,ZodNativeEnum:hr,ZodEffects:Kn,ZodOptional:An,ZodNullable:Cn,ZodDiscriminatedUnion:Sn,ZodBranded:qn,ZodDate:Nn,ZodCatch:gn,ZodPipeline:Bn,ZodLazy:Vn,ZodReadonly:Pn,[U]:bn,[Se]:xn,[we]:Zn,[Ie]:zn,[G]:$n},Ot=({schema:e,isResponse:t,prev:r})=>{if(X(r))return{};let{description:o}=e,i=e instanceof x.ZodLazy,s=r.type!==void 0,a=t&&Te(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:j({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Pr(r)),d.length&&(c.examples=d.slice()),c},At=({schema:e,...t})=>H.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),St=(e,t)=>{if(X(e))return e;let r={...e};return r.properties&&(r.properties=Qe(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Qe(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>St(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>St(o,t))),r},Er=e=>X(e)?e:Qe(["examples"],e),zr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:m,description:l=`${e.toUpperCase()} ${t} ${pt(i)} response ${c?m:""}`.trim()})=>{let f=Er(W({schema:r,isResponse:!0,rules:Rt,onEach:Ot,onMissing:At,serializer:s,getRef:a,makeRef:p,path:t,method:e})),b={schema:d==="components"?p(E(l),f):f,examples:Ir(r,!0)};return{description:l,content:Ee(Je(o,[b]))}},Gn=()=>({type:"http",scheme:"basic"}),Yn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Qn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Jn=({name:e})=>({type:"apiKey",in:"header",name:e}),Wn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Xn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ei=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),dn(rn,e))}),Zr=(e,t)=>{let r={basic:Gn,bearer:Yn,input:Qn,header:Jn,cookie:Wn,openid:Xn,oauth2:ei};return Ve(e,o=>r[o.type](o,t))},We=e=>"or"in e?e.or.map(t=>"and"in t?on(le(({name:r,scopes:o})=>xr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?We(mt(e)):We({or:[e]}),Nr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Rr(t),m=Er(St(W({schema:r,isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(E(d),m):m,examples:Ir(r,!1,c)};return{description:d,content:Ee(Je(o,[l]))}},Mr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Pt=e=>e.length<=gr?e:e.slice(0,gr-1)+"\u2026";var Ct=class extends ri{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||E(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ti.fail(new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;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:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=De}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});J({routing:t,onEndpoint:(l,f,b)=>{let T=b,R={path:f,method:T,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,S]=["short","long"].map(l.getDescription.bind(l)),fe=h?Pt(h):p&&S?Pt(S):void 0,Ze=l.getTags(),ye=r.inputSources?.[T]||nt[T],te=this.ensureUniqOperationId(f,T,l.getOperationId(T)),Ne=wr({...R,inputSources:ye,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:f,operationId:te})}),Me={};for(let N of["positive","negative"]){let q=l.getResponses(N);for(let{mimeTypes:ge,schema:O,statusCodes:A}of q)for(let P of A)Me[P]=zr({...R,variant:N,schema:O,mimeTypes:ge,statusCode:P,hasMultipleStatusCodes:q.length>1||A.length>1,description:a?.[`${N}Response`]?.call(null,{method:T,path:f,operationId:te,statusCode:P})})}let ot=ye.includes("body")?Nr({...R,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:f,operationId:te})}):void 0,ve=We(Ve(Zr(l.getSecurity(),ye),N=>{let q=this.ensureUniqSecuritySchemaName(N),ge=["oauth2","openIdConnect"].includes(N.type)?l.getScopes().slice():[];return this.addSecurityScheme(q,N),{name:q,scopes:ge}}));this.addPath(Or(f),{[T]:{operationId:te,summary:fe,description:S,tags:Ze.length>0?Ze:void 0,parameters:Ne.length>0?Ne:void 0,requestBody:ot,security:ve.length>0?ve:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import vr from"http";var oi=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>w.json),...t}),ni=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:vr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=vr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},ii=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),si=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await or([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=oi({fnMethod:a,requestProps:t}),d=ni({fnMethod:a,responseProps:r}),c=ii({fnMethod:a,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:m,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import z from"typescript";import v from"typescript";import{chain as Lr,toPairs as Dr}from"ramda";var n=v.factory,F=[n.createModifier(v.SyntaxKind.ExportKeyword)],ai=[n.createModifier(v.SyntaxKind.AsyncKeyword)],pi=[n.createModifier(v.SyntaxKind.PublicKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],kr=[n.createModifier(v.SyntaxKind.ProtectedKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],It=n.createTemplateHead(""),me=n.createTemplateTail(""),wt=n.createTemplateMiddle(" "),Et=e=>n.createTemplateLiteralType(It,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?me:wt))),zt=Et(["M","P"]),Xe=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),et=(e,t)=>Lr(([r,o])=>[Xe(n.createIdentifier(r),o,t)],Dr(e)),Zt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),jr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Ur=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),K=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],v.NodeFlags.Const),Nt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),tt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,t),Hr=(e,t,r)=>n.createPropertyDeclaration(pi,e,void 0,t,r),Fr=(e,t,r)=>n.createClassDeclaration(F,e,void 0,void 0,[t,...r]),Kr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Br=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(v.SyntaxKind.AnyKeyword)]),qr=(e,t,r)=>n.createInterfaceDeclaration(F,e,void 0,t,r),Vr=e=>Lr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Dr(e)),Mt=(e,t,r)=>n.createArrowFunction(r?ai:void 0,void 0,e.map(o=>Xe(o)),void 0,void 0,t),vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,et({acc:void 0,key:void 0}),void 0,void 0,t),r]),$r=(...e)=>`"${e.join(" ")}"`;var _r=["get","post","put","delete","patch"];import g from"typescript";import{z as kt}from"zod";import B from"typescript";var{factory:rt}=B,Lt=(e,t)=>{B.addSyntheticLeadingComment(e,B.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ue=(e,t,r)=>{let o=rt.createTypeAliasDeclaration(void 0,rt.createIdentifier(t),void 0,e);return r&&Lt(o,r),o},Dt=(e,t)=>{let r=B.createSourceFile("print.ts","",B.ScriptTarget.Latest,!1,B.ScriptKind.TS);return B.createPrinter(t).printNode(B.EmitHint.Unspecified,e,r)},di=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gr=e=>di.test(e)?rt.createIdentifier(e):rt.createStringLiteral(e);var{factory:u}=g,ci={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},li=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),mi=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Te(a)?a instanceof kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Gr(s),p&&o?u.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},ui=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),fi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Yr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),yi=e=>ci?.[e.kind],gi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,yi(o)),a={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||g.SyntaxKind.AnyKeyword)}return o},hi=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),xi=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},bi=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ti=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Si=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Ri=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Oi=({next:e,schema:t})=>e(t._def.innerType),ee=e=>()=>u.createKeywordTypeNode(e),Ai=({next:e,schema:t})=>e(t.unwrap()),Pi=({next:e,schema:t})=>e(t._def.innerType),Ci=({next:e,schema:t})=>e(t._def.innerType),Ii=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),wi=()=>u.createLiteralTypeNode(u.createNull()),Ei=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},zi=({schema:e})=>{let t=e.unwrap(),r=u.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof kt.ZodString?r:t instanceof kt.ZodUnion?i:o},Zi=({next:e,schema:t})=>e(t.unwrap().shape.raw),Ni={ZodString:ee(g.SyntaxKind.StringKeyword),ZodNumber:ee(g.SyntaxKind.NumberKeyword),ZodBigInt:ee(g.SyntaxKind.BigIntKeyword),ZodBoolean:ee(g.SyntaxKind.BooleanKeyword),ZodAny:ee(g.SyntaxKind.AnyKeyword),[Ie]:ee(g.SyntaxKind.StringKeyword),[we]:ee(g.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:ui,ZodTuple:Ti,ZodRecord:Si,ZodObject:mi,ZodLiteral:li,ZodIntersection:Ri,ZodUnion:Yr,ZodDefault:Oi,ZodEnum:fi,ZodNativeEnum:hi,ZodEffects:gi,ZodOptional:xi,ZodNullable:bi,ZodDiscriminatedUnion:Yr,ZodBranded:Ai,ZodCatch:Ci,ZodPipeline:Ii,ZodLazy:Ei,ZodReadonly:Pi,[U]:zi,[G]:Zi},ze=({schema:e,...t})=>W({schema:e,rules:Ni,onMissing:()=>u.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),...t});var jt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ue(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=De,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){J({routing:t,onEndpoint:(O,A,P)=>{let re={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},he=E(P,A,"input"),xe=ze({...re,schema:O.getSchema("input"),isResponse:!1}),I=i?E(P,A,"positive.response"):void 0,Ut=O.getSchema("positive"),Ht=i?ze({...re,isResponse:!0,schema:Ut}):void 0,be=i?E(P,A,"negative.response"):void 0,Ft=O.getSchema("negative"),Kt=i?ze({...re,isResponse:!0,schema:Ft}):void 0,Bt=E(P,A,"response"),Qr=I&&be?n.createUnionTypeNode([n.createTypeReferenceNode(I),n.createTypeReferenceNode(be)]):ze({...re,isResponse:!0,schema:Ut.or(Ft)});this.program.push(ue(xe,he)),Ht&&I&&this.program.push(ue(Ht,I)),Kt&&be&&this.program.push(ue(Kt,be)),this.program.push(ue(Qr,Bt)),P!=="options"&&(this.paths.push(A),this.registry.set({method:P,path:A},{input:he,positive:I,negative:be,response:Bt,isJson:O.getMimeTypes("positive").includes(w.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Nt(this.ids.pathType,this.paths)),this.program.push(Nt(this.ids.methodType,_r)),this.program.push(tt(this.ids.methodPathType,Et([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[Zt(this.ids.methodPathType,z.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:O,path:A},{isJson:P,tags:re,...he}]of this.registry){let xe=$r(O,A);for(let I of this.interfaces)I.kind in he&&I.props.push(Ur(xe,he[I.kind]));r!=="types"&&(P&&p.push(n.createPropertyAssignment(xe,n.createTrue())),d.push(n.createPropertyAssignment(xe,n.createArrayLiteralExpression(re.map(I=>n.createStringLiteral(I))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(qr(O,a,A));if(r==="types")return;let c=n.createVariableStatement(F,K(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),m=n.createVariableStatement(F,K(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),l=tt(this.ids.providerType,n.createFunctionTypeNode(Vr({M:this.ids.methodType,P:this.ids.pathType}),et({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),zt)}),Kr(this.ids.responseInterface,zt))),f=tt(this.ids.implementationType,n.createFunctionTypeNode(void 0,et({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:Zt(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),Br())),b=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,me)]),T=vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[b,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),R=vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[b]),z.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),h=Fr(this.ids.clientClass,jr([Xe(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),kr)]),[Hr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,R]),!0))]);this.program.push(c,m,l,f,h);let S=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),fe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),Ze=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ye=n.createVariableStatement(void 0,K(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,me)]),n.createObjectLiteralExpression([S,fe,Ze])])))),te=n.createVariableStatement(void 0,K(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ne=n.createVariableStatement(void 0,K(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),me)])))),[Me,ot]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),ve=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(It,[n.createTemplateSpan(this.ids.methodParameter,wt),n.createTemplateSpan(this.ids.pathParameter,me)]),z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Me])),N=n.createVariableStatement(F,K(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([te,Ne,ye,ve,ot]),!0),n.createTypeReferenceNode(this.ids.implementationType))),q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),ge=n.createVariableStatement(void 0,K(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(N,ge,q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
|
|
20
|
+
`)};var fr=e=>{e.startupLogo!==!1&&console.log(ur());let t=e.errorHandler||Pe,r=or(e.logger)?bt(e.logger):e.logger;r.debug("Running","v19.1.1 (ESM)");let o=lr({rootLogger:r,config:e}),i=pr({rootLogger:r,errorHandler:t}),s=ar({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},Ko=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=fr(e);return Tt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Bo=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=fr(e),a=St().disable("x-powered-by").use(s);if(e.server.compression){let l=await X("compression");a.use(l(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||St.json()],raw:[e.server.rawParser||St.raw(),cr],upload:e.server.upload?await dr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Tt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(l,f)=>l.listen(f,()=>{r.info("Listening",f)}),c={httpServer:d(Uo.createServer(a),e.server.listen),httpsServer:e.https?d(Fo.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...c,logger:r}};import Jn from"assert/strict";import{OpenApiBuilder as Wn}from"openapi3-ts/oas31";import{pluck as Xn}from"ramda";import K from"assert/strict";import{isReferenceObject as re}from"openapi3-ts/oas31";import{both as $o,complement as Vo,concat as Go,type as _o,filter as Yo,fromPairs as Ne,has as Qo,isNil as Jo,map as fe,mergeAll as Wo,mergeDeepRight as Xo,mergeDeepWith as en,objOf as br,omit as Je,pipe as Tr,pluck as tn,range as rn,reject as on,toLower as nn,union as sn,when as an,xprod as We,zip as pn}from"ramda";import{z as T}from"zod";import{z as Ee}from"zod";var Ye=e=>!isNaN(e.getTime());var ze=Symbol("DateIn"),yr=()=>Ee.union([Ee.string().date(),Ee.string().datetime(),Ee.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ee.date().refine(Ye)).brand(ze);import{z as qo}from"zod";var Ze=Symbol("DateOut"),gr=()=>qo.date().refine(Ye).transform(e=>e.toISOString()).brand(Ze);var te=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:c=>te(c,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),d=t&&t(e,{prev:p,...i});return d?{...p,...d}:p};var hr=50,Sr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",dn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Rr=/:([A-Za-z0-9_]+)/g,cn=e=>e.match(Rr)?.map(t=>t.slice(1))||[],Or=e=>e.replace(Rr,t=>`{${t.slice(1)}}`),ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),mn=({_def:{innerType:e}},{next:t})=>t(e),un=()=>({format:"any"}),fn=({},e)=>(K(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),yn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof T.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},gn=({options:e},{next:t})=>({oneOf:e.map(t)}),hn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),xn=e=>{let[t,r]=e.filter(i=>!re(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));K(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=en((i,s)=>Array.isArray(i)&&Array.isArray(s)?Go(i,s):i===s?s:K.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=sn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=Q(t.examples||[],r.examples||[],([i,s])=>Xo(i,s))),o},bn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return xn(o)}catch{}return{allOf:o}},Tn=(e,{next:t})=>t(e.unwrap()),Sn=(e,{next:t})=>t(e.unwrap()),Rn=(e,{next:t})=>{let r=t(e.unwrap());return re(r)||(r.type=Pr(r)),r},Ar=e=>{let t=nn(_o(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},xr=e=>({type:Ar(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),On=({value:e})=>({type:Ar(e),const:e}),An=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Oe(p)?p instanceof T.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=Qe(e,r)),s.length&&(a.required=s),a},Pn=()=>({type:"null"}),Cn=({},e)=>(K(!e.isResponse,new P({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Sr}}),In=({},e)=>(K(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Sr}}),wn=({},e)=>K.fail(new P({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),En=()=>({type:"boolean"}),zn=()=>({type:"integer",format:"bigint"}),Zn=e=>e.every(t=>t instanceof T.ZodLiteral),Nn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=Qe(T.object(Ne(We(o,[t]))),r),i.required=o),i}if(e instanceof T.ZodLiteral)return{type:"object",properties:Qe(T.object({[e.value]:t}),r),required:[e.value]};if(e instanceof T.ZodUnion&&Zn(e.options)){let o=fe(s=>`${s.value}`,e.options),i=Ne(We(o,[t]));return{type:"object",properties:Qe(T.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},Mn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},vn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Ln=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(O=>O.kind==="regex"),h=f.find(O=>O.kind==="datetime"),C=m?m.regex:h?h.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let O in Z)if(Z[O]){b.format=O;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},Dn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(({kind:f})=>f==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(({kind:f})=>f==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,c?l.maximum=d:l.exclusiveMaximum=d,l},Qe=({shape:e},t)=>fe(t,e),jn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return dn?.[t]},Pr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},kn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!re(o)){let s=ke(e,jn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.any())}if(!t&&i.type==="preprocess"&&!re(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Hn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Un=(e,{next:t})=>t(e.unwrap()),Fn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},Kn=(e,{next:t})=>t(e.unwrap().shape.raw),Cr=e=>e.length?Ne(pn(rn(1,e.length+1).map(t=>`example${t}`),fe(br("value"),e))):void 0,Ir=(e,t,r=[])=>Tr(U,fe(an($o(v,Vo(Array.isArray)),Je(r))),Cr)({schema:e,variant:t?"parsed":"original",validate:!0}),Bn=(e,t)=>Tr(U,Yo(Qo(t)),tn(t),Cr)({schema:e,variant:"original",validate:!0}),ue=(e,t)=>e instanceof T.ZodObject?e:e instanceof T.ZodBranded?ue(e.unwrap(),t):e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion?e.options.map(r=>ue(r,t)).reduce((r,o)=>r.merge(o.partial()),T.object({})):e instanceof T.ZodEffects?(K(e._def.effect.type==="refinement",t),ue(e._def.schema,t)):ue(e._def.left,t).merge(ue(e._def.right,t)),wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=ue(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),f=cn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&at(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:he})=>{let D=te(l[x],{rules:{...d,...Ot},onEach:At,onMissing:Pt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),V=p==="components"?a(E(c,x),D):D;return{name:x,in:he,required:!l[x].isOptional(),description:D.description||c,schema:V,examples:Bn(r,x)}})},Ot={ZodString:Ln,ZodNumber:Dn,ZodBigInt:zn,ZodBoolean:En,ZodNull:Pn,ZodArray:Mn,ZodTuple:vn,ZodRecord:Nn,ZodObject:An,ZodLiteral:On,ZodIntersection:bn,ZodUnion:gn,ZodAny:un,ZodDefault:ln,ZodEnum:xr,ZodNativeEnum:xr,ZodEffects:kn,ZodOptional:Tn,ZodNullable:Rn,ZodDiscriminatedUnion:hn,ZodBranded:Un,ZodDate:wn,ZodCatch:mn,ZodPipeline:Hn,ZodLazy:Fn,ZodReadonly:Sn,[F]:yn,[Ae]:fn,[Ze]:In,[ze]:Cn,[J]:Kn},At=(e,{isResponse:t,prev:r})=>{if(re(r))return{};let{description:o}=e,i=e instanceof T.ZodLazy,s=r.type!==void 0,a=t&&Oe(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:U({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Pr(r)),d.length&&(c.examples=d.slice()),c},Pt=(e,t)=>K.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Rt=(e,t)=>{if(re(e))return e;let r={...e};return r.properties&&(r.properties=Je(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Je(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Rt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Rt(o,t))),r},Er=e=>re(e)?e:Je(["examples"],e),zr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${dt(i)} response ${c?l:""}`.trim()})=>{let h=Er(te(r,{rules:{...f,...Ot},onEach:At,onMissing:Pt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(E(m),h):h,examples:Ir(r,!0)};return{description:m,content:Ne(We(o,[C]))}},qn=()=>({type:"http",scheme:"basic"}),$n=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Vn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Gn=({name:e})=>({type:"apiKey",in:"header",name:e}),_n=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Yn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Qn=({flows:e={}})=>({type:"oauth2",flows:fe(t=>({...t,scopes:t.scopes||{}}),on(Jo,e))}),Zr=(e,t)=>{let r={basic:qn,bearer:$n,input:Vn,header:Gn,cookie:_n,openid:Yn,oauth2:Qn};return Ve(e,o=>r[o.type](o,t))},Xe=e=>"or"in e?e.or.map(t=>"and"in t?Wo(fe(({name:r,scopes:o})=>br(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?Xe(ut(e)):Xe({or:[e]}),Nr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=Er(Rt(te(r,{rules:{...d,...Ot},onEach:At,onMissing:Pt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(E(l),f):f,examples:Ir(r,!1,c)};return{description:l,content:Ne(We(o,[m]))}},Mr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Ct=e=>e.length<=hr?e:e.slice(0,hr-1)+"\u2026";var It=class extends Wn{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||E(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&Jn.fail(new P({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;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:i,serverUrl:s,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=je}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});ee({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[O,x]=["short","long"].map(m.getDescription.bind(m)),he=O?Ct(O):d&&x?Ct(x):void 0,D=m.getTags(),V=r.inputSources?.[b]||it[b],ne=this.ensureUniqOperationId(h,b,m.getOperationId(b)),xe=wr({...Z,inputSources:V,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:ne})}),ve={};for(let M of["positive","negative"]){let G=m.getResponses(M);for(let{mimeTypes:be,schema:S,statusCodes:R}of G)for(let A of R)ve[A]=zr({...Z,variant:M,schema:S,mimeTypes:be,statusCode:A,hasMultipleStatusCodes:G.length>1||R.length>1,description:a?.[`${M}Response`]?.call(null,{method:b,path:h,operationId:ne,statusCode:A})})}let nt=V.includes("body")?Nr({...Z,paramNames:Xn("name",xe),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:ne})}):void 0,Le=Xe(Ve(Zr(m.getSecurity(),V),M=>{let G=this.ensureUniqSecuritySchemaName(M),be=["oauth2","openIdConnect"].includes(M.type)?m.getScopes().slice():[];return this.addSecurityScheme(G,M),{name:G,scopes:be}}));this.addPath(Or(h),{[b]:{operationId:ne,summary:he,description:x,tags:D.length>0?D:void 0,parameters:xe.length>0?xe:void 0,requestBody:nt,security:Le.length>0?Le:void 0,responses:ve}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import vr from"http";var ei=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>w.json),...t}),ti=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:vr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=vr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},ri=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),oi=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await nr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=ei({fnMethod:a,requestProps:t}),d=ti({fnMethod:a,responseProps:r}),c=ri({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import z from"typescript";import L from"typescript";import{chain as Lr,toPairs as Dr}from"ramda";var n=L.factory,B=[n.createModifier(L.SyntaxKind.ExportKeyword)],ni=[n.createModifier(L.SyntaxKind.AsyncKeyword)],ii=[n.createModifier(L.SyntaxKind.PublicKeyword),n.createModifier(L.SyntaxKind.ReadonlyKeyword)],jr=[n.createModifier(L.SyntaxKind.ProtectedKeyword),n.createModifier(L.SyntaxKind.ReadonlyKeyword)],wt=n.createTemplateHead(""),ye=n.createTemplateTail(""),Et=n.createTemplateMiddle(" "),zt=e=>n.createTemplateLiteralType(wt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ye:Et))),Zt=zt(["M","P"]),et=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),tt=(e,t)=>Lr(([r,o])=>[et(n.createIdentifier(r),o,t)],Dr(e)),Nt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),kr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Hr=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),q=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],L.NodeFlags.Const),Mt=(e,t)=>n.createTypeAliasDeclaration(B,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),rt=(e,t)=>n.createTypeAliasDeclaration(B,e,void 0,t),Ur=(e,t,r)=>n.createPropertyDeclaration(ii,e,void 0,t,r),Fr=(e,t,r)=>n.createClassDeclaration(B,e,void 0,void 0,[t,...r]),Kr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Br=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(L.SyntaxKind.AnyKeyword)]),qr=(e,t,r)=>n.createInterfaceDeclaration(B,e,void 0,t,r),$r=e=>Lr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Dr(e)),vt=(e,t,r)=>n.createArrowFunction(r?ni:void 0,void 0,e.map(o=>et(o)),void 0,void 0,t),Lt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,tt({acc:void 0,key:void 0}),void 0,void 0,t),r]),Vr=(...e)=>`"${e.join(" ")}"`;var Gr=["get","post","put","delete","patch"];import g from"typescript";import{z as kt}from"zod";import $ from"typescript";var{factory:ot}=$,Dt=(e,t)=>{$.addSyntheticLeadingComment(e,$.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ge=(e,t,r)=>{let o=ot.createTypeAliasDeclaration(void 0,ot.createIdentifier(t),void 0,e);return r&&Dt(o,r),o},jt=(e,t)=>{let r=$.createSourceFile("print.ts","",$.ScriptTarget.Latest,!1,$.ScriptKind.TS);return $.createPrinter(t).printNode($.EmitHint.Unspecified,e,r)},si=/^[A-Za-z_$][A-Za-z0-9_$]*$/,_r=e=>si.test(e)?ot.createIdentifier(e):ot.createStringLiteral(e);var{factory:u}=g,ai={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},pi=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),di=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Oe(a)?a instanceof kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,_r(s),p&&o?u.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Dt(d,a.description),d});return u.createTypeLiteralNode(i)},ci=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),li=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Yr=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),mi=e=>ai?.[e.kind],ui=(e,{next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,mi(o)),a={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||g.SyntaxKind.AnyKeyword)}return o},fi=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),yi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},gi=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),hi=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),xi=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),bi=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Ti=({_def:e},{next:t})=>t(e.innerType),oe=e=>()=>u.createKeywordTypeNode(e),Si=(e,{next:t})=>t(e.unwrap()),Ri=(e,{next:t})=>t(e.unwrap()),Oi=({_def:e},{next:t})=>t(e.innerType),Ai=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Pi=()=>u.createLiteralTypeNode(u.createNull()),Ci=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,u.createLiteralTypeNode(u.createNull())),r(s,o(e)))},Ii=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof kt.ZodString?r:t instanceof kt.ZodUnion?i:o},wi=(e,{next:t})=>t(e.unwrap().shape.raw),Ei={ZodString:oe(g.SyntaxKind.StringKeyword),ZodNumber:oe(g.SyntaxKind.NumberKeyword),ZodBigInt:oe(g.SyntaxKind.BigIntKeyword),ZodBoolean:oe(g.SyntaxKind.BooleanKeyword),ZodAny:oe(g.SyntaxKind.AnyKeyword),[ze]:oe(g.SyntaxKind.StringKeyword),[Ze]:oe(g.SyntaxKind.StringKeyword),ZodNull:Pi,ZodArray:ci,ZodTuple:hi,ZodRecord:xi,ZodObject:di,ZodLiteral:pi,ZodIntersection:bi,ZodUnion:Yr,ZodDefault:Ti,ZodEnum:li,ZodNativeEnum:fi,ZodEffects:ui,ZodOptional:yi,ZodNullable:gi,ZodDiscriminatedUnion:Yr,ZodBranded:Si,ZodCatch:Oi,ZodPipeline:Ai,ZodLazy:Ci,ZodReadonly:Ri,[F]:Ii,[J]:wi},Me=(e,{brandHandling:t,ctx:r})=>te(e,{rules:{...t,...Ei},onMissing:()=>u.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),ctx:r});var Ht=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ge(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=je,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){ee({routing:t,onEndpoint:(S,R,A)=>{let ie={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Te=E(A,R,"input"),Se=Me(S.getSchema("input"),{brandHandling:r,ctx:{...ie,isResponse:!1}}),I=s?E(A,R,"positive.response"):void 0,Ut=S.getSchema("positive"),Ft=s?Me(Ut,{brandHandling:r,ctx:{...ie,isResponse:!0}}):void 0,Re=s?E(A,R,"negative.response"):void 0,Kt=S.getSchema("negative"),Bt=s?Me(Kt,{brandHandling:r,ctx:{...ie,isResponse:!0}}):void 0,qt=E(A,R,"response"),Qr=I&&Re?n.createUnionTypeNode([n.createTypeReferenceNode(I),n.createTypeReferenceNode(Re)]):Me(Ut.or(Kt),{brandHandling:r,ctx:{...ie,isResponse:!0}});this.program.push(ge(Se,Te)),Ft&&I&&this.program.push(ge(Ft,I)),Bt&&Re&&this.program.push(ge(Bt,Re)),this.program.push(ge(Qr,qt)),A!=="options"&&(this.paths.push(R),this.registry.set({method:A,path:R},{input:Te,positive:I,negative:Re,response:qt,isJson:S.getMimeTypes("positive").includes(w.json),tags:S.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Mt(this.ids.pathType,this.paths)),this.program.push(Mt(this.ids.methodType,Gr)),this.program.push(rt(this.ids.methodPathType,zt([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,z.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:S,path:R},{isJson:A,tags:ie,...Te}]of this.registry){let Se=Vr(S,R);for(let I of this.interfaces)I.kind in Te&&I.props.push(Hr(Se,Te[I.kind]));o!=="types"&&(A&&d.push(n.createPropertyAssignment(Se,n.createTrue())),c.push(n.createPropertyAssignment(Se,n.createArrayLiteralExpression(ie.map(I=>n.createStringLiteral(I))))))}for(let{id:S,props:R}of this.interfaces)this.program.push(qr(S,p,R));if(o==="types")return;let l=n.createVariableStatement(B,q(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(d))),f=n.createVariableStatement(B,q(this.ids.endpointTagsConst,n.createObjectLiteralExpression(c))),m=rt(this.ids.providerType,n.createFunctionTypeNode($r({M:this.ids.methodType,P:this.ids.pathType}),tt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Zt)}),Kr(this.ids.responseInterface,Zt))),h=rt(this.ids.implementationType,n.createFunctionTypeNode(void 0,tt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:Nt(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),Br())),C=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ye)]),b=Lt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Lt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),z.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),O=Fr(this.ids.clientClass,kr([et(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),jr)]),[Ur(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),vt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,Z]),!0))]);this.program.push(l,f,m,h,O);let x=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),he=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),D=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),V=n.createVariableStatement(void 0,q(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,ye)]),n.createObjectLiteralExpression([x,he,D])])))),ne=n.createVariableStatement(void 0,q(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),xe=n.createVariableStatement(void 0,q(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),ye)])))),[ve,nt]=["json","text"].map(S=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,S),void 0,void 0))),Le=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(wt,[n.createTemplateSpan(this.ids.methodParameter,Et),n.createTemplateSpan(this.ids.pathParameter,ye)]),z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([ve])),M=n.createVariableStatement(B,q(this.ids.exampleImplementationConst,vt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([ne,xe,V,Le,nt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),G=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),be=n.createVariableStatement(void 0,q(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(M,be,G)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:jt(r,t)).join(`
|
|
21
21
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&z.addSyntheticLeadingComment(z.addSyntheticLeadingComment(n.createEmptyStatement(),z.SyntaxKind.SingleLineCommentTrivia," Usage example:"),z.SyntaxKind.MultiLineCommentTrivia,`
|
|
22
|
-
${r}`);return this.program.concat(o||[]).map((i,s)=>
|
|
22
|
+
${r}`);return this.program.concat(o||[]).map((i,s)=>jt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
23
23
|
|
|
24
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
24
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await X("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var zi={dateIn:yr,dateOut:gr,file:Ke,upload:Yt,raw:_t};export{me as AbstractEndpoint,Ie as DependsOnMethod,It as Documentation,P as DocumentationError,Ce as EndpointsFactory,k as InputValidationError,Ht as Integration,ae as MissingPeerError,_ as OutputValidationError,se as RoutingError,we as ServeStatic,Oo as arrayEndpointsFactory,ht as arrayResultHandler,Ko as attachRouting,uo as createConfig,bt as createLogger,yt as createMiddleware,gt as createResultHandler,Bo as createServer,Ro as defaultEndpointsFactory,Pe as defaultResultHandler,zi as ez,U as getExamples,H as getMessageFromError,De as getStatusCodeFromError,oi as testEndpoint};
|
package/package.json
CHANGED