express-zod-api 22.7.0 → 22.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +0 -2
- package/dist/index.cjs +8 -8
- package/dist/index.js +8 -8
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,38 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 22
|
|
4
4
|
|
|
5
|
+
### v22.8.0
|
|
6
|
+
|
|
7
|
+
- Feature: warning about the endpoint input scheme ignoring the parameters of the route to which it is assigned:
|
|
8
|
+
- There is a technological gap between routing and endpoints, which at the same time allows an endpoint to be reused
|
|
9
|
+
across multiple routes. Therefore, there are no constraints between the route parameters and the `input` schema;
|
|
10
|
+
- This version introduces checking for such discrepancies:
|
|
11
|
+
- non-use of the path parameter or,
|
|
12
|
+
- a mistake in manually entering its name;
|
|
13
|
+
- The warning is displayed when the application is launched and NOT in production mode.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
const updateUserEndpoint = factory.build({
|
|
17
|
+
method: "patch",
|
|
18
|
+
input: z.object({
|
|
19
|
+
id: z.string(), // implies path parameter "id"
|
|
20
|
+
}),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const routing: Routing = {
|
|
24
|
+
v1: {
|
|
25
|
+
user: {
|
|
26
|
+
":username": updateUserEndpoint, // path parameter is "username" instead of "id"
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```shell
|
|
33
|
+
warn: The input schema of the endpoint is most likely missing the parameter of the path it is assigned to.
|
|
34
|
+
{ method: 'patch', path: '/v1/user/:username', param: 'username' }
|
|
35
|
+
```
|
|
36
|
+
|
|
5
37
|
### v22.7.0
|
|
6
38
|
|
|
7
39
|
- Technical release in connection with the implementation of workspaces into the project architecture.
|
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:(0,ft.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var $t=require("zod");var Vt=class{},V=class extends Vt{#e;#t;#r;constructor({input:t=$t.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof $t.z.ZodError?new J(o):o}}},ke=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Ce=class{nest(t){return Object.assign(t,{"":this})}};var We=class extends Ce{},ht=class extends We{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:l,shortDescription:g}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:l,short:g},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Cr(r)?"upload":jr(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof _t.z.ZodError?new ne(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof ke))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof _t.z.ZodError?new J(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){gt({...r,error:new se(ae(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Kt(t),a={},c=null,d=null,p=it(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(l){d=ae(l)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var Lr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Or(s,n),o)};var _=require("zod");var je={positive:200,negative:400},Ne=Object.keys(je);var Gt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},de=class extends Gt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Bt(this.#e,{variant:"positive",args:[t],statusCodes:[je.positive],mimeTypes:[v.json]})}getNegativeResponse(){return Bt(this.#t,{variant:"negative",args:[],statusCodes:[je.negative],mimeTypes:[v.json]})}},Le=new de({positive:e=>{let t=te({schema:e,pullProps:!0}),r=_.z.object({status:_.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:_.z.object({status:_.z.literal("error"),error:_.z.object({message:_.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Oe(e);return Je(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Re(a)}})}n.status(je.positive).json({status:"success",data:r})}}),xt=new de({positive:e=>{let t=te({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,n)=>xe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:_.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Oe(r);return Je(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Re(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(je.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var me=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new ke(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=Yt.z.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:l,resultHandler:g}=this,b=typeof p=="string"?[p]:p,f=typeof a=="function"?a:()=>a,R=typeof c=="string"?[c]:c||[],O=typeof d=="string"?[d]:d||[];return new ht({handler:r,middlewares:l,outputSchema:o,resultHandler:g,scopes:R,tags:O,methods:b,getOperationId:f,description:n,shortDescription:s,inputSchema:Lr(l,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Yt.z.object({}),handler:async o=>(await t(o),{})})}},Mr=new me(Le),Ur=new me(xt);var Br=j(require("ansis"),1),$r=require("node:util"),Wt=require("node:perf_hooks");var Q=require("ansis"),Hr=require("ramda");var Jt={debug:Q.blue,info:Q.green,warn:(0,Q.hex)("#FFA500"),error:Q.red,ctx:Q.cyanBright},bt={debug:10,info:20,warn:30,error:40},Kr=e=>xe(e)&&Object.keys(bt).some(t=>t in e),Dr=e=>e in bt,Fr=(e,t)=>bt[e]<bt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Me=(0,Hr.memoizeWith)((e,t)=>`${e}${t}`,gn),qr=e=>e<1e-6?Me("nanosecond",3).format(e/1e-6):e<.001?Me("nanosecond").format(e/1e-6):e<1?Me("microsecond").format(e/.001):e<1e3?Me("millisecond").format(e):e<6e4?Me("second",2).format(e/1e3):Me("minute",2).format(e/6e4);var Ue=class e{config;constructor({color:t=Br.default.isSupported(),level:r=Ie()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return(0,$r.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Fr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Jt.ctx(s):s),d.push(c?`${Jt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Wt.performance.now();return()=>{let o=Wt.performance.now()-r,{message:n,severity:s="debug",formatter:a=qr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Ke=require("ramda");var He=class extends Ce{entries;constructor(t){super();let r=[],o=(0,Ke.keys)(t);for(let n of o){let s=t[n];s&&r.push([n,s,(0,Ke.reject)((0,Ke.equals)(n),o)])}this.entries=Object.freeze(r)}};var Vr=j(require("express"),1),De=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Vr.default.static(...this.params))}};var Tt=j(require("express"),1),lo=j(require("node:http"),1),uo=j(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>j(require(e))))[t]}catch{}throw new ze(e)};var Gr=j(require("http-errors"),1);var St=class{constructor(t){this.logger=t}#e=new WeakSet;check(t,r){if(!this.#e.has(t)){if(t.getRequestType()==="json")try{qt(t.getSchema("input"),"in")}catch(o){this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ne)for(let{mimeTypes:n,schema:s}of t.getResponses(o))if(n?.includes(v.json))try{qt(s,"out")}catch(a){this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:a}))}this.#e.add(t)}}};var _r=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new ge(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),qe=({routing:e,onEndpoint:t,onStatic:r})=>{let o=_r(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof We){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof De)r&&s.apply(n,r);else if(s instanceof He)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new ge(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(..._r(s,n))}};var hn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,Gr.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Qt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new St(t()),a=new Map;if(qe({routing:o,onEndpoint:(d,p,l,g)=>{Ie()||s.check(d,{path:p,method:l});let b=n?.[d.getRequestType()]||[],f=async(R,O)=>{let M=t(R);if(r.cors){let z={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...g||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:R,endpoint:d,logger:M,defaultHeaders:z}):z;for(let H in Z)O.set(H,Z[H])}return d.execute({request:R,response:O,logger:M,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...b,f),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...b,f)},onStatic:e.use.bind(e)}),r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,hn(p))};var Qe=j(require("http-errors"),1);var eo=require("node:timers/promises");var Yr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Jr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Wr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Qr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Xr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Yr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let d=async()=>{for(let p of e)p.on("request",Qr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Wr(p)||Jr(p))&&a(p);for await(let p of(0,eo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Xr))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,Qe.isHttpError)(r)?r:(0,Qe.default)(400,ae(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Qe.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){gt({response:o,logger:s,error:new se(ae(a),n)})}},xn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},bn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await Fe("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(g){return p(g)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:bn(l)})(c,d,p)}),o&&a.push(xn(o)),a},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[x]={logger:s}),n()},ao=e=>t=>t?.res?.locals[x]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
"use strict";var rn=Object.create;var st=Object.defineProperty;var on=Object.getOwnPropertyDescriptor;var nn=Object.getOwnPropertyNames;var sn=Object.getPrototypeOf,an=Object.prototype.hasOwnProperty;var pn=(e,t)=>{for(var r in t)st(e,r,{get:t[r],enumerable:!0})},Rr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of nn(t))!an.call(e,n)&&n!==r&&st(e,n,{get:()=>t[n],enumerable:!(o=on(t,n))||o.enumerable});return e};var C=(e,t,r)=>(r=e!=null?rn(sn(e)):{},Rr(t||!e||!e.__esModule?st(r,"default",{value:e,enumerable:!0}):r,e)),cn=e=>Rr(st({},"__esModule",{value:!0}),e);var Js={};pn(Js,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>At,DocumentationError:()=>q,EndpointsFactory:()=>ue,EventStreamFactory:()=>Lt,InputValidationError:()=>Y,Integration:()=>Nt,Middleware:()=>V,MissingPeerError:()=>Ie,OutputValidationError:()=>se,ResultHandler:()=>le,RoutingError:()=>he,ServeStatic:()=>Fe,arrayEndpointsFactory:()=>Dr,arrayResultHandler:()=>St,attachRouting:()=>bo,createConfig:()=>Ar,createServer:()=>So,defaultEndpointsFactory:()=>Kr,defaultResultHandler:()=>Me,ensureHttpError:()=>Re,ez:()=>tn,getExamples:()=>re,getMessageFromError:()=>ae,testEndpoint:()=>qo,testMiddleware:()=>Bo});module.exports=cn(Js);var K=require("ramda"),Se=require("zod");var te=require("ramda"),Kt=require("zod");var I={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var he=class extends Error{name="RoutingError"},q=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},it=class extends Error{name="IOSchemaError"},se=class extends it{constructor(r){super(ae(r),{cause:r});this.cause=r}name="OutputValidationError"},Y=class extends it{constructor(r){super(ae(r),{cause:r});this.cause=r}name="InputValidationError"},ie=class extends Error{constructor(r,o){super(ae(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ie=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Dt=/:([A-Za-z0-9_]+)/g,at=e=>e.match(Dt)?.map(t=>t.slice(1))||[],dn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(I.upload);return"files"in e&&r},Ft={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},mn=["body","query","params"],qt=e=>e.method.toLowerCase(),pt=(e,t={})=>{let r=qt(e);return r==="options"?{}:(t[r]||Ft[r]||mn).filter(o=>o==="files"?dn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},pe=e=>e instanceof Error?e:new Error(String(e)),ae=e=>e instanceof Kt.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof se?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,ln=e=>Object.entries(e.shape).reduce((t,[r,o])=>xe(t,(o._def[x]?.examples||[]).map((0,te.objOf)(r)),([n,s])=>({...n,...s})),[]),re=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[x]?.examples||[];if(!n.length&&o&&e instanceof Kt.z.ZodObject&&(n=ln(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},xe=(e,t,r)=>e.length&&t.length?(0,te.xprod)(e,t).map(r):e.concat(t),Ge=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Bt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ce=(...e)=>{let t=(0,te.chain)(o=>o.split(/[^A-Z0-9]/gi),e);return(0,te.chain)(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Bt).join("")},ct=(e,t)=>{try{return typeof e.parse(t)}catch{return}},be=e=>typeof e=="object"&&e!==null,ve=(0,te.memoizeWith)(()=>"static",()=>process.env.NODE_ENV==="production"),dt=e=>e.length?e:void 0;var mt=require("ramda"),x=Symbol.for("express-zod-api"),lt=e=>{let t=e.describe(e.description);return t._def[x]=(0,mt.clone)(t._def[x])||{examples:[]},t},Pr=(e,t)=>{if(!(x in e._def))return t;let r=lt(t);return r._def[x].examples=xe(r._def[x].examples,e._def[x].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?(0,mt.mergeDeepRight)({...o},{...n}):n),r};var un=function(e){let t=lt(this);return t._def[x].examples.push(e),t},yn=function(e){let t=lt(this);return t._def[x].defaultLabel=e,t},fn=function(e){return new Se.z.ZodBranded({typeName:Se.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[x]:{examples:[],...(0,K.clone)(this._def[x]),brand:e}})},gn=function(e){let t=typeof e=="function"?e:(0,K.pipe)(K.toPairs,(0,K.map)(([n,s])=>(0,K.pair)(e[String(n)]||n,s)),K.fromPairs),r=t((0,K.clone)(this.shape)),o=Se.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};x in globalThis||(globalThis[x]=!0,Object.defineProperties(Se.z.ZodType.prototype,{example:{get(){return un.bind(this)}},brand:{set(){},get(){return fn.bind(this)}}}),Object.defineProperty(Se.z.ZodDefault.prototype,"label",{get(){return yn.bind(this)}}),Object.defineProperty(Se.z.ZodObject.prototype,"remap",{get(){return gn.bind(this)}}));function Ar(e){return e}var Yt=require("zod");var Jt=require("zod");var j=require("node:assert/strict");var Ze=require("zod");var ut=e=>!isNaN(e.getTime());var Te=Symbol("DateIn"),wr=()=>Ze.z.union([Ze.z.string().date(),Ze.z.string().datetime(),Ze.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ze.z.date().refine(ut)).brand(Te);var Er=require("zod");var Oe=Symbol("DateOut"),zr=()=>Er.z.date().refine(ut).transform(e=>e.toISOString()).brand(Oe);var Je=require("zod"),Q=Symbol("File"),Ir=Je.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),hn={buffer:()=>Ir.brand(Q),string:()=>Je.z.string().brand(Q),binary:()=>Ir.or(Je.z.string()).brand(Q),base64:()=>Je.z.string().base64().brand(Q)};function yt(e){return hn[e||"string"]()}var vr=require("zod");var de=Symbol("Raw"),Zr=(e={})=>vr.z.object({raw:yt("buffer")}).extend(e).brand(de);var kr=require("zod"),ke=Symbol("Upload"),Cr=()=>kr.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 jr=(e,{next:t})=>e.options.some(t),xn=({_def:e},{next:t})=>[e.left,e.right].some(t),ft=(e,{next:t})=>t(e.unwrap()),$t={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:jr,ZodDiscriminatedUnion:jr,ZodIntersection:xn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:ft,ZodNullable:ft,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=$t,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[x]?.brand]||r[e._def.typeName]:void 0;return s?s(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Nr=e=>gt(e,{condition:t=>t._def[x]?.brand===ke}),Lr=e=>gt(e,{condition:t=>t._def[x]?.brand===de,maxDepth:3}),Mr=(e,t)=>{let r=new WeakSet;return gt(e,{maxDepth:300,rules:{...$t,ZodBranded:ft,ZodReadonly:ft,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:$t.ZodEffects}[t],ZodNaN:()=>(0,j.fail)("z.nan()"),ZodSymbol:()=>(0,j.fail)("z.symbol()"),ZodFunction:()=>(0,j.fail)("z.function()"),ZodMap:()=>(0,j.fail)("z.map()"),ZodSet:()=>(0,j.fail)("z.set()"),ZodBigInt:()=>(0,j.fail)("z.bigint()"),ZodVoid:()=>(0,j.fail)("z.void()"),ZodPromise:()=>(0,j.fail)("z.promise()"),ZodNever:()=>(0,j.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,j.fail)("z.date()"),[Oe]:()=>t==="in"&&(0,j.fail)("ez.dateOut()"),[Te]:()=>t==="out"&&(0,j.fail)("ez.dateIn()"),[de]:()=>t==="out"&&(0,j.fail)("ez.raw()"),[ke]:()=>t==="out"&&(0,j.fail)("ez.upload()"),[Q]:()=>!1}})};var ht=C(require("http-errors"),1);var We=C(require("http-errors"),1),Ur=require("zod");var Vt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Ur.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ie(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},Ye=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Re=e=>(0,We.isHttpError)(e)?e:(0,We.default)(e instanceof Y?400:500,ae(e),{cause:e.cause||e}),Pe=e=>ve()&&!e.expose?(0,We.default)(e.statusCode).message:e.message;var xt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Pe((0,ht.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:(0,ht.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var _t=require("zod");var Gt=class{},V=class extends Gt{#e;#t;#r;constructor({input:t=_t.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof _t.z.ZodError?new Y(o):o}}},Ce=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var je=class{nest(t){return Object.assign(t,{"":this})}};var Qe=class extends je{},bt=class extends Qe{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:l,shortDescription:g}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:l,short:g},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Nr(r)?"upload":Lr(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof Jt.z.ZodError?new se(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof Ce))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof Jt.z.ZodError?new Y(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){xt({...r,error:new ie(pe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=qt(t),a={},c=null,d=null,p=pt(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(l){d=pe(l)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var me=require("zod");var Hr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Pr(s,n),o)},_=e=>e instanceof me.z.ZodObject?e:e instanceof me.z.ZodBranded?_(e.unwrap()):e instanceof me.z.ZodUnion||e instanceof me.z.ZodDiscriminatedUnion?e.options.map(t=>_(t)).reduce((t,r)=>t.merge(r.partial()),me.z.object({})):e instanceof me.z.ZodEffects?_(e._def.schema):e instanceof me.z.ZodPipeline?_(e._def.in):_(e._def.left).merge(_(e._def.right));var G=require("zod");var Ne={positive:200,negative:400},Le=Object.keys(Ne);var Wt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},le=class extends Wt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Vt(this.#e,{variant:"positive",args:[t],statusCodes:[Ne.positive],mimeTypes:[I.json]})}getNegativeResponse(){return Vt(this.#t,{variant:"negative",args:[],statusCodes:[Ne.negative],mimeTypes:[I.json]})}},Me=new le({positive:e=>{let t=re({schema:e,pullProps:!0}),r=G.z.object({status:G.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:G.z.object({status:G.z.literal("error"),error:G.z.object({message:G.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Re(e);return Ye(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Pe(a)}})}n.status(Ne.positive).json({status:"success",data:r})}}),St=new le({positive:e=>{let t=re({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof G.z.ZodArray?e.shape.items:G.z.array(G.z.any());return t.reduce((o,n)=>be(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:G.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Re(r);return Ye(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Pe(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Ne.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ue=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ce(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=Yt.z.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:l,resultHandler:g}=this,b=typeof p=="string"?[p]:p,f=typeof a=="function"?a:()=>a,R=typeof c=="string"?[c]:c||[],O=typeof d=="string"?[d]:d||[];return new bt({handler:r,middlewares:l,outputSchema:o,resultHandler:g,scopes:R,tags:O,methods:b,getOperationId:f,description:n,shortDescription:s,inputSchema:Hr(l,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Yt.z.object({}),handler:async o=>(await t(o),{})})}},Kr=new ue(Me),Dr=new ue(St);var _r=C(require("ansis"),1),Gr=require("node:util"),Xt=require("node:perf_hooks");var X=require("ansis"),Fr=require("ramda");var Qt={debug:X.blue,info:X.green,warn:(0,X.hex)("#FFA500"),error:X.red,ctx:X.cyanBright},Tt={debug:10,info:20,warn:30,error:40},qr=e=>be(e)&&Object.keys(Tt).some(t=>t in e),Br=e=>e in Tt,$r=(e,t)=>Tt[e]<Tt[t],bn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ue=(0,Fr.memoizeWith)((e,t)=>`${e}${t}`,bn),Vr=e=>e<1e-6?Ue("nanosecond",3).format(e/1e-6):e<.001?Ue("nanosecond").format(e/1e-6):e<1?Ue("microsecond").format(e/.001):e<1e3?Ue("millisecond").format(e):e<6e4?Ue("second",2).format(e/1e3):Ue("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=_r.default.isSupported(),level:r=ve()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return(0,Gr.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||$r(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Qt.ctx(s):s),d.push(c?`${Qt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Xt.performance.now();return()=>{let o=Xt.performance.now()-r,{message:n,severity:s="debug",formatter:a=Vr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var De=require("ramda");var Ke=class extends je{entries;constructor(t){super();let r=[],o=(0,De.keys)(t);for(let n of o){let s=t[n];s&&r.push([n,s,(0,De.reject)((0,De.equals)(n),o)])}this.entries=Object.freeze(r)}};var Jr=C(require("express"),1),Fe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Jr.default.static(...this.params))}};var Rt=C(require("express"),1),go=C(require("node:http"),1),ho=C(require("node:https"),1);var qe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>C(require(e))))[t]}catch{}throw new Ie(e)};var Qr=C(require("http-errors"),1);var Wr=require("ramda");var Ot=class{constructor(t){this.logger=t;this.#e=(0,Wr.tryCatch)(Mr)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Le){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(I.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=at(t);if(s.length===0)return;let a=n?.shape||_(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Yr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new he(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Be=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Yr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Qe){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Fe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new he(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Yr(s,n))}};var Sn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,Qr.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},er=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new Ot(t()),a=new Map;if(Be({routing:o,onEndpoint:(d,p,l,g)=>{ve()||(s?.checkJsonCompat(d,{path:p,method:l}),s?.checkPathParams(p,d,{method:l}));let b=n?.[d.getRequestType()]||[],f=async(R,O)=>{let L=t(R);if(r.cors){let E={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...g||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},v=typeof r.cors=="function"?await r.cors({request:R,endpoint:d,logger:L,defaultHeaders:E}):E;for(let U in v)O.set(U,v[U])}return d.execute({request:R,response:O,logger:L,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...b,f),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...b,f)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,Sn(p))};var Xe=C(require("http-errors"),1);var no=require("node:timers/promises");var Xr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",eo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",to=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ro=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),oo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var so=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Xr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let d=async()=>{for(let p of e)p.on("request",ro);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(to(p)||eo(p))&&a(p);for await(let p of(0,no.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(oo))};return{sockets:n,shutdown:()=>o??=d()}};var io=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,Xe.isHttpError)(r)?r:(0,Xe.default)(400,pe(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),ao=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Xe.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){xt({response:o,logger:s,error:new ie(pe(a),n)})}},Tn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},On=e=>({log:e.debug.bind(e)}),po=async({getLogger:e,config:t})=>{let r=await qe("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(g){return p(g)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:On(l)})(c,d,p)}),o&&a.push(Tn(o)),a},co=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},mo=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[x]={logger:s}),n()},lo=e=>t=>t?.res?.locals[x]?.logger||e,uo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),yo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=so(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var B=require("ansis"),fo=e=>{if(e.columns<132)return;let t=(0,B.italic)("Proudly supports transgender community.".padStart(109)),r=(0,B.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,B.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,B.italic)("for Tai".padEnd(20)),s=(0,B.hex)("#F5A9B8"),a=(0,B.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(B.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill(B.gray,12,13),d=`
|
|
4
4
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
5
5
|
888 d88P 888 d88888 888 Y88b 888
|
|
6
6
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -15,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,l)=>c[l]?c[l](p):p).join(`
|
|
18
|
-
`))};var yo=e=>{e.startupLogo!==!1&&mo(process.stdout);let t=e.errorHandler||Le,r=Kr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v22.7.0 (CJS)",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},a=oo(s),c=ro(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},fo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=yo(e);return Qt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},go=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=yo(e),c=(0,Tt.default)().disable("x-powered-by").use(a);if(e.compression){let b=await Fe("compression");c.use(b(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Tt.default.json()],raw:[e.rawParser||Tt.default.raw(),so],upload:e.upload?await no({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Qt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],l=(b,f)=>()=>b.listen(f,()=>r.info("Listening",f)),g=[];if(e.http){let b=lo.default.createServer(c);p.push(b),g.push(l(b,e.http.listen))}if(e.https){let b=uo.default.createServer(e.https.options,c);p.push(b),g.push(l(b,e.https.listen))}return e.gracefulShutdown&&co({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:g.map(b=>b())}};var Mo=require("openapi3-ts/oas31"),Uo=require("ramda");var T=require("ramda");var ho=e=>xe(e)&&"or"in e,xo=e=>xe(e)&&"and"in e,Xt=e=>!xo(e)&&!ho(e),bo=e=>{let t=(0,T.filter)(Xt,e),r=(0,T.chain)((0,T.prop)("and"),(0,T.filter)(xo,e)),[o,n]=(0,T.partition)(Xt,r),s=(0,T.concat)(t,o),a=(0,T.filter)(ho,e);return(0,T.map)((0,T.prop)("or"),(0,T.concat)(a,n)).reduce((d,p)=>he(d,(0,T.map)(l=>Xt(l)?[l]:l.and,p),([l,g])=>(0,T.concat)(l,g)),(0,T.reject)(T.isEmpty,[s]))};var re=require("openapi3-ts/oas31"),m=require("ramda"),P=require("zod");var Pe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[x]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>Pe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var So=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var To=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Tn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Po=/:([A-Za-z0-9_]+)/g,On=/^\d{4}-\d{2}-\d{2}$/,Rn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Pn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,An=e=>e.match(Po)?.map(t=>t.slice(1))||[],Ao=e=>e.replace(Po,t=>`{${t.slice(1)}}`),wn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),En=({_def:{innerType:e}},{next:t})=>t(e),zn=()=>({format:"any"}),In=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},vn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof P.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Zn=({options:e},{next:t})=>({oneOf:e.map(t)}),kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Cn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},jn=e=>{let[t,r]=e.filter(re.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Cn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=he(t.examples||[],r.examples||[],([n,s])=>(0,m.mergeDeepRight)(n,s))),o},Nn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return jn(o)}catch{}return{allOf:o}},Ln=(e,{next:t})=>t(e.unwrap()),Mn=(e,{next:t})=>t(e.unwrap()),Un=(e,{next:t})=>{let r=t(e.unwrap());return(0,re.isSchemaObject)(r)&&(r.type=Eo(r)),r},wo=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Oo=e=>({type:wo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Hn=({value:e})=>({type:wo(e),const:e}),Kn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&_e(c)?c instanceof P.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Ot(e,r)),s.length&&(a.required=s),a},Dn=()=>({type:"null"}),Fn=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ro}}},qn=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}}},Bn=({},e)=>{throw new q(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},$n=()=>({type:"boolean"}),Vn=()=>({type:"integer",format:"bigint"}),_n=e=>e.every(t=>t instanceof P.z.ZodLiteral),Gn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof P.z.ZodEnum||e instanceof P.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Ot(P.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof P.z.ZodLiteral)return{type:"object",properties:Ot(P.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof P.z.ZodUnion&&_n(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:Ot(P.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Yn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Jn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Wn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:g,isDate:b,isTime:f,isBase64:R,isNANOID:O,isBase64url:M,isDuration:U,_def:{checks:S}})=>{let z=S.find(C=>C.kind==="regex"),Z=S.find(C=>C.kind==="datetime"),H=S.some(C=>C.kind==="jwt"),k=S.find(C=>C.kind==="length"),I={type:"string"},ye={"date-time":l,byte:R,base64url:M,date:b,time:f,duration:U,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:O,jwt:H,ip:d,cidr:g,emoji:p};for(let C in ye)if(ye[C]){I.format=C;break}return k&&([I.minLength,I.maxLength]=[k.value,k.value]),r!==null&&(I.minLength=r),o!==null&&(I.maxLength=o),b&&(I.pattern=On.source),f&&(I.pattern=Rn.source),l&&(I.pattern=Pn(Z?.offset).source),z&&(I.pattern=z.regex.source),I},Qn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(g=>g.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(g=>g.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,p?l.maximum=d:l.exclusiveMaximum=d,l},Ot=({shape:e},t)=>(0,m.map)(t,e),Xn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Tn?.[t]},Eo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",es=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,re.isSchemaObject)(o)){let s=at(e,Xn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(P.z.any())}if(!t&&n.type==="preprocess"&&(0,re.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ts=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),rs=(e,{next:t})=>t(e.unwrap()),os=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ns=(e,{next:t})=>t(e.unwrap().shape.raw),zo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,Io=(e,t,r=[])=>(0,m.pipe)(te,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),zo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ss=(e,t)=>(0,m.pipe)(te,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),zo)({schema:e,variant:"original",validate:!0,pullProps:!0}),le=e=>e instanceof P.z.ZodObject?e:e instanceof P.z.ZodBranded?le(e.unwrap()):e instanceof P.z.ZodUnion||e instanceof P.z.ZodDiscriminatedUnion?e.options.map(t=>le(t)).reduce((t,r)=>t.merge(r.partial()),P.z.object({})):e instanceof P.z.ZodEffects?le(e._def.schema):e instanceof P.z.ZodPipeline?le(e._def.in):le(e._def.left).merge(le(e._def.right)),is=(e,t)=>t?.includes(e)||e.startsWith("x-")||So.includes(e),vo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let l=le(r),g=An(e),b=o.includes("query"),f=o.includes("params"),R=o.includes("headers"),O=S=>f&&g.includes(S),M=(0,m.chain)((0,m.filter)(S=>S.type==="header"),d??[]).map(({name:S})=>S),U=S=>R&&(c?.(S,t,e)??is(S,M));return Object.entries(l.shape).reduce((S,[z,Z])=>{let H=O(z)?"path":U(z)?"header":b?"query":void 0;if(!H)return S;let k=Pe(Z,{rules:{...a,...tr},onEach:rr,onMissing:or,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),I=s==="components"?n(Z,k,pe(p,z)):k;return S.concat({name:z,in:H,required:!Z.isOptional(),description:k.description||p,schema:I,examples:ss(l,z)})},[])},tr={ZodString:Wn,ZodNumber:Qn,ZodBigInt:Vn,ZodBoolean:$n,ZodNull:Dn,ZodArray:Yn,ZodTuple:Jn,ZodRecord:Gn,ZodObject:Kn,ZodLiteral:Hn,ZodIntersection:Nn,ZodUnion:Zn,ZodAny:zn,ZodDefault:wn,ZodEnum:Oo,ZodNativeEnum:Oo,ZodEffects:es,ZodOptional:Ln,ZodNullable:Un,ZodDiscriminatedUnion:kn,ZodBranded:rs,ZodDate:Bn,ZodCatch:En,ZodPipeline:ts,ZodLazy:os,ZodReadonly:Mn,[W]:vn,[Ze]:In,[Te]:qn,[Se]:Fn,[ce]:ns},rr=(e,{isResponse:t,prev:r})=>{if((0,re.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof P.z.ZodLazy,s=r.type!==void 0,a=t&&_e(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=Eo(r)),!n){let p=te({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},or=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},er=(e,t)=>{if((0,re.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>er(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>er(o,t))),r},Zo=e=>(0,re.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),ko=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${Dt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let g=Zo(Pe(r,{rules:{...p,...tr},onEach:rr,onMissing:or,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b={schema:a==="components"?s(r,g,pe(l)):g,examples:Io(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[b]))}},as=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ps=({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},cs=({name:e})=>({type:"apiKey",in:"header",name:e}),ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ms=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ls=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Co=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?as(o):o.type==="input"?ps(o,t):o.type==="header"?cs(o):o.type==="cookie"?ds(o):o.type==="openid"?ms(o):ls(o);return e.map(o=>o.map(r))},jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),No=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=Zo(er(Pe(r,{rules:{...a,...tr},onEach:rr,onMissing:or,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:s==="components"?n(r,p,pe(d)):p,examples:Io(le(r),!1,c)};return{description:d,content:{[o]:l}}},Lo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),nr=e=>e.length<=To?e:e.slice(0,To-1)+"\u2026";var Rt=class extends Mo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||pe(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});qe({routing:t,onEndpoint:(f,R,O)=>{let M={path:R,method:O,endpoint:f,composition:g,brandHandling:c,makeRef:this.makeRef.bind(this)},[U,S]=["short","long"].map(f.getDescription.bind(f)),z=U?nr(U):l&&S?nr(S):void 0,Z=r.inputSources?.[O]||Ht[O],H=this.ensureUniqOperationId(R,O,f.getOperationId(O)),k=bo(f.getSecurity()),I=vo({...M,inputSources:Z,isHeader:p,security:k,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:R,operationId:H})}),ye={};for(let oe of Ne){let fe=f.getResponses(oe);for(let{mimeTypes:Lt,schema:rt,statusCodes:ot}of fe)for(let Mt of ot)ye[Mt]=ko({...M,variant:oe,schema:rt,mimeTypes:Lt,statusCode:Mt,hasMultipleStatusCodes:fe.length>1||ot.length>1,description:a?.[`${oe}Response`]?.call(null,{method:O,path:R,operationId:H,statusCode:Mt})})}let C=Z.includes("body")?No({...M,paramNames:(0,Uo.pluck)("name",I),schema:f.getSchema("input"),mimeType:v[f.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:R,operationId:H})}):void 0,Nt=jo(Co(k,Z),f.getScopes(),oe=>{let fe=this.ensureUniqSecuritySchemaName(oe);return this.addSecurityScheme(fe,oe),fe});this.addPath(Ao(R),{[O]:{operationId:H,summary:z,description:S,tags:pt(f.getTags()),parameters:pt(I),requestBody:C,security:pt(Nt),responses:ye}})}}),d&&(this.rootDoc.tags=Lo(d))}};var Pt=require("node-mocks-http"),us=e=>(0,Pt.createRequest)({...e,headers:{"content-type":v.json,...e?.headers}}),ys=e=>(0,Pt.createResponse)(e),fs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Ho=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=us(e),s=ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=fs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Ko=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Ho(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Do=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Ho(o),d=it(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(ae(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var Go=require("ramda"),tt=j(require("typescript"),1),Yo=require("zod");var Vo=require("ramda"),Y=j(require("typescript"),1);var Fo=["get","post","put","delete","patch"];var Be=require("ramda"),u=j(require("typescript"),1),i=u.default.factory,At=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],gs=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],Xe={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},sr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),ir=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ar=e=>typeof e=="string"&&hs.test(e)?i.createIdentifier(e):E(e),wt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Et=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?y(t):void 0,o),$e=e=>Object.entries(e).map(([t,r])=>Et(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),pr=(e,t=[])=>i.createConstructorDeclaration(Xe.public,e,i.createBlock(t)),y=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&(0,Be.map)(y,t)):e,cr=y("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ae=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,ar(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,y(t));return o?sr(n,o):n},dr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),mr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&At,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?y(r):void 0,t)],u.default.NodeFlags.Const)),lr=(e,t)=>X(e,i.createUnionTypeNode((0,Be.map)(F,t)),{expose:!0}),X=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?At:void 0,e,n&&gr(n),t);return o?sr(s,o):s},qo=(e,t)=>i.createPropertyDeclaration(Xe.public,e,void 0,y(t),void 0),ur=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Xe.public,void 0,e,void 0,o&&gr(o),t,n,i.createBlock(r)),yr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(At,e,r&&gr(r),void 0,t),fr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,y(e)),zt=e=>y(Promise.name,[e]),It=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?At:void 0,e,void 0,void 0,t);return o?sr(n,o):n},gr=e=>(Array.isArray(e)?e.map(t=>(0,Be.pair)(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?y(o):void 0,n?y(n):void 0)}),we=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?(0,Be.map)(Et,e):$e(e),void 0,void 0,t),A=e=>e,et=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),w=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ve=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),vt=(e,t)=>y("Extract",[e,t]),hr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),G=(e,t)=>i.createIndexedAccessTypeNode(y(e),y(t)),Bo=e=>i.createUnionTypeNode([y(e),zt(e)]),xr=(e,t)=>i.createFunctionTypeNode(void 0,$e(e),y(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(E(e)),xs=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],$o=e=>xs.includes(e.kind);var Zt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=lr("Method",Fo);someOfType=X("SomeOf",G("T",fr("T")),{params:["T"]});requestType=X("Request",fr(this.interfaces.input),{expose:!0});someOf=({name:t})=>y(this.someOfType.name,[t]);makePathType=()=>lr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>It(this.interfaces[t],Array.from(this.registry).map(([r,o])=>Ae(r,o[t])),{expose:!0}));makeEndpointTags=()=>L("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(ar(t),i.createArrayLiteralExpression((0,Vo.map)(E,r))))),{expose:!0});makeImplementationType=()=>X(this.ids.implementationType,xr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:cr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},zt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.ids.parseRequestFn,we({[this.ids.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(w(this.ids.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([y(this.methodType.name),y(this.ids.pathType)]))));makeSubstituteFn=()=>L(this.ids.substituteFn,we({[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:cr},i.createBlock([L(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],Y.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([hr(this.ids.pathParameter,w(this.ids.pathParameter,A("replace"))(wt(":",[this.ids.keyParameter]),we([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),y("const")))])));makeProvider=()=>ur(this.ids.provideMethod,$e({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:G(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[L(mr(this.ids.methodParameter,this.ids.pathParameter),w(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(w(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(w(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:zt(G(this.interfaces.response,"K"))});makeClientClass=t=>yr(t,[pr([Et(this.ids.implementationArgument,{type:y(this.ids.implementationType,["T"]),mod:Xe.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>wt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,wt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),w(this.ids.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),et(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(v.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(A("body"),et(this.ids.hasBodyConst,w(JSON[Symbol.toStringTag],A("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=L(this.ids.responseConst,i.createAwaitExpression(w(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=L(this.ids.hasBodyConst,i.createLogicalNot(w(i.createArrayLiteralExpression([E("get"),E("delete")]),A("includes"))(this.ids.methodParameter))),a=L(this.ids.searchParamsConst,et(this.ids.hasBodyConst,E(""),this.makeSearchParams(this.ids.paramsArgument))),c=L(this.ids.contentTypeConst,w(this.ids.responseConst,A("headers"),A("get"))(E("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=L(this.ids.isJsonConst,w(this.ids.contentTypeConst,A("startsWith"))(E(v.json))),l=i.createReturnStatement(w(this.ids.responseConst,et(this.ids.isJsonConst,E(A("json")),E(A("text"))))());return L(this.ids.defaultImplementationConst,we([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>pr($e({request:"K",params:G(this.interfaces.input,"K")}),[L(mr(this.ids.pathParameter,this.ids.restConst),w(this.ids.substituteFn)(i.createElementAccessExpression(w(this.ids.parseRequestFn)(this.ids.requestParameter),E(1)),this.ids.paramsArgument)),L(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),hr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([Ae(A("event"),t)]);makeOnMethod=()=>ur(this.ids.onMethod,$e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:xr({[this.ids.dataParameter.text]:G(vt("R",dr(this.makeEventNarrow("E"))),F(A("data")))},Bo(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(w(i.createThis(),this.ids.sourceProp,A("addEventListener"))(this.ids.eventParameter,we([this.ids.msgParameter],w(this.ids.handlerParameter)(w(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,y(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:G("R",F(A("event")))}});makeSubscriptionClass=t=>yr(t,[qo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:vt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(y(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:vt(G(this.interfaces.positive,"K"),dr(this.makeEventNarrow(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.ids.clientConst,Ve(t)),w(this.ids.clientConst,this.ids.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),w(Ve(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(E("time"),we(["time"],i.createBlock([])))]};var K=require("ramda"),h=j(require("typescript"),1),kt=require("zod");var{factory:$}=h.default,bs={[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},br={name:(0,K.path)(["name","text"]),type:(0,K.path)(["type"]),optional:(0,K.path)(["questionToken"])},Ss=({value:e})=>F(e),Ts=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&_e(a)?a instanceof kt.z.ZodOptional:a.isOptional();return Ae(s,r(a),{isOptional:c&&o,comment:a.description})});return $.createTypeLiteralNode(n)},Os=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Rs=({options:e})=>$.createUnionTypeNode(e.map(F)),_o=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set($o(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},Ps=e=>bs?.[e.kind],As=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=at(e,Ps(o)),s={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return y(n&&s[n]||h.default.SyntaxKind.AnyKeyword)}return o},ws=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),Es=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,y(h.default.SyntaxKind.UndefinedKeyword)]):o},zs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),Is=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),vs=({keySchema:e,valueSchema:t},{next:r})=>y("Record",[e,t].map(r)),Zs=e=>{if(!e.every(h.default.isTypeLiteralNode))throw new Error("Not objects");let r=(0,K.chain)((0,K.prop)("members"),e),o=(0,K.uniqWith)((...n)=>{if(!(0,K.eqBy)(br.name,...n))return!1;if((0,K.eqBy)(br.type,...n)&&(0,K.eqBy)(br.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return $.createTypeLiteralNode(o)},ks=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Zs(o)}catch{}return $.createIntersectionTypeNode(o)},Cs=({_def:e},{next:t})=>t(e.innerType),ue=e=>()=>y(e),js=(e,{next:t})=>t(e.unwrap()),Ns=(e,{next:t})=>t(e.unwrap()),Ls=({_def:e},{next:t})=>t(e.innerType),Ms=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Us=()=>F(null),Hs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ks=e=>{let t=e.unwrap(),r=y(h.default.SyntaxKind.StringKeyword),o=y("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof kt.z.ZodString?r:t instanceof kt.z.ZodUnion?n:o},Ds=(e,{next:t})=>t(e.unwrap().shape.raw),Fs={ZodString:ue(h.default.SyntaxKind.StringKeyword),ZodNumber:ue(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ue(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ue(h.default.SyntaxKind.BooleanKeyword),ZodAny:ue(h.default.SyntaxKind.AnyKeyword),ZodUndefined:ue(h.default.SyntaxKind.UndefinedKeyword),[Se]:ue(h.default.SyntaxKind.StringKeyword),[Te]:ue(h.default.SyntaxKind.StringKeyword),ZodNull:Us,ZodArray:Os,ZodTuple:Is,ZodRecord:vs,ZodObject:Ts,ZodLiteral:Ss,ZodIntersection:ks,ZodUnion:_o,ZodDefault:Cs,ZodEnum:Rs,ZodNativeEnum:ws,ZodEffects:As,ZodOptional:Es,ZodNullable:zs,ZodDiscriminatedUnion:_o,ZodBranded:js,ZodCatch:Ls,ZodPipeline:Ms,ZodLazy:Hs,ZodReadonly:Ns,[W]:Ks,[ce]:Ds},Sr=(e,{brandHandling:t,ctx:r})=>Pe(e,{rules:{...t,...Fs},onMissing:()=>y(h.default.SyntaxKind.AnyKeyword),ctx:r});var Ct=class extends Zt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=F(null);this.aliases.set(t,X(o,n)),this.aliases.set(t,X(o,r()))}return y(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Yo.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},g={brandHandling:r,ctx:{...p,isResponse:!0}};qe({routing:t,onEndpoint:(f,R,O)=>{let M=pe.bind(null,O,R),U=`${O} ${R}`,S=X(M("input"),Sr(f.getSchema("input"),l),{comment:U});this.program.push(S);let z=Ne.reduce((H,k)=>{let I=f.getResponses(k),ye=(0,Go.chain)(([Nt,{schema:oe,mimeTypes:fe,statusCodes:Lt}])=>{let rt=X(M(k,"variant",`${Nt+1}`),Sr(fe?oe:d,g),{comment:U});return this.program.push(rt),Lt.map(ot=>Ae(ot,rt.name))},Array.from(I.entries())),C=It(M(k,"response","variants"),ye,{comment:U});return this.program.push(C),Object.assign(H,{[k]:C})},{});this.paths.add(R);let Z=F(U);this.registry.set(U,{input:y(S.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:i.createUnionTypeNode([G(this.interfaces.positive,Z),G(this.interfaces.negative,Z)]),encoded:i.createIntersectionTypeNode([y(z.positive.name),y(z.negative.name)])}),this.tags.set(U,f.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:ir(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((n,s)=>
|
|
18
|
+
`))};var xo=e=>{e.startupLogo!==!1&&fo(process.stdout);let t=e.errorHandler||Me,r=qr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.8.0 (CJS)",env:process.env.NODE_ENV||"development"}),uo(r);let o=mo({logger:r,config:e}),s={getLogger:lo(r),errorHandler:t},a=ao(s),c=io(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},bo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=xo(e);return er({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},So=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=xo(e),c=(0,Rt.default)().disable("x-powered-by").use(a);if(e.compression){let b=await qe("compression");c.use(b(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Rt.default.json()],raw:[e.rawParser||Rt.default.raw(),co],upload:e.upload?await po({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),er({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],l=(b,f)=>()=>b.listen(f,()=>r.info("Listening",f)),g=[];if(e.http){let b=go.default.createServer(c);p.push(b),g.push(l(b,e.http.listen))}if(e.https){let b=ho.default.createServer(e.https.options,c);p.push(b),g.push(l(b,e.https.listen))}return e.gracefulShutdown&&yo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:g.map(b=>b())}};var Ko=require("openapi3-ts/oas31"),Do=require("ramda");var T=require("ramda");var To=e=>be(e)&&"or"in e,Oo=e=>be(e)&&"and"in e,tr=e=>!Oo(e)&&!To(e),Ro=e=>{let t=(0,T.filter)(tr,e),r=(0,T.chain)((0,T.prop)("and"),(0,T.filter)(Oo,e)),[o,n]=(0,T.partition)(tr,r),s=(0,T.concat)(t,o),a=(0,T.filter)(To,e);return(0,T.map)((0,T.prop)("or"),(0,T.concat)(a,n)).reduce((d,p)=>xe(d,(0,T.map)(l=>tr(l)?[l]:l.and,p),([l,g])=>(0,T.concat)(l,g)),(0,T.reject)(T.isEmpty,[s]))};var oe=require("openapi3-ts/oas31"),m=require("ramda"),D=require("zod");var Ae=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[x]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>Ae(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var Po=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var Ao=50,Eo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Pn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},An=/^\d{4}-\d{2}-\d{2}$/,wn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,En=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,zo=e=>e.replace(Dt,t=>`{${t.slice(1)}}`),zn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),In=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),Zn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},kn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof D.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Cn=({options:e},{next:t})=>({oneOf:e.map(t)}),jn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Nn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Ln=e=>{let[t,r]=e.filter(oe.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Nn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=xe(t.examples||[],r.examples||[],([n,s])=>(0,m.mergeDeepRight)(n,s))),o},Mn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ln(o)}catch{}return{allOf:o}},Un=(e,{next:t})=>t(e.unwrap()),Hn=(e,{next:t})=>t(e.unwrap()),Kn=(e,{next:t})=>{let r=t(e.unwrap());return(0,oe.isSchemaObject)(r)&&(r.type=vo(r)),r},Io=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},wo=e=>({type:Io(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Dn=({value:e})=>({type:Io(e),const:e}),Fn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ge(c)?c instanceof D.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Pt(e,r)),s.length&&(a.required=s),a},qn=()=>({type:"null"}),Bn=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Eo}}},$n=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Eo}}},Vn=({},e)=>{throw new q(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},_n=()=>({type:"boolean"}),Gn=()=>({type:"integer",format:"bigint"}),Jn=e=>e.every(t=>t instanceof D.z.ZodLiteral),Wn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof D.z.ZodEnum||e instanceof D.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Pt(D.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof D.z.ZodLiteral)return{type:"object",properties:Pt(D.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof D.z.ZodUnion&&Jn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:Pt(D.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Yn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Qn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Xn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:g,isDate:b,isTime:f,isBase64:R,isNANOID:O,isBase64url:L,isDuration:M,_def:{checks:S}})=>{let E=S.find(k=>k.kind==="regex"),v=S.find(k=>k.kind==="datetime"),U=S.some(k=>k.kind==="jwt"),Z=S.find(k=>k.kind==="length"),z={type:"string"},fe={"date-time":l,byte:R,base64url:L,date:b,time:f,duration:M,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:O,jwt:U,ip:d,cidr:g,emoji:p};for(let k in fe)if(fe[k]){z.format=k;break}return Z&&([z.minLength,z.maxLength]=[Z.value,Z.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),b&&(z.pattern=An.source),f&&(z.pattern=wn.source),l&&(z.pattern=En(v?.offset).source),E&&(z.pattern=E.regex.source),z},es=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(g=>g.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(g=>g.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,p?l.maximum=d:l.exclusiveMaximum=d,l},Pt=({shape:e},t)=>(0,m.map)(t,e),ts=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Pn?.[t]},vo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",rs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,oe.isSchemaObject)(o)){let s=ct(e,ts(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(D.z.any())}if(!t&&n.type==="preprocess"&&(0,oe.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},os=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ns=(e,{next:t})=>t(e.unwrap()),ss=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),is=(e,{next:t})=>t(e.unwrap().shape.raw),Zo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,ko=(e,t,r=[])=>(0,m.pipe)(re,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),Zo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),as=(e,t)=>(0,m.pipe)(re,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),Zo)({schema:e,variant:"original",validate:!0,pullProps:!0}),ps=(e,t)=>t?.includes(e)||e.startsWith("x-")||Po.includes(e),Co=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let l=_(r),g=at(e),b=o.includes("query"),f=o.includes("params"),R=o.includes("headers"),O=S=>f&&g.includes(S),L=(0,m.chain)((0,m.filter)(S=>S.type==="header"),d??[]).map(({name:S})=>S),M=S=>R&&(c?.(S,t,e)??ps(S,L));return Object.entries(l.shape).reduce((S,[E,v])=>{let U=O(E)?"path":M(E)?"header":b?"query":void 0;if(!U)return S;let Z=Ae(v,{rules:{...a,...or},onEach:nr,onMissing:sr,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),z=s==="components"?n(v,Z,ce(p,E)):Z;return S.concat({name:E,in:U,required:!v.isOptional(),description:Z.description||p,schema:z,examples:as(l,E)})},[])},or={ZodString:Xn,ZodNumber:es,ZodBigInt:Gn,ZodBoolean:_n,ZodNull:qn,ZodArray:Yn,ZodTuple:Qn,ZodRecord:Wn,ZodObject:Fn,ZodLiteral:Dn,ZodIntersection:Mn,ZodUnion:Cn,ZodAny:vn,ZodDefault:zn,ZodEnum:wo,ZodNativeEnum:wo,ZodEffects:rs,ZodOptional:Un,ZodNullable:Kn,ZodDiscriminatedUnion:jn,ZodBranded:ns,ZodDate:Vn,ZodCatch:In,ZodPipeline:os,ZodLazy:ss,ZodReadonly:Hn,[Q]:kn,[ke]:Zn,[Oe]:$n,[Te]:Bn,[de]:is},nr=(e,{isResponse:t,prev:r})=>{if((0,oe.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof D.z.ZodLazy,s=r.type!==void 0,a=t&&Ge(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=vo(r)),!n){let p=re({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},sr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},rr=(e,t)=>{if((0,oe.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>rr(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>rr(o,t))),r},jo=e=>(0,oe.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),No=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${Bt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let g=jo(Ae(r,{rules:{...p,...or},onEach:nr,onMissing:sr,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b={schema:a==="components"?s(r,g,ce(l)):g,examples:ko(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[b]))}},cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ds=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),ls=({name:e})=>({type:"apiKey",in:"cookie",name:e}),us=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ys=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Lo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?cs(o):o.type==="input"?ds(o,t):o.type==="header"?ms(o):o.type==="cookie"?ls(o):o.type==="openid"?us(o):ys(o);return e.map(o=>o.map(r))},Mo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Uo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=jo(rr(Ae(r,{rules:{...a,...or},onEach:nr,onMissing:sr,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:s==="components"?n(r,p,ce(d)):p,examples:ko(_(r),!1,c)};return{description:d,content:{[o]:l}}},Ho=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),ir=e=>e.length<=Ao?e:e.slice(0,Ao-1)+"\u2026";var At=class extends Ko.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||ce(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});Be({routing:t,onEndpoint:(f,R,O)=>{let L={path:R,method:O,endpoint:f,composition:g,brandHandling:c,makeRef:this.makeRef.bind(this)},[M,S]=["short","long"].map(f.getDescription.bind(f)),E=M?ir(M):l&&S?ir(S):void 0,v=r.inputSources?.[O]||Ft[O],U=this.ensureUniqOperationId(R,O,f.getOperationId(O)),Z=Ro(f.getSecurity()),z=Co({...L,inputSources:v,isHeader:p,security:Z,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:R,operationId:U})}),fe={};for(let ne of Le){let ge=f.getResponses(ne);for(let{mimeTypes:Ut,schema:ot,statusCodes:nt}of ge)for(let Ht of nt)fe[Ht]=No({...L,variant:ne,schema:ot,mimeTypes:Ut,statusCode:Ht,hasMultipleStatusCodes:ge.length>1||nt.length>1,description:a?.[`${ne}Response`]?.call(null,{method:O,path:R,operationId:U,statusCode:Ht})})}let k=v.includes("body")?Uo({...L,paramNames:(0,Do.pluck)("name",z),schema:f.getSchema("input"),mimeType:I[f.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:R,operationId:U})}):void 0,Mt=Mo(Lo(Z,v),f.getScopes(),ne=>{let ge=this.ensureUniqSecuritySchemaName(ne);return this.addSecurityScheme(ge,ne),ge});this.addPath(zo(R),{[O]:{operationId:U,summary:E,description:S,tags:dt(f.getTags()),parameters:dt(z),requestBody:k,security:dt(Mt),responses:fe}})}}),d&&(this.rootDoc.tags=Ho(d))}};var wt=require("node-mocks-http"),fs=e=>(0,wt.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),gs=e=>(0,wt.createResponse)(e),hs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Br(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Fo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=fs(e),s=gs({req:n,...t});s.req=t?.req||n,n.res=s;let a=hs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},qo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Fo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Bo=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Fo(o),d=pt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(pe(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var Yo=require("ramda"),rt=C(require("typescript"),1),Qo=require("zod");var Jo=require("ramda"),W=C(require("typescript"),1);var $o=["get","post","put","delete","patch"];var $e=require("ramda"),u=C(require("typescript"),1),i=u.default.factory,Et=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],xs=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],et={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ar=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),pr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,cr=e=>typeof e=="string"&&bs.test(e)?i.createIdentifier(e):w(e),zt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),It=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?y(t):void 0,o),Ve=e=>Object.entries(e).map(([t,r])=>It(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),dr=(e,t=[])=>i.createConstructorDeclaration(et.public,e,i.createBlock(t)),y=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&(0,$e.map)(y,t)):e,mr=y("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),we=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,cr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,y(t));return o?ar(n,o):n},lr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),ur=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),N=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Et,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?y(r):void 0,t)],u.default.NodeFlags.Const)),yr=(e,t)=>ee(e,i.createUnionTypeNode((0,$e.map)(F,t)),{expose:!0}),ee=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Et:void 0,e,n&&xr(n),t);return o?ar(s,o):s},Vo=(e,t)=>i.createPropertyDeclaration(et.public,e,void 0,y(t),void 0),fr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(et.public,void 0,e,void 0,o&&xr(o),t,n,i.createBlock(r)),gr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Et,e,r&&xr(r),void 0,t),hr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,y(e)),vt=e=>y(Promise.name,[e]),Zt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Et:void 0,e,void 0,void 0,t);return o?ar(n,o):n},xr=e=>(Array.isArray(e)?e.map(t=>(0,$e.pair)(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?y(o):void 0,n?y(n):void 0)}),Ee=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?(0,$e.map)(It,e):Ve(e),void 0,void 0,t),P=e=>e,tt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),_e=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),kt=(e,t)=>y("Extract",[e,t]),br=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),J=(e,t)=>i.createIndexedAccessTypeNode(y(e),y(t)),_o=e=>i.createUnionTypeNode([y(e),vt(e)]),Sr=(e,t)=>i.createFunctionTypeNode(void 0,Ve(e),y(t)),w=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(w(e)),Ss=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],Go=e=>Ss.includes(e.kind);var Ct=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=yr("Method",$o);someOfType=ee("SomeOf",J("T",hr("T")),{params:["T"]});requestType=ee("Request",hr(this.interfaces.input),{expose:!0});someOf=({name:t})=>y(this.someOfType.name,[t]);makePathType=()=>yr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Zt(this.interfaces[t],Array.from(this.registry).map(([r,o])=>we(r,o[t])),{expose:!0}));makeEndpointTags=()=>N("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(cr(t),i.createArrayLiteralExpression((0,Jo.map)(w,r))))),{expose:!0});makeImplementationType=()=>ee(this.ids.implementationType,Sr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:mr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},vt(W.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:W.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.ids.parseRequestFn,Ee({[this.ids.requestParameter.text]:W.default.SyntaxKind.StringKeyword},i.createAsExpression(A(this.ids.requestParameter,P("split"))(i.createRegularExpressionLiteral("/ (.+)/"),w(2)),i.createTupleTypeNode([y(this.methodType.name),y(this.ids.pathType)]))));makeSubstituteFn=()=>N(this.ids.substituteFn,Ee({[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:mr},i.createBlock([N(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],W.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([br(this.ids.pathParameter,A(this.ids.pathParameter,P("replace"))(zt(":",[this.ids.keyParameter]),Ee([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),y("const")))])));makeProvider=()=>fr(this.ids.provideMethod,Ve({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:J(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[N(ur(this.ids.methodParameter,this.ids.pathParameter),A(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(A(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(A(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:vt(J(this.interfaces.response,"K"))});makeClientClass=t=>gr(t,[dr([It(this.ids.implementationArgument,{type:y(this.ids.implementationType,["T"]),mod:et.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>zt("?",[_e(URLSearchParams.name,t)]);makeFetchURL=()=>_e(URL.name,zt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(P("method"),A(this.ids.methodParameter,P("toUpperCase"))()),r=i.createPropertyAssignment(P("headers"),tt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(w("Content-Type"),w(I.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(P("body"),tt(this.ids.hasBodyConst,A(JSON[Symbol.toStringTag],P("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=N(this.ids.responseConst,i.createAwaitExpression(A(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=N(this.ids.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([w("get"),w("delete")]),P("includes"))(this.ids.methodParameter))),a=N(this.ids.searchParamsConst,tt(this.ids.hasBodyConst,w(""),this.makeSearchParams(this.ids.paramsArgument))),c=N(this.ids.contentTypeConst,A(this.ids.responseConst,P("headers"),P("get"))(w("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(W.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=N(this.ids.isJsonConst,A(this.ids.contentTypeConst,P("startsWith"))(w(I.json))),l=i.createReturnStatement(A(this.ids.responseConst,tt(this.ids.isJsonConst,w(P("json")),w(P("text"))))());return N(this.ids.defaultImplementationConst,Ee([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>dr(Ve({request:"K",params:J(this.interfaces.input,"K")}),[N(ur(this.ids.pathParameter,this.ids.restConst),A(this.ids.substituteFn)(i.createElementAccessExpression(A(this.ids.parseRequestFn)(this.ids.requestParameter),w(1)),this.ids.paramsArgument)),N(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),br(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),_e("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([we(P("event"),t)]);makeOnMethod=()=>fr(this.ids.onMethod,Ve({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Sr({[this.ids.dataParameter.text]:J(kt("R",lr(this.makeEventNarrow("E"))),F(P("data")))},_o(W.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.ids.sourceProp,P("addEventListener"))(this.ids.eventParameter,Ee([this.ids.msgParameter],A(this.ids.handlerParameter)(A(JSON[Symbol.toStringTag],P("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,y(MessageEvent.name))),P("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:J("R",F(P("event")))}});makeSubscriptionClass=t=>gr(t,[Vo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:kt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(y(W.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:kt(J(this.interfaces.positive,"K"),lr(this.makeEventNarrow(W.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.ids.clientConst,_e(t)),A(this.ids.clientConst,this.ids.provideMethod)(w("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",w("10"))])),A(_e(r,w("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(w("time"),Ee(["time"],i.createBlock([])))]};var H=require("ramda"),h=C(require("typescript"),1),jt=require("zod");var{factory:$}=h.default,Ts={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Tr={name:(0,H.path)(["name","text"]),type:(0,H.path)(["type"]),optional:(0,H.path)(["questionToken"])},Os=({value:e})=>F(e),Rs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&Ge(a)?a instanceof jt.z.ZodOptional:a.isOptional();return we(s,r(a),{isOptional:c&&o,comment:a.description})});return $.createTypeLiteralNode(n)},Ps=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),As=({options:e})=>$.createUnionTypeNode(e.map(F)),Wo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Go(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},ws=e=>Ts?.[e.kind],Es=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ct(e,ws(o)),s={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return y(n&&s[n]||h.default.SyntaxKind.AnyKeyword)}return o},zs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),Is=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,y(h.default.SyntaxKind.UndefinedKeyword)]):o},vs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),Zs=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),ks=({keySchema:e,valueSchema:t},{next:r})=>y("Record",[e,t].map(r)),Cs=e=>{if(!e.every(h.default.isTypeLiteralNode))throw new Error("Not objects");let r=(0,H.chain)((0,H.prop)("members"),e),o=(0,H.uniqWith)((...n)=>{if(!(0,H.eqBy)(Tr.name,...n))return!1;if((0,H.eqBy)(Tr.type,...n)&&(0,H.eqBy)(Tr.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return $.createTypeLiteralNode(o)},js=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Cs(o)}catch{}return $.createIntersectionTypeNode(o)},Ns=({_def:e},{next:t})=>t(e.innerType),ye=e=>()=>y(e),Ls=(e,{next:t})=>t(e.unwrap()),Ms=(e,{next:t})=>t(e.unwrap()),Us=({_def:e},{next:t})=>t(e.innerType),Hs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ks=()=>F(null),Ds=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Fs=e=>{let t=e.unwrap(),r=y(h.default.SyntaxKind.StringKeyword),o=y("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof jt.z.ZodString?r:t instanceof jt.z.ZodUnion?n:o},qs=(e,{next:t})=>t(e.unwrap().shape.raw),Bs={ZodString:ye(h.default.SyntaxKind.StringKeyword),ZodNumber:ye(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ye(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ye(h.default.SyntaxKind.BooleanKeyword),ZodAny:ye(h.default.SyntaxKind.AnyKeyword),ZodUndefined:ye(h.default.SyntaxKind.UndefinedKeyword),[Te]:ye(h.default.SyntaxKind.StringKeyword),[Oe]:ye(h.default.SyntaxKind.StringKeyword),ZodNull:Ks,ZodArray:Ps,ZodTuple:Zs,ZodRecord:ks,ZodObject:Rs,ZodLiteral:Os,ZodIntersection:js,ZodUnion:Wo,ZodDefault:Ns,ZodEnum:As,ZodNativeEnum:zs,ZodEffects:Es,ZodOptional:Is,ZodNullable:vs,ZodDiscriminatedUnion:Wo,ZodBranded:Ls,ZodCatch:Us,ZodPipeline:Hs,ZodLazy:Ds,ZodReadonly:Ms,[Q]:Fs,[de]:qs},Or=(e,{brandHandling:t,ctx:r})=>Ae(e,{rules:{...t,...Bs},onMissing:()=>y(h.default.SyntaxKind.AnyKeyword),ctx:r});var Nt=class extends Ct{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=F(null);this.aliases.set(t,ee(o,n)),this.aliases.set(t,ee(o,r()))}return y(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Qo.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},g={brandHandling:r,ctx:{...p,isResponse:!0}};Be({routing:t,onEndpoint:(f,R,O)=>{let L=ce.bind(null,O,R),M=`${O} ${R}`,S=ee(L("input"),Or(f.getSchema("input"),l),{comment:M});this.program.push(S);let E=Le.reduce((U,Z)=>{let z=f.getResponses(Z),fe=(0,Yo.chain)(([Mt,{schema:ne,mimeTypes:ge,statusCodes:Ut}])=>{let ot=ee(L(Z,"variant",`${Mt+1}`),Or(ge?ne:d,g),{comment:M});return this.program.push(ot),Ut.map(nt=>we(nt,ot.name))},Array.from(z.entries())),k=Zt(L(Z,"response","variants"),fe,{comment:M});return this.program.push(k),Object.assign(U,{[Z]:k})},{});this.paths.add(R);let v=F(M);this.registry.set(M,{input:y(S.name),positive:this.someOf(E.positive),negative:this.someOf(E.negative),response:i.createUnionTypeNode([J(this.interfaces.positive,v),J(this.interfaces.negative,v)]),encoded:i.createIntersectionTypeNode([y(E.positive.name),y(E.negative.name)])}),this.tags.set(M,f.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:pr(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&rt.default.addSyntheticLeadingComment(rt.default.addSyntheticLeadingComment(i.createEmptyStatement(),rt.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),rt.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>pr(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await qe("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};var ze=require("zod");var en=(e,t)=>ze.z.object({data:t,event:ze.z.literal(e),id:ze.z.string().optional(),retry:ze.z.number().int().positive().optional()}),$s=(e,t,r)=>en(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Vs=1e4,Xo=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":I.sse,"cache-control":"no-cache"}),_s=e=>new V({handler:async({response:t})=>setTimeout(()=>Xo(t),Vs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Xo(t),t.write($s(e,r,o),"utf-8"),t.flush?.()}}}),Gs=e=>new le({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>en(o,n));return{mimeType:I.sse,schema:r.length?ze.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ze.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Re(r);Ye(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(Pe(a),"utf-8")}t.end()}}),Lt=class extends ue{constructor(t){super(Gs(t)),this.middlewares=[_s(t)]}};var tn={dateIn:wr,dateOut:zr,file:yt,upload:Cr,raw:Zr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{clone as
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:nn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Pr}from"zod";var wt=class{},F=class extends wt{#e;#t;#r;constructor({input:t=Pr.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Pr.ZodError?new V(o):o}}},Se=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Te=class{nest(t){return Object.assign(t,{"":this})}};var je=class extends Te{},tt=class extends je{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:m,shortDescription:f}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:m,short:f},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Tr(r)?"upload":Or(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof Ar.ZodError?new oe(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof Se))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof Ar.ZodError?new V(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){et({...r,error:new G(Y(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Tt(t),a={},c=null,d=null,p=$e(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(m){d=Y(m)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var wr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>ur(s,n),o)};import{z as q}from"zod";var Oe={positive:200,negative:400},Re=Object.keys(Oe);var Et=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},de=class extends Et{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return At(this.#e,{variant:"positive",args:[t],statusCodes:[Oe.positive],mimeTypes:[z.json]})}getNegativeResponse(){return At(this.#t,{variant:"negative",args:[],statusCodes:[Oe.negative],mimeTypes:[z.json]})}},Ne=new de({positive:e=>{let t=J({schema:e,pullProps:!0}),r=q.object({status:q.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:q.object({status:q.literal("error"),error:q.object({message:q.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=be(e);return Ce(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ce(a)}})}n.status(Oe.positive).json({status:"success",data:r})}}),zt=new de({positive:e=>{let t=J({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof q.ZodArray?e.shape.items:q.array(q.any());return t.reduce((o,n)=>ie(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:q.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=be(r);return Ce(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ce(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Oe.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var me=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Se(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Er.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:m,resultHandler:f}=this,x=typeof p=="string"?[p]:p,y=typeof a=="function"?a:()=>a,T=typeof c=="string"?[c]:c||[],S=typeof d=="string"?[d]:d||[];return new tt({handler:r,middlewares:m,outputSchema:o,resultHandler:f,scopes:T,tags:S,methods:x,getOperationId:y,description:n,shortDescription:s,inputSchema:wr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Er.object({}),handler:async o=>(await t(o),{})})}},sn=new me(Ne),an=new me(zt);import fn from"ansis";import{inspect as gn}from"node:util";import{performance as kr}from"node:perf_hooks";import{blue as pn,green as cn,hex as dn,red as mn,cyanBright as ln}from"ansis";import{memoizeWith as un}from"ramda";var It={debug:pn,info:cn,warn:dn("#FFA500"),error:mn,ctx:ln},rt={debug:10,info:20,warn:30,error:40},zr=e=>ie(e)&&Object.keys(rt).some(t=>t in e),Ir=e=>e in rt,vr=(e,t)=>rt[e]<rt[t],yn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Pe=un((e,t)=>`${e}${t}`,yn),Zr=e=>e<1e-6?Pe("nanosecond",3).format(e/1e-6):e<.001?Pe("nanosecond").format(e/1e-6):e<1?Pe("microsecond").format(e/.001):e<1e3?Pe("millisecond").format(e):e<6e4?Pe("second",2).format(e/1e3):Pe("minute",2).format(e/6e4);var Le=class e{config;constructor({color:t=fn.isSupported(),level:r=ge()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return gn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||vr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?It.ctx(s):s),d.push(c?`${It[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=kr.now();return()=>{let o=kr.now()-r,{message:n,severity:s="debug",formatter:a=Zr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import{keys as hn,reject as xn,equals as bn}from"ramda";var Me=class extends Te{entries;constructor(t){super();let r=[],o=hn(t);for(let n of o){let s=t[n];s&&r.push([n,s,xn(bn(n),o)])}this.entries=Object.freeze(r)}};import Sn from"express";var Ue=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Sn.static(...this.params))}};import Zt from"express";import In from"node:http";import vn from"node:https";var Ae=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new ve(e)};import Tn from"http-errors";var ot=class{constructor(t){this.logger=t}#e=new WeakSet;check(t,r){if(!this.#e.has(t)){if(t.getRequestType()==="json")try{Pt(t.getSchema("input"),"in")}catch(o){this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Re)for(let{mimeTypes:n,schema:s}of t.getResponses(o))if(n?.includes(z.json))try{Pt(s,"out")}catch(a){this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:a}))}this.#e.add(t)}}};var Cr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new fe(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),we=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Cr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof je){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Ue)r&&s.apply(n,r);else if(s instanceof Me)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new fe(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Cr(s,n))}};var On=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=Tn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},vt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new ot(t()),a=new Map;if(we({routing:o,onEndpoint:(d,p,m,f)=>{ge()||s.check(d,{path:p,method:m});let x=n?.[d.getRequestType()]||[],y=async(T,S)=>{let C=t(T);if(r.cors){let w={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[m,...f||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},I=typeof r.cors=="function"?await r.cors({request:T,endpoint:d,logger:C,defaultHeaders:w}):w;for(let N in I)S.set(N,I[N])}return d.execute({request:T,response:S,logger:C,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...x,y),a.get(p)?.push("options"))),a.get(p)?.push(m),e[m](p,...x,y)},onStatic:e.use.bind(e)}),r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,On(p))};import Kr,{isHttpError as Pn}from"http-errors";import{setInterval as Rn}from"node:timers/promises";var jr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Nr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Lr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Mr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Ur=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Hr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(jr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let m of["connection","secureConnection"])p.on(m,c);let d=async()=>{for(let p of e)p.on("request",Mr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Lr(p)||Nr(p))&&a(p);for await(let p of Rn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Ur))};return{sockets:n,shutdown:()=>o??=d()}};var Dr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:Pn(r)?r:Kr(400,Y(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Fr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Kr(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){et({response:o,logger:s,error:new G(Y(a),n)})}},An=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},wn=e=>({log:e.debug.bind(e)}),qr=async({getLogger:e,config:t})=>{let r=await Ae("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let m=e(c);try{await n?.({request:c,logger:m})}catch(f){return p(f)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:wn(m)})(c,d,p)}),o&&a.push(An(o)),a},Br=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},$r=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},Vr=e=>t=>t?.res?.locals[g]?.logger||e,_r=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
import{clone as gr,fromPairs as Fo,map as qo,pipe as Bo,toPairs as $o,pair as Vo}from"ramda";import{z as xe}from"zod";import{chain as ur,memoizeWith as jo,objOf as No,xprod as Lo}from"ramda";import{z as yr}from"zod";var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var ge=class extends Error{name="RoutingError"},H=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},$e=class extends Error{name="IOSchemaError"},oe=class extends $e{constructor(r){super(ne(r),{cause:r});this.cause=r}name="OutputValidationError"},_=class extends $e{constructor(r){super(ne(r),{cause:r});this.cause=r}name="InputValidationError"},J=class extends Error{constructor(r,o){super(ne(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ze=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ot=/:([A-Za-z0-9_]+)/g,Ve=e=>e.match(Ot)?.map(t=>t.slice(1))||[],Mo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Rt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Uo=["body","query","params"],Pt=e=>e.method.toLowerCase(),_e=(e,t={})=>{let r=Pt(e);return r==="options"?{}:(t[r]||Rt[r]||Uo).filter(o=>o==="files"?Mo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},W=e=>e instanceof Error?e:new Error(String(e)),ne=e=>e instanceof yr.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof oe?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Ho=e=>Object.entries(e.shape).reduce((t,[r,o])=>se(t,(o._def[g]?.examples||[]).map(No(r)),([n,s])=>({...n,...s})),[]),Y=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[g]?.examples||[];if(!n.length&&o&&e instanceof yr.ZodObject&&(n=Ho(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},se=(e,t,r)=>e.length&&t.length?Lo(e,t).map(r):e.concat(t),ke=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,At=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),Q=(...e)=>{let t=ur(o=>o.split(/[^A-Z0-9]/gi),e);return ur(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(At).join("")},Ge=(e,t)=>{try{return typeof e.parse(t)}catch{return}},ie=e=>typeof e=="object"&&e!==null,he=jo(()=>"static",()=>process.env.NODE_ENV==="production"),Je=e=>e.length?e:void 0;import{clone as Ko,mergeDeepRight as Do}from"ramda";var g=Symbol.for("express-zod-api"),We=e=>{let t=e.describe(e.description);return t._def[g]=Ko(t._def[g])||{examples:[]},t},fr=(e,t)=>{if(!(g in e._def))return t;let r=We(t);return r._def[g].examples=se(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Do({...o},{...n}):n),r};var _o=function(e){let t=We(this);return t._def[g].examples.push(e),t},Go=function(e){let t=We(this);return t._def[g].defaultLabel=e,t},Jo=function(e){return new xe.ZodBranded({typeName:xe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...gr(this._def[g]),brand:e}})},Wo=function(e){let t=typeof e=="function"?e:Bo($o,qo(([n,s])=>Vo(e[String(n)]||n,s)),Fo),r=t(gr(this.shape)),o=xe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(xe.ZodType.prototype,{example:{get(){return _o.bind(this)}},brand:{set(){},get(){return Jo.bind(this)}}}),Object.defineProperty(xe.ZodDefault.prototype,"label",{get(){return Go.bind(this)}}),Object.defineProperty(xe.ZodObject.prototype,"remap",{get(){return Wo.bind(this)}}));function Yo(e){return e}import{z as vr}from"zod";import{z as zr}from"zod";import{fail as N}from"node:assert/strict";import{z as Ce}from"zod";var Ye=e=>!isNaN(e.getTime());var ae=Symbol("DateIn"),hr=()=>Ce.union([Ce.string().date(),Ce.string().datetime(),Ce.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ce.date().refine(Ye)).brand(ae);import{z as Qo}from"zod";var pe=Symbol("DateOut"),xr=()=>Qo.date().refine(Ye).transform(e=>e.toISOString()).brand(pe);import{z as Qe}from"zod";var F=Symbol("File"),br=Qe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Xo={buffer:()=>br.brand(F),string:()=>Qe.string().brand(F),binary:()=>br.or(Qe.string()).brand(F),base64:()=>Qe.string().base64().brand(F)};function Xe(e){return Xo[e||"string"]()}import{z as en}from"zod";var X=Symbol("Raw"),Sr=(e={})=>en.object({raw:Xe("buffer")}).extend(e).brand(X);import{z as tn}from"zod";var be=Symbol("Upload"),Tr=()=>tn.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(be);var Or=(e,{next:t})=>e.options.some(t),rn=({_def:e},{next:t})=>[e.left,e.right].some(t),et=(e,{next:t})=>t(e.unwrap()),wt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Or,ZodDiscriminatedUnion:Or,ZodIntersection:rn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:et,ZodNullable:et,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},tt=(e,{condition:t,rules:r=wt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[g]?.brand]||r[e._def.typeName]:void 0;return s?s(e,{next:a=>tt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Rr=e=>tt(e,{condition:t=>t._def[g]?.brand===be}),Pr=e=>tt(e,{condition:t=>t._def[g]?.brand===X,maxDepth:3}),Ar=(e,t)=>{let r=new WeakSet;return tt(e,{maxDepth:300,rules:{...wt,ZodBranded:et,ZodReadonly:et,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:wt.ZodEffects}[t],ZodNaN:()=>N("z.nan()"),ZodSymbol:()=>N("z.symbol()"),ZodFunction:()=>N("z.function()"),ZodMap:()=>N("z.map()"),ZodSet:()=>N("z.set()"),ZodBigInt:()=>N("z.bigint()"),ZodVoid:()=>N("z.void()"),ZodPromise:()=>N("z.promise()"),ZodNever:()=>N("z.never()"),ZodDate:()=>t==="in"&&N("z.date()"),[pe]:()=>t==="in"&&N("ez.dateOut()"),[ae]:()=>t==="out"&&N("ez.dateIn()"),[X]:()=>t==="out"&&N("ez.raw()"),[be]:()=>t==="out"&&N("ez.upload()"),[F]:()=>!1}})};import sn,{isHttpError as an}from"http-errors";import wr,{isHttpError as on}from"http-errors";import{z as nn}from"zod";var Et=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof nn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new J(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},je=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Se=e=>on(e)?e:wr(e instanceof _?400:500,ne(e),{cause:e.cause||e}),ce=e=>he()&&!e.expose?wr(e.statusCode).message:e.message;var rt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ce(sn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:an(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Er}from"zod";var zt=class{},q=class extends zt{#e;#t;#r;constructor({input:t=Er.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Er.ZodError?new _(o):o}}},Te=class extends q{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Oe=class{nest(t){return Object.assign(t,{"":this})}};var Ne=class extends Oe{},ot=class extends Ne{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:m,shortDescription:f}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:m,short:f},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Rr(r)?"upload":Pr(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof zr.ZodError?new oe(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof Te))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof zr.ZodError?new _(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){rt({...r,error:new J(W(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Pt(t),a={},c=null,d=null,p=_e(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(m){d=W(m)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};import{z as de}from"zod";var Ir=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>fr(s,n),o)},K=e=>e instanceof de.ZodObject?e:e instanceof de.ZodBranded?K(e.unwrap()):e instanceof de.ZodUnion||e instanceof de.ZodDiscriminatedUnion?e.options.map(t=>K(t)).reduce((t,r)=>t.merge(r.partial()),de.object({})):e instanceof de.ZodEffects?K(e._def.schema):e instanceof de.ZodPipeline?K(e._def.in):K(e._def.left).merge(K(e._def.right));import{z as B}from"zod";var Re={positive:200,negative:400},Pe=Object.keys(Re);var It=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},me=class extends It{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Et(this.#e,{variant:"positive",args:[t],statusCodes:[Re.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Et(this.#t,{variant:"negative",args:[],statusCodes:[Re.negative],mimeTypes:[E.json]})}},Le=new me({positive:e=>{let t=Y({schema:e,pullProps:!0}),r=B.object({status:B.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:B.object({status:B.literal("error"),error:B.object({message:B.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Se(e);return je(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ce(a)}})}n.status(Re.positive).json({status:"success",data:r})}}),vt=new me({positive:e=>{let t=Y({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof B.ZodArray?e.shape.items:B.array(B.any());return t.reduce((o,n)=>ie(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:B.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Se(r);return je(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ce(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Re.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var le=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Te(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new q({handler:t})),this.resultHandler)}build({input:t=vr.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:m,resultHandler:f}=this,x=typeof p=="string"?[p]:p,y=typeof a=="function"?a:()=>a,T=typeof c=="string"?[c]:c||[],S=typeof d=="string"?[d]:d||[];return new ot({handler:r,middlewares:m,outputSchema:o,resultHandler:f,scopes:T,tags:S,methods:x,getOperationId:y,description:n,shortDescription:s,inputSchema:Ir(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:vr.object({}),handler:async o=>(await t(o),{})})}},pn=new le(Le),cn=new le(vt);import hn from"ansis";import{inspect as xn}from"node:util";import{performance as Nr}from"node:perf_hooks";import{blue as dn,green as mn,hex as ln,red as un,cyanBright as yn}from"ansis";import{memoizeWith as fn}from"ramda";var Zt={debug:dn,info:mn,warn:ln("#FFA500"),error:un,ctx:yn},nt={debug:10,info:20,warn:30,error:40},Zr=e=>ie(e)&&Object.keys(nt).some(t=>t in e),kr=e=>e in nt,Cr=(e,t)=>nt[e]<nt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ae=fn((e,t)=>`${e}${t}`,gn),jr=e=>e<1e-6?Ae("nanosecond",3).format(e/1e-6):e<.001?Ae("nanosecond").format(e/1e-6):e<1?Ae("microsecond").format(e/.001):e<1e3?Ae("millisecond").format(e):e<6e4?Ae("second",2).format(e/1e3):Ae("minute",2).format(e/6e4);var Me=class e{config;constructor({color:t=hn.isSupported(),level:r=he()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return xn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Cr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Zt.ctx(s):s),d.push(c?`${Zt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Nr.now();return()=>{let o=Nr.now()-r,{message:n,severity:s="debug",formatter:a=jr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import{keys as bn,reject as Sn,equals as Tn}from"ramda";var Ue=class extends Oe{entries;constructor(t){super();let r=[],o=bn(t);for(let n of o){let s=t[n];s&&r.push([n,s,Sn(Tn(n),o)])}this.entries=Object.freeze(r)}};import On from"express";var He=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,On.static(...this.params))}};import Ct from"express";import kn from"node:http";import Cn from"node:https";var we=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ze(e)};import Pn from"http-errors";import{tryCatch as Rn}from"ramda";var st=class{constructor(t){this.logger=t;this.#e=Rn(Ar)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Pe){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(E.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=Ve(t);if(s.length===0)return;let a=n?.shape||K(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Lr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new ge(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Ee=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Lr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Ne){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof He)r&&s.apply(n,r);else if(s instanceof Ue)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new ge(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Lr(s,n))}};var An=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=Pn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new st(t()),a=new Map;if(Ee({routing:o,onEndpoint:(d,p,m,f)=>{he()||(s?.checkJsonCompat(d,{path:p,method:m}),s?.checkPathParams(p,d,{method:m}));let x=n?.[d.getRequestType()]||[],y=async(T,S)=>{let k=t(T);if(r.cors){let A={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[m,...f||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},z=typeof r.cors=="function"?await r.cors({request:T,endpoint:d,logger:k,defaultHeaders:A}):A;for(let j in z)S.set(j,z[j])}return d.execute({request:T,response:S,logger:k,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...x,y),a.get(p)?.push("options"))),a.get(p)?.push(m),e[m](p,...x,y)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,An(p))};import qr,{isHttpError as En}from"http-errors";import{setInterval as wn}from"node:timers/promises";var Mr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Ur=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Hr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Kr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Dr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Fr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Mr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let m of["connection","secureConnection"])p.on(m,c);let d=async()=>{for(let p of e)p.on("request",Kr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Hr(p)||Ur(p))&&a(p);for await(let p of wn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Dr))};return{sockets:n,shutdown:()=>o??=d()}};var Br=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:En(r)?r:qr(400,W(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),$r=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=qr(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){rt({response:o,logger:s,error:new J(W(a),n)})}},zn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},In=e=>({log:e.debug.bind(e)}),Vr=async({getLogger:e,config:t})=>{let r=await we("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let m=e(c);try{await n?.({request:c,logger:m})}catch(f){return p(f)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:In(m)})(c,d,p)}),o&&a.push(zn(o)),a},_r=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Gr=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},Jr=e=>t=>t?.res?.locals[g]?.logger||e,Wr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),Yr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Fr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as vn,hex as Qr,italic as it,whiteBright as Zn}from"ansis";var Xr=e=>{if(e.columns<132)return;let t=it("Proudly supports transgender community.".padStart(109)),r=it("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=it("Thank you for choosing Express Zod API for your project.".padStart(132)),n=it("for Tai".padEnd(20)),s=Qr("#F5A9B8"),a=Qr("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(Zn,5,7).fill(s,7,9).fill(a,9,12).fill(vn,12,13),d=`
|
|
4
4
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
5
5
|
888 d88P 888 d88888 888 Y88b 888
|
|
6
6
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -15,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,m)=>c[m]?c[m](p):p).join(`
|
|
18
|
-
`))};var Wr=e=>{e.startupLogo!==!1&&Jr(process.stdout);let t=e.errorHandler||Ne,r=zr(e.logger)?e.logger:new Le(e.logger);r.debug("Running",{build:"v22.7.0 (ESM)",env:process.env.NODE_ENV||"development"}),_r(r);let o=$r({logger:r,config:e}),s={getLogger:Vr(r),errorHandler:t},a=Fr(s),c=Dr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Wr(e);return vt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},kn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Wr(e),c=Zt().disable("x-powered-by").use(a);if(e.compression){let x=await Ae("compression");c.use(x(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Zt.json()],raw:[e.rawParser||Zt.raw(),Br],upload:e.upload?await qr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),vt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let x=In.createServer(c);p.push(x),f.push(m(x,e.http.listen))}if(e.https){let x=vn.createServer(e.https.options,c);p.push(x),f.push(m(x,e.https.listen))}return e.gracefulShutdown&&Gr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(x=>x())}};import{OpenApiBuilder as Bs}from"openapi3-ts/oas31";import{pluck as $s}from"ramda";import{chain as Cn,isEmpty as jn,map as Qr,partition as Nn,prop as Xr,reject as Ln,filter as kt,concat as Ct}from"ramda";var eo=e=>ie(e)&&"or"in e,to=e=>ie(e)&&"and"in e,jt=e=>!to(e)&&!eo(e),ro=e=>{let t=kt(jt,e),r=Cn(Xr("and"),kt(to,e)),[o,n]=Nn(jt,r),s=Ct(t,o),a=kt(eo,e);return Qr(Xr("or"),Ct(a,n)).reduce((d,p)=>se(d,Qr(m=>jt(m)?[m]:m.and,p),([m,f])=>Ct(m,f)),Ln(jn,[s]))};import{isReferenceObject as Mt,isSchemaObject as it}from"openapi3-ts/oas31";import{concat as Un,chain as Hn,type as io,filter as ao,fromPairs as at,has as Kn,isNil as Dn,map as He,mergeDeepRight as Fn,mergeDeepWith as qn,objOf as Bn,omit as pt,pipe as po,pluck as $n,reject as Vn,times as _n,toLower as Gn,union as Yn,when as Jn,xprod as Nt,zip as Wn}from"ramda";import{z as A}from"zod";var le=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>le(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var oo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var no=50,co="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Qn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},mo=/:([A-Za-z0-9_]+)/g,Xn=/^\d{4}-\d{2}-\d{2}$/,es=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,ts=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,rs=e=>e.match(mo)?.map(t=>t.slice(1))||[],lo=e=>e.replace(mo,t=>`{${t.slice(1)}}`),os=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),ns=({_def:{innerType:e}},{next:t})=>t(e),ss=()=>({format:"any"}),is=({},e)=>{if(e.isResponse)throw new H("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},as=e=>{let t=e.unwrap();return{type:"string",format:t instanceof A.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ps=({options:e},{next:t})=>({oneOf:e.map(t)}),cs=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ds=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Un(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},ms=e=>{let[t,r]=e.filter(it).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=qn(ds,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Yn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>Fn(n,s))),o},ls=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return ms(o)}catch{}return{allOf:o}},us=(e,{next:t})=>t(e.unwrap()),ys=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t})=>{let r=t(e.unwrap());return it(r)&&(r.type=yo(r)),r},uo=e=>{let t=Gn(io(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},so=e=>({type:uo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),gs=({value:e})=>({type:uo(e),const:e}),hs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ze(c)?c instanceof A.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=st(e,r)),s.length&&(a.required=s),a},xs=()=>({type:"null"}),bs=({},e)=>{if(e.isResponse)throw new H("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:co}}},Ss=({},e)=>{if(!e.isResponse)throw new H("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:co}}},Ts=({},e)=>{throw new H(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Os=()=>({type:"boolean"}),Rs=()=>({type:"integer",format:"bigint"}),Ps=e=>e.every(t=>t instanceof A.ZodLiteral),As=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof A.ZodEnum||e instanceof A.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=st(A.object(at(Nt(o,[t]))),r),n.required=o),n}if(e instanceof A.ZodLiteral)return{type:"object",properties:st(A.object({[e.value]:t}),r),required:[e.value]};if(e instanceof A.ZodUnion&&Ps(e.options)){let o=He(s=>`${s.value}`,e.options),n=at(Nt(o,[t]));return{type:"object",properties:st(A.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ws=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),zs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:x,isTime:y,isBase64:T,isNANOID:S,isBase64url:C,isDuration:j,_def:{checks:b}})=>{let w=b.find(Z=>Z.kind==="regex"),I=b.find(Z=>Z.kind==="datetime"),N=b.some(Z=>Z.kind==="jwt"),v=b.find(Z=>Z.kind==="length"),E={type:"string"},te={"date-time":m,byte:T,base64url:C,date:x,time:y,duration:j,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:S,jwt:N,ip:d,cidr:f,emoji:p};for(let Z in te)if(te[Z]){E.format=Z;break}return v&&([E.minLength,E.maxLength]=[v.value,v.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),x&&(E.pattern=Xn.source),y&&(E.pattern=es.source),m&&(E.pattern=ts(I?.offset).source),w&&(E.pattern=w.regex.source),E},Is=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},st=({shape:e},t)=>He(t,e),vs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Qn?.[t]},yo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Zs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&it(o)){let s=Ve(e,vs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(A.any())}if(!t&&n.type==="preprocess"&&it(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ks=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Cs=(e,{next:t})=>t(e.unwrap()),js=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ns=(e,{next:t})=>t(e.unwrap().shape.raw),fo=e=>e.length?at(Wn(_n(t=>`example${t+1}`,e.length),He(Bn("value"),e))):void 0,go=(e,t,r=[])=>po(J,He(Jn(o=>io(o)==="Object",pt(r))),fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Ls=(e,t)=>po(J,ao(Kn(t)),$n(t),fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),X=e=>e instanceof A.ZodObject?e:e instanceof A.ZodBranded?X(e.unwrap()):e instanceof A.ZodUnion||e instanceof A.ZodDiscriminatedUnion?e.options.map(t=>X(t)).reduce((t,r)=>t.merge(r.partial()),A.object({})):e instanceof A.ZodEffects?X(e._def.schema):e instanceof A.ZodPipeline?X(e._def.in):X(e._def.left).merge(X(e._def.right)),Ms=(e,t)=>t?.includes(e)||e.startsWith("x-")||oo.includes(e),ho=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=X(r),f=rs(e),x=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=b=>y&&f.includes(b),C=Hn(ao(b=>b.type==="header"),d??[]).map(({name:b})=>b),j=b=>T&&(c?.(b,t,e)??Ms(b,C));return Object.entries(m.shape).reduce((b,[w,I])=>{let N=S(w)?"path":j(w)?"header":x?"query":void 0;if(!N)return b;let v=le(I,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),E=s==="components"?n(I,v,W(p,w)):v;return b.concat({name:w,in:N,required:!I.isOptional(),description:v.description||p,schema:E,examples:Ls(m,w)})},[])},Ut={ZodString:zs,ZodNumber:Is,ZodBigInt:Rs,ZodBoolean:Os,ZodNull:xs,ZodArray:ws,ZodTuple:Es,ZodRecord:As,ZodObject:hs,ZodLiteral:gs,ZodIntersection:ls,ZodUnion:ps,ZodAny:ss,ZodDefault:os,ZodEnum:so,ZodNativeEnum:so,ZodEffects:Zs,ZodOptional:us,ZodNullable:fs,ZodDiscriminatedUnion:cs,ZodBranded:Cs,ZodDate:Ts,ZodCatch:ns,ZodPipeline:ks,ZodLazy:js,ZodReadonly:ys,[D]:as,[xe]:is,[pe]:Ss,[ae]:bs,[Q]:Ns},Ht=(e,{isResponse:t,prev:r})=>{if(Mt(r))return{};let{description:o}=e,n=e instanceof A.ZodLazy,s=r.type!==void 0,a=t&&Ze(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=yo(r)),!n){let p=J({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Kt=(e,t)=>{throw new H(`Zod type ${e.constructor.name} is unsupported.`,t)},Lt=(e,t)=>{if(Mt(e))return e;let r={...e};return r.properties&&(r.properties=pt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>pt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Lt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Lt(o,t))),r},xo=e=>Mt(e)?e:pt(["examples"],e),bo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${Ot(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=xo(le(r,{rules:{...p,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x={schema:a==="components"?s(r,f,W(m)):f,examples:go(r,!0)};return{description:m,content:at(Nt(o,[x]))}},Us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Hs=({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},Ks=({name:e})=>({type:"apiKey",in:"header",name:e}),Ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),qs=({flows:e={}})=>({type:"oauth2",flows:He(t=>({...t,scopes:t.scopes||{}}),Vn(Dn,e))}),So=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Us(o):o.type==="input"?Hs(o,t):o.type==="header"?Ks(o):o.type==="cookie"?Ds(o):o.type==="openid"?Fs(o):qs(o);return e.map(o=>o.map(r))},To=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Oo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=xo(Lt(le(r,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,W(d)):p,examples:go(X(r),!1,c)};return{description:d,content:{[o]:m}}},Ro=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Dt=e=>e.length<=no?e:e.slice(0,no-1)+"\u2026";var Ft=class extends Bs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||W(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new H(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});we({routing:t,onEndpoint:(y,T,S)=>{let C={path:T,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[j,b]=["short","long"].map(y.getDescription.bind(y)),w=j?Dt(j):m&&b?Dt(b):void 0,I=r.inputSources?.[S]||St[S],N=this.ensureUniqOperationId(T,S,y.getOperationId(S)),v=ro(y.getSecurity()),E=ho({...C,inputSources:I,isHeader:p,security:v,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:T,operationId:N})}),te={};for(let _ of Re){let re=y.getResponses(_);for(let{mimeTypes:xt,schema:Fe,statusCodes:qe}of re)for(let bt of qe)te[bt]=bo({...C,variant:_,schema:Fe,mimeTypes:xt,statusCode:bt,hasMultipleStatusCodes:re.length>1||qe.length>1,description:a?.[`${_}Response`]?.call(null,{method:S,path:T,operationId:N,statusCode:bt})})}let Z=I.includes("body")?Oo({...C,paramNames:$s("name",E),schema:y.getSchema("input"),mimeType:z[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:T,operationId:N})}):void 0,ht=To(So(v,I),y.getScopes(),_=>{let re=this.ensureUniqSecuritySchemaName(_);return this.addSecurityScheme(re,_),re});this.addPath(lo(T),{[S]:{operationId:N,summary:w,description:b,tags:_e(y.getTags()),parameters:_e(E),requestBody:Z,security:_e(ht),responses:te}})}}),d&&(this.rootDoc.tags=Ro(d))}};import{createRequest as Vs,createResponse as _s}from"node-mocks-http";var Gs=e=>Vs({...e,headers:{"content-type":z.json,...e?.headers}}),Ys=e=>_s(e),Js=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Ir(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Po=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Gs(e),s=Ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=Js(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Ws=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Po(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Qs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Po(o),d=$e(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(Y(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Zi}from"ramda";import gt from"typescript";import{z as ki}from"zod";import{map as oi}from"ramda";import $ from"typescript";var Ao=["get","post","put","delete","patch"];import{map as qt,pair as Xs}from"ramda";import l from"typescript";var i=l.factory,ct=[i.createModifier(l.SyntaxKind.ExportKeyword)],ei=[i.createModifier(l.SyntaxKind.AsyncKeyword)],Ke={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Bt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),$t=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},ti=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vt=e=>typeof e=="string"&&ti.test(e)?i.createIdentifier(e):P(e),dt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),mt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),Ee=e=>Object.entries(e).map(([t,r])=>mt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),_t=(e,t=[])=>i.createConstructorDeclaration(Ke.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&qt(u,t)):e,Gt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),ue=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,Vt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t));return o?Bt(n,o):n},Yt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Jt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),k=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&ct,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),Wt=(e,t)=>B(e,i.createUnionTypeNode(qt(M,t)),{expose:!0}),B=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?ct:void 0,e,n&&tr(n),t);return o?Bt(s,o):s},wo=(e,t)=>i.createPropertyDeclaration(Ke.public,e,void 0,u(t),void 0),Qt=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ke.public,void 0,e,void 0,o&&tr(o),t,n,i.createBlock(r)),Xt=(e,t,{typeParams:r}={})=>i.createClassDeclaration(ct,e,r&&tr(r),void 0,t),er=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),lt=e=>u(Promise.name,[e]),ut=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?ct:void 0,e,void 0,void 0,t);return o?Bt(n,o):n},tr=e=>(Array.isArray(e)?e.map(t=>Xs(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?u(o):void 0,n?u(n):void 0)}),ye=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ei:void 0,void 0,Array.isArray(e)?qt(mt,e):Ee(e),void 0,void 0,t),O=e=>e,De=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),ze=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),yt=(e,t)=>u("Extract",[e,t]),rr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),K=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Eo=e=>i.createUnionTypeNode([u(e),lt(e)]),or=(e,t)=>i.createFunctionTypeNode(void 0,Ee(e),u(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),M=e=>i.createLiteralTypeNode(P(e)),ri=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],zo=e=>ri.includes(e.kind);var ft=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Wt("Method",Ao);someOfType=B("SomeOf",K("T",er("T")),{params:["T"]});requestType=B("Request",er(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>Wt(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>ut(this.interfaces[t],Array.from(this.registry).map(([r,o])=>ue(r,o[t])),{expose:!0}));makeEndpointTags=()=>k("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Vt(t),i.createArrayLiteralExpression(oi(P,r))))),{expose:!0});makeImplementationType=()=>B(this.ids.implementationType,or({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},lt($.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:$.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>k(this.ids.parseRequestFn,ye({[this.ids.requestParameter.text]:$.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>k(this.ids.substituteFn,ye({[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt},i.createBlock([k(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],$.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([rr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(dt(":",[this.ids.keyParameter]),ye([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>Qt(this.ids.provideMethod,Ee({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:K(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[k(Jt(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:lt(K(this.interfaces.response,"K"))});makeClientClass=t=>Xt(t,[_t([mt(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:Ke.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>dt("?",[ze(URLSearchParams.name,t)]);makeFetchURL=()=>ze(URL.name,dt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),De(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(z.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),De(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=k(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=k(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=k(this.ids.searchParamsConst,De(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=k(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression($.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=k(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(z.json))),m=i.createReturnStatement(R(this.ids.responseConst,De(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return k(this.ids.defaultImplementationConst,ye([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>_t(Ee({request:"K",params:K(this.interfaces.input,"K")}),[k(Jt(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),k(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),rr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),ze("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ue(O("event"),t)]);makeOnMethod=()=>Qt(this.ids.onMethod,Ee({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:or({[this.ids.dataParameter.text]:K(yt("R",Yt(this.makeEventNarrow("E"))),M(O("data")))},Eo($.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,ye([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:K("R",M(O("event")))}});makeSubscriptionClass=t=>Xt(t,[wo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:yt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u($.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:yt(K(this.interfaces.positive,"K"),Yt(this.makeEventNarrow($.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[k(this.ids.clientConst,ze(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(ze(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),ye(["time"],i.createBlock([])))]};import{chain as ni,eqBy as nr,path as sr,prop as si,uniqWith as ii}from"ramda";import h from"typescript";import{z as ar}from"zod";var{factory:U}=h,ai={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},ir={name:sr(["name","text"]),type:sr(["type"]),optional:sr(["questionToken"])},pi=({value:e})=>M(e),ci=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&Ze(a)?a instanceof ar.ZodOptional:a.isOptional();return ue(s,r(a),{isOptional:c&&o,comment:a.description})});return U.createTypeLiteralNode(n)},di=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),mi=({options:e})=>U.createUnionTypeNode(e.map(M)),Io=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(zo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},li=e=>ai?.[e.kind],ui=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ve(e,li(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},yi=e=>U.createUnionTypeNode(Object.values(e.enum).map(M)),fi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},gi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),M(null)]),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("Record",[e,t].map(r)),bi=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=ni(si("members"),e),o=ii((...n)=>{if(!nr(ir.name,...n))return!1;if(nr(ir.type,...n)&&nr(ir.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},Si=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return bi(o)}catch{}return U.createIntersectionTypeNode(o)},Ti=({_def:e},{next:t})=>t(e.innerType),ee=e=>()=>u(e),Oi=(e,{next:t})=>t(e.unwrap()),Ri=(e,{next:t})=>t(e.unwrap()),Pi=({_def:e},{next:t})=>t(e.innerType),Ai=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),wi=()=>M(null),Ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),zi=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof ar.ZodString?r:t instanceof ar.ZodUnion?n:o},Ii=(e,{next:t})=>t(e.unwrap().shape.raw),vi={ZodString:ee(h.SyntaxKind.StringKeyword),ZodNumber:ee(h.SyntaxKind.NumberKeyword),ZodBigInt:ee(h.SyntaxKind.BigIntKeyword),ZodBoolean:ee(h.SyntaxKind.BooleanKeyword),ZodAny:ee(h.SyntaxKind.AnyKeyword),ZodUndefined:ee(h.SyntaxKind.UndefinedKeyword),[ae]:ee(h.SyntaxKind.StringKeyword),[pe]:ee(h.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:di,ZodTuple:hi,ZodRecord:xi,ZodObject:ci,ZodLiteral:pi,ZodIntersection:Si,ZodUnion:Io,ZodDefault:Ti,ZodEnum:mi,ZodNativeEnum:yi,ZodEffects:ui,ZodOptional:fi,ZodNullable:gi,ZodDiscriminatedUnion:Io,ZodBranded:Oi,ZodCatch:Pi,ZodPipeline:Ai,ZodLazy:Ei,ZodReadonly:Ri,[D]:zi,[Q]:Ii},pr=(e,{brandHandling:t,ctx:r})=>le(e,{rules:{...t,...vi},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var cr=class extends ft{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=M(null);this.aliases.set(t,B(o,n)),this.aliases.set(t,B(o,r()))}return u(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=ki.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},f={brandHandling:r,ctx:{...p,isResponse:!0}};we({routing:t,onEndpoint:(y,T,S)=>{let C=W.bind(null,S,T),j=`${S} ${T}`,b=B(C("input"),pr(y.getSchema("input"),m),{comment:j});this.program.push(b);let w=Re.reduce((N,v)=>{let E=y.getResponses(v),te=Zi(([ht,{schema:_,mimeTypes:re,statusCodes:xt}])=>{let Fe=B(C(v,"variant",`${ht+1}`),pr(re?_:d,f),{comment:j});return this.program.push(Fe),xt.map(qe=>ue(qe,Fe.name))},Array.from(E.entries())),Z=ut(C(v,"response","variants"),te,{comment:j});return this.program.push(Z),Object.assign(N,{[v]:Z})},{});this.paths.add(T);let I=M(j);this.registry.set(j,{input:u(b.name),positive:this.someOf(w.positive),negative:this.someOf(w.negative),response:i.createUnionTypeNode([K(this.interfaces.positive,I),K(this.interfaces.negative,I)]),encoded:i.createIntersectionTypeNode([u(w.positive.name),u(w.negative.name)])}),this.tags.set(j,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:$t(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((n,s)
|
|
18
|
+
`))};var eo=e=>{e.startupLogo!==!1&&Xr(process.stdout);let t=e.errorHandler||Le,r=Zr(e.logger)?e.logger:new Me(e.logger);r.debug("Running",{build:"v22.8.0 (ESM)",env:process.env.NODE_ENV||"development"}),Wr(r);let o=Gr({logger:r,config:e}),s={getLogger:Jr(r),errorHandler:t},a=$r(s),c=Br(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},jn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=eo(e);return kt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Nn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=eo(e),c=Ct().disable("x-powered-by").use(a);if(e.compression){let x=await we("compression");c.use(x(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Ct.json()],raw:[e.rawParser||Ct.raw(),_r],upload:e.upload?await Vr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),kt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let x=kn.createServer(c);p.push(x),f.push(m(x,e.http.listen))}if(e.https){let x=Cn.createServer(e.https.options,c);p.push(x),f.push(m(x,e.https.listen))}return e.gracefulShutdown&&Yr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(x=>x())}};import{OpenApiBuilder as Vs}from"openapi3-ts/oas31";import{pluck as _s}from"ramda";import{chain as Ln,isEmpty as Mn,map as to,partition as Un,prop as ro,reject as Hn,filter as jt,concat as Nt}from"ramda";var oo=e=>ie(e)&&"or"in e,no=e=>ie(e)&&"and"in e,Lt=e=>!no(e)&&!oo(e),so=e=>{let t=jt(Lt,e),r=Ln(ro("and"),jt(no,e)),[o,n]=Un(Lt,r),s=Nt(t,o),a=jt(oo,e);return to(ro("or"),Nt(a,n)).reduce((d,p)=>se(d,to(m=>Lt(m)?[m]:m.and,p),([m,f])=>Nt(m,f)),Hn(Mn,[s]))};import{isReferenceObject as Ht,isSchemaObject as pt}from"openapi3-ts/oas31";import{concat as Dn,chain as Fn,type as co,filter as mo,fromPairs as ct,has as qn,isNil as Bn,map as Ke,mergeDeepRight as $n,mergeDeepWith as Vn,objOf as _n,omit as dt,pipe as lo,pluck as Gn,reject as Jn,times as Wn,toLower as Yn,union as Qn,when as Xn,xprod as Mt,zip as es}from"ramda";import{z as M}from"zod";var ue=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>ue(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var io=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var ao=50,uo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",ts={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},rs=/^\d{4}-\d{2}-\d{2}$/,os=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,ns=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,yo=e=>e.replace(Ot,t=>`{${t.slice(1)}}`),ss=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),is=({_def:{innerType:e}},{next:t})=>t(e),as=()=>({format:"any"}),ps=({},e)=>{if(e.isResponse)throw new H("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},cs=e=>{let t=e.unwrap();return{type:"string",format:t instanceof M.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ds=({options:e},{next:t})=>({oneOf:e.map(t)}),ms=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ls=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Dn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},us=e=>{let[t,r]=e.filter(pt).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Vn(ls,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Qn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>$n(n,s))),o},ys=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return us(o)}catch{}return{allOf:o}},fs=(e,{next:t})=>t(e.unwrap()),gs=(e,{next:t})=>t(e.unwrap()),hs=(e,{next:t})=>{let r=t(e.unwrap());return pt(r)&&(r.type=go(r)),r},fo=e=>{let t=Yn(co(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},po=e=>({type:fo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),xs=({value:e})=>({type:fo(e),const:e}),bs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&ke(c)?c instanceof M.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=at(e,r)),s.length&&(a.required=s),a},Ss=()=>({type:"null"}),Ts=({},e)=>{if(e.isResponse)throw new H("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:uo}}},Os=({},e)=>{if(!e.isResponse)throw new H("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:uo}}},Rs=({},e)=>{throw new H(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Ps=()=>({type:"boolean"}),As=()=>({type:"integer",format:"bigint"}),ws=e=>e.every(t=>t instanceof M.ZodLiteral),Es=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof M.ZodEnum||e instanceof M.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=at(M.object(ct(Mt(o,[t]))),r),n.required=o),n}if(e instanceof M.ZodLiteral)return{type:"object",properties:at(M.object({[e.value]:t}),r),required:[e.value]};if(e instanceof M.ZodUnion&&ws(e.options)){let o=Ke(s=>`${s.value}`,e.options),n=ct(Mt(o,[t]));return{type:"object",properties:at(M.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},zs=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),vs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:x,isTime:y,isBase64:T,isNANOID:S,isBase64url:k,isDuration:C,_def:{checks:b}})=>{let A=b.find(v=>v.kind==="regex"),z=b.find(v=>v.kind==="datetime"),j=b.some(v=>v.kind==="jwt"),I=b.find(v=>v.kind==="length"),w={type:"string"},te={"date-time":m,byte:T,base64url:k,date:x,time:y,duration:C,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:S,jwt:j,ip:d,cidr:f,emoji:p};for(let v in te)if(te[v]){w.format=v;break}return I&&([w.minLength,w.maxLength]=[I.value,I.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),x&&(w.pattern=rs.source),y&&(w.pattern=os.source),m&&(w.pattern=ns(z?.offset).source),A&&(w.pattern=A.regex.source),w},Zs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},at=({shape:e},t)=>Ke(t,e),ks=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return ts?.[t]},go=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Cs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&pt(o)){let s=Ge(e,ks(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(M.any())}if(!t&&n.type==="preprocess"&&pt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},js=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ns=(e,{next:t})=>t(e.unwrap()),Ls=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ms=(e,{next:t})=>t(e.unwrap().shape.raw),ho=e=>e.length?ct(es(Wn(t=>`example${t+1}`,e.length),Ke(_n("value"),e))):void 0,xo=(e,t,r=[])=>lo(Y,Ke(Xn(o=>co(o)==="Object",dt(r))),ho)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Us=(e,t)=>lo(Y,mo(qn(t)),Gn(t),ho)({schema:e,variant:"original",validate:!0,pullProps:!0}),Hs=(e,t)=>t?.includes(e)||e.startsWith("x-")||io.includes(e),bo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=K(r),f=Ve(e),x=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=b=>y&&f.includes(b),k=Fn(mo(b=>b.type==="header"),d??[]).map(({name:b})=>b),C=b=>T&&(c?.(b,t,e)??Hs(b,k));return Object.entries(m.shape).reduce((b,[A,z])=>{let j=S(A)?"path":C(A)?"header":x?"query":void 0;if(!j)return b;let I=ue(z,{rules:{...a,...Kt},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),w=s==="components"?n(z,I,Q(p,A)):I;return b.concat({name:A,in:j,required:!z.isOptional(),description:I.description||p,schema:w,examples:Us(m,A)})},[])},Kt={ZodString:vs,ZodNumber:Zs,ZodBigInt:As,ZodBoolean:Ps,ZodNull:Ss,ZodArray:zs,ZodTuple:Is,ZodRecord:Es,ZodObject:bs,ZodLiteral:xs,ZodIntersection:ys,ZodUnion:ds,ZodAny:as,ZodDefault:ss,ZodEnum:po,ZodNativeEnum:po,ZodEffects:Cs,ZodOptional:fs,ZodNullable:hs,ZodDiscriminatedUnion:ms,ZodBranded:Ns,ZodDate:Rs,ZodCatch:is,ZodPipeline:js,ZodLazy:Ls,ZodReadonly:gs,[F]:cs,[be]:ps,[pe]:Os,[ae]:Ts,[X]:Ms},Dt=(e,{isResponse:t,prev:r})=>{if(Ht(r))return{};let{description:o}=e,n=e instanceof M.ZodLazy,s=r.type!==void 0,a=t&&ke(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=go(r)),!n){let p=Y({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Ft=(e,t)=>{throw new H(`Zod type ${e.constructor.name} is unsupported.`,t)},Ut=(e,t)=>{if(Ht(e))return e;let r={...e};return r.properties&&(r.properties=dt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>dt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ut(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ut(o,t))),r},So=e=>Ht(e)?e:dt(["examples"],e),To=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${At(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=So(ue(r,{rules:{...p,...Kt},onEach:Dt,onMissing:Ft,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x={schema:a==="components"?s(r,f,Q(m)):f,examples:xo(r,!0)};return{description:m,content:ct(Mt(o,[x]))}},Ks=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ds=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Fs=({name:e})=>({type:"apiKey",in:"header",name:e}),qs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Bs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),$s=({flows:e={}})=>({type:"oauth2",flows:Ke(t=>({...t,scopes:t.scopes||{}}),Jn(Bn,e))}),Oo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Ks(o):o.type==="input"?Ds(o,t):o.type==="header"?Fs(o):o.type==="cookie"?qs(o):o.type==="openid"?Bs(o):$s(o);return e.map(o=>o.map(r))},Ro=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Po=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=So(Ut(ue(r,{rules:{...a,...Kt},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,Q(d)):p,examples:xo(K(r),!1,c)};return{description:d,content:{[o]:m}}},Ao=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),qt=e=>e.length<=ao?e:e.slice(0,ao-1)+"\u2026";var Bt=class extends Vs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||Q(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new H(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});Ee({routing:t,onEndpoint:(y,T,S)=>{let k={path:T,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(y.getDescription.bind(y)),A=C?qt(C):m&&b?qt(b):void 0,z=r.inputSources?.[S]||Rt[S],j=this.ensureUniqOperationId(T,S,y.getOperationId(S)),I=so(y.getSecurity()),w=bo({...k,inputSources:z,isHeader:p,security:I,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:T,operationId:j})}),te={};for(let G of Pe){let re=y.getResponses(G);for(let{mimeTypes:St,schema:qe,statusCodes:Be}of re)for(let Tt of Be)te[Tt]=To({...k,variant:G,schema:qe,mimeTypes:St,statusCode:Tt,hasMultipleStatusCodes:re.length>1||Be.length>1,description:a?.[`${G}Response`]?.call(null,{method:S,path:T,operationId:j,statusCode:Tt})})}let v=z.includes("body")?Po({...k,paramNames:_s("name",w),schema:y.getSchema("input"),mimeType:E[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:T,operationId:j})}):void 0,bt=Ro(Oo(I,z),y.getScopes(),G=>{let re=this.ensureUniqSecuritySchemaName(G);return this.addSecurityScheme(re,G),re});this.addPath(yo(T),{[S]:{operationId:j,summary:A,description:b,tags:Je(y.getTags()),parameters:Je(w),requestBody:v,security:Je(bt),responses:te}})}}),d&&(this.rootDoc.tags=Ao(d))}};import{createRequest as Gs,createResponse as Js}from"node-mocks-http";var Ws=e=>Gs({...e,headers:{"content-type":E.json,...e?.headers}}),Ys=e=>Js(e),Qs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:kr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},wo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ws(e),s=Ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=Qs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Xs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=wo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},ei=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=wo(o),d=_e(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(W(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Ci}from"ramda";import xt from"typescript";import{z as ji}from"zod";import{map as si}from"ramda";import V from"typescript";var Eo=["get","post","put","delete","patch"];import{map as $t,pair as ti}from"ramda";import l from"typescript";var i=l.factory,mt=[i.createModifier(l.SyntaxKind.ExportKeyword)],ri=[i.createModifier(l.SyntaxKind.AsyncKeyword)],De={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Vt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),_t=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},oi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gt=e=>typeof e=="string"&&oi.test(e)?i.createIdentifier(e):P(e),lt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),ut=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),ze=e=>Object.entries(e).map(([t,r])=>ut(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Jt=(e,t=[])=>i.createConstructorDeclaration(De.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&$t(u,t)):e,Wt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),ye=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,Gt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t));return o?Vt(n,o):n},Yt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Qt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),Z=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&mt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),Xt=(e,t)=>$(e,i.createUnionTypeNode($t(L,t)),{expose:!0}),$=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?mt:void 0,e,n&&or(n),t);return o?Vt(s,o):s},zo=(e,t)=>i.createPropertyDeclaration(De.public,e,void 0,u(t),void 0),er=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(De.public,void 0,e,void 0,o&&or(o),t,n,i.createBlock(r)),tr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(mt,e,r&&or(r),void 0,t),rr=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),yt=e=>u(Promise.name,[e]),ft=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?mt:void 0,e,void 0,void 0,t);return o?Vt(n,o):n},or=e=>(Array.isArray(e)?e.map(t=>ti(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?u(o):void 0,n?u(n):void 0)}),fe=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ri:void 0,void 0,Array.isArray(e)?$t(ut,e):ze(e),void 0,void 0,t),O=e=>e,Fe=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ie=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),gt=(e,t)=>u("Extract",[e,t]),nr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),D=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Io=e=>i.createUnionTypeNode([u(e),yt(e)]),sr=(e,t)=>i.createFunctionTypeNode(void 0,ze(e),u(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),L=e=>i.createLiteralTypeNode(P(e)),ni=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],vo=e=>ni.includes(e.kind);var ht=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Xt("Method",Eo);someOfType=$("SomeOf",D("T",rr("T")),{params:["T"]});requestType=$("Request",rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>Xt(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>ft(this.interfaces[t],Array.from(this.registry).map(([r,o])=>ye(r,o[t])),{expose:!0}));makeEndpointTags=()=>Z("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Gt(t),i.createArrayLiteralExpression(si(P,r))))),{expose:!0});makeImplementationType=()=>$(this.ids.implementationType,sr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Wt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},yt(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>Z(this.ids.parseRequestFn,fe({[this.ids.requestParameter.text]:V.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>Z(this.ids.substituteFn,fe({[this.ids.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Wt},i.createBlock([Z(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],V.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([nr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(lt(":",[this.ids.keyParameter]),fe([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>er(this.ids.provideMethod,ze({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:D(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[Z(Qt(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:yt(D(this.interfaces.response,"K"))});makeClientClass=t=>tr(t,[Jt([ut(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:De.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>lt("?",[Ie(URLSearchParams.name,t)]);makeFetchURL=()=>Ie(URL.name,lt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),Fe(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(E.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),Fe(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=Z(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=Z(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=Z(this.ids.searchParamsConst,Fe(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=Z(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=Z(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(E.json))),m=i.createReturnStatement(R(this.ids.responseConst,Fe(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return Z(this.ids.defaultImplementationConst,fe([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>Jt(ze({request:"K",params:D(this.interfaces.input,"K")}),[Z(Qt(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),Z(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),nr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ie("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ye(O("event"),t)]);makeOnMethod=()=>er(this.ids.onMethod,ze({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:sr({[this.ids.dataParameter.text]:D(gt("R",Yt(this.makeEventNarrow("E"))),L(O("data")))},Io(V.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,fe([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:D("R",L(O("event")))}});makeSubscriptionClass=t=>tr(t,[zo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:gt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u(V.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:gt(D(this.interfaces.positive,"K"),Yt(this.makeEventNarrow(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[Z(this.ids.clientConst,Ie(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(Ie(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),fe(["time"],i.createBlock([])))]};import{chain as ii,eqBy as ir,path as ar,prop as ai,uniqWith as pi}from"ramda";import h from"typescript";import{z as cr}from"zod";var{factory:U}=h,ci={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},pr={name:ar(["name","text"]),type:ar(["type"]),optional:ar(["questionToken"])},di=({value:e})=>L(e),mi=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&ke(a)?a instanceof cr.ZodOptional:a.isOptional();return ye(s,r(a),{isOptional:c&&o,comment:a.description})});return U.createTypeLiteralNode(n)},li=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),ui=({options:e})=>U.createUnionTypeNode(e.map(L)),Zo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(vo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},yi=e=>ci?.[e.kind],fi=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ge(e,yi(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},gi=e=>U.createUnionTypeNode(Object.values(e.enum).map(L)),hi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},xi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),L(null)]),bi=({items:e,_def:{rest:t}},{next:r})=>U.createTupleTypeNode(e.map(r).concat(t===null?[]:U.createRestTypeNode(r(t)))),Si=({keySchema:e,valueSchema:t},{next:r})=>u("Record",[e,t].map(r)),Ti=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=ii(ai("members"),e),o=pi((...n)=>{if(!ir(pr.name,...n))return!1;if(ir(pr.type,...n)&&ir(pr.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},Oi=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ti(o)}catch{}return U.createIntersectionTypeNode(o)},Ri=({_def:e},{next:t})=>t(e.innerType),ee=e=>()=>u(e),Pi=(e,{next:t})=>t(e.unwrap()),Ai=(e,{next:t})=>t(e.unwrap()),wi=({_def:e},{next:t})=>t(e.innerType),Ei=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),zi=()=>L(null),Ii=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),vi=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof cr.ZodString?r:t instanceof cr.ZodUnion?n:o},Zi=(e,{next:t})=>t(e.unwrap().shape.raw),ki={ZodString:ee(h.SyntaxKind.StringKeyword),ZodNumber:ee(h.SyntaxKind.NumberKeyword),ZodBigInt:ee(h.SyntaxKind.BigIntKeyword),ZodBoolean:ee(h.SyntaxKind.BooleanKeyword),ZodAny:ee(h.SyntaxKind.AnyKeyword),ZodUndefined:ee(h.SyntaxKind.UndefinedKeyword),[ae]:ee(h.SyntaxKind.StringKeyword),[pe]:ee(h.SyntaxKind.StringKeyword),ZodNull:zi,ZodArray:li,ZodTuple:bi,ZodRecord:Si,ZodObject:mi,ZodLiteral:di,ZodIntersection:Oi,ZodUnion:Zo,ZodDefault:Ri,ZodEnum:ui,ZodNativeEnum:gi,ZodEffects:fi,ZodOptional:hi,ZodNullable:xi,ZodDiscriminatedUnion:Zo,ZodBranded:Pi,ZodCatch:wi,ZodPipeline:Ei,ZodLazy:Ii,ZodReadonly:Ai,[F]:vi,[X]:Zi},dr=(e,{brandHandling:t,ctx:r})=>ue(e,{rules:{...t,...ki},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var mr=class extends ht{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=L(null);this.aliases.set(t,$(o,n)),this.aliases.set(t,$(o,r()))}return u(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=ji.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},f={brandHandling:r,ctx:{...p,isResponse:!0}};Ee({routing:t,onEndpoint:(y,T,S)=>{let k=Q.bind(null,S,T),C=`${S} ${T}`,b=$(k("input"),dr(y.getSchema("input"),m),{comment:C});this.program.push(b);let A=Pe.reduce((j,I)=>{let w=y.getResponses(I),te=Ci(([bt,{schema:G,mimeTypes:re,statusCodes:St}])=>{let qe=$(k(I,"variant",`${bt+1}`),dr(re?G:d,f),{comment:C});return this.program.push(qe),St.map(Be=>ye(Be,qe.name))},Array.from(w.entries())),v=ft(k(I,"response","variants"),te,{comment:C});return this.program.push(v),Object.assign(j,{[I]:v})},{});this.paths.add(T);let z=L(C);this.registry.set(C,{input:u(b.name),positive:this.someOf(A.positive),negative:this.someOf(A.negative),response:i.createUnionTypeNode([D(this.interfaces.positive,z),D(this.interfaces.negative,z)]),encoded:i.createIntersectionTypeNode([u(A.positive.name),u(A.negative.name)])}),this.tags.set(C,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&xt.addSyntheticLeadingComment(xt.addSyntheticLeadingComment(i.createEmptyStatement(),xt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),xt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>_t(n,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await we("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};import{z as ve}from"zod";var Co=(e,t)=>ve.object({data:t,event:ve.literal(e),id:ve.string().optional(),retry:ve.number().int().positive().optional()}),Ni=(e,t,r)=>Co(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Li=1e4,ko=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Mi=e=>new q({handler:async({response:t})=>setTimeout(()=>ko(t),Li)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{ko(t),t.write(Ni(e,r,o),"utf-8"),t.flush?.()}}}),Ui=e=>new me({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Co(o,n));return{mimeType:E.sse,schema:r.length?ve.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ve.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Se(r);je(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ce(a),"utf-8")}t.end()}}),lr=class extends le{constructor(t){super(Ui(t)),this.middlewares=[Mi(t)]}};var Hi={dateIn:hr,dateOut:xr,file:Xe,upload:Tr,raw:Sr};export{Me as BuiltinLogger,Ue as DependsOnMethod,Bt as Documentation,H as DocumentationError,le as EndpointsFactory,lr as EventStreamFactory,_ as InputValidationError,mr as Integration,q as Middleware,Ze as MissingPeerError,oe as OutputValidationError,me as ResultHandler,ge as RoutingError,He as ServeStatic,cn as arrayEndpointsFactory,vt as arrayResultHandler,jn as attachRouting,Yo as createConfig,Nn as createServer,pn as defaultEndpointsFactory,Le as defaultResultHandler,Se as ensureHttpError,Hi as ez,Y as getExamples,ne as getMessageFromError,Xs as testEndpoint,ei as testMiddleware};
|
package/package.json
CHANGED